forked from hermanschaaf/chinese-ime
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jQuery.chineseIME.js
474 lines (413 loc) · 18.3 KB
/
jQuery.chineseIME.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
var _callbacks_ = {
'loadWords': function(rep){
/* =========================
Example Response from Google:
_callbacks_.loadWords(["SUCCESS",[["o",["哦","噢","喔","嚄","迲","筽"]]]])
["SUCCESS",[["sdsa",["岁的萨","上的","受到","说的","时代","速度","是","上","说","时"],[4,2,2,2,2,2,1,1,1,1],{"matched_length":[4,2,2,2,2,2,1,1,1,1]}]]]
========================= */
var success = rep[0],
reply = rep[1][0],
word = reply[0],
words = reply[1],
lens = reply[2];
if (typeof lens == 'undefined') {
lens = new Array(words.length);
for (var i = 0; i < lens.length; i++) {
lens[i] = word.length;
}
}
$.wordDatabase.setChoices(word, words, lens);
}
};
(function($){
function Word(name, choices, options){
var self = this;
self.defaultOptions = {
pending: false,
length: choices.length
};
self.name = name;
self.choices = $.extend(true, [], choices);
self.lens = []; // matched lengths
self.num = (typeof options.num == 'undefined') ? choices.length : options.num;
self.options = $.extend({}, self.defaultOptions, options);
self.pending = self.options.pending;
self.traditional = self.options.traditional === true ? true : false;
self.setChoices = function(choices, lens){
self.choices = $.extend(true, [], choices);
self.lens = lens;
self.pending = false;
//self.num = self.choices.length;
}
}
function WordDatabase(){
var self = this;
self.words = {};
self.loading = {};
self.traditional = false; // convert simplified to traditional if true
self.getChoices = function(word){
var word = self.words[word];
if (word && word.traditional == self.traditional){
return word.choices;
}
return [];
}
self.getLength = function(word, choice) {
var word = self.words[word];
if (word){
return word.lens[choice];
}
return word.length;
}
self.hasWord = function(word, num){
hasWord = (self.words.hasOwnProperty(word) && self.words[word].num >= num);
if (hasWord){
var w = self.words[word];
if (w.traditional != self.traditional) {
return false;
}
if (w.pending === true && w.traditional != self.traditional) {
return true;
}
}
return hasWord;
}
self.addWord = function(word, num){
num = (typeof num == 'undefined' ? 10 : num);
self.words[word] = new Word(word, [], {pending: true, num: num, traditional: self.traditional});
};
self.setChoices = function(word, choices, lens, options){
if (word.length > 0 && choices instanceof Array && self.words[word]) {
wordObj = self.words[word];
if (self.traditional && typeof $.toTraditional !== 'undefined') {
var convert = function(simpArray){
var ar = [];
for (var i = 0; i < simpArray.length; i++) {
var fullWord = $.toTraditional(simpArray[i]);
ar.push(fullWord);
}
return ar;
}
choices = convert(choices);
}
if (wordObj.pending === true) {
if (choices.length < wordObj.num) {
// we've reached the end of the pages,
// so add a stop word to indicate that
choices.push(word);
lens.push(word.length);
}
}
wordObj.setChoices(choices, lens);
return self.words[word];
}
return false;
};
};
$.wordDatabase = new WordDatabase();
$.fn.extend({
insertAtCaret: function(myValue){
return this.each(function(i) {
if (document.selection) {
//For browsers like Internet Explorer
this.focus();
sel = document.selection.createRange();
sel.text = myValue;
this.focus();
}
else if (this.selectionStart || this.selectionStart == '0') {
//For browsers like Firefox and Webkit based
var startPos = this.selectionStart;
var endPos = this.selectionEnd;
var scrollTop = this.scrollTop;
this.value = this.value.substring(0, startPos)+myValue+this.value.substring(endPos,this.value.length);
this.focus();
this.selectionStart = startPos + myValue.length;
this.selectionEnd = startPos + myValue.length;
this.scrollTop = scrollTop;
} else {
this.value += myValue;
this.focus();
}
})
}
});
$.chineseInput = function(el, options){
// To avoid scope issues, use 'self' instead of 'this'
// to reference this class from internal events and functions.
var self = this;
// Access to jQuery and DOM versions of element
self.$el = $(el);
self.el = el;
self.id = String(parseInt(Math.random() * 10000) * parseInt(Math.random() * 10000));
// Set null options object if no options are provided
if(!options || typeof options !== 'object') options = {};
// Sanitize option data
if(typeof options.input !== 'object') options.input = {initial: 'simplified', allowChange: true};
if(typeof options.input.initial !== 'string') options.input.initial = 'simplified';
if(options.input.initial.toLowerCase() != 'simplified' && options.input.initial.toLowerCase() != 'traditional') options.input.initial = 'simplified';
options.active = options.active == true;
options.input.allowChange = options.input.allowChange == true; // set it to boolean value true if it evaluates to true
options.allowHide = options.allowHide == true;
self.currentText = '';
self.currentPage = 0; // page of given options
self.currentSelection = 1; // current selection on the current page (normally 1-5)
self.lastPage = false; // are we at the last page of options?
//self.options = [];
self.html = '<span class="typing"></span><ul class="options"></ul>';
self.url = '//www.google.com/inputtools/request?ime=pinyin&ie=utf-8&oe=utf-8&app=translate&uv'
self.paramNames = {'text': 'text',
'num': 'num',
'callback': 'cb'}
self.defaultNum = 10; // default number of options to load
// Add a reverse reference to the DOM object
self.$el.data("chineseInput", self);
self.init = function(){
self.options = $.extend({},$.chineseInput.defaultOptions, options);
// Further initialization
self.$el.keydown(self.keyDown);
self.$el.keypress(self.keyPress);
self.$toolbar = $('<div id="chinese-toolbar-' + self.id + '"></div>');
self.$active = $('<label class="chinese-checkbox" for="check_' + self.id + '"><input type="checkbox"' + (self.options.active ? ' checked="checked"' : '')+ ' id="check_' + self.id + '"/> phonetic typing</label>');
self.$input = $('<label class="chinese-checkbox" for="type_' + self.id + '"><input type="checkbox"' + (self.options.input.initial == 'traditional' ? ' checked="checked"' : '')+ ' id="type_' + self.id + '"/> traditional</label>')
self.$toolbar.insertAfter(self.$el);
self.$toolbar.css({'position': 'absolute', 'z-index': 1000}).show();
self.reposition(self.$toolbar);
if (self.options.allowHide) {
var $hide = self.$active;
$hide.appendTo(self.$toolbar);
$hide.find('input').click(function(){
self.options.active = $(this).is(':checked');
if (self.options.active === false){
self.currentText = '';
self.currentPage = 0;
self.updateDialog();
}
self.$el.focus();
});
}
if (self.options.input.allowChange){
self.$input.appendTo(self.$toolbar);
self.$input.find('input').click(function(){
var trad = $(this).is(':checked');
// self.options.input.initial = ( trad === true ? 'traditional' : 'simplified');
$.wordDatabase.traditional = trad;
self.updateDialog();
self.$el.focus();
});
}
if (self.options.input.initial == 'traditional'){
$.wordDatabase.traditional = true;
}
$(window).resize($.proxy(function() { // TODO: attach to textarea resize event
this.self.updateDialog();
this.self.reposition();
}, {'self': self}));
self.reposition();
};
self.keyDown = function(event){
if (self.options.active) {
if (self.currentText.length > 0){
switch(event.which){
case 37: // left
self.previousChoice();
return false;
case 39: // right
self.nextChoice();
return false;
}
}
switch(event.which){
case 8: // backspace
if (self.currentText.length > 0){
self.currentText = self.currentText.substring(0,self.currentText.length-1);
self.updateDialog();
break;
}
default:
return true; // continue with keypress if one of the above criteria not met
}
event.preventDefault();
return false;
}
};
self.keyPress = function(event){
if (self.options.active) {
var key = String.fromCharCode(event.which);
var pat = /[a-zA-Z]/;
if (pat.test(key)){
// pressed a character
if (self.currentText.length <= 20){
// set maximum num characters to arbitrary 20 limit
self.currentText += key;
}
} else if (self.currentText.length > 0) {
if (key == ' '){
// pressed space
self.makeSelection(self.currentSelection - 1);
} else if (event.which >= 49 && event.which <= 53) {
// pressed number between 1 and 5
self.makeSelection(event.which - 49);
} else if (key == ',') { // go to previous page
self.previousPage();
} else if (key == '.') { // go to next page
self.nextPage();
} else if (event.which == 13) {
// enter key pressed -- accept phonetic input
self.addText(self.currentText);
self.currentText = '';
self.currentPage = 0;
self.currentSelection = 1;
self.lastPage = false;
}
} else {
if (key == '.') { // pressed period
self.addText('\u3002');
return false;
}
return true;
}
self.updateDialog();
event.preventDefault();
return false;
}
};
self.addText = function(text){
self.$el.insertAtCaret(text);
};
self.nextPage = function(){
if (!self.lastPage) {
self.currentPage += 1;
}
self.updateDialog();
}
self.previousPage = function(){
self.currentPage = parseInt(Math.max(0, self.currentPage - 1));
self.lastPage = false;
self.updateDialog();
}
self.nextChoice = function(){
if (self.currentSelection < 5) {
self.currentSelection += 1;
self.updateDialog();
} else {
self.currentSelection = 1;
self.nextPage();
}
}
self.previousChoice = function(){
if (self.currentSelection > 1) {
self.currentSelection -= 1;
self.updateDialog();
} else if (self.currentPage > 0) {
self.currentSelection = 5;
self.previousPage();
}
}
self.makeSelection = function(selectionIndex){
var choices = $.wordDatabase.getChoices(self.currentText);
selectionIndex += self.currentPage * 5; // add current page to index
if (selectionIndex < 0) {
// if selection is smaller than zero, we use the text input as is, effectively canceling smart input
self.addText(self.currentText);
self.currentText = '';
self.currentPage = 0;
self.currentSelection = 1;
self.lastPage = false;
}
if (choices && selectionIndex < choices.length){
choice = choices[selectionIndex];
len = $.wordDatabase.getLength(self.currentText, selectionIndex);
self.addText(choice);
self.currentText = '' + self.currentText.substring(len);
self.currentPage = 0;
self.currentSelection = 1;
self.lastPage = false;
}
};
self.reposition = function($el){
var $toolbar = $el;
if (!$toolbar){
$toolbar = self.$toolbar;
}
$toolbar.css({'padding': '0 0 10px 5px'}).
position({my: 'left bottom',
at: 'left bottom',
of: self.$el,
collision: "none"});
}
self.updateDialog = function(){
if (self.currentText.length > 0) {
var options = self.getOptionsFromDatabase(self.currentText, self.currentPage);
if (options && options.length){
var $box = $('#chinese-ime');
if (!$box.size()){
$box = $(document.createElement('div')).draggable().
attr({'id': 'chinese-ime'}).
html(self.html)
$('body').append($box);
}
$box.find('.typing').text(self.currentText);
var lis = [];
for (var i = 0; i < 5 && i < options.length; i++) {
lis.push('<li ' + (i + 1 == self.currentSelection ? 'class="current"' : '') + '> ' + (i + 1) + '. ' + options[i] +'</li>');
}
$box.find('ul').html(lis.join('\n'));
$box.show();
var caretPosition = self.$el.getCaretPosition();
$box.css({
position: 'absolute',
left: self.$el.offset().left + caretPosition.left,
top: self.$el.offset().top + caretPosition.top
});
} else { // load options with ajax
self.callAjax(self.currentText, self.currentPage);
}
} else {
var $box = $('#chinese-ime').hide();
}
};
self.getOptionsFromDatabase = function(text, page, num){
if (typeof page == 'undefined') { page = self.currentPage; }
if (typeof num == 'undefined') { num = 5; }
var options = $.wordDatabase.getChoices(text);
if (options && options.length >= (page + 1) * num) {
// we have options in the database already, and enough of them
return options.slice(page*num, (page+1)*num);
} else if (options && options[options.length-1] == text) {
// if the last option is the text itself, it means we've exhausted all suggestions
self.lastPage = true;
return options.slice(page*num);
}
return false; // we need to call ajax first
};
self.callAjax = function(text, page, num, callback){
var params = {};
num = (typeof num == 'undefined' ? self.defaultNum : num);
num = num + parseInt(Math.floor(page / 2)) * num;
params[self.paramNames['text']] = text;
params[self.paramNames['num']] = num; // assuming page length is 10 here
if (typeof callback != 'undefined') {
params[self.paramNames['callback']] = callback;
} else {
params[self.paramNames['callback']] = '_callbacks_.loadWords';
}
if (!$.wordDatabase.hasWord(text, num)){
$.wordDatabase.addWord(text, num);
$.get(self.url, params, $.proxy(function(response, success){
self.updateDialog();
}, {'text': text, 'page': page, 'num': num, 'callback': callback}), 'script');
}
};
// Run initializer
self.init();
};
$.chineseInput.defaultOptions = {
debug: false
};
$.fn.chineseInput = function(options){
return this.each(function(){
(new $.chineseInput(this, options));
});
};
})(jQuery);