-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpopup.js
228 lines (212 loc) · 5.57 KB
/
popup.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
document.addEventListener('DOMContentLoaded', function() {
const formElement = document.querySelector('#form');
const resultElement = document.querySelector('#result');
const loadingElement = document.querySelector('#loading');
const { action: url, method } = formElement;
/**
* If the word to be translated is the same as last word, nothing happens.
*
* @param {Function} next
* @returns
*/
function withLastWordNotModified(next) {
return word => {
if (word !== formElement.dataset.lastWord) {
formElement.dataset.lastWord = word;
next(word);
}
};
}
/**
* Show loading while translating
*
* @param {Function} next
* @returns
*/
function withLoading(next) {
return (...args) => {
toggle(loadingElement);
toggle(resultElement);
return next(...args).then(
() => {
toggle(loadingElement);
toggle(resultElement);
},
() => {
toggle(loadingElement);
toggle(resultElement);
}
);
};
}
/**
* Generate html using extracted translation info.
*
* @param {any} next
* @returns
*/
function generateContent(next) {
return (...args) =>
next(...args).then(translation => {
console.log(translation);
resultElement.innerHTML = convertToHtml(translation);
});
}
/**
* Cache translation history.
*
* @param {Function} next
* @returns
*/
function withCache(next) {
const cache = new Map();
return key => {
if (cache.has(key)) return Promise.resolve(cache.get(key));
return Promise.resolve(next(key)).then(resp => {
cache.set(key, resp);
return resp;
});
};
}
/**
* Extract translation info from response html.
*
* @param {Function} next
* @returns
*/
function extractResponse(next) {
return (...args) => {
return next(...args).then(response => {
const container = response.querySelector('.qdef');
return [extractBasic, extractTranslate, extractPluralForm].reduce(
(result, current, index) =>
Object.assign(result, current(container.children[index])),
{}
);
});
};
}
/**
* Get translation from bing site.
*
* @param {string} word
* @returns
*/
function fetchTranslation(word) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.responseType = 'document';
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
resolve(xhr.responseXML);
} else {
reject(xhr.status);
}
}
};
xhr.open(method, `${url}?q=${word}`, true);
xhr.send();
});
}
const submitHandler = compose(
withLastWordNotModified,
withLoading,
generateContent,
withCache,
extractResponse
)(fetchTranslation);
formElement.addEventListener('submit', function(e) {
e.preventDefault();
e.stopImmediatePropagation();
const { value: query } = formElement.elements['query'];
submitHandler(query);
});
formElement.elements['query'].addEventListener('input', function(e) {
formElement.elements['submitBtn'].disabled = !e.target.value;
});
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
formElement.elements['query'].value = request.word;
formElement.elements['submitBtn'].disabled = false;
formElement.elements['submitBtn'].click();
});
});
function convertToHtml(translation) {
return `
<dl>
<dt>翻译:</dt>
${translation.translates
.map(item => `<dd><strong>${item.pos}:</strong>${item.def}</dd>`)
.join('\n')}
</dl>
<dl>
<dt>复数:</dt>
<dd>${translation.plural}</dd>
</dl>
`;
}
function compose(...fns) {
const fnList = fns.filter(fn => typeof fn === 'function');
if (fnList.length === 0)
throw new Error(
'Argument error, at least one `function` should be provided'
);
return fnList.reduce((f, g) => (...args) => f(g(...args)));
}
function extractBasic(doc) {
var word = doc.querySelector('#headword').innerText.trim();
var hd_p1_1 = doc.querySelector('.hd_p1_1');
var lang = hd_p1_1.getAttribute('lang');
var pronounceChildren = hd_p1_1.querySelectorAll('div');
var pronounces =
pronounceChildren.length > 0
? Array.prototype.reduce
.call(
pronounceChildren,
function(result, current, index) {
if (index % 2 === 0) {
result.push([current]);
} else {
result[result.length - 1].push(current);
}
return result;
},
[]
)
.map(function(divs) {
var pronounce = {
locale: divs[0].innerText,
};
return pronounce;
})
: hd_p1_1.innerText;
return {
word,
pronounces,
lang,
};
}
function extractTranslate(doc) {
return {
translates: Array.prototype.map.call(doc.querySelectorAll('li'), item => {
return {
pos: item.querySelector('.pos').innerText,
def: item.querySelector('.def').innerText,
};
}),
};
}
function extractPluralForm(doc) {
const anchor = doc.querySelector('.hd_div1 .hd_if a');
return {
plural: anchor.innerText,
};
}
/**
* toggle display status of html element
* @param element html element
*/
function toggle(element) {
const oldDisplay = element.style.display;
element.style.display = oldDisplay === 'block' ? 'none' : 'block';
}