This repository has been archived by the owner on Nov 22, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 27
/
index.js
398 lines (351 loc) · 11.9 KB
/
index.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
/* global require */
'use strict'
const self = require('sdk/self')
const sp = require('sdk/simple-prefs')
const ps = require('sdk/preferences/service')
const tabs = require('sdk/tabs')
const { getMostRecentBrowserWindow } = require('sdk/window/utils')
const addonUnload = require('sdk/system/unload')
const windows = require('sdk/windows').browserWindows
const { viewFor } = require('sdk/view/core')
const request = require('sdk/request').Request
const clipboard = require('sdk/clipboard')
const _ = require('sdk/l10n').get
const {
translate,
translateUrl,
translatePageUrl,
LABEL_TRANSLATE_ERROR,
} = require('./providers/google-translate')
// Get the available languages
const getLanguages = () => new Promise((resolve) => {
request({
url: self.data.url('languages.json'),
overrideMimeType: 'application/json',
onComplete: response => resolve(response.json),
}).get()
})
// Replace params in a string à la Python str.format()
const format = (origStr, ...args) => Array.from(args).reduce(
(str, arg, i) => str.replace(new RegExp(`\\{${i}\\}`, 'g'), arg), origStr
)
// Get the From language from the preferences
const currentFrom = () => sp.prefs.langFrom
// Get the To language from the preferences
const currentTo = () => {
let langCode = sp.prefs.langTo
const locale = ps.getLocalized('general.useragent.locale', 'en')
if (langCode === 'auto') {
if (!locale.startsWith('zh')) {
langCode = locale.replace(/-[a-zA-Z]+$/, '')
}
}
return langCode
}
// Utility function to create elements
const eltCreator = doc => (name, props, attrs, parent) => {
const elt = doc.createElement(name)
if (props) Object.keys(props).forEach(p => elt[p] = props[p])
if (attrs) Object.keys(attrs).forEach(a => elt.setAttribute(a, attrs[a]))
if (parent) parent.appendChild(elt)
return elt
}
const cmpLanguages = (a, b) => {
if (a === 'auto')
return -1
else if (b === 'auto')
return 1
else
return _(a).localeCompare(_(b))
}
const langToItems = (languages, doc) => {
return Object.keys(languages)
.filter(lang => !languages[lang].onlyFrom)
.sort(cmpLanguages)
.map(lang => {
const item = doc.createElement('menuitem')
item.setAttribute('label', _(lang))
item.setAttribute('data-gtranslate-to', lang)
return item
})
}
const langFromMenus = (languages, doc) => {
const toItemsPopup = doc.createElement('menupopup')
langToItems(languages, doc).forEach(item => toItemsPopup.appendChild(item))
return Object.keys(languages)
.filter(lang => !languages[lang].onlyTo)
.sort(cmpLanguages)
.map(lang => {
const menu = doc.createElement('menu')
menu.setAttribute('label', _(lang))
menu.setAttribute('data-gtranslate-from', lang)
menu.appendChild(toItemsPopup.cloneNode(true))
return menu
})
}
// Returns the current selection based on the active node
const getSelectionFromNode = (node) => {
const contentWin = node.ownerDocument.defaultView
const name = node.nodeName.toLowerCase()
const text = contentWin.getSelection().toString().trim()
if (text) {
return text
}
if (name === 'input' || name === 'textarea') {
return node.value.substr(
node.selectionStart,
node.selectionEnd - node.selectionStart
) || null
}
if (name === 'a') {
return node.textContent || node.title || null
}
if (name === 'img') {
return (node.alt !== node.src && node.alt) || node.title || null
}
return null
}
// Returns the popupNode of a window or null
const getPopupNode = (win) => (
win.gContextMenuContentData.popupNode || null
)
// Returns the current selection from a window
const getSelectionFromWin = (win) => {
const popupNode = getPopupNode(win)
return popupNode ? getSelectionFromNode(popupNode) : ''
}
// Get active tab url
const getCurrentUrl = () => {
if (tabs.length === 0) return null
const currentUrl = tabs.activeTab.url
if (currentUrl.startsWith('about:')) return null
return currentUrl
}
// Open a new tab near to the active tab
const openTab = url => {
const browser = getMostRecentBrowserWindow().gBrowser
const tab = browser.loadOneTab(url, {relatedToCurrent: true})
browser.selectedTab = tab
}
// Determines if the page can be translated, by checking if a node is displayed
// in a special viewer or not (image, video, etc.), and its mime type.
// For images, the document should be an instance of window.ImageDocument.
// For other types, we have to check type as the document is an HtmlDocument.
// node: the node from which the contextual menu has been opened
// window: the current browser window
const translatablePage = (node, window) => {
const doc = node.ownerDocument
const contentType = doc.contentType
if (!/^https?:/.test(doc.location.protocol)) return false
if (doc instanceof window.ImageDocument) return false
if (contentType.startsWith('video')) return false
if (contentType.startsWith('audio')) return false
if (contentType === 'application/ogg') return false
return true
}
// Add a gtranslate menu on a window
const initMenu = (win, languages) => {
let selection = ''
const doc = win.document
const cmNode = doc.getElementById('contentAreaContextMenu')
const elt = eltCreator(doc)
const translateMenu = elt(
'menu',
{ className: 'menu-iconic', id: 'context-gtranslate' },
{ label: _('translate'), image: self.data.url('menuitem.svg') }
)
const translatePage = elt(
'menuitem',
{ className: 'menuitem-iconic'},
{ label: _('translate_page'), image: self.data.url('menuitem.svg') }
)
const translatePopup = elt('menupopup', null, null, translateMenu)
const result = elt('menuitem', null, null, translatePopup)
elt('menuseparator', null, null, translatePopup)
const clipboardItem = elt(
'menuitem', null, { label: _('copy_to_clipboard') },
translatePopup
)
const langMenu = elt('menu', null, null, translatePopup)
const fromPopup = elt('menupopup', null, null, langMenu)
const fromMenus = langFromMenus(languages, doc)
fromMenus.forEach(menu => fromPopup.appendChild(menu))
const updateResult = (translation, dict) => {
result.setAttribute('tooltiptext', translation + (dict ? '\n' + dict : ''))
result.setAttribute('label', translation || _('fetch_translation'))
clipboardItem.setAttribute('hidden', (
result.label === _('fetch_translation') ||
result.label === LABEL_TRANSLATE_ERROR
))
}
// Update the languages menu label (“Change Languages […]”)
const updateLangMenuLabel = detected => {
const from = detected ? detected : currentFrom()
const to = currentTo()
langMenu.setAttribute('label', format(
_('change_languages'),
_(from) + (detected ? _('language_detected') : ''),
_(to)
))
translatePage.setAttribute('label', format(
_('translate_page'),
from,
to
))
}
// Update the languages menu selection
const updateLangMenuChecks = () => {
// Uncheck
const checkedElts = fromPopup.querySelectorAll('[checked]')
for (let checkedElt of checkedElts) checkedElt.removeAttribute('checked')
// Check
const from = currentFrom()
const to = currentTo()
const fromSel = `[data-gtranslate-from="${from}"]`
const toSel = `[data-gtranslate-to="${to}"]`
const fromMenu = fromPopup.querySelector(fromSel)
const toItem = fromMenu && fromMenu.querySelector(toSel)
if (fromMenu && toItem) {
fromMenu.setAttribute('checked', true)
toItem.setAttribute('checked', true)
}
}
// Show the context menupopup
const showContextMenu = () => {
if (selection === '') {
selection = getSelectionFromWin(win)
}
translateMenu.setAttribute('hidden', !selection)
translatePage.setAttribute('hidden', (
!!selection ||
!getCurrentUrl() ||
!translatablePage(getPopupNode(win), win) ||
!sp.prefs.fullPage
))
if (selection) {
translateMenu.setAttribute('label', format(_('translate'),
selection.length > 15 ? selection.substr(0, 15) + '…' : selection
))
updateResult(null)
}
updateLangMenuLabel()
}
// Show the results menupopup
const showResultsMenu = () => {
if (selection === '') {
selection = getSelectionFromWin(win)
}
const fromCode = currentFrom()
const toCode = currentTo()
translate(fromCode, toCode, selection, res => {
switch (sp.prefs.dictionaryPref) {
case 'A':
if (res.alternatives) {
updateResult(res.translation, res.alternatives)
} else if (res.dictionary) {
updateResult(res.translation, res.dictionary)
} else {
updateResult(res.translation, res.synonyms)
}
break
case 'D':
if (res.dictionary) {
updateResult(res.translation, res.dictionary)
} else if (res.alternatives) {
updateResult(res.translation, res.alternatives)
} else {
updateResult(res.translation, res.synonyms)
}
break
case 'S':
if (res.synonyms) {
updateResult(res.translation, res.synonyms)
} else if (res.dictionary) {
updateResult(res.translation, res.dictionary)
} else {
updateResult(res.translation, res.alternatives)
}
break
}
if (sp.prefs.langFrom === 'auto') {
updateLangMenuLabel(res.detectedSource)
}
})
}
// Listen to popupshowing events
const onPopupshowing = event => {
if (event.target === cmNode) {
return showContextMenu(event)
}
if (event.target === translatePopup) {
return showResultsMenu(event)
}
}
// Listen to popuphiding events
const onPopuphiding = event => {
if (event.target === cmNode) {
selection = '' // clear old selection
}
}
// Listen to command events
const onContextCommand = event => {
const target = event.target
const parent = target.parentNode && target.parentNode.parentNode
const from = currentFrom()
const to = currentTo()
// Open the translation page
if (target === result) {
openTab(translateUrl(from, to, selection))
return
}
// Open the visited translation page
if (target === translatePage) {
openTab(translatePageUrl(from, to, getCurrentUrl()))
return
}
// Language change
if (target.hasAttribute('data-gtranslate-to') &&
parent && parent.hasAttribute('data-gtranslate-from')) {
sp.prefs.langTo = target.getAttribute('data-gtranslate-to')
sp.prefs.langFrom = parent.getAttribute('data-gtranslate-from')
}
}
const onClickCopyToClipboard = () => {
clipboard.set(result.label)
}
// Update the menu when the preferences are updated
sp.on('', () => {
updateLangMenuLabel()
updateLangMenuChecks()
})
const inspectorSeparatorElement = doc.getElementById('inspect-separator')
cmNode.insertBefore(translateMenu, inspectorSeparatorElement)
cmNode.insertBefore(translatePage, inspectorSeparatorElement)
cmNode.addEventListener('popupshowing', onPopupshowing)
cmNode.addEventListener('popuphiding', onPopuphiding)
cmNode.addEventListener('command', onContextCommand)
clipboardItem.addEventListener('click', onClickCopyToClipboard)
updateLangMenuChecks()
return function destroy() {
cmNode.removeEventListener('popupshowing', onPopupshowing)
cmNode.removeEventListener('popuphiding', onPopuphiding)
cmNode.removeEventListener('command', onContextCommand)
clipboardItem.removeEventListener('click', onClickCopyToClipboard)
cmNode.removeChild(translateMenu)
cmNode.removeChild(translatePage)
}
}
// Init the addon
getLanguages().then(languages => {
const destroyFns = []
const initWin = sdkWin => {
const destroy = initMenu(viewFor(sdkWin), languages)
if (destroy) destroyFns.push(destroy)
}
// Init an instance when a new window is opened
windows.on('open', initWin)
// Init new instances on startup
Array.from(windows).forEach(initWin)
// When the addon is unloaded, destroy all gtranslate instances
addonUnload.when(() => destroyFns.forEach(fn => fn()))
})