forked from Mte90/GlotDict
-
Notifications
You must be signed in to change notification settings - Fork 0
/
glotdict.js
424 lines (404 loc) · 14.6 KB
/
glotdict.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
/* global key, glotdict_version, $gp, pluralize */
'use strict';
var glotdict_version = "1.0.0";
jQuery(document).ready(function () {
/**
* Saniitize the value striping html
* @param {string} value
* @returns {string} sanitized
*/
function sanitize_value(value) {
return value.replace(/<![\s\S]*?--[ \t\n\r]*>/gi, '');
}
/**
* Get the today with the format dd/mm/yyyy used for the update daily check
*
* @returns String
*/
function gd_today() {
var today = new Date();
var todayn = today.getDate();
if (todayn.length === 1) {
todayn = '0' + todayn;
}
var monthn = today.getMonth() + 1;
if (monthn.length === 1) {
monthn = '0' + monthn;
}
return todayn + '/' + monthn + '/' + today.getFullYear();
}
/**
* Get the the list of locales cached
*
* @returns Array
*/
function gd_list_locales_cached() {
var locales = JSON.parse(JSON.parse(localStorage.getItem('gd_locales')));
if (typeof locales === 'undefined') {
gd_locales();
locales = gd_list_locales_cached();
}
return locales;
}
/**
* Get the the glossary cached
*
* @returns Array
*/
function gd_glossary_file_cached() {
return JSON.parse(JSON.parse(localStorage.getItem('gd_glossary_file')));
}
/**
* Get the glossary file saved
*
* @param {string} lang The language.
* @returns Array
*/
function gd_glossary_cached(lang) {
if (typeof lang === 'undefined' || lang === false) {
return;
}
var glossary_date_cache = localStorage.getItem('gd_glossary_date');
var locales_cache = gd_list_locales_cached();
if (glossary_date_cache === null || glossary_date_cache.length === 0 || glossary_date_cache !== locales_cache[lang].time) {
jQuery.ajax({
url: 'https://codeat.co/glotdict/dictionaries/' + glotdict_version + '/' + lang + '.json',
dataType: 'text',
async: false
}).done(function (data) {
localStorage.setItem('gd_glossary_file', JSON.stringify(data));
var glossary_date = gd_list_locales_cached();
localStorage.setItem('gd_glossary_date', glossary_date[gd_get_lang()].time);
}).fail(function (xhr, ajaxOptions, thrownError) {
console.error(thrownError);
alert('GlotDict: error on loading ' + gd_get_lang() + '.json');
});
}
return gd_glossary_file_cached();
}
/**
* Get the list of locales avalaible
*
* @returns Array
*/
function gd_locales() {
var locales = ['ast', 'bg_BG', 'cy', 'da_DK', 'de_DE', 'en_AU', 'en_CA', 'en_GB', 'es_ES', 'fi', 'fr_FR', 'he_IL', 'hi_IN', 'hr_HR', 'it_IT', 'ja', 'lt_LT', 'lv_LV', 'nl_BE', 'nl_NL', 'pt_BR', 'ro_RO', 'sv_SE', 'th', 'tr_TR', 'uk'];
var locales_date_cache = localStorage.getItem('gd_locales_date');
if (locales_date_cache === null || locales_date_cache !== gd_today()) {
jQuery.ajax({
url: 'https://codeat.co/glotdict/dictionaries/' + glotdict_version + '.json',
dataType: 'text'
}).done(function (data) {
localStorage.setItem('gd_locales', JSON.stringify(data));
localStorage.setItem('gd_locales_date', gd_today());
}).fail(function (xhr, ajaxOptions, thrownError) {
console.error(thrownError);
alert('GlotDict Syntax: error on loading the Glossary Syntax');
});
}
var locales_cache = gd_glossary_cached();
if (typeof locales_cache !== 'undefined') {
locales = Object.keys(locales_cache).map(function (key) {
return key;
});
}
return locales;
}
/**
* Get the language saved in GlotDict
*
* @returns string
*/
function gd_get_lang() {
var lang = localStorage.getItem('gd_language');
if (lang === '' || lang === null) {
return false;
}
return sanitize_value(lang);
}
/**
* Easy way to validate the html to avoid horrible errors
* Happen that the code generated by the extension is an horrible HTML,
* With this function we avoid to inject that html in the page
* @param {String} html
* @returns {Boolean}
*/
function checkHTML(html) {
var doc = document.createElement('div');
doc.innerHTML = html;
return (doc.innerHTML === html);
}
/**
* Get the language for consistency
*
* @returns string
*/
function gd_get_lang_consistency() {
var lang = localStorage.getItem('gd_language');
var reallang = lang.split('_');
if (typeof reallang[1] !== 'undefined') {
reallang = reallang[1].toLowerCase();
}
return sanitize_value(reallang);
}
/**
* Add the term in the page with the HTML code compatible with GlotPress
*
* @param {string} word The term.
* @param {string} element The div box.
* @param {string} item The glossary term.
* @returns void
*/
function gd_add_term_json(word, element, item) {
if (item !== '') {
word = word.replace(/\)/g, "\\)").replace(/\(/g, "\\(");
// The first part in [] check for term that don't have at the left that symbol
// The second search for the term
// The third like the first part
var rgxp = new RegExp('(?=^|$|[^\W\"\(\/\-])\\b(' + word + ')\\b(?=^|$|[^\w\"\)\/\-])', 'gi');
var print = JSON.stringify(item);
print = print.replace(/\'/g, "").replace(/\"/g, """);
if (!item.length) {
print = '[' + print + ']';
}
var repl = '<a target="_blank" href="https://translate.wordpress.org/consistency?search=$1&set=' + gd_get_lang_consistency() + '%2Fdefault"><span class="glossary-word-glotdict" data-translations="' + print + '">$1</span></a>';
var content_html = jQuery(element).html();
var content = content_html.replace(rgxp, repl);
if (content !== content_html) {
if (checkHTML(content)) {
jQuery('#preview-' + jQuery(element).parents().eq(2).attr('row')).addClass('has-glotdict');
jQuery(element).html(content);
}
}
}
}
/**
* Add links for Translation global status and Language projects archive
* @returns void
*/
function gd_add_project_links() {
if (jQuery('.gp-content .breadcrumb li:last-child a').length > 0) {
var lang = jQuery('.gp-content .breadcrumb li:last-child a').attr('href').split('/');
lang = sanitize_value(lang[lang.length - 2]);
jQuery('.gp-content').prepend('<a style="float:right" href="https://translate.wordpress.org/locale/' + lang + '/default">' + jQuery('.gp-content .breadcrumb li:last-child a').text() + ' Projects to Translate</a>');
jQuery('.gp-content h2').prepend('<a class="glossary-link" style="float:right;padding-left:5px;margin-left:5px;border-left: 1px solid black;" href="https://translate.wordpress.org/stats">Translation Global Status</a>');
}
}
/**
* Add the button to scroll to the row of the language choosen
* @returns void
*/
function gd_add_button() {
if (jQuery('title').text().substring(0, 27) === 'Translation status overview') {
jQuery('.gp-content').prepend('<button style="float:right" class="gd_scroll">Scroll to ' + gd_get_lang() + '</button>');
jQuery('.gd_scroll').on('click', function () {
var row = jQuery("#stats-table tr th a:contains('" + gd_get_lang() + "')");
row.html('<b> ' + row.text() + '</b>');
jQuery('html, body').animate({scrollTop: row.offset().top - 50});
});
}
}
/**
* Print the locales selector
*
* @returns void
*/
function gd_locales_selector() {
var lang = gd_get_lang();
var lang_date = localStorage.getItem('gd_glossary_date');
if (lang_date !== null) {
if (lang_date === null || lang_date.length === 0 || lang_date === '' || lang_date === 'null') {
if (gd_glossary_cached(gd_get_lang())) {
lang_date = sanitize_value(localStorage.getItem('gd_glossary_date'));
}
}
if (lang_date === 'null') {
lang_date = gd_today();
}
if (lang_date !== '') {
lang_date = ' Glossary Update: ' + lang_date;
}
}
jQuery('.filters-toolbar:last div:first').append('<span class="separator">•</span><label for="gd-language-picker">Pick glossary: </label><select id="gd-language-picker" class="glotdict_language"></select>' + lang_date);
jQuery('.glotdict_language').append(jQuery('<option></option>'));
var gd_locales_array = gd_locales();
jQuery.each(gd_locales_array, function (key, value) {
var new_option = jQuery('<option></option>').attr('value', value).text(value);
if (lang === value) {
new_option.attr('selected', true);
}
jQuery('.glotdict_language').append(new_option);
});
if (lang === '' || lang === false) {
jQuery('.filters-toolbar:last div:first').append('<h3 style="background-color:#ddd;padding:4px;width:130px;display:inline;margin-left:4px;color:red;">← Set the glossary!</h3>')
.append('<br><h2 style="background-color:#fff;padding:0;display:block;text-align:center;margin-top: 6px;">Welcome to GlotDict! Discover the features and the hotkeys on the <a href="https://github.com/Mte90/GlotDict/blob/master/README.md#features" target="_blank">Readme</a> before to use it.</h2>');
return;
}
jQuery('.glossary-word').contents().unwrap();
}
/**
* Create the tooltip for every terms added
*
* @returns void
*/
function gd_terms_tooltip() {
var lang = gd_get_lang();
var plural = '';
if (lang === false) {
return false;
}
var data = gd_glossary_cached(lang);
// Loop all the editor string views
jQuery('.editor .original').each(function () {
var editor_in_loop = this;
// Clean from other span
var editor = jQuery(editor_in_loop).html().replace(/<\/?span[^>]*>/g, "");
jQuery(editor_in_loop).html(editor);
jQuery.each(data, function (i, item) {
if (i !== '&') {
gd_add_term_json(i, editor_in_loop, item);
plural = pluralize.plural(i);
if (plural !== i && !Array.isArray(data[plural])) {
gd_add_term_json(plural, editor_in_loop, item);
}
}
});
});
jQuery('.editor .original .glossary-word-glotdict').css({'cursor': 'help', 'border-bottom': '1px dashed'});
// Generate the HTML code for the tooltips
jQuery('.editor').tooltip({
items: '.editor .original .glossary-word-glotdict',
content: function () {
var content = jQuery('<ul>');
jQuery.each(jQuery(this).data('translations'), function (i, e) {
var def = jQuery('<li>');
def.append(jQuery('<span>', {text: sanitize_value(e.pos)}).addClass('pos'))
.append(jQuery('<span>', {text: sanitize_value(e.translation)}).addClass('translation'))
.append(jQuery('<span>', {text: sanitize_value(e.comment)}).addClass('comment'));
content.append(def);
});
return content;
}
});
}
/**
* Add the hotkeys in GlotPress
*
* @returns void
*/
function gd_hotkeys() {
jQuery($gp.editor.table).off("keydown", 'tr.editor textarea', $gp.editor.hooks.keydown);
key.filter = function (event) {
var tagName = (event.target || event.srcElement).tagName;
key.setScope(/^(SELECT)$/.test(tagName) ? 'input' : 'other');
return true;
};
key('ctrl+enter', function () {
if (jQuery('.editor:visible').length > 0) {
jQuery('.editor:visible .actions button.ok').trigger('click');
} else {
alert('No opened string to add!');
}
return false;
});
key('ctrl+shift+z', function () {
if (jQuery('.editor:visible').length > 0) {
jQuery('.editor:visible .actions a.close').trigger('click');
}
return false;
});
key('ctrl+shift+a', function () {
if (jQuery('.editor:visible .meta button.approve').length > 0) {
jQuery('.editor:visible .meta button.approve').trigger('click');
} else {
alert('No opened string to approve!');
}
return false;
});
key('ctrl+shift+b', function () {
if (jQuery('.editor:visible .copy').length > 0) {
jQuery('.editor:visible .copy').trigger('click');
}
return false;
});
key('ctrl+shift+r', function () {
if (jQuery('.editor:visible .meta button.reject').length > 0) {
jQuery('.editor:visible .meta button.reject').trigger('click');
} else {
alert('No opened string to reject!');
}
return false;
});
key('ctrl+shift+f', function () {
jQuery('textarea.foreign-text:visible:first').val(function (index, text) {
// Replace space-colon or nbsp-colon with just colon, then replace colons with nbsp-colon
var s = text.replace(/( :| :)/g, ':').replace(/:/g, ' :');
// Fix http and https from the above replace
s = s.replace(/http :/g, 'http:').replace(/https :/g, 'https:');
// Replace space-question or nbsp-question with just question, then replace question with nbsp-question
s = s.replace(/( \?| \?)/g, '?').replace(/\?/g, ' ?');
// Replace space-exclamation or nbsp-exclamation with just exclamation, then replace exclamation with nbsp-exclamation
s = s.replace(/( !| !)/g, '!').replace(/!/g, ' !');
// Replace space-%-space with nbsp-%-space
s = s.replace(/( % )/g, ' % ');
// Replace space-dot-space or space-dot with just dot-space, same for comma
s = s.replace(/( \. | \.)/g, '. ').replace(/( , | ,)/g, ', ');
// Replace space-closebracket-space or space-closebracket with just closebracket-space, same for squarebracket
s = s.replace(/( \) | \))/g, ') ').replace(/( ] | ])/g, '] ');
// Replace space-openbracket-space or openbracket-space with just space-openbracket, same for squarebracket
s = s.replace(/( \( |\( )/g, ' (').replace(/( \[ |\[ )/g, ' [');
return s;
});
return false;
});
key('pageup', function () {
if (jQuery('.editor:visible').length > 0) {
jQuery('.editor').next().trigger('click');
}
return false;
});
key('pagedown', function () {
if (jQuery('.editor:visible').length > 0) {
jQuery('.editor').prev().trigger('click');
}
return false;
});
key('ctrl+alt+r', function () {
localStorage.removeItem('gd_glossary_date');
localStorage.removeItem('gd_glossary_file');
localStorage.removeItem('gd_language');
localStorage.removeItem('gd_locales');
localStorage.removeItem('gd_locales_date');
location.reload();
return false;
});
}
gd_add_project_links();
gd_add_button();
if (jQuery('.filters-toolbar:last div:first').length > 0) {
//Fix for PTE align
if (jQuery('#bulk-actions-toolbar').length > 0) {
jQuery('#upper-filters-toolbar').css('clear', 'both');
}
if (jQuery('.preview').length === 1) {
jQuery('.preview .action').trigger('click');
}
jQuery("<style type='text/css'>.has-glotdict td:first-child,.has-glotdict th:first-child,.box.has-glotdict{border-left-width: 2px !important;border-left-color: blue !important;}</style>").appendTo("head");
jQuery("<div class='box has-glotdict'></div><div>Contain a GlotDict term</div>").appendTo("#legend");
gd_terms_tooltip();
gd_locales_selector();
gd_hotkeys();
}
jQuery('.glotdict_language').change(function () {
localStorage.setItem('gd_language', jQuery('.glotdict_language option:selected').text());
localStorage.setItem('gd_glossary_date', '');
gd_locales();
location.reload();
});
jQuery('.glossary-word-glotdict').contextmenu(function (e) {
var info = jQuery(this).data('translations');
jQuery('.editor:visible textarea').val(jQuery('.editor:visible textarea').val() + info[0].translation);
e.preventDefault();
return false;
});
});