-
Notifications
You must be signed in to change notification settings - Fork 285
/
app.js
2457 lines (2026 loc) · 68.5 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
/*
* Copyright (C) Pootle contributors.
*
* This file is a part of the Pootle project. It is distributed under the GPL3
* or later license. See the LICENSE file for a copy of the license and the
* AUTHORS file for copyright and authorship information.
*/
import $ from 'jquery';
import _ from 'underscore';
import React from 'react';
import ReactDOM from 'react-dom';
import TimeSince from 'components/TimeSince';
import ReactRenderer from 'utils/ReactRenderer';
// jQuery plugins
import 'jquery-caret';
import 'jquery-easing';
import 'jquery-highlightRegex';
import 'jquery-history';
import 'jquery-serializeObject';
import 'jquery-utils';
// Other plugins
import autosize from 'autosize';
import cx from 'classnames';
import Levenshtein from 'levenshtein';
import mousetrap from 'mousetrap';
import assign from 'object-assign';
import StatsAPI from 'api/StatsAPI';
import UnitAPI from 'api/UnitAPI';
import cookie from 'utils/cookie';
import fetch from 'utils/fetch';
import linkHashtags from 'utils/linkHashtags';
import SuggestionFeedbackForm from './components/SuggestionFeedbackForm';
import UploadTimeSince from './components/UploadTimeSince';
import captcha from '../captcha';
import { UnitSet } from '../collections';
import helpers from '../helpers';
import msg from '../msg';
import score from '../score';
import search from '../search';
import utils from '../utils';
import {
decodeEntities, escapeUnsafeRegexSymbols, makeRegexForMultipleWords,
} from './utils';
const CTX_STEP = 1;
const ALLOWED_SORTS = ['oldest', 'newest', 'default'];
const filterSelectOpts = {
dropdownAutoWidth: true,
width: 'off',
};
const sortSelectOpts = assign({
minimumResultsForSearch: -1,
}, filterSelectOpts);
const mtProviders = [];
function _refreshChecksSnippet(newChecks) {
const $checks = $('.js-unit-checks');
const focusedArea = $('.focusthis')[0];
$checks.html(newChecks).show();
utils.blinkClass($checks, 'blink', 4, 200);
focusedArea.focus();
}
window.PTL = window.PTL || {};
PTL.editor = {
/* Initializes the editor */
init(options) {
/* Default settings */
this.settings = {
mt: [],
displayPriority: false,
};
if (options) {
assign(this.settings, options);
}
/* Cached elements */
this.backToBrowserEl = document.querySelector('.js-back-to-browser');
this.$editorActivity = $('#js-editor-act');
this.$editorBody = $('.js-editor-body');
this.editorTableEl = document.querySelector('.js-editor-table');
this.$filterStatus = $('#js-filter-status');
this.$filterChecks = $('#js-filter-checks');
this.$filterChecksWrapper = $('.js-filter-checks-wrapper');
this.$filterSortBy = $('#js-filter-sort');
this.$msgOverlay = $('#js-editor-msg-overlay');
this.$navNext = $('#js-nav-next');
this.$navPrev = $('#js-nav-prev');
this.unitCountEl = document.querySelector('.js-unit-count');
this.unitIndexEl = document.querySelector('.js-unit-index');
this.offsetRequested = 0;
/* Initialize variables */
this.units = new UnitSet([], {
chunkSize: this.settings.chunkSize,
});
this.editorRow = null;
this.filter = 'all';
this.checks = [];
this.sortBy = 'default';
this.modifiedSince = null;
this.user = null;
this.ctxGap = 0;
this.ctxQty = parseInt(cookie('ctxQty'), 10) || 1;
this.preventNavigation = false;
this.isUnitDirty = false;
this.isLoading = true;
this.showActivity();
this.fetchingOffsets = [];
/* Regular expressions */
this.cpRE = /^(<[^>]+>|\[n\|t]|\W$^\n)*(\b|$)/gm;
/* Levenshtein word comparer */
this.wordComparer = new Levenshtein({ compare: 'words' });
/* Compile templates */
this.tmpl = {
vUnit: _.template($('#view_unit').html()),
tm: _.template($('#tm_suggestions').html()),
editCtx: _.template($('#editCtx').html()),
msg: _.template($('#js-editor-msg').html()),
};
/* Initialize search */
search.init({
onSearch: this.onSearch,
});
if (options.displayPriority) {
ALLOWED_SORTS.push('priority');
}
/* Select2 */
this.$filterStatus.select2(filterSelectOpts);
this.$filterSortBy.select2(sortSelectOpts);
/* Screenshot images */
$(document).on('click', '.js-dev-img', function displayScreenshot(e) {
e.preventDefault();
$(this).magnificPopup({
type: 'image',
gallery: {
enabled: true,
},
}).magnificPopup('open');
});
/*
* Bind event handlers
*/
/* State changes */
$(document).on('input', '.js-translation-area',
(e) => this.onTextareaChange(e));
$(document).on('change', 'input.fuzzycheck',
() => this.onStateChange());
$(document).on('click', 'input.fuzzycheck',
() => this.onStateClick());
$(document).on('input', '#id_translator_comment',
() => this.handleTranslationChange());
/* Suggest / submit */
$(document).on('click', '.switch-suggest-mode a',
(e) => this.toggleSuggestMode(e));
/* Update focus when appropriate */
$(document).on('focus', '.focusthis', (e) => {
PTL.editor.focused = e.target;
});
/* General */
$(document).on('click', '.js-editor-reload', (e) => {
e.preventDefault();
$.history.load('');
});
/* Write TM results, special chars... into the currently focused element */
$(document).on('click', '.js-editor-copytext', (e) => this.copyText(e));
/* Copy translator comment */
$(document).on('click', '.js-editor-copy-comment', (e) => {
const text = e.currentTarget.dataset.string;
this.copyComment(text);
});
/* Copy original translation */
$(document).on('click', '.js-copyoriginal', (e) => {
const uId = e.currentTarget.dataset.uid;
const sources = [
...document.querySelectorAll(`#js-unit-${uId} .js-translation-text`),
].map((el) => el.textContent);
this.copyOriginal(sources);
});
/* Editor navigation/submission */
$(document).on('mouseup', 'tr.view-row, tr.ctx-row', this.gotoUnit);
$(document).on('keypress', '.js-unit-index', (e) => this.gotoIndex(e));
$(document).on('dblclick click', '.js-unit-index', (e) => this.unitIndex(e));
$(document).on('click', 'input.submit', (e) => {
e.preventDefault();
this.handleSubmit();
});
$(document).on('click', 'input.suggest', (e) => {
e.preventDefault();
this.handleSuggest();
});
$(document).on('click', '#js-nav-prev', () => this.gotoPrev());
$(document).on('click', '#js-nav-next', () => this.gotoNext());
$(document).on('click', '.js-suggestion-reject', (e) => {
e.stopPropagation();
this.rejectSuggestion(e.currentTarget.dataset.suggId);
});
$(document).on('click', '.js-suggestion-accept', (e) => {
e.stopPropagation();
this.acceptSuggestion(e.currentTarget.dataset.suggId);
});
$(document).on('click', '.js-suggestion-toggle',
(e) => this.toggleSuggestion(e, { canHide: true }));
if (this.settings.canReview) {
$(document).on('click', '.js-user-suggestion',
(e) => this.toggleSuggestion(e, { canHide: false }));
}
$(document).on('click', '.js-translate-lightbox', () => this.closeSuggestion());
$(document).on('click', '#js-toggle-timeline', (e) => this.toggleTimeline(e));
$(document).on('click', '.js-toggle-check', (e) => {
this.toggleCheck(e.currentTarget.dataset.checkId);
});
/* Filtering */
$(document).on('change', '#js-filter-status', () => this.filterStatus());
$(document).on('change', '#js-filter-checks', () => this.filterChecks());
$(document).on('change', '#js-filter-sort', () => this.filterSort());
$(document).on('click', '.js-more-ctx', () => this.moreContext());
$(document).on('click', '.js-less-ctx', () => this.lessContext());
$(document).on('click', '.js-show-ctx', () => this.showContext());
$(document).on('click', '.js-hide-ctx', () => this.hideContext());
/* Commenting */
$(document).on('click', '.js-editor-comment', (e) => {
e.preventDefault();
const $elem = $('.js-editor-comment-form');
const $comment = $('.js-editor-comment');
$comment.toggleClass('selected');
if ($comment.hasClass('selected')) {
$elem.css('display', 'inline-block');
$('#id_translator_comment').focus();
} else {
$elem.css('display', 'none');
}
});
$(document).on('submit', '#js-comment-form', (e) => this.addComment(e));
$(document).on('click', '.js-comment-remove', (e) => this.removeComment(e));
/* Misc */
$(document).on('click', '.js-editor-msg-hide', () => this.hideMsg());
$(document).on('click', '.js-toggle-raw', (e) => {
e.preventDefault();
$('.js-translate-translation').toggleClass('raw');
$('.js-toggle-raw').toggleClass('selected');
autosize.update(document.querySelector('.js-translation-area'));
});
/* Confirmation prompt */
window.addEventListener('beforeunload', (e) => {
if (PTL.editor.isUnitDirty || PTL.editor.isSuggestionFeedbackFormDirty) {
// eslint-disable-next-line no-param-reassign
e.returnValue = gettext(
'You have unsaved changes in this string. Navigating away will discard those changes.'
);
}
});
/* Bind hotkeys */
const hotkeys = mousetrap(document.body);
// FIXME: move binding to `SuggestionFeedbackForm` component
hotkeys.bind('esc', () => {
if (this.selectedSuggestionId !== undefined) {
this.closeSuggestion();
}
});
hotkeys.bind('ctrl+return', (e) => {
e.preventDefault();
if (this.isSuggestMode()) {
this.handleSuggest();
} else {
this.handleSubmit();
}
});
hotkeys.bind('ctrl+space', () => this.toggleState());
hotkeys.bind('ctrl+shift+space', (e) => this.toggleSuggestMode(e));
hotkeys.bind('ctrl+up', () => this.gotoPrev());
hotkeys.bind('ctrl+,', () => this.gotoPrev());
hotkeys.bind('ctrl+down', () => this.gotoNext({ isSubmission: false }));
hotkeys.bind('ctrl+.', () => this.gotoNext({ isSubmission: false }));
if (navigator.platform.toUpperCase().indexOf('MAC') >= 0) {
// Optimize string join with '<br/>' as separator
this.$navNext.attr('title',
gettext(
'Go to the next string (Ctrl+.)<br/><br/>Also:<br/>Next page: ' +
'Ctrl+Shift+.<br/>Last page: Ctrl+Shift+End'
)
);
this.$navPrev.attr('title',
gettext(
'Go to the previous string (Ctrl+,)<br/><br/>Also:</br>Previous page: ' +
'Ctrl+Shift+,<br/>First page: Ctrl+Shift+Home'
)
);
}
hotkeys.bind('ctrl+shift+n', (e) => this.unitIndex(e));
/* XHR activity indicator */
$(document).ajaxStart(() => {
clearTimeout(this.delayedActivityTimer);
this.delayedActivityTimer = setTimeout(() => {
this.showActivity();
}, 3000);
});
$(document).ajaxStop(() => {
clearTimeout(this.delayedActivityTimer);
if (!this.isLoading) {
this.hideActivity();
}
});
/* Load MT providers */
this.settings.mt.forEach((provider) => {
require.ensure([], () => {
// Retrieve actual module name: FOO_BAR_BAZ => FooBarBaz
const moduleName = provider.name.split('_').map(
(x) => x[0] + x.slice(1).toLowerCase()
).join('');
// Webpack doesn't like template strings for now...
// eslint-disable-next-line prefer-template
const Module = require('./mt/providers/' + moduleName).default;
mtProviders.push(new Module(provider.key));
});
});
// Update relative dates every minute
setInterval(helpers.updateRelativeDates, 6e4);
/* History support */
$.history.init((hash) => {
const params = utils.getParsedHash(hash);
let isInitial = true;
let uId = 0;
let initialOffset = 0;
if (this.selectedSuggestionId !== undefined) {
this.closeSuggestion({ checkIfCanNavigate: false });
}
ReactRenderer.unmountComponents();
// Walk through known filtering criterias and apply them to the editor object
if (params.unit) {
const uIdParam = parseInt(params.unit, 10);
if (uIdParam && !isNaN(uIdParam)) {
const current = this.units.getCurrent();
const newUnit = this.units.get(uIdParam);
if (newUnit && newUnit !== current) {
this.setUnit(newUnit);
return;
}
uId = uIdParam;
// Don't retrieve initial data if there are existing results
isInitial = !this.units.length;
}
}
if (params.offset) {
const offset = parseInt(params.offset, 10);
if (offset && !isNaN(offset)) {
initialOffset = this.getStartOfChunk(offset);
}
}
// Reset to defaults
this.filter = 'all';
this.checks = [];
this.category = [];
this.sortBy = 'default';
if ('filter' in params) {
const filterName = params.filter;
// Set current state
this.filter = filterName;
if (filterName === 'checks' && 'checks' in params) {
this.checks = params.checks.split(',');
}
if (filterName === 'checks' && 'category' in params) {
this.category = params.category;
}
if ('sort' in params) {
const { sort } = params;
this.sortBy = ALLOWED_SORTS.indexOf(sort) !== -1 ? sort : 'default';
}
}
if ('modified-since' in params) {
this.modifiedSince = params['modified-since'];
} else {
this.modifiedSince = null;
}
if ('month' in params) {
this.month = params.month;
} else {
this.month = null;
}
// Only accept the user parameter for 'user-*' filters
if ('user' in params && this.filter.indexOf('user-') === 0) {
this.user = encodeURIComponent(params.user);
const user = this.user;
const values = {
'user-suggestions':
// Translators: '%s' is a username
interpolate(gettext("%s's pending suggestions"), [user]),
'user-suggestions-accepted':
// Translators: '%s' is a username
interpolate(gettext("%s's accepted suggestions"), [user]),
'user-suggestions-rejected':
// Translators: '%s' is a username
interpolate(gettext("%s's rejected suggestions"), [user]),
'user-submissions':
// Translators: '%s' is a username
interpolate(gettext("%s's submissions"), [user]),
'user-submissions-overwritten':
// Translators: '%s' is a username, meaning "submissions by %s,
// that were overwritten"
interpolate(gettext("%s's overwritten submissions"), [user]),
};
const newOpts = [];
for (const key in values) {
if (!values.hasOwnProperty(key)) {
continue;
}
newOpts.push(`
<option value="${key}" data-user="${user}" class="js-user-filter">
${values[key]}
</option>
`);
}
$('.js-user-filter').remove();
this.$filterStatus.append(newOpts.join(''));
}
if ('search' in params) {
// Note that currently the search, if provided along with the other
// filters, would override them
this.filter = 'search';
const newState = {
searchText: params.search,
};
if ('sfields' in params) {
newState.searchFields = params.sfields.split(',');
}
if ('soptions' in params) {
newState.searchOptions = params.soptions.split(',');
}
search.setState(newState);
}
// Update the filter UI to match the current filter
// disable navigation on UI toolbar events to prevent data reload
this.preventNavigation = true;
const filterValue = this.filter === 'search' ? 'all' : this.filter;
this.$filterStatus.select2('val', filterValue);
if (this.filter === 'checks') {
// if the checks selector is empty (i.e. the 'change' event was not fired
// because the selection did not change), force the update to populate the selector
if (this.$filterChecks.is(':hidden')) {
this.getCheckOptions();
}
}
this.$filterSortBy.select2('val', this.sortBy);
if (this.filter === 'search') {
this.$filterChecksWrapper.hide();
}
// re-enable normal event handling
this.preventNavigation = false;
this.fetchUnits({
uId,
initialOffset,
initial: isInitial,
}).then((hasResults) => {
if (!hasResults) {
return;
}
if (this.units.uIds.indexOf(uId) === -1) {
if (this.offsetRequested > this.initialOffset &&
this.offsetRequested <= this.getOffsetOfLastUnit()) {
uId = this.units.uIds[this.offsetRequested - this.initialOffset - 1];
} else {
uId = this.units.uIds[0];
$.history.load(utils.updateHashPart('unit', uId));
}
}
this.offsetRequested = 0;
this.setUnit(uId);
});
}, { unescape: true });
},
/* Stuff to be done when the editor is ready */
ready() {
const currentUnit = this.units.getCurrent();
if (currentUnit.get('isObsolete')) {
this.displayObsoleteMsg();
}
autosize(document.querySelector('textarea.expanding:not([disabled="disabled"])'));
// set direction of the comment body
$('.extra-item-comment').filter(':not([dir])').bidi();
// set direction of the suggestion body
$('.suggestion-translation-body').filter(':not([dir])').bidi();
// Focus on the first textarea, if any
const firstArea = $('.focusthis')[0];
if (firstArea) {
firstArea.focus();
}
const $devComments = $('.js-developer-comments');
$devComments.html(linkHashtags($devComments.html()));
if (this.filter === 'search') {
this.hlSearch();
}
if (this.settings.tmUrl !== '') {
this.getTMUnits();
}
if (this.tmData !== null) {
const tmContent = this.getTMUnitsContent(this.tmData);
$('#extras-container').append(tmContent);
}
this.runHooks();
this.isUnitDirty = false;
this.keepState = false;
this.isLoading = false;
this.hideActivity();
this.updateExportLink();
helpers.updateRelativeDates();
},
/* Things to do when no results are returned */
noResults() {
this.displayMsg({ body: gettext('No results.') });
this.reDraw();
},
canNavigate() {
if (this.isUnitDirty || this.isSuggestionFeedbackFormDirty) {
return window.confirm( // eslint-disable-line no-alert
gettext(
'You have unsaved changes in this string. Navigating away will discard those changes.'
)
);
}
return true;
},
/*
* Text utils
*/
/* Highlights search results */
hlSearch() {
const { searchText, searchFields, searchOptions } = search.state;
const selMap = {
notes: 'div.developer-comments',
locations: 'div.translate-locations',
source: 'td.translate-original, .original .js-translation-text',
target: 'td.translate-translation',
};
// Build highlighting selector based on chosen search fields
const sel = searchFields.map((fieldName) => [
`tr.edit-row ${selMap[fieldName]}`,
`tr.view-row ${selMap[fieldName]}`,
]).reduce((a, b) => a.concat(b), []);
let hlRegex;
if (searchOptions.indexOf('exact') >= 0) {
hlRegex = new RegExp(`(${escapeUnsafeRegexSymbols(searchText)})`);
} else {
hlRegex = new RegExp(makeRegexForMultipleWords(searchText), 'i');
}
$(sel.join(', ')).highlightRegex(hlRegex);
},
/* Copies text into the focused textarea */
copyText(e) {
const $el = $(e.currentTarget);
const action = $el.data('action');
const text = $el.data('string') || $el.data('translation-aid') || $el.text();
const $target = $(this.focused);
let start;
if (action === 'overwrite') {
$target.val(text).trigger('input');
start = text.length;
} else {
start = $target.caret().start + text.length;
$target.val($target.caret().replace(text)).trigger('input');
}
$target.caret(start, start);
autosize.update(this.focused);
},
/* Copies source text(s) into the target textarea(s)*/
copyOriginal(sources) {
const targets = $('.js-translation-area');
if (targets.length) {
const max = sources.length - 1;
for (let i = 0; i < targets.length; i++) {
const newval = sources[i] || sources[max];
$(targets.get(i)).val(newval).trigger('input');
}
// Focus on the first textarea
const active = $(targets)[0];
active.focus();
autosize.update(active);
// Make this fuzzy
this.goFuzzy();
// Place cursor at start of target text
this.cpRE.exec($(active).val());
const i = this.cpRE.lastIndex;
$(active).caret(i, i);
this.cpRE.lastIndex = 0;
}
},
copyComment(text) {
const comment = document.querySelector('.js-editor-comment');
const commentForm = document.querySelector('.js-editor-comment-form');
const commentInput = document.querySelector('#id_translator_comment');
if (!comment.classList.contains('selected')) {
commentForm.style.display = 'inline-block';
comment.classList.add('selected');
}
commentInput.focus();
commentInput.value = text;
},
/*
* Fuzzying / unfuzzying functions
*/
/* Sets the current unit's styling as fuzzy */
doFuzzyStyle() {
$('tr.edit-row').addClass('fuzzy-unit');
},
/* Unsets the current unit's styling as fuzzy */
undoFuzzyStyle() {
$('tr.edit-row').removeClass('fuzzy-unit');
},
/* Checks the current unit's fuzzy checkbox */
doFuzzyBox() {
const $checkbox = $('input.fuzzycheck');
$checkbox.prop('checked', true);
if (!this.settings.isAdmin) {
if (!this.isSuggestMode()) {
$('.js-fuzzy-block').show();
}
$checkbox[0].defaultChecked = true;
}
$checkbox.trigger('change');
},
/* Unchecks the current unit's fuzzy checkbox */
undoFuzzyBox() {
const $checkbox = $('input.fuzzycheck');
$checkbox.prop('checked', false);
$checkbox.trigger('change');
},
/* Sets the current unit status as fuzzy (both styling and checkbox) */
goFuzzy() {
if (!this.isFuzzy()) {
this.doFuzzyStyle();
this.doFuzzyBox();
}
},
/* Unsets the current unit status as fuzzy (both styling and checkbox) */
ungoFuzzy() {
if (this.isFuzzy()) {
this.undoFuzzyStyle();
this.undoFuzzyBox();
}
},
/* Returns whether the current unit is fuzzy or not */
isFuzzy() {
return $('input.fuzzycheck').prop('checked');
},
toggleFuzzyStyle() {
if (this.isFuzzy()) {
this.doFuzzyStyle();
} else {
this.undoFuzzyStyle();
}
},
toggleState() {
// `blur()` prevents a double-click effect if the checkbox was
// previously clicked using the mouse
$('input.fuzzycheck:visible').blur().click();
},
/* Updates unit textarea and input's `default*` values. */
updateUnitDefaultProperties() {
$('.js-translation-area').each(function setDefaultValue() {
this.defaultValue = this.value;
});
const checkbox = document.querySelector('#id_state');
checkbox.defaultChecked = checkbox.checked;
this.handleTranslationChange();
},
/* Updates comment area's `defaultValue` value. */
updateCommentDefaultProperties() {
const comment = document.querySelector('#id_translator_comment');
comment.defaultValue = comment.value;
this.handleTranslationChange();
},
handleTranslationChange() {
const comment = document.querySelector('#id_translator_comment');
const commentChanged = comment !== null ?
comment.value !== comment.defaultValue : false;
const submit = document.querySelector('.js-submit');
const suggest = document.querySelector('.js-suggest');
const translations = $('.js-translation-area').get();
const suggestions = $('.js-user-suggestion').map(function getSuggestions() {
return $(this).data('translation-aid');
}).get();
const checkbox = document.querySelector('#id_state');
const stateChanged = checkbox.defaultChecked !== checkbox.checked;
let areaChanged = false;
let needsReview = false;
let suggestionExists = false;
let area;
// Non-admin users are required to clear the fuzzy checkbox
if (!this.settings.isAdmin) {
needsReview = checkbox.checked === true;
}
for (let i = 0; i < translations.length && !areaChanged; i++) {
area = translations[i];
areaChanged = area.defaultValue !== area.value;
}
if (suggestions.length) {
for (let i = 0; i < translations.length && !suggestionExists; i++) {
area = translations[i];
suggestionExists = suggestions.indexOf(area.value) !== -1;
}
}
// Store dirty state for the current unit
this.isUnitDirty = areaChanged || stateChanged || commentChanged;
if (submit !== null) {
submit.disabled = !(stateChanged || areaChanged) || needsReview;
}
if (suggest !== null) {
suggest.disabled = !areaChanged || suggestionExists;
}
},
onStateChange() {
this.handleTranslationChange();
this.toggleFuzzyStyle();
},
onStateClick() {
// Prevent automatic unfuzzying on explicit user action
this.keepState = true;
},
onTextareaChange(e) {
this.handleTranslationChange();
const el = e.target;
const hasChanged = el.defaultValue !== el.value;
if (hasChanged && !this.keepState) {
this.ungoFuzzy();
}
clearTimeout(this.similarityTimer);
this.similarityTimer = setTimeout(() => {
this.checkSimilarTranslations();
this.similarityTimer = null; // So we know the code was run
}, 200);
},
/*
* Translation's similarity
*/
getSimilarityData() {
const currentUnit = this.units.getCurrent();
return {
similarity: currentUnit.get('similarityHuman'),
mt_similarity: currentUnit.get('similarityMT'),
};
},
calculateSimilarity(newTranslation, $elements, dataSelector) {
let maxSimilarity = 0;
let boxId = null;
for (let i = 0; i < $elements.length; i++) {
const $element = $elements.eq(i);
const aidText = $element.data(dataSelector);
const similarity = this.wordComparer.similarity(newTranslation, aidText);
if (similarity > maxSimilarity) {
maxSimilarity = similarity;
boxId = $element.hasClass('js-translation-area') ?
null : $element.val('id');
}
}
return {
boxId,
max: maxSimilarity,
};
},
checkSimilarTranslations() {
const dataSelector = 'translation-aid';
const dataSelectorMT = 'translation-aid-mt';
const $aidElementsMT = $(`[data-${dataSelectorMT}]`);
let aidElementsSelector = `[data-${dataSelector}]`;
// Exclude own suggestions for non-anonymous users
if (!this.settings.isAnonymous) {
aidElementsSelector += `[data-suggestor-id!=${this.settings.userId}]`;
}
const $aidElements = $(aidElementsSelector);
if (!$aidElements.length && !$aidElementsMT.length) {
return false;
}
const currentUnit = this.units.getCurrent();
const newTranslation = $('.js-translation-area').val();
let simHuman = { max: 0, boxId: null };
let simMT = { max: 0, boxId: null };
if ($aidElements.length) {
simHuman = this.calculateSimilarity(newTranslation, $aidElements,
dataSelector);
}
if ($aidElementsMT.length) {
simMT = this.calculateSimilarity(newTranslation, $aidElementsMT,
dataSelectorMT);
}
currentUnit.set({
similarityHuman: simHuman.max,
similarityMT: simMT.max,
});
const similarity = (simHuman.max > simMT.max) ? simHuman : simMT;
this.highlightBox(similarity.boxId, similarity.max === 1);
return true;
},
/* Applies highlight classes to `boxId`. */
highlightBox(boxId, isExact) {
const bestMatchCls = 'best-match';
const exactMatchCls = 'exact-match';
$('.translate-table').find(`.${bestMatchCls}`)
.removeClass(`${bestMatchCls} ${exactMatchCls}`);
if (boxId === null) {
return false;
}
$(boxId).addClass(cx({
[bestMatchCls]: true,
[exactMatchCls]: isExact,
}));
return true;
},
/*
* Suggest / submit mode functions
*/
/* Changes the editor into suggest mode */
doSuggestMode() {
this.editorTableEl.classList.add('suggest-mode');
},
/* Changes the editor into submit mode */
undoSuggestMode() {
this.editorTableEl.classList.remove('suggest-mode');
},
/* Returns true if the editor is in suggest mode */
isSuggestMode() {
return this.editorTableEl.classList.contains('suggest-mode');
},