Share Gaia assets and adapters, keep private profiles and development documents local, and update both public READMEs.
328 lines
No EOL
143 KiB
JavaScript
328 lines
No EOL
143 KiB
JavaScript
;'use strict';(function(exports){var L10nLoader=function(){this.loadStarted=false;};L10nLoader.prototype.SCRIPT_URL='/shared/js/l10n.js';L10nLoader.prototype.load=function(){if(this.loadStarted){return;}
|
||
this.loadStarted=true;document.documentElement.lang='x-untranslated';var script=document.createElement('script');script.src=this.SCRIPT_URL;document.body.appendChild(script);};exports.L10nLoader=L10nLoader;})(window);;'use strict';(function(exports){var UserPress=function(obj,coords){this.target=obj;this.updateCoords(coords,false);this.startTime=Date.now();this.startCoords=coords;this.startTarget=obj;};UserPress.prototype.updateCoords=function(coords,moved){this.moved=moved;this.clientX=coords.clientX;this.clientY=coords.clientY;this.endTime=Date.now();};var UserPressManager=function(app){this._started=false;this._ignoreMouseEvents=false;this.presses=new Map();this.touchstartCounts=new WeakMap();this.app=app;};UserPressManager.prototype.onpressstart=null;UserPressManager.prototype.onpressmove=null;UserPressManager.prototype.onpressend=null;UserPressManager.prototype.MOVE_LIMIT=5;UserPressManager.prototype.MIN_BOGUS_EVENT_DISTANCE=20;UserPressManager.prototype.MIN_BOGUS_EVENT_VELOCITY=0.3;UserPressManager.prototype.start=function(){this.app.console.log('UserPressManager.start()');if(this._started){throw new Error('UserPressManager: '+'Instance should not be start()\'ed twice.');}
|
||
this._started=true;this._container=this.app.getContainer();this._container.addEventListener('touchstart',this);this._container.addEventListener('mousedown',this);this._container.addEventListener('contextmenu',this);this._isLowEndDevice=false;this.settings=new UserPressManagerSettings();this.settings.promiseManager=this.app.settingsPromiseManager;this.settings.onsettingchange=this._handleSettingsChange.bind(this);this.settings.initSettings().then(this._handleSettingsChange.bind(this),function rejected(err){console.error('Fatal Error! Failed to get initial '+'targetHandlersManager settings.',err);});};UserPressManager.prototype.stop=function(){this.app.console.log('UserPressManager.stop()');if(!this._started){throw new Error('UserPressManager: '+'Instance was never start()\'ed but stop() is called.');}
|
||
this._started=false;this._container.removeEventListener('touchstart',this);this._container.removeEventListener('mousedown',this);this._container.removeEventListener('mousemove',this);this._container.removeEventListener('mouseup',this);this._container.removeEventListener('mouseleave',this);this._container.removeEventListener('contextmenu',this);this.settings=null;};UserPressManager.prototype.handleEvent=function(evt){var touch,touchId,el,i,touchstartCount;switch(evt.type){case'contextmenu':evt.preventDefault();break;case'touchstart':this._ignoreMouseEvents=true;touchstartCount=this.touchstartCounts.get(evt.target)||0;touchstartCount++;this.touchstartCounts.set(evt.target,touchstartCount);evt.target.addEventListener('touchmove',this);evt.target.addEventListener('touchend',this);evt.target.addEventListener('touchcancel',this);for(i=0;i<evt.changedTouches.length;i++){touch=evt.changedTouches[i];touchId=touch.identifier;el=touch.target;this._handleNewPress(el,touch,touchId);}
|
||
break;case'touchmove':for(i=0;i<evt.changedTouches.length;i++){touch=evt.changedTouches[i];touchId=touch.identifier;if(!this._distanceReachesLimit(touchId,touch)){continue;}
|
||
el=document.elementFromPoint(touch.clientX,touch.clientY);this._handleChangedPress(el,touch,touchId);}
|
||
break;case'touchend':case'touchcancel':touchstartCount=this.touchstartCounts.get(evt.target);touchstartCount--;if(touchstartCount){this.touchstartCounts.set(evt.target,touchstartCount);}else{evt.target.removeEventListener('touchmove',this);evt.target.removeEventListener('touchend',this);evt.target.removeEventListener('touchcancel',this);this.touchstartCounts.delete(evt.target);}
|
||
if(!this._started){return;}
|
||
for(i=0;i<evt.changedTouches.length;i++){touch=evt.changedTouches[i];touchId=touch.identifier;el=document.elementFromPoint(touch.clientX,touch.clientY);this._handleFinishPress(el,touch,touchId);}
|
||
break;case'mousedown':evt.preventDefault();if(this._ignoreMouseEvents){return;}
|
||
this._container.addEventListener('mousemove',this);this._container.addEventListener('mouseup',this);this._container.addEventListener('mouseleave',this);this._handleNewPress(evt.target,evt,'_mouse');break;case'mousemove':if(!this._distanceReachesLimit('_mouse',evt)){return;}
|
||
this._handleChangedPress(evt.target,evt,'_mouse');break;case'mouseup':case'mouseleave':this._container.removeEventListener('mousemove',this);this._container.removeEventListener('mouseup',this);this._container.removeEventListener('mouseleave',this);this._handleFinishPress(evt.target,evt,'_mouse');break;}};UserPressManager.prototype._handleNewPress=function(el,coords,id){this.app.console.info('UserPressManager._handleNewPress()');var press=new UserPress(this.app.layoutRenderingManager.getTargetObject(el),coords);this.presses.set(id,press);if(typeof this.onpressstart==='function'){this.onpressstart(press,id);}};UserPressManager.prototype._handleChangedPress=function(el,coords,id){this.app.console.info('UserPressManager._handleChangedPress()');var press=this.presses.get(id);press.target=this.app.layoutRenderingManager.getTargetObject(el);press.updateCoords(coords,true);if(typeof this.onpressmove==='function'){this.onpressmove(press,id);}};UserPressManager.prototype._handleFinishPress=function(el,coords,id){this.app.console.info('UserPressManager._handleFinishPress()');if(this._isLowEndDevice){this._handleLowEndDeviceFinishPress(el,coords,id);return;}
|
||
var press=this.presses.get(id);press.target=this.app.layoutRenderingManager.getTargetObject(el);press.updateCoords(coords,press.moved||this._distanceReachesLimit(id,coords));if(typeof this.onpressend==='function'){this.onpressend(press,id);}
|
||
this.presses.delete(id);};UserPressManager.prototype._handleLowEndDeviceFinishPress=function(el,coords,id){this.app.console.info('UserPressManager._handleLowEndDeviceFinishPress()');var press=this.presses.get(id);press.target=this.app.layoutRenderingManager.getTargetObject(el);press.updateCoords(coords,press.moved||this._distanceReachesLimit(id,coords));if(this._exceedSpeedLimit(press)&&press.target.keyCode!==press.startTarget.keyCode){var currentTargetObject=press.target;press.target=press.startTarget;press.updateCoords(press.startCoords,true);if(typeof this.onpressmove==='function'){this.onpressmove(press,id);}
|
||
if(typeof this.onpressend==='function'){this.onpressend(press,id);}
|
||
this.presses.delete(id);var syntheticPress=new UserPress(currentTargetObject,coords);if(typeof this.onpressstart==='function'){this.onpressstart(syntheticPress,id);}
|
||
syntheticPress.updateCoords(coords,false);if(typeof this.onpressend==='function'){this.onpressend(syntheticPress,id);}}else{if(typeof this.onpressend==='function'){this.onpressend(press,id);}
|
||
this.presses.delete(id);}};UserPressManager.prototype._exceedSpeedLimit=function(press){var dx=press.startCoords.clientX-press.clientX;var dy=press.startCoords.clientY-press.clientY;if(dx+dy===0){return false;}
|
||
var time=press.endTime-press.startTime;var distance=Math.sqrt(dx*dx+dy*dy);if(distance<this.MIN_BOGUS_EVENT_DISTANCE){return false;}
|
||
return(distance/time>this.MIN_BOGUS_EVENT_VELOCITY);};UserPressManager.prototype._distanceReachesLimit=function(id,newCoord){var press=this.presses.get(id);var dx=press.clientX-newCoord.clientX;var dy=press.clientY-newCoord.clientY;var limit=this.MOVE_LIMIT;return(dx>=limit||dx<=-limit||dy>=limit||dy<=-limit);};UserPressManager.prototype._handleSettingsChange=function(values){this._isLowEndDevice=values.deviceinfoHardware==='sp8810'||values.deviceinfoHardware==='roamer2'||values.deviceinfoProductModel==='GP-KEON'||values.deviceinfoProductModel==='GoFox F15';};exports.UserPress=UserPress;exports.UserPressManager=UserPressManager;})(window);;'use strict';(function(exports){var HandwritingPadsManager=function(app){this._started=false;this._timeOutId=undefined;this._strokeWidth=5;this._responseTime=200;this._strokePoints=[];this._currentTarget=null;this._cleared=false;this.app=app;};HandwritingPadsManager.prototype.MAX_RESPONSE_TIME=600;HandwritingPadsManager.prototype.start=function(){if(this._started){throw new Error('HandwritingPadsManager: '+'Instance should not be start()\'ed twice.');}
|
||
this.handwritingPadSettings=new HandwritingPadSettings();this.handwritingPadSettings.promiseManager=this.app.settingsPromiseManager;this.handwritingPadSettings.onsettingchange=this._handleSettingsChange.bind(this);this.handwritingPadSettings.initSettings().then(this._handleSettingsChange.bind(this),function rejected(){console.error('Fatal Error! Failed to get initial '+'handwriting pad settings.');});this._started=true;};HandwritingPadsManager.prototype.stop=function(){if(!this._started){throw new Error('HandwritingPadsManager: '+'Instance was never start()\'ed but stop() is called.');}
|
||
this.handwritingPadSettings=null;this._started=false;};HandwritingPadsManager.prototype._handleSettingsChange=function(values){this._strokeWidth=values.strokeWidth;this._responseTime=values.responseTime;};HandwritingPadsManager.prototype.handlePressStart=function(press){clearTimeout(this._timeOutId);if(!this._currentTarget){this._currentTarget=press.target;}else if(this._currentTarget!=press.target&&!this._cleared){this.app.layoutRenderingManager.clearHandwritingPad(this._currentTarget);this._strokePoints=[];this._currentTarget=press.target;}
|
||
this._cleared=false;var point=this.app.layoutRenderingManager.drawHandwritingPad(press,true,this._strokeWidth);this._strokePoints.push(point.posX,point.posY);};HandwritingPadsManager.prototype.handlePressMove=function(press){var point=this.app.layoutRenderingManager.drawHandwritingPad(press,false,this._strokeWidth);this._strokePoints.push(point.posX,point.posY);};HandwritingPadsManager.prototype.handlePressEnd=function(){this._timeOutId=setTimeout(this._sendStrokePoints.bind(this),this.MAX_RESPONSE_TIME-this._responseTime);this._strokePoints.push(-1,0);};HandwritingPadsManager.prototype._sendStrokePoints=function(){if(this._strokePoints.length<=1){return;}
|
||
var ime=this.app.inputMethodManager.currentIMEngine;if(ime.sendStrokePoints){ime.sendStrokePoints(this._strokePoints);}};HandwritingPadsManager.prototype.clear=function(){this.app.layoutRenderingManager.clearHandwritingPad(this._currentTarget);this._strokePoints=[];this._cleared=true;};exports.HandwritingPadsManager=HandwritingPadsManager;})(window);;'use strict';(function(exports){var AlternativesCharMenuManager=function(app){this.app=app;this.isShown=false;this._originalTarget=null;this._menuAreaTop=this._menuAreaLeft=this._menuAreaRight=this._menuAreaBottom=0;};AlternativesCharMenuManager.prototype.start=function(){this._currentMenuView=null;};AlternativesCharMenuManager.prototype.stop=function(){this._currentMenuView=null;};AlternativesCharMenuManager.prototype.show=function(target){var alternatives=this._getAlternativesForTarget(target);if(!alternatives){return;}
|
||
var viewManager=this.app.viewManager;var targetRect=viewManager.getView(target).element.getBoundingClientRect();this._currentMenuView=viewManager.showAlternativesCharMenu(target,alternatives);this.isShown=true;this._originalTarget=target;var menuRect=this._currentMenuView.getBoundingClientRect();this._menuAreaTop=menuRect.top;this._menuAreaLeft=Math.min(targetRect.left,menuRect.left);this._menuAreaLeft-=targetRect.width;this._menuAreaBottom=targetRect.bottom;this._menuAreaRight=Math.max(targetRect.right,menuRect.right);this._menuAreaRight+=targetRect.width;};AlternativesCharMenuManager.prototype._getAlternativesForTarget=function _getAlternativesForTarget(key){var alternatives;var altMap=this.app.layoutManager.currentPage.alt;var origKey=null;if(this.app.upperCaseStateManager.isUpperCaseLocked){origKey=key.uppercaseValue;alternatives=altMap[origKey]&&(altMap[origKey].upperCaseLocked||altMap[origKey]);}else if(this.app.upperCaseStateManager.isUpperCase){origKey=key.uppercaseValue;alternatives=altMap[origKey];}else{origKey=key.lowercaseValue;alternatives=altMap[origKey];}
|
||
if(!alternatives||!alternatives.length){return false;}
|
||
return[].concat(origKey,alternatives);};AlternativesCharMenuManager.prototype.hide=function(){if(!this.isShown){return;}
|
||
this.app.viewManager.hideAlternativesCharMenu();this.isShown=false;this._originalTarget=null;this._menuAreaTop=this._menuAreaLeft=this._menuAreaRight=this._menuAreaBottom=0;this._currentMenuView=null;};AlternativesCharMenuManager.prototype.isMenuTarget=function(target){if(!this._currentMenuView){return false;}
|
||
return this._currentMenuView.isMenuTarget(target);};AlternativesCharMenuManager.prototype.getMenuTarget=function(press){if(!this.isShown){throw new Error('AlternativesCharMenuManager: '+'getMenuTarget called but menu is not shown');}
|
||
return this._currentMenuView.getMenuTarget(press.clientX,press.clientY);};AlternativesCharMenuManager.prototype.isInMenuArea=function(press){if(!this.isShown){return false;}
|
||
return(press.clientY>=this._menuAreaTop&&press.clientY<=this._menuAreaBottom&&press.clientX>=this._menuAreaLeft&&press.clientX<=this._menuAreaRight);};exports.AlternativesCharMenuManager=AlternativesCharMenuManager;})(window);;'use strict';(function(exports){var VisualHighlightManager=function(app){this.app=app;this.highlightDelayTimers=new Map();};VisualHighlightManager.prototype.HIGHTLIGHT_DELAY_MS=85;VisualHighlightManager.prototype.start=function(){};VisualHighlightManager.prototype.stop=function(){};VisualHighlightManager.prototype.show=function(target){this.highlightDelayTimers.forEach(function(timer,target){clearTimeout(timer);this.highlightDelayTimers.delete(target);this.app.viewManager.unHighlightKey(target);},this);this.app.viewManager.highlightKey(target);};VisualHighlightManager.prototype.hide=function(target){if(this.highlightDelayTimers.has(target)){clearTimeout(this.highlightDelayTimers.get(target));}
|
||
var timer=setTimeout(function(){this.highlightDelayTimers.delete(target);this.app.viewManager.unHighlightKey(target);}.bind(this),this.HIGHTLIGHT_DELAY_MS);this.highlightDelayTimers.set(target,timer);};exports.VisualHighlightManager=VisualHighlightManager;})(window);;'use strict';(function(exports){var DefaultTargetHandler=function(target,app){this.target=target;this.app=app;this.ignoreCommitActions=false;};DefaultTargetHandler.prototype.activate=function(){this.app.console.log('DefaultTargetHandler.activate()');this.app.feedbackManager.triggerFeedback(this.target);this.app.visualHighlightManager.show(this.target);};DefaultTargetHandler.prototype.longPress=function(){this.app.console.log('DefaultTargetHandler.longPress()');if(!('longPressValue'in this.target)){return;}
|
||
this.ignoreCommitActions=true;var keyCode=this.target.longPressKeyCode;var promise=Promise.resolve(this.app.inputMethodManager.currentIMEngine.click(keyCode));this.app.visualHighlightManager.hide(this.target);return promise;};DefaultTargetHandler.prototype.moveOut=function(){this.app.console.log('DefaultTargetHandler.moveOut()');this.app.visualHighlightManager.hide(this.target);};DefaultTargetHandler.prototype.moveIn=function(){this.app.console.log('DefaultTargetHandler.moveIn()');this.app.visualHighlightManager.show(this.target);};DefaultTargetHandler.prototype.commit=function(){this.app.console.log('DefaultTargetHandler.commit()');if(this.ignoreCommitActions){this.app.console.log('DefaultTargetHandler.commit()::return early');return;}
|
||
var keyCode=this.target.keyCode;var keyCodeUpper=this.target.keyCodeUpper;var engine=this.app.inputMethodManager.currentIMEngine;var code=this.app.upperCaseStateManager.isUpperCase?keyCodeUpper:keyCode;this.app.console.log('DefaultTargetHandler.commit()::engine.click',code);var promise=Promise.resolve(engine.click(code));this.app.visualHighlightManager.hide(this.target);return promise;};DefaultTargetHandler.prototype.cancel=function(){this.app.console.log('DefaultTargetHandler.cancel()');this.app.visualHighlightManager.hide(this.target);};DefaultTargetHandler.prototype.doubleTap=function(){this.app.console.log('DefaultTargetHandler.doubleTap()');return this.commit();};DefaultTargetHandler.prototype.newTargetActivate=function(){this.commit();this.ignoreCommitActions=true;};DefaultTargetHandler.prototype.move=function(){};var NullTargetHandler=function(target,app){DefaultTargetHandler.apply(this,arguments);};NullTargetHandler.prototype=Object.create(DefaultTargetHandler.prototype);NullTargetHandler.prototype.activate=NullTargetHandler.prototype.moveIn=NullTargetHandler.prototype.moveOut=NullTargetHandler.prototype.commit=NullTargetHandler.prototype.cancel=NullTargetHandler.prototype.doubleTap=function(){};var SpaceKeyTargetHandler=function(target,app){DefaultTargetHandler.apply(this,arguments);};SpaceKeyTargetHandler.prototype=Object.create(DefaultTargetHandler.prototype);SpaceKeyTargetHandler.prototype.longPress=function(){this.app.targetHandlersManager.activeTargetsManager.clearAllTargets();navigator.mozInputMethod.mgmt.hide();this.app.visualHighlightManager.hide(this.target);};var CandidateSelectionTargetHandler=function(target,app){DefaultTargetHandler.apply(this,arguments);};CandidateSelectionTargetHandler.prototype=Object.create(DefaultTargetHandler.prototype);CandidateSelectionTargetHandler.prototype.commit=function(){if(this.ignoreCommitActions){this.app.console.log('CandidateSelectionTargetHandler.commit()::return early');return;}
|
||
this.app.candidatePanelManager.hideFullPanel();var engine=this.app.inputMethodManager.currentIMEngine;if(typeof engine.select==='function'){engine.select(this.target.text,this.target.data);}
|
||
this.app.visualHighlightManager.hide(this.target);};var BackspaceTargetHandler=function(target,app){DefaultTargetHandler.apply(this,arguments);this.deleteTimeout=undefined;this.deleteInterval=undefined;this.ignoreCommitActions=false;};BackspaceTargetHandler.prototype=Object.create(DefaultTargetHandler.prototype);BackspaceTargetHandler.prototype.REPEAT_RATE=50;BackspaceTargetHandler.prototype.REPEAT_TIMEOUT=500;BackspaceTargetHandler.prototype._sendDelete=function(isRepeat){var engine=this.app.inputMethodManager.currentIMEngine;engine.click(KeyEvent.DOM_VK_BACK_SPACE,null,isRepeat);};BackspaceTargetHandler.prototype.activate=function(){this.app.feedbackManager.triggerFeedback(this.target);this.app.visualHighlightManager.show(this.target);this.deleteTimeout=setTimeout(function(){this._sendDelete(true);this.deleteInterval=setInterval(function(){this._sendDelete(true);}.bind(this),this.REPEAT_RATE);}.bind(this),this.REPEAT_TIMEOUT);};BackspaceTargetHandler.prototype.moveOut=function(){this.app.visualHighlightManager.hide(this.target);clearTimeout(this.deleteTimeout);clearInterval(this.deleteInterval);};BackspaceTargetHandler.prototype.moveIn=function(){this.ignoreCommitActions=true;};BackspaceTargetHandler.prototype.commit=function(){if(this.ignoreCommitActions){this.app.console.log('BackspaceTargetHandler.commit()::return early');return;}
|
||
clearTimeout(this.deleteTimeout);clearInterval(this.deleteInterval);this._sendDelete(false);this.app.visualHighlightManager.hide(this.target);};BackspaceTargetHandler.prototype.cancel=function(){clearTimeout(this.deleteTimeout);clearInterval(this.deleteInterval);this.app.visualHighlightManager.hide(this.target);};var CompositeTargetHandler=function(target,app){DefaultTargetHandler.apply(this,arguments);};CompositeTargetHandler.prototype=Object.create(DefaultTargetHandler.prototype);CompositeTargetHandler.prototype.commit=function(){if(this.ignoreCommitActions){this.app.console.log('CompositeTargetHandler.commit()::return early');return;}
|
||
var compositeString=this.target.compositeKey;var promise;var engine=this.app.inputMethodManager.currentIMEngine;if(engine.handleKey){promise=engine.handleKey({key:compositeString,printable:true});}else{promise=Promise.resolve();compositeString.split('').forEach(function(chr){promise=promise.then(function(){return engine.click(chr.charCodeAt(0));},function(e){console.error(e);return engine.click(chr.charCodeAt(0));});});}
|
||
this.app.visualHighlightManager.hide(this.target);return promise;};var PageSwitchingTargetHandler=function(target,app){DefaultTargetHandler.apply(this,arguments);};PageSwitchingTargetHandler.prototype=Object.create(DefaultTargetHandler.prototype);PageSwitchingTargetHandler.prototype.commit=function(){if(this.ignoreCommitActions){this.app.console.log('PageSwitchingTargetHandler.commit()::return early');return;}
|
||
var page=this.target.targetPage;this.app.setLayoutPage(page);this.app.visualHighlightManager.hide(this.target);var currentIMEngine=this.app.inputMethodManager.currentIMEngine;if(typeof currentIMEngine.empty==='function'){currentIMEngine.empty();}};var CapsLockTargetHandler=function(target,app){DefaultTargetHandler.apply(this,arguments);this.isPreviouslyUpperCase=undefined;};CapsLockTargetHandler.prototype=Object.create(DefaultTargetHandler.prototype);CapsLockTargetHandler.prototype.isNewTargetActivated=false;CapsLockTargetHandler.prototype.activate=function(){this.isPreviouslyUpperCase=this.app.upperCaseStateManager.isUpperCase;this.app.upperCaseStateManager.switchUpperCaseState({isUpperCaseLocked:true});this.app.feedbackManager.triggerFeedback(this.target);this.app.visualHighlightManager.show(this.target);};CapsLockTargetHandler.prototype.commit=function(){if(this.isNewTargetActivated){this.app.upperCaseStateManager.switchUpperCaseState({isUpperCase:false,isUpperCaseLocked:false});}else{this.app.upperCaseStateManager.switchUpperCaseState({isUpperCase:!this.isPreviouslyUpperCase,isUpperCaseLocked:false});}
|
||
this.app.visualHighlightManager.hide(this.target);};CapsLockTargetHandler.prototype.doubleTap=function(){this.app.upperCaseStateManager.switchUpperCaseState({isUpperCaseLocked:true});this.app.visualHighlightManager.hide(this.target);};CapsLockTargetHandler.prototype.newTargetActivate=function(){this.isNewTargetActivated=true;};var SwitchKeyboardTargetHandler=function(target,app){DefaultTargetHandler.apply(this,arguments);};SwitchKeyboardTargetHandler.prototype=Object.create(DefaultTargetHandler.prototype);SwitchKeyboardTargetHandler.prototype.longPress=function(){this.ignoreCommitActions=true;this.app.targetHandlersManager.activeTargetsManager.clearAllTargets();navigator.mozInputMethod.mgmt.showAll();this.app.visualHighlightManager.hide(this.target);};SwitchKeyboardTargetHandler.prototype.commit=function(){if(this.ignoreCommitActions){return;}
|
||
this.app.targetHandlersManager.activeTargetsManager.clearAllTargets();navigator.mozInputMethod.mgmt.next();this.app.visualHighlightManager.hide(this.target);};var ToggleCandidatePanelTargetHandler=function(target,app){DefaultTargetHandler.apply(this,arguments);};ToggleCandidatePanelTargetHandler.prototype=Object.create(DefaultTargetHandler.prototype);ToggleCandidatePanelTargetHandler.prototype.commit=function(){if(this.ignoreCommitActions){this.app.console.log('ToggleCandidatePanelTargetHandler.commit()::return early');return;}
|
||
this.app.candidatePanelManager.toggleFullPanel();this.app.visualHighlightManager.hide(this.target);};var DismissSuggestionsTargetHandler=function(target,app){DefaultTargetHandler.apply(this,arguments);};DismissSuggestionsTargetHandler.prototype=Object.create(DefaultTargetHandler.prototype);DismissSuggestionsTargetHandler.prototype.commit=function(){if(this.ignoreCommitActions){this.app.console.log('DismissSuggestionsTargetHandler.commit()::return early');return;}
|
||
var engine=this.app.inputMethodManager.currentIMEngine;if(typeof engine.dismissSuggestions==='function'){engine.dismissSuggestions();}
|
||
this.app.visualHighlightManager.hide(this.target);};var HandwritingPadTargetHandler=function(target,app){DefaultTargetHandler.apply(this,arguments);};HandwritingPadTargetHandler.prototype=Object.create(DefaultTargetHandler.prototype);HandwritingPadTargetHandler.prototype.activate=function(press){this.app.handwritingPadsManager.handlePressStart(press);};HandwritingPadTargetHandler.prototype.move=function(press){this.app.handwritingPadsManager.handlePressMove(press);};HandwritingPadTargetHandler.prototype.moveOut=function(press){};HandwritingPadTargetHandler.prototype.moveIn=function(press){this.app.handwritingPadsManager.handlePressStart(press);};HandwritingPadTargetHandler.prototype.commit=function(){this.app.handwritingPadsManager.handlePressEnd();};HandwritingPadTargetHandler.prototype.newTargetActivate=function(){};exports.DefaultTargetHandler=DefaultTargetHandler;exports.NullTargetHandler=NullTargetHandler;exports.SpaceKeyTargetHandler=SpaceKeyTargetHandler;exports.CandidateSelectionTargetHandler=CandidateSelectionTargetHandler;exports.BackspaceTargetHandler=BackspaceTargetHandler;exports.CompositeTargetHandler=CompositeTargetHandler;exports.PageSwitchingTargetHandler=PageSwitchingTargetHandler;exports.CapsLockTargetHandler=CapsLockTargetHandler;exports.SwitchKeyboardTargetHandler=SwitchKeyboardTargetHandler;exports.ToggleCandidatePanelTargetHandler=ToggleCandidatePanelTargetHandler;exports.DismissSuggestionsTargetHandler=DismissSuggestionsTargetHandler;exports.HandwritingPadTargetHandler=HandwritingPadTargetHandler;})(window);;'use strict';(function(exports){var TargetHandlersManager=function(app){this.handlers=undefined;this.activeTargetsManager=null;this.app=app;this.promiseQueue=Promise.resolve();};TargetHandlersManager.prototype.start=function(){this.app.console.log('TargetHandlersManager.start()');this.handlers=new WeakMap();var activeTargetsManager=this.activeTargetsManager=new ActiveTargetsManager(this.app);activeTargetsManager.ontargetactivated=this._callTargetAction.bind(this,'activate',true,false);activeTargetsManager.ontargetlongpressed=this._callTargetAction.bind(this,'longPress',false,false);activeTargetsManager.ontargetmoved=this._callTargetAction.bind(this,'move',false,false);activeTargetsManager.ontargetmovedout=this._callTargetAction.bind(this,'moveOut',false,true);activeTargetsManager.ontargetmovedin=this._callTargetAction.bind(this,'moveIn',true,false);activeTargetsManager.ontargetcommitted=this._callTargetAction.bind(this,'commit',false,true);activeTargetsManager.ontargetcancelled=this._callTargetAction.bind(this,'cancel',false,true);activeTargetsManager.ontargetdoubletapped=this._callTargetAction.bind(this,'doubleTap',false,true);activeTargetsManager.onnewtargetwillactivate=this._callTargetAction.bind(this,'newTargetActivate',false,false);activeTargetsManager.start();};TargetHandlersManager.prototype.stop=function(){this.app.console.log('TargetHandlersManager.stop()');this.handlers=null;this.activeTargetsManager.stop();this.activeTargetsManager=null;};TargetHandlersManager.prototype._callTargetAction=function(action,setHandler,deleteHandler,target,press){this.app.console.log('TargetHandlersManager._callTargetAction()',action,setHandler,deleteHandler,target);this._preprocessActions(action,target);var handler;if(this.handlers.has(target)){handler=this.handlers.get(target);if(setHandler){console.warn('TargetHandlersManager: '+'calling targetHandler.'+action+'() on existing handler.');}
|
||
if(deleteHandler){this.handlers.delete(target);}}else{handler=this._createHandlerForTarget(target);if(!setHandler){console.warn('TargetHandlersManager: '+'calling targetHandler.'+action+'() on non-existing handler.');}
|
||
if(!deleteHandler){this.handlers.set(target,handler);}}
|
||
this.promiseQueue=this.promiseQueue.then(function(){return handler[action](press);}).catch(function(e){console.warn('TargetHandlersManager: '+'Error occurred for '+action+': ',e);});};TargetHandlersManager.prototype._createHandlerForTarget=function(target){this.app.console.log('TargetHandlersManager._createHandlerForTarget()');var handler;if('isDismissSuggestionsButton'in target){handler=new DismissSuggestionsTargetHandler(target,this.app);}else if('suggestion'in target){handler=new CandidateSelectionTargetHandler(target,this.app);}else if('compositeKey'in target){handler=new CompositeTargetHandler(target,this.app);}else if(target.isHandwritingPad){handler=new HandwritingPadTargetHandler(target,this.app);}else if('keyCode'in target){switch(target.keyCode){case KeyEvent.DOM_VK_BACK_SPACE:handler=new BackspaceTargetHandler(target,this.app);break;case KeyEvent.DOM_VK_SPACE:handler=new SpaceKeyTargetHandler(target,this.app);break;case KeyEvent.DOM_VK_ALT:handler=new PageSwitchingTargetHandler(target,this.app);break;case this.app.layoutManager.KEYCODE_SWITCH_KEYBOARD:handler=new SwitchKeyboardTargetHandler(target,this.app);break;case this.app.layoutManager.KEYCODE_TOGGLE_CANDIDATE_PANEL:handler=new ToggleCandidatePanelTargetHandler(target,this.app);break;case KeyEvent.DOM_VK_CAPS_LOCK:handler=new CapsLockTargetHandler(target,this.app);break;default:handler=new DefaultTargetHandler(target,this.app);break;}}else{handler=new NullTargetHandler(target,this.app);}
|
||
return handler;};TargetHandlersManager.prototype._preprocessActions=function(action,target){switch(action){case'activate':case'moveIn':if(target.isHandwritingPad){this.activeTargetsManager.blockNewUserPress=true;this.activeTargetsManager.blockTargetMovedOut=true;}
|
||
break;case'commit':case'doubleTap':if(target.isHandwritingPad){this.activeTargetsManager.blockNewUserPress=false;this.activeTargetsManager.blockTargetMovedOut=false;}
|
||
break;}};exports.TargetHandlersManager=TargetHandlersManager;})(window);;'use strict';(function(exports){var ActiveTargetsManager=function(app){this.app=app;this.activeTargets=null;this.blockNewUserPress=false;this.blockTargetMovedOut=false;this.userPressManager=null;this.alternativesCharMenuManager=null;this.longPressTimer=undefined;this.doubleTapTimer=undefined;this.doubleTapPreviousTarget=null;};ActiveTargetsManager.prototype.ontargetactivated=null;ActiveTargetsManager.prototype.ontargetlongpressed=null;ActiveTargetsManager.prototype.ontargetmoved=null;ActiveTargetsManager.prototype.ontargetmovedout=null;ActiveTargetsManager.prototype.ontargetmovedin=null;ActiveTargetsManager.prototype.ontargetcommitted=null;ActiveTargetsManager.prototype.ontargetcancelled=null;ActiveTargetsManager.prototype.ontargetdoubletapped=null;ActiveTargetsManager.prototype.onnewtargetwillactivate=null;ActiveTargetsManager.prototype.LONG_PRESS_TIMEOUT=700;ActiveTargetsManager.prototype.DOUBLE_TAP_TIMEOUT=450;ActiveTargetsManager.prototype.start=function(){this.app.console.log('ActiveTargetsManager.start()');this.activeTargets=new Map();var userPressManager=this.userPressManager=new UserPressManager(this.app);userPressManager.onpressstart=this._handlePressStart.bind(this);userPressManager.onpressmove=this._handlePressMove.bind(this);userPressManager.onpressend=this._handlePressEnd.bind(this);userPressManager.start();this.alternativesCharMenuManager=new AlternativesCharMenuManager(this.app);this.alternativesCharMenuManager.start();};ActiveTargetsManager.prototype.stop=function(){this.app.console.log('ActiveTargetsManager.stop()');this.activeTargets=null;this.userPressManager.stop();this.userPressManager=null;this.alternativesCharMenuManager.stop();this.alternativesCharMenuManager=null;clearTimeout(this.longPressTimer);this.doubleTapTimer=undefined;this.doubleTapPreviousTarget=null;};ActiveTargetsManager.prototype.clearAllTargets=function(){this.app.console.log('ActiveTargetsManager.clearAllTargets()');if(this.activeTargets.size){console.warn('ActiveTargetsManager: clear '+
|
||
this.activeTargets.size+' active target(s).');}
|
||
this.activeTargets.forEach(function(target,id){if(typeof this.ontargetcancelled==='function'){this.ontargetcancelled(target);}},this);this.activeTargets.clear();this.alternativesCharMenuManager.hide();clearTimeout(this.longPressTimer);};ActiveTargetsManager.prototype._handlePressStart=function(press,id){this.app.console.log('ActiveTargetsManager._handlePressStart()');if(this.blockNewUserPress||this.alternativesCharMenuManager.isShown){return;}
|
||
if(typeof this.onnewtargetwillactivate==='function'){this.activeTargets.forEach(function(target,id){this.onnewtargetwillactivate(target);},this);}
|
||
var target=press.target;this.activeTargets.set(id,target);if(typeof this.ontargetactivated==='function'){this.ontargetactivated(target,press);}
|
||
clearTimeout(this.longPressTimer);if(this.activeTargets.size===1){this.longPressTimer=setTimeout(this._handleLongPress.bind(this,press,id),this.LONG_PRESS_TIMEOUT);}};ActiveTargetsManager.prototype._handlePressMove=function(press,id){this.app.console.log('ActiveTargetsManager._handlePressMove()');if(!this.activeTargets.has(id)){return;}
|
||
var target=press.target;if(this.alternativesCharMenuManager.isShown&&this.alternativesCharMenuManager.isInMenuArea(press)){target=this.alternativesCharMenuManager.getMenuTarget(press);}
|
||
if(!target){return;}
|
||
var oldTarget=this.activeTargets.get(id);if(press.moved&&('selection'in oldTarget)){this.activeTargets.delete(id);this.ontargetcancelled(oldTarget);this.alternativesCharMenuManager.hide();clearTimeout(this.longPressTimer);return;}
|
||
if(target===oldTarget){if(typeof this.ontargetmoved==='function'){this.ontargetmoved(target,press);}
|
||
return;}
|
||
if(this.blockTargetMovedOut){return;}
|
||
this.activeTargets.set(id,target);if(typeof this.ontargetmovedout==='function'){this.ontargetmovedout(oldTarget,press);}
|
||
if(typeof this.ontargetmovedin==='function'){this.ontargetmovedin(target,press);}
|
||
if(!this.alternativesCharMenuManager.isMenuTarget(target)&&!this.alternativesCharMenuManager.isInMenuArea(press)){this.alternativesCharMenuManager.hide();}
|
||
clearTimeout(this.longPressTimer);if(this.activeTargets.size===1){this.longPressTimer=setTimeout(this._handleLongPress.bind(this,press,id),this.LONG_PRESS_TIMEOUT);}};ActiveTargetsManager.prototype._handleLongPress=function(press,id){this.app.console.log('ActiveTargetsManager._handleLongPress()');if(!this.activeTargets.has(id)){return;}
|
||
var target=this.activeTargets.get(id);if(typeof this.ontargetlongpressed==='function'){this.ontargetlongpressed(target);}
|
||
this.alternativesCharMenuManager.show(target);if(this.alternativesCharMenuManager.isShown){this._handlePressMove(press,id);}};ActiveTargetsManager.prototype._handlePressEnd=function(press,id){this.app.console.log('ActiveTargetsManager._handlePressEnd()');if(!this.activeTargets.has(id)){return;}
|
||
var target=this.activeTargets.get(id);this.activeTargets.delete(id);this.alternativesCharMenuManager.hide();clearTimeout(this.longPressTimer);if(this.doubleTapTimer&&this.doubleTapPreviousTarget===target){window.clearTimeout(this.doubleTapTimer);this.doubleTapTimer=undefined;this.doubleTapPreviousTarget=null;if(typeof this.ontargetdoubletapped==='function'){this.ontargetdoubletapped(target);}}else{window.clearTimeout(this.doubleTapTimer);this.doubleTapTimer=window.setTimeout(function(){this.doubleTapTimer=undefined;this.doubleTapPreviousTarget=null;}.bind(this),this.DOUBLE_TAP_TIMEOUT);this.doubleTapPreviousTarget=target;if(typeof this.ontargetcommitted==='function'){this.ontargetcommitted(target);}}};exports.ActiveTargetsManager=ActiveTargetsManager;})(window);;'use strict';(function(exports){var Keyboards={};Keyboards.defaultLayout={pages:[{},{alt:{'1':['¹'],'2':['²'],'3':['³'],'4':['⁴'],'5':['⁵'],'6':['⁶'],'7':['⁷'],'8':['⁸'],'9':['⁹'],'0':['⁰','º'],'$':['€','£','¢','¥'],'"':['“','”'],'\'':['‘','’'],'?':['¿'],'!':['¡'],'+':['-','×','÷','±']},keys:[[{value:'1'},{value:'2'},{value:'3'},{value:'4'},{value:'5'},{value:'6'},{value:'7'},{value:'8'},{value:'9'},{value:'0'}],[{value:'@'},{value:'#'},{value:'$',className:'alternate-indicator'},{value:'&'},{value:'*'},{value:'-'},{value:'_'},{value:'/'},{value:'('},{value:')'}],[{value:'Alt',ratio:1.5,keyCode:KeyboardEvent.DOM_VK_ALT,className:'page-switch-key',targetPage:2},{value:'+',supportsSwitching:{value:','}},{value:':'},{value:';'},{value:'"'},{value:'\''},{value:'!'},{value:'?'},{value:'⌫',ratio:1.5,keyCode:KeyboardEvent.DOM_VK_BACK_SPACE}],[{value:' ',ratio:8,keyCode:KeyboardEvent.DOM_VK_SPACE},{value:'↵',ratio:2,keyCode:KeyboardEvent.DOM_VK_RETURN}]]},{alt:{'+':['-','×','÷','±'],'®':['™']},keys:[[{value:'€'},{value:'£'},{value:'¢'},{value:'¥'},{value:'%'},{value:'©'},{value:'®'},{value:'·'},{value:'|'},{value:'\\'}],[{value:'~'},{value:'℃'},{value:'℉'},{value:'°'},{value:'<'},{value:'>'},{value:'['},{value:']'},{value:'{'},{value:'}'}],[{value:'Alt',ratio:1.5,keyCode:KeyboardEvent.DOM_VK_ALT,className:'page-switch-key',targetPage:1},{value:'+'},{value:'='},{value:'`'},{value:'^'},{value:'§'},{value:'«'},{value:'»'},{value:'⌫',ratio:1.5,keyCode:KeyboardEvent.DOM_VK_BACK_SPACE}],[{value:' ',ratio:8,keyCode:KeyboardEvent.DOM_VK_SPACE},{value:'↵',ratio:2,keyCode:KeyboardEvent.DOM_VK_RETURN}]]}]};Keyboards.numberLayout={width:3,keyClassName:'big-key special-key',keys:[[{value:'1'},{value:'2'},{value:'3'}],[{value:'4'},{value:'5'},{value:'6'}],[{value:'7'},{value:'8'},{value:'9'}],[{value:'.',longPressValue:','},{value:'0',longPressValue:'-'},{value:'⌫',keyCode:KeyboardEvent.DOM_VK_BACK_SPACE}]]};Keyboards.pinLayout={width:3,keyClassName:'big-key special-key bottom-symbol',keys:[[{value:'1'},{value:'2'},{value:'3'}],[{value:'4'},{value:'5'},{value:'6'}],[{value:'7'},{value:'8'},{value:'9'}],[{value:''},{value:'0'},{value:'⌫',keyCode:KeyboardEvent.DOM_VK_BACK_SPACE}]]};Keyboards.telLayout={width:3,keyClassName:'big-key special-key bottom-symbol',keys:[[{value:'1',longPressValue:'('},{value:'2',longPressValue:')'},{value:'3',longPressValue:'/'}],[{value:'4',longPressValue:'-'},{value:'5',longPressValue:'_'},{value:'6',longPressValue:','}],[{value:'7',longPressValue:':'},{value:'8',longPressValue:'.'},{value:'9',longPressValue:';'}],[{value:'*',longPressValue:'#'},{value:'0',longPressValue:'+'},{value:'⌫',keyCode:KeyboardEvent.DOM_VK_BACK_SPACE}]]};var LayoutLoader=function(app){this.app=app;};LayoutLoader.prototype.SOURCE_DIR='./js/layouts/';LayoutLoader.prototype.start=function(){this._initializedLayouts={};this._layoutsPromises={};this.initLayouts();};LayoutLoader.prototype.initLayouts=function(){var Keyboards=exports.Keyboards;exports.Keyboards={};var layoutName;for(layoutName in Keyboards){if(this._initializedLayouts[layoutName]){console.warn('LayoutLoader: '+layoutName+' is overwritten.');}
|
||
var layoutNormalizer=new LayoutNormalizer(Keyboards[layoutName]);layoutNormalizer.normalize();this._initializedLayouts[layoutName]=layoutNormalizer.normalizedLayout;if(!this._layoutsPromises[layoutName]){this._layoutsPromises[layoutName]=Promise.resolve(this._initializedLayouts[layoutName]);}}};LayoutLoader.prototype.getLayout=function(layoutName){return this._initializedLayouts[layoutName];};LayoutLoader.prototype.getLayoutAsync=function(layoutName){if(this._layoutsPromises[layoutName]){return this._layoutsPromises[layoutName];}
|
||
var p=new Promise(function(resolve,reject){var script=document.createElement('script');script.onload=function(){this.initLayouts();resolve(this._initializedLayouts[layoutName]);}.bind(this);script.onerror=function(){this._layoutsPromises[layoutName]=null;console.error('LayoutLoader: unable to load '+layoutName+'.');reject();}.bind(this);script.src=this.SOURCE_DIR+layoutName+'.js';document.body.appendChild(script);}.bind(this));this._layoutsPromises[layoutName]=p;return p;};exports.Keyboards=Keyboards;exports.LayoutLoader=LayoutLoader;})(window);;'use strict';(function(exports){var LayoutManager=function(app){this.app=app;this._typeGenericLayoutName=undefined;this.currentPage=null;this.currentPageIndex=this.PAGE_INDEX_DEFAULT;};LayoutManager.prototype.start=function(){this.loader=new LayoutLoader();this.loader.start();};LayoutManager.prototype.KEYCODE_SWITCH_KEYBOARD=-3;LayoutManager.prototype.KEYCODE_TOGGLE_CANDIDATE_PANEL=-4;LayoutManager.prototype.DEFAULT_LAYOUT_NAME='defaultLayout';LayoutManager.prototype.PAGE_INDEX_DEFAULT=0;LayoutManager.prototype.switchCurrentLayout=function(layoutName){var loaderPromise=this.loader.getLayoutAsync(layoutName);var p=loaderPromise.then(function(layout){this._typeGenericLayoutName=layoutName;this.currentPageIndex=this.PAGE_INDEX_DEFAULT;this._updateCurrentPage();}.bind(this));return p;};LayoutManager.prototype.updateLayoutPage=function(page){this.currentPageIndex=page;this._updateCurrentPage();};LayoutManager.prototype._updateCurrentPage=function(){if(!this.app.inputContext||!this._typeGenericLayoutName){console.warn('LayoutManager: '+'calling _updateCurrentPage() when there is no '+'inputContext or _typeGenericLayoutName.');this.currentPage=null;return;}
|
||
var inputMode=this.app.inputContext.inputMode;var basicInputType=this.app.getBasicInputType();var supportsSwitching=this.app.supportsSwitching();var typeSpecificLayoutName=this._typeSpecificLayoutName(basicInputType,inputMode);var layout=this.loader.getLayout(typeSpecificLayoutName||this._typeGenericLayoutName);if(!layout){console.error('LayoutManager: Can\'t load the layout.','typeSpecificLayoutName=',typeSpecificLayoutName,'typeGenericLayoutName=',this._typeGenericLayoutName,'currentPageIndex=',this.currentPageIndex);this.currentPage=null;return;}
|
||
var page=layout.pages[this.currentPageIndex];if(!page){var defaultLayout=this.loader.getLayout(this.DEFAULT_LAYOUT_NAME);page=defaultLayout.pages[this.currentPageIndex];}
|
||
if(!page){console.error('LayoutManager: Can\'t load the page from layout.','typeSpecificLayoutName=',typeSpecificLayoutName,'typeGenericLayoutName=',this._typeGenericLayoutName,'currentPageIndex=',this.currentPageIndex);this.currentPage=null;return;}
|
||
page=this.currentPage=Object.create(page);var keyNormalizer=new LayoutKeyNormalizer(page);['imEngine','autoCorrectLanguage','autoCorrectPunctuation','needsCandidatePanel','lang'].forEach(function(prop){if(prop in layout){page[prop]=layout[prop];}});page.layoutName=typeSpecificLayoutName||this._typeGenericLayoutName;page.pageIndex=this.currentPageIndex;var spaceKeyFindResult=this._findKey(page,KeyboardEvent.DOM_VK_SPACE);var spaceKeyRowCount=spaceKeyFindResult.keyRowCount;var spaceKeyCount=spaceKeyFindResult.keyCount;if(!spaceKeyFindResult.keyFound){console.warn('LayoutManager:'+'No space key found. No special keys will be added.');return;}
|
||
page.keys=[].concat(page.keys);var copiedRows=[];var spaceKeyRow=page.keys[spaceKeyRowCount]=[].concat(page.keys[spaceKeyRowCount]);copiedRows.push(spaceKeyRowCount);var spaceKeyObject=page.keys[spaceKeyRowCount][spaceKeyCount]=Object.create(page.keys[spaceKeyRowCount][spaceKeyCount]);var enterKeyFindResult=this._findKey(page,KeyboardEvent.DOM_VK_RETURN);var enterKeyCount=enterKeyFindResult.keyCount;var enterKeyObject=page.keys[spaceKeyRowCount][enterKeyCount]=Object.create(page.keys[spaceKeyRowCount][enterKeyCount]);var pageSwitchingKeyObject=null;if(!layout.disableAlternateLayout){spaceKeyObject.ratio-=2;pageSwitchingKeyObject={keyCode:KeyboardEvent.DOM_VK_ALT,ratio:2,className:'page-switch-key'};if(this.currentPageIndex===this.PAGE_INDEX_DEFAULT){Object.assign(pageSwitchingKeyObject,{value:layout.alternateLayoutKey||'12&',ariaLabel:'alternateLayoutKey2',targetPage:1});}else{Object.assign(pageSwitchingKeyObject,{value:layout.basicLayoutKey||'ABC',ariaLabel:'basicLayoutKey2',targetPage:this.PAGE_INDEX_DEFAULT});}
|
||
pageSwitchingKeyObject=keyNormalizer.normalizeKey(pageSwitchingKeyObject,false);spaceKeyRow.splice(spaceKeyCount,0,pageSwitchingKeyObject);spaceKeyCount++;}
|
||
var needsSwitchingKey=supportsSwitching&&!layout.hidesSwitchKey;if(needsSwitchingKey){var imeSwitchKey={value:'🌐',uppercaseValue:'🌐',keyCode:this.KEYCODE_SWITCH_KEYBOARD,className:'switch-key',isSpecialKey:true};if(layout.shortLabel){imeSwitchKey.value=layout.shortLabel;imeSwitchKey.uppercaseValue=layout.shortLabel;imeSwitchKey.className+=' alternate-indicator';}
|
||
spaceKeyObject.ratio-=1;spaceKeyRow.splice(spaceKeyCount,0,imeSwitchKey);spaceKeyCount++;var r=page.keys.length,c,row,key;while(r--){row=page.keys[r];c=row.length;while(c--){key=row[c];if(key.supportsSwitching){if(copiedRows.indexOf(r)===-1){page.keys[r]=[].concat(page.keys[r]);copiedRows.push(r);}
|
||
page.keys[r][c]=Object.create(key.supportsSwitching);}}}}
|
||
if(!page.typeInsensitive){var periodKey=keyNormalizer.normalizeKey({value:'.'},!!(page.alt&&page.alt['.']));var modifyType='default';if(this.currentPageIndex===this.PAGE_INDEX_DEFAULT){switch(basicInputType){case'url':modifyType='url';break;case'email':modifyType='email';break;case'text':modifyType='default';break;case'search':modifyType='search';break;}}else{if('search'===basicInputType){modifyType='search';}else{modifyType='default';}}
|
||
switch(modifyType){case'url':spaceKeyObject.ratio-=2.0;spaceKeyRow.splice(spaceKeyCount,0,keyNormalizer.normalizeKey({value:'/'},false));spaceKeyCount++;spaceKeyRow.splice(spaceKeyCount+1,0,periodKey);break;case'email':spaceKeyObject.ratio-=2;spaceKeyRow.splice(spaceKeyCount,0,keyNormalizer.normalizeKey({value:'@'},false));spaceKeyCount++;spaceKeyRow.splice(spaceKeyCount+1,0,periodKey);break;case'search':if(enterKeyObject){enterKeyObject.className='search-icon';}
|
||
case'default':var overwrites=page.textLayoutOverwrite||{};if(overwrites[',']!==false&&(!needsSwitchingKey||page.needsCommaKey)){var commaKey;if(overwrites[',']){commaKey=overwrites[','];}else{commaKey=keyNormalizer.normalizeKey({value:','},!!(page.alt&&page.alt[',']));}
|
||
spaceKeyObject.ratio-=1;spaceKeyRow.splice(spaceKeyCount,0,commaKey);spaceKeyCount++;}
|
||
if(overwrites['.']!==false){if(overwrites['.']){periodKey=overwrites['.'];}
|
||
spaceKeyObject.ratio-=1;spaceKeyRow.splice(spaceKeyCount+1,0,periodKey);}
|
||
break;}}
|
||
var keyCount=page.width?page.width:10;if(!layout.disableAlternateLayout){if(spaceKeyCount==3&&keyCount==10){if(enterKeyObject){enterKeyObject.ratio=2.5;}
|
||
pageSwitchingKeyObject.ratio=1.5;}}};LayoutManager.prototype._typeSpecificLayoutName=function(basicInputType,inputMode){switch(basicInputType){case'tel':return'telLayout';case'number':switch(inputMode){case'digit':return'pinLayout';default:return'numberLayout';}
|
||
break;case'text':switch(inputMode){case'digit':return'pinLayout';case'numeric':return'numberLayout';case'-moz-sms':var smsLayoutName=this._typeGenericLayoutName+'-sms';if(this.loader.getLayout(smsLayoutName)){return smsLayoutName;}}
|
||
break;}
|
||
return'';};LayoutManager.prototype._findKey=function(page,keyCode){var r=page.keys.length,c,row,key;while(r--){row=page.keys[r];c=row.length;while(c--){key=row[c];if(key.keyCode==keyCode){return{keyFound:true,keyRowCount:r,keyCount:c};}}}
|
||
return{keyFound:false,keyRowCount:-1,keyCount:-1};};exports.SWITCH_KEYBOARD=LayoutManager.prototype.KEYCODE_SWITCH_KEYBOARD;exports.TOGGLE_CANDIDATE_PANEL=LayoutManager.prototype.KEYCODE_TOGGLE_CANDIDATE_PANEL;exports.PAGE_INDEX_DEFAULT=LayoutManager.prototype.PAGE_INDEX_DEFAULT;exports.LayoutManager=LayoutManager;})(window);;'use strict';(function(exports){var LayoutKeyNormalizer=function(page){this._page=page;};LayoutKeyNormalizer.prototype._isSpecialKey=function(key){var SPECIAL_CODES=[KeyEvent.DOM_VK_BACK_SPACE,KeyEvent.DOM_VK_CAPS_LOCK,KeyEvent.DOM_VK_RETURN,KeyEvent.DOM_VK_ALT];var hasSpecialCode=key.keyCode&&(SPECIAL_CODES.indexOf(key.keyCode)!==-1);return hasSpecialCode||key.keyCode<=0;};LayoutKeyNormalizer.prototype._isButton=function(key){var SPECIAL_BUTTONS=[KeyEvent.DOM_VK_RETURN];return this._isSpecialKey(key)&&SPECIAL_BUTTONS.indexOf(key.keyCode)!==-1;};LayoutKeyNormalizer.prototype._getUpperCaseValue=function(key){if(KeyEvent.DOM_VK_SPACE===key.keyCode||this._isSpecialKey(key)||key.compositeKey){return key.value;}
|
||
var upperCase=this._page.upperCase||{};return upperCase[key.value]||key.value.toUpperCase();};LayoutKeyNormalizer.prototype.normalizeKey=function(key,showAlternatesIndicator){var keyChar=key.value;var upperCaseKeyChar=this._getUpperCaseValue(key);var code=key.keyCode||keyChar.charCodeAt(0);var upperCode=key.keyCode||upperCaseKeyChar.charCodeAt(0);key.keyCode=code;key.keyCodeUpper=upperCode;key.lowercaseValue=keyChar;key.uppercaseValue=upperCaseKeyChar;key.isSpecialKey=this._isSpecialKey(key);key.isButton=this._isButton(key);if(showAlternatesIndicator){key.className='alternate-indicator';}
|
||
if(key.longPressValue){var longPressKeyCode=key.longPressKeyCode||key.longPressValue.charCodeAt(0);key.longPressKeyCode=longPressKeyCode;}
|
||
if(key.supportsSwitching){this.normalizeKey(key.supportsSwitching,false);}
|
||
if(KeyboardEvent.DOM_VK_ALT===code&&!('targetPage'in key)){console.error('LayoutNormalizer: no targetPage for switching key.');}
|
||
return key;};var LayoutNormalizer=function(layout){this._layout=layout;this._normalizedLayout=null;};LayoutNormalizer.prototype._hasAlternativeKeys=function(key,page){var alt=page.alt||{};return key in alt;};LayoutNormalizer.prototype._normalizePageKeys=function(page){var keyRows=page.keys||[];var keyNormalizer=new LayoutKeyNormalizer(page);page.keys=keyRows.map(function(keyRow){return keyRow.map(function(key){return keyNormalizer.normalizeKey(key,false);},this);},this);var overwrites=page.textLayoutOverwrite||{};page.textLayoutOverwrite=Object.keys(overwrites).reduce(function(result,overwrittenKey){if(false===overwrites[overwrittenKey]){result[overwrittenKey]=false;}else{var hasAlternativeKeys=this._hasAlternativeKeys(overwrites[overwrittenKey],page);result[overwrittenKey]=keyNormalizer.normalizeKey({value:overwrites[overwrittenKey]},hasAlternativeKeys);}
|
||
return result;}.bind(this),{});};LayoutNormalizer.prototype._normalizePageAltKeys=function(page){var alt=page.alt=page.alt||{};var upperCase=page.upperCase=page.upperCase||{};var altKeys=Object.keys(alt);altKeys.forEach(function(key){var alternatives=alt[key];if(!Array.isArray(alternatives)){if(alternatives.indexOf(' ')!==-1){alternatives=alternatives.split(' ');if(alternatives.length===2&&alternatives[1]===''){alternatives.pop();}}else{alternatives=alternatives.split('');}}
|
||
alt[key]=alternatives;var upperCaseKey=upperCase[key]||key.toUpperCase();if(!alt[upperCaseKey]){var needDifferentUpperCaseLockedAlternatives=false;alt[upperCaseKey]=alternatives.map(function(key){if(key.length===1){return key.toUpperCase();}
|
||
needDifferentUpperCaseLockedAlternatives=needDifferentUpperCaseLockedAlternatives||(key.substr(1).toUpperCase()!==key.substr(1));return key[0].toUpperCase()+key.substr(1);});if(needDifferentUpperCaseLockedAlternatives){alt[upperCaseKey].upperCaseLocked=alternatives.map(function(key){return key.toUpperCase();});}}},this);};LayoutNormalizer.prototype.normalize=function(){var pages;if('pages'in this._layout){pages=this._layout.pages;}else{pages=this._layout.pages=[];}
|
||
if(!pages[0]){pages[0]={};['alt','keys','upperCase','width','keyClassName','typeInsensitive','textLayoutOverwrite','needsCommaKey','secondLayout','specificCssRule'].forEach(function(prop){if(this._layout[prop]){pages[0][prop]=this._layout[prop];delete this._layout[prop];}},this);}
|
||
pages.forEach(function(page){this._normalizePageKeys(page);this._normalizePageAltKeys(page);},this);this._normalizedLayout=this._layout;};Object.defineProperty(LayoutNormalizer.prototype,'normalizedLayout',{configurable:true,get:function ln_getNormalizedLayout(){if(!this._normalizedLayout){throw Error('Tried to get normalized layout before calling normalize()');}
|
||
return this._normalizedLayout;}});exports.LayoutKeyNormalizer=LayoutKeyNormalizer;exports.LayoutNormalizer=LayoutNormalizer;})(window);;'use strict';(function(exports){function ViewManager(app){this.app=app;this.viewMap=new WeakMap();this.currentPageView=null;this.pageViews=new Map();this.alternativesCharMenu=null;this.columnCount=10;}
|
||
ViewManager.prototype={get candidatePanel(){if(!this.currentPageView||!this.currentPageView.candidatePanel){return;}
|
||
return this.currentPageView.candidatePanel.element;}};ViewManager.prototype.start=function(){this.container=document.getElementById('keyboard');this.cachedWindowHeight=window.innerHeight||window.screen.height;this.cachedWindowWidth=window.innerWidth||window.screen.width;window.addEventListener('resize',this);};ViewManager.prototype.stop=function(){this.container=null;this.viewMap=null;this.currentPageView=null;this.pageViews=null;window.removeEventListener('resize',this);};ViewManager.prototype.handleEvent=function(evt){if(evt.type!=='resize'){return;}
|
||
this.cachedWindowHeight=window.innerHeight||window.screen.height;this.cachedWindowWidth=window.innerWidth||window.screen.width;};ViewManager.prototype.setUpperCaseLock=function(state){if(!this.currentPageView){console.error('No current page view!');return;}
|
||
this.currentPageView.setUpperCaseLock(state);};ViewManager.prototype.render=function(layout,flags,callback){this.app.console.log('ViewManager.render()');this.app.console.time('ViewManager.render()');flags=flags||{};this.columnCount=layout.width||10;var supportsSwitching='mozInputMethod'in navigator?navigator.mozInputMethod.mgmt.supportsSwitching():false;var pageId=[layout.layoutName,layout.pageIndex,(''+flags.inputType).substr(0,1),(''+flags.showCandidatePanel).substr(0,1),supportsSwitching].join('-');var pageView=this.pageViews.get(pageId);if(!pageView){var options={classNames:['keyboard-type-container'],totalWidth:this.container.clientWidth,showCandidatePanel:flags.showCandidatePanel};pageView=this._createPageView(layout,options);if(!layout.updateByIMEngine){this.pageViews.set(pageId,pageView);}
|
||
pageView.render();this.container.appendChild(pageView.element);if(flags.showCandidatePanel){this.showCandidates([]);}}
|
||
pageView.setUpperCaseLock({isUpperCase:flags.uppercase,isUpperCaseLocked:false});if(this.currentPageView!==pageView){if(this.currentPageView){this.currentPageView.hide();}
|
||
if(this.currentPageView&&this.currentPageView.layout.updateByIMEngine){this.currentPageView.destroy();}
|
||
pageView.show();this.currentPageView=pageView;this.resize(callback);}else if((this.container.classList.contains('landscape')&&this.screenInPortraitMode())||(this.container.classList.contains('portrait')&&!this.screenInPortraitMode())){this.resize(callback);}
|
||
else{if(callback){window.requestAnimationFrame(callback);}}
|
||
this.app.console.timeEnd('ViewManager.render()');};ViewManager.prototype.drawHandwritingPad=function(press,start,strokeWidth){var handwritingPadView=this.viewMap.get(press.target);return handwritingPadView.drawHandwritingPad(press,start,strokeWidth);};ViewManager.prototype.clearHandwritingPad=function(target){var handwritingPadView=this.viewMap.get(target);return handwritingPadView.clearHandwritingPad();};ViewManager.prototype.highlightKey=function(target){if(!this.currentPageView){console.error('No current page view!');return;}
|
||
this.currentPageView.highlightKey(target);};ViewManager.prototype.unHighlightKey=function(target){if(!this.currentPageView){console.error('ViewManager: No current page view!');return;}
|
||
this.currentPageView.unHighlightKey(target);};ViewManager.prototype.toggleCandidatePanel=function(expand){if(!this.currentPageView){console.error('ViewManager: No current page view!');return;}
|
||
this.currentPageView.resetCandidatePanel();this._toggleCandidatePanelWithoutResetScroll(expand);};ViewManager.prototype._toggleCandidatePanelWithoutResetScroll=function(expand){if(expand){this.container.classList.remove('candidate-panel');this.container.classList.add('full-candidate-panel');}else{this.container.classList.remove('full-candidate-panel');this.container.classList.add('candidate-panel');}};ViewManager.prototype.showAlternativesCharMenu=function(key,altChars){var options={keyWidth:(this.cachedWindowWidth/this.columnCount)|0,screenInPortraitMode:this.screenInPortraitMode};var alternativesCharMenu=new AlternativesCharMenuView(this.currentPageView.element,altChars,options,this);var keyElement=this.viewMap.get(key).element;alternativesCharMenu.show(keyElement);this.alternativesCharMenu=alternativesCharMenu;return alternativesCharMenu;};ViewManager.prototype.hideAlternativesCharMenu=function(){if(!this.alternativesCharMenu){console.error('No alternative char menu to hide!');return;}
|
||
this.alternativesCharMenu.hide();};ViewManager.prototype.resize=function(callback){var changeScale;if(this.screenInPortraitMode()){changeScale=this.cachedWindowWidth/32;document.documentElement.style.fontSize=changeScale+'px';this.container.classList.remove('landscape');this.container.classList.add('portrait');}else{changeScale=this.cachedWindowWidth/64;document.documentElement.style.fontSize=changeScale+'px';this.container.classList.remove('portrait');this.container.classList.add('landscape');}
|
||
if(!this.currentPageView){return;}
|
||
this.currentPageView.resize(this.cachedWindowWidth);if(callback){window.requestAnimationFrame(callback);}};ViewManager.prototype.getWidth=function(){if(!this.currentPageView){return 0;}
|
||
return this.cachedWindowWidth;};ViewManager.prototype.getHeight=function(){if(!this.currentPageView){return 0;}
|
||
return this.currentPageView.getHeight()|0;};ViewManager.prototype.showCandidates=function(candidates){if(!this.currentPageView){return;}
|
||
this._toggleCandidatePanelWithoutResetScroll(false);this.currentPageView.showCandidates(candidates);};ViewManager.prototype.showMoreCandidates=function(rowLimit,candidates){if(!this.currentPageView){return;}
|
||
this.currentPageView.showMoreCandidates(rowLimit,candidates);};ViewManager.prototype.getNumberOfCandidatesPerRow=function(){if(!this.currentPageView){return;}
|
||
return this.currentPageView.getNumberOfCandidatesPerRow();};ViewManager.prototype.getKeyArray=function(){return this.currentPageView.getVisualData();};ViewManager.prototype.getKeyWidth=function(){return Math.ceil(this.cachedWindowWidth/this.columnCount);};ViewManager.prototype.getKeyHeight=function(){if(!this.currentPageView){return 0;}
|
||
return this.currentPageView.getKeyHeight();};ViewManager.prototype.registerView=function(target,view){this.app.layoutRenderingManager.domObjectMap.set(view.element,target);this.viewMap.set(target,view);};ViewManager.prototype.screenInPortraitMode=function(){return this.cachedWindowWidth<=this.cachedWindowHeight;};ViewManager.prototype.getRemToPx=function(){return this.screenInPortraitMode()?this.cachedWindowWidth/32:this.cachedWindowWidth/64;};ViewManager.prototype.getView=function(target){return this.viewMap.get(target);};ViewManager.prototype._createPageView=function(layout,options){var pageView;if(layout.panelKeys){pageView=new SwipeablePageView(layout,options,this);}else{pageView=new LayoutPageView(layout,options,this);}
|
||
return pageView;};exports.ViewManager=ViewManager;})(window);;'use strict';(function(exports){function SwipingDetector(element){this.element=element;this.state=this.STATE_INIT;}
|
||
SwipingDetector.prototype.EVENT_TYPES=['touchstart','touchmove','touchend'];SwipingDetector.prototype.VELOCITY_SMOOTHING=0.5;SwipingDetector.prototype.STATE_INIT=0;SwipingDetector.prototype.STATE_PANNING=1;SwipingDetector.prototype.onpan=null;SwipingDetector.prototype.onswipe=null;SwipingDetector.prototype.start=function(){this.EVENT_TYPES.forEach(function(type){this.element.addEventListener(type,this);},this);};SwipingDetector.prototype.stop=function(){this.EVENT_TYPES.forEach(function(type){this.element.removeEventListener(type,this);},this);};SwipingDetector.prototype.handleEvent=function(evt){var current;var touch;switch(evt.type){case'touchstart':if(this.state===this.STATE_PANNING){return;}
|
||
touch=evt.touches[0];this.touchStartTimestamp=evt.timeStamp;this.startX=touch.pageX;this.startCoords=this.getCoordinates(evt,touch);this.last=this.startCoords;this.deltaX=0;this.touchID=touch.identifier;this.vx=this.vy=null;if(typeof this.ontouchstart==='function'){this.ontouchstart({position:this.getCoordinates(evt,touch)});}
|
||
break;case'touchmove':if(evt.timeStamp==this.last.timeStamp){return;}
|
||
touch=evt.touches[0];if(touch.identifier!=this.touchID){return;}
|
||
this.state=this.STATE_PANNING;current=this.getCoordinates(evt,touch);if(typeof this.onpan==='function'){this.onpan({dx:current.screenX-this.startX,position:this.getCoordinates(evt,touch)});}
|
||
var dt=current.timeStamp-this.last.timeStamp;var vx=(current.screenX-this.last.screenX)/dt;var vy=(current.screenY-this.last.screenY)/dt;if(this.vx==null){this.vx=vx;this.vy=vy;}else{this.vx=this.vx*this.VELOCITY_SMOOTHING+
|
||
vx*(1-this.VELOCITY_SMOOTHING);this.vy=this.vy*this.VELOCITY_SMOOTHING+
|
||
vy*(1-this.VELOCITY_SMOOTHING);}
|
||
this.last=current;break;case'touchend':for(var i=0;i<evt.changedTouches.length;i++){if(evt.changedTouches[i].identifier!==this.touchID){continue;}
|
||
current=this.getCoordinates(evt,evt.changedTouches[i]);var dx=current.screenX-this.startCoords.screenX;var dy=current.screenY-this.startCoords.screenY;var angle=Math.atan2(dy,dx)*180/Math.PI;if(angle<0){angle+=360;}
|
||
var direction;if(angle>=315||angle<45){direction='right';}else if(angle>=45&&angle<135){direction='down';}else if(angle>=135&&angle<225){direction='left';}else if(angle>=225&&angle<315){direction='up';}
|
||
if(typeof this.onswipe==='function'){this.onswipe({start:this.startCoords,end:current,dx:dx,dy:dy,dt:evt.timeStamp-this.startCoords.timeStamp,vx:this.vx,vy:this.vy,direction:direction,angle:angle});}
|
||
this.state=this.STATE_INIT;}
|
||
break;}};SwipingDetector.prototype.getCoordinates=function(event,touch){return Object.freeze({screenX:touch.screenX,screenY:touch.screenY,clientX:touch.clientX,clientY:touch.clientY,timeStamp:event.timeStamp});};exports.SwipingDetector=SwipingDetector;})(window);;'use strict';(function(exports){var ViewUtils={};var scaleContext;ViewUtils.getScale=function(text,textWidth){if(!scaleContext){scaleContext=document.createElement('canvas').getContext('2d',{willReadFrequently:true});scaleContext.font='2rem sans-serif';}
|
||
var elementWidth=scaleContext.measureText(text).width;var s=textWidth/elementWidth;if(s>=1){return 1;}
|
||
if(s>=0.8){return 0.8;}
|
||
if(s>=0.7){return 0.7;}
|
||
if(s>=0.65){return 0.65;}
|
||
if(s>=0.6){return 0.6;}
|
||
return s;};ViewUtils.fitText=function(container,text,length,totalWidth){container.textContent='';if(!text){return null;}
|
||
var span=document.createElement('span');span.textContent=text;container.appendChild(span);var limit=0.6;var textWidth=(totalWidth-36)/length|0;textWidth-=6;var scale=ViewUtils.getScale(text,textWidth);if(scale<limit){var charactersReplaced=text.length%2;while(scale<limit&&charactersReplaced<text.length-2){charactersReplaced+=2;var halflen=(text.length-charactersReplaced)/2;span.textContent=text.substring(0,halflen)+'…'+
|
||
text.substring(text.length-halflen);scale=ViewUtils.getScale(text,textWidth);}}
|
||
span.style.display='inline-block';if(scale<1){span.style.width=(100/scale)+'%';span.style.transformOrigin='left';span.style.transform='scale('+scale+')';}else{span.style.width='100%';}
|
||
return span;};exports.ViewUtils=ViewUtils;}(window));;'use strict';(function(exports){function BaseView(target,options,viewManager){this.target=target;this.options=options;this.viewManager=viewManager;}
|
||
BaseView.prototype.element=null;BaseView.prototype.highlight=function(){this.element.classList.add('highlighted');};BaseView.prototype.unHighlight=function(){this.element.classList.remove('highlighted');};BaseView.prototype.show=function(){this.element.classList.remove('hide');};BaseView.prototype.hide=function(){this.element.classList.add('hide');};exports.BaseView=BaseView;})(window);;'use strict';(function(exports){function AlternativesCharMenuView(rootElement,altChars,options,viewManager){this.rootElement=rootElement;this.altChars=altChars;this.keyWidth=options.keyWidth;this.screenInPortraitMode=options.screenInPortraitMode;this.menu=null;this._rowCount=0;this.altKeyTargets=[];this.viewManager=viewManager;}
|
||
exports.AlternativesCharMenuView=AlternativesCharMenuView;AlternativesCharMenuView.prototype.MENU_LINE_HEIGHT=6;AlternativesCharMenuView.prototype.show=function(keyElem){var content=document.createDocumentFragment();var cachedWindowWidth=window.innerWidth;var left=(cachedWindowWidth/2>keyElem.offsetLeft);this._direction=left?'left':'right';var menu=document.createElement('div');menu.id='keyboard-accent-char-menu';if(!left){menu.classList.add('kbr-menu-left');}
|
||
var widthRatio=0;if(this.altChars.length>5){widthRatio=Math.ceil(this.altChars.length/2);menu.style.top=(keyElem.offsetTop-this.getLineHeight()*2)+'px';this._columnCount=widthRatio;this._rowCount=2;menu.style.width=this.keyWidth*widthRatio+'px';menu.classList.add('multi-row');}else{menu.style.top=(keyElem.offsetTop-this.getLineHeight()+4)+'px';this._rowCount=1;this._columnCount=this.altChars.length;}
|
||
if(left){var keyRight=keyElem.offsetLeft+keyElem.offsetWidth;var posLeft=keyRight-this.keyWidth;menu.style.left=posLeft+'px';if(posLeft===0){menu.classList.add('left-edge');}}else{var menuRight=keyElem.offsetLeft+this.keyWidth;var posRight=cachedWindowWidth-menuRight;menu.style.right=posRight+'px';if(posRight===0){menu.classList.add('right-edge');}}
|
||
this.altChars.forEach(function(alt,index){var altKeyTarget=alt.length==1?{value:alt,keyCode:alt.charCodeAt(0),keyCodeUpper:alt.toUpperCase().charCodeAt(0)}:{'compositeKey':alt,value:alt};var width=this.keyWidth;if(alt.length>1&&this._rowCount===1){width=this._getCharWidth(alt)+10;width=Math.max(width,this.keyWidth);}
|
||
var altKey=new KeyView(altKeyTarget,{keyWidth:width},this.viewManager);altKey.render();content.appendChild(altKey.element);this.altKeyTargets.push(altKeyTarget);}.bind(this));menu.appendChild(content);this.rootElement.appendChild(menu);this.menu=menu;};AlternativesCharMenuView.prototype.hide=function(){this.rootElement.removeChild(this.menu);};AlternativesCharMenuView.prototype.getRowCount=function(){return this._rowCount;};AlternativesCharMenuView.prototype.getMenuContainer=function(){return this.menu;};AlternativesCharMenuView.prototype.getBoundingClientRect=function(){return this.menu.getBoundingClientRect();};AlternativesCharMenuView.prototype.getLineHeight=function(){var scale=parseFloat(document.documentElement.style.fontSize);return this.MENU_LINE_HEIGHT*scale;};AlternativesCharMenuView.prototype._getCharWidth=function(textContent){var scaleContext=document.createElement('canvas').getContext('2d',{willReadFrequently:true});var fontSize=this.screenInPortraitMode()?'2.4rem':'2.8rem';scaleContext.font=fontSize+' sans-serif';return scaleContext.measureText(textContent).width;};AlternativesCharMenuView.prototype.getMenuTarget=function(x,y){var menuRect=this.getBoundingClientRect();if(x<=menuRect.left){x=menuRect.left+1;}else if(x>=menuRect.right){x=menuRect.right-1;}
|
||
var xOffset=0;if(this._direction==='left'){xOffset=x-menuRect.left;}else{xOffset=menuRect.right-x;}
|
||
y=y-this.getLineHeight();if(y<=menuRect.top){y=menuRect.top+1;}
|
||
var columnCount=this._columnCount;var targetIndex=Math.floor(xOffset/menuRect.width*columnCount);if((menuRect.bottom-y)>this.getLineHeight()){targetIndex+=columnCount;}
|
||
if(targetIndex>=this.altKeyTargets.length){targetIndex=this.altKeyTargets.length-1;}
|
||
return this.altKeyTargets[targetIndex];};AlternativesCharMenuView.prototype.isMenuTarget=function(target){return(this.altKeyTargets.indexOf(target)!==-1);};})(window);;'use strict';(function(exports){var HandwritingPadView=function(target,options,viewManager){this.target=target;this.options=options;this.viewManager=viewManager;this.element=null;this.lastX=this.lastY=0;};HandwritingPadView.prototype.render=function render(){this.element=document.createElement('canvas');this.element.className='handwriting-pad';this.viewManager.registerView(this.target,this);};HandwritingPadView.prototype.drawHandwritingPad=function drawHandwritingPad(press,start,strokeWidth){var ctx=this.element.getContext('2d');ctx.strokeStyle='#df4b26';ctx.lineJoin='round';ctx.lineWidth=strokeWidth;var point=this._getPressPoint(press);ctx.beginPath();if(start){this.lastX=point.posX-1;this.lastY=point.posY;}
|
||
ctx.moveTo(this.lastX,this.lastY);ctx.lineTo(point.posX,point.posY);ctx.closePath();ctx.stroke();this.lastX=point.posX;this.lastY=point.posY;return point;};HandwritingPadView.prototype.clearHandwritingPad=function clearHandwritingPad(){var ctx=this.element.getContext('2d');var width=this.element.width;var height=this.element.height;ctx.clearRect(0,0,width,height);};HandwritingPadView.prototype._getPressPoint=function getPressPoint(press){var canvasRect=this.element.getBoundingClientRect();var posTop=canvasRect.top-document.body.clientTop;var posLeft=canvasRect.left-document.body.clientLeft;var posX=press.clientX-posLeft;var posY=press.clientY-posTop;posX*=window.devicePixelRatio;posY*=window.devicePixelRatio;return{posX:posX,posY:posY};};HandwritingPadView.prototype.resize=function resize(width,height){var canvas=this.element;canvas.width=width*window.devicePixelRatio;canvas.style.width=width+'px';canvas.height=height*window.devicePixelRatio;canvas.style.height=height+'px';};exports.HandwritingPadView=HandwritingPadView;})(window);;'use strict';(function(exports){function KeyView(target,options,viewManager){this.target=target;this.attributeList=options.attributeList||[];this.classNames=['keyboard-key'];if(!target.isButton){this.attributeList.push({key:'role',value:'key'});}
|
||
if(target.isSpecialKey){this.classNames.push('special-key');}else{if(options.classNames){this.classNames=this.classNames.concat(options.classNames);}}
|
||
if(target.className){this.classNames=this.classNames.concat(target.className.split(' '));}
|
||
if(target.disabled){this.attributeList.push({key:'disabled',value:'true'});}
|
||
var ARIA_LABELS=this.ARIA_LABELS||{};if(target.ariaLabel||ARIA_LABELS[target.value]){this.attributeList.push({key:'data-l10n-id',value:target.ariaLabel||ARIA_LABELS[target.value]});}else{this.attributeList.push({key:'aria-label',value:target.ariaLabel||target.value});}
|
||
this.outputChar=(options.outputChar)||target.value;this.altOutputChar=options.altOutputChar;this.innerRatio=options.innerRatio;this.outerRatio=options.outerRatio;this.width=options.keyWidth;this.viewManager=viewManager;}
|
||
KeyView.prototype.ARIA_LABELS={'⇪':'upperCaseKey2','⌫':'backSpaceKey2',' ':'spaceKey2','↵':'returnKey2','.':'periodKey2',',':'commaKey2',':':'colonKey2',';':'semicolonKey2','?':'questionMarkKey2','!':'exclamationPointKey2','(':'leftBracketKey2',')':'rightBracketKey2','"':'doubleQuoteKey2','«':'leftDoubleAngleQuoteKey2','»':'rightDoubleAngleQuoteKey2'};KeyView.prototype.render=function render(){var contentNode=document.createElement('button');if(this.classNames){contentNode.classList.add.apply(contentNode.classList,this.classNames);}
|
||
if(this.outerRatio&&this.outerRatio!=1){contentNode.style.flex=this.outerRatio;}
|
||
if(this.width){contentNode.style.width=this.width+'px';}
|
||
if(this.attributeList){this.attributeList.forEach(function(attribute){contentNode.setAttribute(attribute.key,attribute.value);});}
|
||
var vWrapperNode=document.createElement('span');vWrapperNode.className='visual-wrapper';if(this.outerRatio!==this.innerRatio){vWrapperNode.style.width=100*this.innerRatio/this.outerRatio+'%';}
|
||
var labelNode=document.createElement('span');labelNode.innerHTML=this.outputChar;labelNode.className='key-element';labelNode.dataset.label=this.outputChar;vWrapperNode.appendChild(labelNode);labelNode=document.createElement('span');labelNode.innerHTML=this.altOutputChar||this.outputChar;labelNode.className='key-element lowercase';labelNode.dataset.label=this.altOutputChar||this.outputChar;vWrapperNode.appendChild(labelNode);labelNode=document.createElement('span');labelNode.innerHTML=this.outputChar;labelNode.className='uppercase popup';vWrapperNode.appendChild(labelNode);labelNode=document.createElement('span');labelNode.innerHTML=this.target.lowercaseValue;labelNode.className='lowercase popup';vWrapperNode.appendChild(labelNode);if(this.target.longPressValue){var altNoteNode=document.createElement('div');altNoteNode.className='alt-note';altNoteNode.textContent=this.target.longPressValue;vWrapperNode.appendChild(altNoteNode);}
|
||
contentNode.appendChild(vWrapperNode);contentNode.dataset.keycode=this.target.keyCode;contentNode.dataset.keycodeUpper=this.target.keyCodeUpper;if('targetPage'in this.target){contentNode.dataset.targetPage=this.target.targetPage;}
|
||
this.element=contentNode;this.viewManager.registerView(this.target,this);};KeyView.prototype.highlight=function highlight(options){options=options||{};if(options.upperCase){this.element.classList.add('uppercase-popup');}else{this.element.classList.add('lowercase-popup');}
|
||
this.element.classList.add('highlighted');};KeyView.prototype.unHighlight=function unHighlight(){this.element.classList.remove('highlighted');this.element.classList.remove('uppercase-popup');this.element.classList.remove('lowercase-popup');};exports.KeyView=KeyView;})(window);;'use strict';(function(exports){function EmojiKeyView(){BaseView.apply(this,arguments);}
|
||
EmojiKeyView.prototype=Object.create(BaseView.prototype);EmojiKeyView.prototype.render=function(){var contentNode=document.createElement('button');if(this.options.classNames){contentNode.classList.add.apply(contentNode.classList,this.options.classNames);}
|
||
contentNode.classList.add('emoji');contentNode.innerHTML=this.options.outputChar||this.target.value||this.target.compositeKey;this.element=contentNode;this.viewManager.registerView(this.target,this);};exports.EmojiKeyView=EmojiKeyView;})(window);;'use strict';(function(exports){function SwipeablePanelView(layout,options,viewManager){this.layout=layout;this.options=options;this.viewManager=viewManager;this.sections=[];this.currentSectionIndex=0;this.indicators=[];this.startX=0;this.swipingDetector=null;}
|
||
SwipeablePanelView.prototype.COLUMN_COUNT=6;SwipeablePanelView.prototype.KEY_COUNT_PER_PANEL=18;SwipeablePanelView.prototype.SWIPE_THRESHOLD=20;SwipeablePanelView.prototype.SWIPE_FRACTION=0.25;SwipeablePanelView.prototype.SWIPE_SPEED=0.5;SwipeablePanelView.prototype.render=function(){var panel=document.createElement('div');panel.classList.add('swipe-panel');var i=0;while(true){var section=this._renderSection(i);if(!section){break;}
|
||
this.sections.push(section);section.classList.add('swipe-section');panel.appendChild(section);i++;}
|
||
if(this.sections.length>1){this._createSwipingDetector(panel);this._renderSectionIndicator(panel);}
|
||
this.element=panel;};SwipeablePanelView.prototype.gotoSection=function(index){if(index===this.currentSectionIndex){var currentPos=this.sections[this.currentSectionIndex].getBoundingClientRect();if(currentPos.left!==0){if(index>0){this._moveSection(index-1,-this.options.totalWidth);}
|
||
this._moveSection(index,0);if(index<this.sections.length-1){this._moveSection(index+1,this.options.totalWidth);}}
|
||
return;}
|
||
this._moveSection(index,0);var forward=(index>=this.currentSectionIndex)?1:-1;this._moveSection(this.currentSectionIndex,-forward*this.options.totalWidth);this.currentSectionIndex=index;this._updateIndicator();};SwipeablePanelView.prototype.resize=function resize(totalWidth){this.options.totalWidth=totalWidth;this.swipeDetectingPaused=true;this.sections.forEach(function(section,index){var translateX;if(index===this.currentSectionIndex){translateX=0;}else if(this.currentSectionIndex>index){translateX=-totalWidth;}else{translateX=totalWidth;}
|
||
section.style.transform='translateX('+translateX+'px)';},this);};SwipeablePanelView.prototype._moveSection=function(index,distance){var style=this.sections[index].style;style.transform='translateX('+distance+'px)';style.transition='transform '+300+'ms ease';};SwipeablePanelView.prototype._updateIndicator=function(){this.indicators.forEach(function(indicator,index){indicator.classList.toggle('active',(index==this.currentSectionIndex));},this);};SwipeablePanelView.prototype._handleTouchStart=function(evt){this.startX=evt.position.clientX;this.deltaX=0;this.swipeDetectingPaused=false;};SwipeablePanelView.prototype._handlePan=function(evt){if(this.swipeDetectingPaused){return;}
|
||
var totalWidth=this.options.totalWidth;this.sections.forEach(function(section){section.style.transition='';});var currentX=evt.position.clientX;this.deltaX=currentX-this.startX;var previous;var next;var current;var forward=this.deltaX<0;if(this.currentSectionIndex===0){if(forward){this.sections[1].style.transform='translateX('+(totalWidth+this.deltaX)+'px)';this.sections[0].style.transform='translateX('+this.deltaX+'px)';}else{this.startX=currentX;}}else if(this.currentSectionIndex===this.sections.length-1){previous=this.sections[this.currentSectionIndex-1].style;if(this.deltaX>=0){previous.transform='translateX('+(-totalWidth+this.deltaX)+'px)';this.sections[this.currentSectionIndex].style.transform='translateX('+this.deltaX+'px)';}else{this.startX=currentX;}}else{previous=this.sections[this.currentSectionIndex-1].style;next=this.sections[this.currentSectionIndex+1].style;if(this.deltaX>=0){previous.transform='translateX('+(-totalWidth+this.deltaX)+'px)';next.transform='translateX('+totalWidth+'px)';}else{next.transform='translateX('+(totalWidth+this.deltaX)+'px)';previous.transform='translateX(-'+totalWidth+'px)';}
|
||
current=this.sections[this.currentSectionIndex].style;current.transform='translateX('+this.deltaX+'px)';}};SwipeablePanelView.prototype._handleSwipe=function(evt){if(this.swipeDetectingPaused){return;}
|
||
var totalWidth=this.options.totalWidth;var targetIndex=this.currentSectionIndex;var forward=evt.direction==='left';var isFarEnough=Math.abs(this.deltaX)>totalWidth*this.SWIPE_FRACTION;var velocity=evt.vx;var isFastEnough=Math.abs(velocity)>this.SWIPE_SPEED;var isSameDirection=velocity===0||this.deltaX/velocity>=0;if((isFarEnough||isFastEnough)&&isSameDirection){if(forward&&this.currentSectionIndex<this.sections.length-1){targetIndex=this.currentSectionIndex+1;}else if(!forward&&this.currentSectionIndex>0){targetIndex=this.currentSectionIndex-1;}}
|
||
this.gotoSection(targetIndex);};SwipeablePanelView.prototype._renderSection=function(index){var panelKeys=this.layout.panelKeys;var startIndex=this.KEY_COUNT_PER_PANEL*index;if(startIndex>=panelKeys.length){return null;}
|
||
var endIndex=Math.min(startIndex+this.KEY_COUNT_PER_PANEL,panelKeys.length);var section=document.createElement('div');for(var i=startIndex;i<endIndex;i++){var keyView=this._createKeyView(panelKeys[i]);keyView.render();section.appendChild(keyView.element);}
|
||
var itemCount=i-startIndex;if(itemCount%this.COLUMN_COUNT!==0){var dummyEl=document.createElement('span');dummyEl.style.flex=this.COLUMN_COUNT-(itemCount%this.COLUMN_COUNT);section.appendChild(dummyEl);}
|
||
this.element=section;return section;};SwipeablePanelView.prototype._renderSectionIndicator=function(panel){var indicatorContainer=document.createElement('div');indicatorContainer.classList.add('section-indicator-container');for(var j=0;j<this.sections.length;j++){var dot=document.createElement('span');dot.classList.add('section-indicator');this.indicators.push(dot);indicatorContainer.appendChild(dot);}
|
||
this._updateIndicator();panel.appendChild(indicatorContainer);};SwipeablePanelView.prototype._createSwipingDetector=function(panel){this.swipingDetector=new SwipingDetector(panel);this.swipingDetector.start();this.swipingDetector.ontouchstart=this._handleTouchStart.bind(this);this.swipingDetector.onpan=this._handlePan.bind(this);this.swipingDetector.onswipe=this._handleSwipe.bind(this);};SwipeablePanelView.prototype._createKeyView=function(keyObject){var target=Object.create(keyObject);target.selection=true;var keyView;switch(target.type){case'emoji':keyView=new EmojiKeyView(target,{},this.viewManager);break;default:keyView=new KeyView(target,{},this.viewManager);break;}
|
||
return keyView;};exports.SwipeablePanelView=SwipeablePanelView;})(window);;'use strict';(function(exports){function LayoutPageView(layout,options,viewManager){this.layout=layout;this.options=options;this.viewManager=viewManager;this.isUpperCase=undefined;this.rows=new Map();this.candidatePanel=null;this.keyArrays=new Map();}
|
||
LayoutPageView.prototype.render=function render(){var layout=this.layout;var content=document.createDocumentFragment();var container=document.createElement('div');if(this.options.classNames){container.classList.add.apply(container.classList,this.options.classNames);}
|
||
if(layout.specificCssRule){container.classList.add(layout.layoutName);}
|
||
if(this.options.showCandidatePanel){var candidatePanel=this.createCandidatePanel(this.layout.imEngine);candidatePanel.render();container.classList.add('candidate-panel');container.appendChild(candidatePanel.element);this.candidatePanel=candidatePanel;}
|
||
if('handwritingPadOptions'in layout){var target={isHandwritingPad:true};var handwritingPadView=new HandwritingPadView(target,null,this.viewManager);handwritingPadView.render();content.appendChild(handwritingPadView.element);this.handwritingPadView=handwritingPadView;}
|
||
container.classList.add('rows-'+layout.keys.length);if(layout.keys.length!==4&&layout.keys.length!==5){console.warn('LayoutPageView: Layout to render is neither 4 or 5 rows; '+'might not be render with expected height.',layout.keys.length);}
|
||
layout.keys.forEach((function buildKeyboardRow(row,nrow){var kbRow=document.createElement('div');var rowLayoutWidth=0;kbRow.classList.add('keyboard-row');kbRow.classList.add('row'+nrow);if(nrow===layout.keys.length-1){kbRow.classList.add('keyboard-last-row');}
|
||
var keyCount=0;var keyMap=new Map();row.forEach(function calcRowRatio(key,keyIndex){var ratio=key.ratio||1;rowLayoutWidth+=ratio;});if('handwritingPadOptions'in layout&&nrow<layout.handwritingPadOptions.rowspan){rowLayoutWidth+=layout.handwritingPadOptions.ratio;}
|
||
row.forEach((function buildKeyboardColumns(key,keyIndex){var ratio=key.ratio||1;var target=Object.freeze(Object.create(key));var options={classNames:[],outputChar:key.uppercaseValue,outerRatio:ratio,innerRatio:ratio};if(layout.keyClassName){options.classNames=options.classNames.concat(layout.keyClassName.split(' '));}
|
||
var layoutWidth=layout.width||10;if(layoutWidth!=rowLayoutWidth&&(keyIndex===0||keyIndex===row.length-1)){options.outerRatio=ratio+((layoutWidth-rowLayoutWidth)/2);}
|
||
options.altOutputChar=key.value;var keyView=new KeyView(target,options,this.viewManager);keyView.render();kbRow.appendChild(keyView.element);keyMap.set(keyCount,keyView);keyCount++;}.bind(this)));this.rows.set(nrow,{element:kbRow,keys:keyMap});content.appendChild(kbRow);}).bind(this));container.appendChild(content);container.setAttribute('lang',layout.lang);this.element=container;};LayoutPageView.prototype.setUpperCaseLock=function setUpperCaseLock(state){this.isUpperCase=(state.isUpperCase||state.isUpperCaseLocked);var container=this.element;container.classList.toggle('lowercase',!this.isUpperCase);var capsLockKey=container.querySelector('button:not([disabled])'+'[data-keycode="'+KeyboardEvent.DOM_VK_CAPS_LOCK+'"]');if(!capsLockKey){return;}
|
||
if(state.isUpperCaseLocked){capsLockKey.classList.remove('kbr-key-active');capsLockKey.classList.add('kbr-key-hold');}else if(state.isUpperCase){capsLockKey.classList.add('kbr-key-active');capsLockKey.classList.remove('kbr-key-hold');}else{capsLockKey.classList.remove('kbr-key-active');capsLockKey.classList.remove('kbr-key-hold');}
|
||
capsLockKey.setAttribute('aria-pressed',state.isUpperCaseLocked||state.isUpperCase);};LayoutPageView.prototype.hide=function hide(){delete this.element.dataset.active;};LayoutPageView.prototype.show=function show(){this.element.dataset.active=true;};LayoutPageView.prototype.highlightKey=function highlightKey(target){var keyView=this.viewManager.getView(target);keyView.highlight({upperCase:this.isUpperCase});};LayoutPageView.prototype.unHighlightKey=function unHighlightKey(target){var keyView=this.viewManager.getView(target);keyView.unHighlight();};LayoutPageView.prototype.resize=function resize(totalWidth){this.options.totalWidth=totalWidth;if(this.handwritingPadView){var placeHolderWidth=totalWidth/(this.layout.width||10);var width=Math.floor(placeHolderWidth*this.layout.handwritingPadOptions.ratio);var height=this.rows.get(0).element.clientHeight*this.layout.handwritingPadOptions.rowspan;this.handwritingPadView.resize(width,height);}};LayoutPageView.prototype.getVisualData=function getVisualData(){var totalWidth=this.options.totalWidth;var keyArray=this.keyArrays.get(totalWidth);if(keyArray){return keyArray;}
|
||
keyArray=[];this.rows.forEach(function(row){row.keys.forEach(function(keyView){var visualKey=keyView.element.querySelector('.visual-wrapper');keyArray.push({code:keyView.target.keyCode,x:visualKey.offsetLeft,y:visualKey.offsetTop,width:visualKey.clientWidth,height:visualKey.clientHeight});});});this.keyArrays.set(totalWidth,keyArray);return keyArray;};LayoutPageView.prototype.createCandidatePanel=function(inputMethodName){var candidatePanel;var target={};var options={className:inputMethodName,totalWidth:this.options.totalWidth};switch(inputMethodName){case'latin':candidatePanel=new LatinCandidatePanelView(target,options,this.viewManager);break;case'vietnamese':options.widthUnit=1;candidatePanel=new CandidatePanelView(target,options,this.viewManager);break;default:candidatePanel=new CandidatePanelView(target,options,this.viewManager);break;}
|
||
return candidatePanel;};LayoutPageView.prototype.resetCandidatePanel=function(){if(!this.candidatePanel){return;}
|
||
this.candidatePanel.resetScroll();};LayoutPageView.prototype.showCandidates=function(candidates){if(!this.candidatePanel){return;}
|
||
this.candidatePanel.showCandidates(candidates);};LayoutPageView.prototype.showMoreCandidates=function(rowLimit,candidates){if(!this.candidatePanel){return;}
|
||
this.candidatePanel.showMoreCandidates(rowLimit,candidates);};LayoutPageView.prototype.getNumberOfCandidatesPerRow=function(){if(!this.candidatePanel){return;}
|
||
return this.candidatePanel.COUNT_PER_ROW;};LayoutPageView.prototype.getHeight=function(){var height=this.rows.size*this.getKeyHeight();if(this.candidatePanel){height+=this.candidatePanel.getHeight();}
|
||
return height;};LayoutPageView.prototype.getKeyHeight=function(){var keyHeightInRem=0.8;if(this.viewManager.screenInPortraitMode()){if(this.layout.keys.length===5){keyHeightInRem+=3.4;}else{keyHeightInRem+=4.5;}}else{if(this.layout.keys.length===5){keyHeightInRem+=2.85;}else{keyHeightInRem+=3.8;}}
|
||
return keyHeightInRem*this.viewManager.getRemToPx();};LayoutPageView.prototype.destroy=function(){if(this.element){this.element.remove();}};exports.LayoutPageView=LayoutPageView;})(window);;'use strict';(function(exports){function SwipeablePageView(){LayoutPageView.apply(this,arguments);}
|
||
SwipeablePageView.prototype=Object.create(LayoutPageView.prototype);SwipeablePageView.prototype.render=function(){var layout=this.layout;var container=document.createElement('div');if(this.options.classNames){container.classList.add.apply(container.classList,this.options.classNames);}
|
||
if(layout.specificCssRule){container.classList.add(layout.layoutName);}
|
||
var swipeablePanel=new SwipeablePanelView(this.layout,{totalWidth:this.options.totalWidth},this.viewManager);swipeablePanel.render();this.swipeablePanel=swipeablePanel;container.appendChild(swipeablePanel.element);layout.keys.forEach(function buildKeyboardRow(row){var kbRow=document.createElement('div');kbRow.classList.add('keyboard-row','swipe-switching-buttons');row.forEach(function buildKeyboardColumns(key,keyIndex){var ratio=key.ratio||1;var target=Object.freeze(Object.create(key));var options={classNames:[],outputChar:key.uppercaseValue,outerRatio:ratio,innerRatio:ratio};if(layout.keyClassName){options.classNames=options.classNames.concat(layout.keyClassName.split(' '));}
|
||
var keyView=new KeyView(target,options,this.viewManager);keyView.render();kbRow.appendChild(keyView.element);},this);container.appendChild(kbRow);},this);if(!layout.secondLayout){container.classList.add('uppercase-only');}
|
||
this.element=container;};SwipeablePageView.prototype.resize=function resize(totalWidth){this.options.totalWidth=totalWidth;this.swipeablePanel.resize(totalWidth);};SwipeablePageView.prototype.getHeight=function(){return this.element.clientHeight;};exports.SwipeablePageView=SwipeablePageView;})(window);;'use strict';(function(exports){function CandidateView(){BaseView.apply(this,arguments);}
|
||
CandidateView.prototype=Object.create(BaseView.prototype);CandidateView.prototype.render=function render(){var span=document.createElement('span');span.textContent=this.target.text;span.style.flex=this.options.unit;span.dataset.data=this.target.data;this.element=span;this.viewManager.registerView(this.target,this);};function CandidateToggleButtonView(){BaseView.apply(this,arguments);}
|
||
CandidateToggleButtonView.prototype=Object.create(BaseView.prototype);CandidateToggleButtonView.prototype.render=function(){var toggleButton=document.createElement('div');toggleButton.classList.add('keyboard-candidate-panel-toggle-button');toggleButton.classList.add('hide');this.element=toggleButton;this.viewManager.registerView(this.target,this);};CandidateToggleButtonView.prototype.show=function(){this.element.classList.remove('hide');};CandidateToggleButtonView.prototype.hide=function(){this.element.classList.add('hide');};function CandidatePanelView(target,options,viewManager){BaseView.apply(this,arguments);}
|
||
CandidatePanelView.prototype.COUNT_PER_ROW=8;CandidatePanelView.prototype.HEIGHT_IN_REM=3.2;CandidatePanelView.prototype.render=function render(){var candidatePanel=document.createElement('div');candidatePanel.setAttribute('role','group');candidatePanel.dataset.l10nId='wordSuggestions2';candidatePanel.classList.add('keyboard-candidate-panel');if(this.options.className){candidatePanel.classList.add(this.options.className);}
|
||
var suggestionsContainer=document.createElement('div');suggestionsContainer.classList.add('suggestions-container');suggestionsContainer.setAttribute('role','listbox');candidatePanel.appendChild(suggestionsContainer);this.suggestionsContainer=suggestionsContainer;var KEYCODE_TOGGLE_CANDIDATE_PANEL=-4;this.toggleButton=new CandidateToggleButtonView({keyCode:KEYCODE_TOGGLE_CANDIDATE_PANEL},null,this.viewManager);this.toggleButton.render();candidatePanel.appendChild(this.toggleButton.element);this.element=candidatePanel;};CandidatePanelView.prototype.showCandidates=function(candidates){if(!this.element){console.error('CandidatePanelView: CandidatePanel is not ready yet!');return;}
|
||
var candidatePanel=this.element;candidatePanel.dataset.candidateIndicator=0;this.suggestionsContainer.innerHTML='';this.toggleButton.hide();var docFragment=this.renderCandidatePanel(1,candidates,true);this.suggestionsContainer.appendChild(docFragment);};CandidatePanelView.prototype.renderCandidatePanel=function(rowLimit,candidates,indentFirstRow){var candidatePanel=this.element;var docFragment=document.createDocumentFragment();if(candidates.length===0){candidatePanel.dataset.rowCount=0;return docFragment;}
|
||
var rowDiv=document.createElement('div');rowDiv.classList.add('candidate-row');if(indentFirstRow){rowDiv.classList.add('candidate-row-first');}
|
||
var nowUnit=0;var rowCount=0;if(rowLimit<0){rowLimit=Number.Infinity;}
|
||
var candidatesLength=candidates.length;var dummyEl=null;var i=0;candidates.some(function(candidate,index){var cand,data;if(typeof candidate=='string'){cand=data=candidate;}else{cand=candidate[0];data=candidate[1];}
|
||
var unit=this.options.widthUnit?this.options.widthUnit:(cand.length>>1)+1;var candidateView=new CandidateView({suggestion:true,selection:true,text:cand,data:data},{unit:unit},this.viewManager);candidateView.render();nowUnit+=unit;i++;var needBreak=false;if(rowCount===0&&indentFirstRow&&nowUnit>=this.COUNT_PER_ROW&&index!=candidatesLength-1){needBreak=true;}
|
||
if(nowUnit>this.COUNT_PER_ROW||needBreak){if(rowCount===0&&needBreak){this.toggleButton.show();dummyEl=document.createElement('span');dummyEl.style.flex=this.COUNT_PER_ROW-(nowUnit-unit);rowDiv.appendChild(dummyEl);}
|
||
if(rowCount>=rowLimit-1){return true;}
|
||
docFragment.appendChild(rowDiv);rowCount++;rowDiv=document.createElement('div');rowDiv.classList.add('candidate-row');nowUnit=unit;}
|
||
rowDiv.appendChild(candidateView.element);},this);if(nowUnit<this.COUNT_PER_ROW&&typeof this.options.widthUnit==='undefined'){dummyEl=document.createElement('span');dummyEl.style.flex=this.COUNT_PER_ROW-nowUnit;rowDiv.appendChild(dummyEl);}
|
||
if(i!=candidatesLength){candidatePanel.dataset.truncated=true;}else{delete candidatePanel.dataset.truncated;}
|
||
candidatePanel.dataset.rowCount=rowCount+1;candidatePanel.dataset.candidateIndicator=parseInt(candidatePanel.dataset.candidateIndicator)+i;docFragment.appendChild(rowDiv);rowDiv=null;return docFragment;};CandidatePanelView.prototype.showMoreCandidates=function(rowLimit,candidates){if(!candidates){return;}
|
||
if(!rowLimit){rowLimit=-1;}
|
||
this.suggestionsContainer.appendChild(this.renderCandidatePanel(rowLimit,candidates));};CandidatePanelView.prototype.resetScroll=function(){this.suggestionsContainer.scrollTop=this.suggestionsContainer.scrollLeft=0;};CandidatePanelView.prototype.getHeight=function(){return this.HEIGHT_IN_REM*this.viewManager.getRemToPx();};exports.CandidatePanelView=CandidatePanelView;})(window);;'use strict';(function(exports){function LatinCandidateView(){BaseView.apply(this,arguments);}
|
||
LatinCandidateView.prototype=Object.create(BaseView.prototype);LatinCandidateView.prototype.render=function render(){var div=document.createElement('div');div.setAttribute('role','option');var span=ViewUtils.fitText(div,this.target.text,this.options.candidatesLength,this.options.totalWidth);span.setAttribute('role','presentation');span.dataset.data=this.target.data;if(this.options.correction){div.classList.add('autocorrect');}
|
||
div.appendChild(span);this.element=div;this.viewManager.registerView(this.target,this);};function DismissButtonView(){BaseView.apply(this,arguments);}
|
||
DismissButtonView.prototype=Object.create(BaseView.prototype);DismissButtonView.prototype.render=function render(){var dismissButton=document.createElement('div');dismissButton.classList.add('dismiss-suggestions-button');dismissButton.classList.add('hide');dismissButton.setAttribute('role','button');dismissButton.dataset.l10nId='dismiss2';this.element=dismissButton;this.viewManager.registerView(this.target,this);};function LatinCandidatePanelView(){CandidatePanelView.apply(this,arguments);}
|
||
LatinCandidatePanelView.prototype=Object.create(CandidatePanelView.prototype);LatinCandidatePanelView.prototype.HEIGHT_IN_REM=3.1;LatinCandidatePanelView.prototype.render=function render(){var candidatePanel=document.createElement('div');candidatePanel.setAttribute('role','group');candidatePanel.dataset.l10nId='wordSuggestions2';candidatePanel.classList.add('keyboard-candidate-panel');if(this.options.className){candidatePanel.classList.add(this.options.className);}
|
||
this.dismissButton=new DismissButtonView({isDismissSuggestionsButton:true},null,this.viewManager);this.dismissButton.render();candidatePanel.appendChild(this.dismissButton.element);var suggestionsContainer=document.createElement('div');suggestionsContainer.classList.add('suggestions-container');suggestionsContainer.setAttribute('role','listbox');candidatePanel.appendChild(suggestionsContainer);this.suggestionsContainer=suggestionsContainer;this.element=candidatePanel;};LatinCandidatePanelView.prototype.showCandidates=function(candidates){if(!this.element){console.error('LatinCandidatePanelView: CandidatePanel is not ready yet!');return;}
|
||
if(candidates.length===0){this.dismissButton.hide();}else{this.dismissButton.show();}
|
||
this.suggestionsContainer.innerHTML='';candidates.forEach(function buildCandidateEntry(candidate){if(!candidate){return;}
|
||
var text,data,correction=false;if(typeof candidate==='string'){if(candidate[0]==='*'){candidate=candidate.substring(1);correction=true;}
|
||
data=text=candidate;}else{text=candidate[0];data=candidate[1];}
|
||
var candidateView=new LatinCandidateView({suggestion:true,text:text,data:data},{candidatesLength:candidates.length,correction:correction,totalWidth:this.options.totalWidth},this.viewManager);candidateView.render();this.suggestionsContainer.appendChild(candidateView.element);},this);};exports.LatinCandidatePanelView=LatinCandidatePanelView;})(window);;'use strict';(function(exports){var KeyboardConsole=function KeyboardConsole(){this._timers=null;};KeyboardConsole.prototype.start=function(){var timers=this._timers=new Map();timers.set('domLoading',performance.timing.domLoading);this._startTime=Date.now();};KeyboardConsole.prototype.LOG_LEVEL=0;KeyboardConsole.prototype.trace=function(){if(this.LOG_LEVEL<3){return;}
|
||
console.trace.apply(console,arguments);};KeyboardConsole.prototype.time=function(timerName){if(this.LOG_LEVEL<2){return;}
|
||
console.time(timerName);};KeyboardConsole.prototype.timeEnd=function(timerName){if(this.LOG_LEVEL<2){return;}
|
||
if(this._timers.has(timerName)){console.log(timerName+': '+
|
||
(Date.now()-this._timers.get(timerName))+'ms');return;}
|
||
console.timeEnd(timerName);};KeyboardConsole.prototype.log=function(){if(this.LOG_LEVEL<2){return;}
|
||
console.log.apply(console,arguments);};KeyboardConsole.prototype.info=function(){if(this.LOG_LEVEL<1){return;}
|
||
console.info.apply(console,arguments);};exports.KeyboardConsole=KeyboardConsole;})(window);;'use strict';(function(exports){var InputMethods={};InputMethods['default']={init:function(glue){this._glue=glue;},click:function(keyCode,isRepeat){return this._glue.sendKey(keyCode,isRepeat);},handleKey:function(dict){return this._glue.sendKey(dict);},displaysCandidates:function(){return false;}};var InputMethodGlue=function InputMethodGlue(){this.app=null;};InputMethodGlue.prototype.SOURCE_DIR='./js/imes/';InputMethodGlue.prototype.init=function(app,imEngineName){this.app=app;this.imEngineName=imEngineName;this.path=this.SOURCE_DIR+imEngineName;};InputMethodGlue.prototype.sendCandidates=function(candidates){this.app.console.trace();if(!this.app.inputContext){console.warn('InputMethodGlue: call sendCandidates() when '+'inputContext does not exist.');return;}
|
||
this.app.candidatePanelManager.updateCandidates(candidates);};InputMethodGlue.prototype.setComposition=function(symbols,cursor){this.app.console.trace();if(!this.app.inputContext){console.warn('InputMethodGlue: call setComposition() when '+'inputContext does not exist.');return;}
|
||
cursor=cursor||symbols.length;this.app.console.info('inputContext.setComposition()');return this.app.inputContext.setComposition(symbols,cursor).catch(function(e){console.warn('InputMethodGlue: setComposition() rejected with error',e);this.app.console.log(symbols,cursor);return Promise.reject(e);}.bind(this));};InputMethodGlue.prototype.endComposition=function(text){this.app.console.trace();if(!this.app.inputContext){console.warn('InputMethodGlue: call endComposition() when '+'inputContext does not exist.');return;}
|
||
text=text||'';this.app.console.info('inputContext.endComposition()');return this.app.inputContext.endComposition(text).catch(function(e){console.warn('InputMethodGlue: endComposition() rejected with error',e);this.app.console.log(text);return Promise.reject(e);}.bind(this));};InputMethodGlue.prototype.sendKey=function(keyCodeOrDict,isRepeat){this.app.console.trace();if(!this.app.inputContext){console.warn('InputMethodGlue: call sendKey() when '+'inputContext does not exist.');return Promise.reject();}
|
||
var promise;if(typeof keyCodeOrDict==='object'){this.app.console.info('inputContext.sendKey(), dict:',keyCodeOrDict);promise=this.app.inputContext.sendKey(keyCodeOrDict);}else{this.app.console.info('inputContext.sendKey(), code:'+keyCodeOrDict);switch(keyCodeOrDict){case KeyEvent.DOM_VK_BACK_SPACE:promise=this.app.inputContext.sendKey(keyCodeOrDict,0,0,isRepeat);break;case KeyEvent.DOM_VK_RETURN:promise=this.app.inputContext.sendKey(keyCodeOrDict,0,0);break;default:promise=this.app.inputContext.sendKey(0,keyCodeOrDict,0);break;}}
|
||
return promise.catch(function(e){console.warn('InputMethodGlue: sendKey() rejected with error',e);this.app.console.log(keyCodeOrDict,isRepeat);return Promise.reject(e);}.bind(this));};InputMethodGlue.prototype.sendString=function(str){this.app.console.trace();for(var i=0;i<str.length;i++){this.sendKey(str.charCodeAt(i));}};InputMethodGlue.prototype.setLayoutPage=function(newpage){this.app.console.trace();if(!this.app.inputContext){console.warn('InputMethodGlue: call setLayoutPage() when '+'inputContext does not exist.');return;}
|
||
if(newpage!==this.app.layoutManager.PAGE_INDEX_DEFAULT){throw new Error('InputMethodGlue: '+'imEngine is only allowed to switch to default page');}
|
||
this.app.setLayoutPage(newpage);};InputMethodGlue.prototype.setUpperCase=function(state){this.app.console.trace();if(!this.app.inputContext){console.warn('InputMethodGlue: call setUpperCase() when '+'inputContext does not exist.');return;}
|
||
this.app.upperCaseStateManager.switchUpperCaseState(state);};InputMethodGlue.prototype.replaceSurroundingText=function(text,offset,length){this.app.console.trace();if(!this.app.inputContext){console.warn('InputMethodGlue: call replaceSurroundingText() when '+'inputContext does not exist.');return Promise.reject();}
|
||
this.app.console.info('inputContext.replaceSurroundingText()');var p=this.app.inputContext.replaceSurroundingText(text,offset,length);p.catch(function(e){console.warn('InputMethodGlue: '+'replaceSurroundingText() rejected with error',e);this.app.console.log(text,offset,length);return Promise.reject(e);}.bind(this));return p;};InputMethodGlue.prototype.getNumberOfCandidatesPerRow=function(){return this.app.viewManager.getNumberOfCandidatesPerRow();};InputMethodGlue.prototype.getData=function(dataPath){return this.app.inputMethodDatabaseLoader.load(this.imEngineName,dataPath);};var InputMethodLoader=function(app){this.app=app;};InputMethodLoader.prototype.SOURCE_DIR='./js/imes/';InputMethodLoader.prototype.start=function(){this._initializedIMEngines={};this._imEnginesPromises={};this.initPreloadedInputMethod();};InputMethodLoader.prototype.initPreloadedInputMethod=function(){var imEngineName;var InputMethods=exports.InputMethods;for(imEngineName in InputMethods){this.initInputMethod(imEngineName);this._imEnginesPromises[imEngineName]=Promise.resolve(this._initializedIMEngines[imEngineName]);}};InputMethodLoader.prototype.getInputMethod=function(imEngineName){return this._initializedIMEngines[imEngineName];};InputMethodLoader.prototype.getInputMethodAsync=function(imEngineName){if(this._imEnginesPromises[imEngineName]){return this._imEnginesPromises[imEngineName];}
|
||
var p=new Promise(function(resolve,reject){var script=document.createElement('script');script.onload=resolve;script.onerror=function(){this._imEnginesPromises[imEngineName]=null;console.error('InputMethodLoader: unable to load '+imEngineName+'.');reject();}.bind(this);script.src=this.SOURCE_DIR+imEngineName+'/'+imEngineName+'.js';document.body.appendChild(script);}.bind(this)).then(function(){return this.initInputMethod(imEngineName);}.bind(this)).then(function(){return this._initializedIMEngines[imEngineName];}.bind(this));this._imEnginesPromises[imEngineName]=p;return p;};InputMethodLoader.prototype.initInputMethod=function(imEngineName){var InputMethods=exports.InputMethods;if(!(imEngineName in InputMethods)){throw new Error('InputMethodLoader: '+imEngineName+' did not expose itself correctly.');}
|
||
var imEngine=InputMethods[imEngineName];var glue=new InputMethodGlue();glue.init(this.app,imEngineName);this._initializedIMEngines[imEngineName]=InputMethods[imEngineName];InputMethods[imEngineName]=null;return imEngine.init(glue);};var InputMethodManager=function InputMethodManager(app){this.currentIMEngine=null;this.app=app;};InputMethodManager.prototype.start=function(){this.loader=new InputMethodLoader(this.app);this.loader.start();this.imEngineSettings=new IMEngineSettings();this.imEngineSettings.promiseManager=this.app.settingsPromiseManager;this.imEngineSettings.initSettings().catch(function rejected(){console.error('Fatal Error! Failed to get initial imEngine settings.');});this.currentIMEngine=this.loader.getInputMethod('default');};InputMethodManager.prototype.activateIMEngine=function(imEngineName){this.app.console.log('InputMethodManager.activateIMEngine()',imEngineName);var loaderPromise=this.loader.getInputMethodAsync(imEngineName);var settingsPromise=this.imEngineSettings.initSettings();var p=Promise.all([loaderPromise,settingsPromise]).then(function(values){var imEngine=values[0];if(typeof imEngine.activate==='function'){var settingsValues=values[1];var currentPage=this.app.layoutManager.currentPage;var lang=this.app.layoutManager.currentPage.autoCorrectLanguage||this.app.layoutManager.currentPage.handwritingLanguage;var correctPunctuation='autoCorrectPunctuation'in currentPage?currentPage.autoCorrectPunctuation:true;var inputContext=this.app.inputContext;this.app.console.log('InputMethodManager::currentIMEngine.activate()');imEngine.activate(lang,{type:inputContext.inputType,inputmode:inputContext.inputMode,selectionStart:inputContext.selectionStart,selectionEnd:inputContext.selectionEnd,text:inputContext.text},{suggest:settingsValues.suggestionsEnabled,correct:settingsValues.correctionsEnabled,correctPunctuation:correctPunctuation});}
|
||
if(typeof imEngine.stateChange==='function'){this.app.inputContext.addEventListener('selectionchange',this);this.app.inputContext.addEventListener('surroundingtextchange',this);}
|
||
this.currentIMEngine=imEngine;}.bind(this));return p;};InputMethodManager.prototype.deactivateIMEngine=function(){if(this.currentIMEngine&&this.currentIMEngine.deactivate){this.app.console.log('InputMethodManager::currentIMEngine.deactivate()');this.currentIMEngine.deactivate();}
|
||
if(this.app.inputContext){this.app.inputContext.removeEventListener('selectionchange',this);this.app.inputContext.removeEventListener('surroundingtextchange',this);}
|
||
this.currentIMEngine=this.loader.getInputMethod('default');};InputMethodManager.prototype.handleEvent=function(evt){this.app.console.info('InputMethodManager.handleEvent()',evt);var inputContext=this.app.inputContext;var inputContextStates={ownAction:evt.detail.ownAction,type:inputContext.inputType,inputmode:inputContext.inputMode,selectionStart:inputContext.selectionStart,selectionEnd:inputContext.selectionEnd,text:inputContext.text};this.app.console.log('InputMethodManager::currentIMEngine.stateChange()',inputContextStates);this.currentIMEngine.stateChange(inputContextStates);};exports.InputMethods=InputMethods;exports.InputMethodGlue=InputMethodGlue;exports.InputMethodLoader=InputMethodLoader;exports.InputMethodManager=InputMethodManager;})(window);;'use strict';(function(exports){var InputMethodDatabaseConfig=function(){this._configPromise=null;};InputMethodDatabaseConfig.prototype.CONFIG_FILE_PATH='./js/settings/layouts.json';InputMethodDatabaseConfig.prototype.start=function(){this._getConfig();};InputMethodDatabaseConfig.prototype.stop=function(){this._configPromise=null;};InputMethodDatabaseConfig.prototype.isDataPreloaded=function(imEngineName,dataPath){return this._configPromise.then(function(layouts){if(!layouts){return true;}
|
||
var layout=layouts.find(function(layout){return(layout.dictFilePath===dataPath&&layout.imEngineId===imEngineName);});if(!layout){console.warn('InputMethodDatabaseConfig: '+'Ask for isDataPreloaded for data unlisted in config','imEngineName=',imEngineName,'dataPath=',dataPath);return true;}
|
||
return layout.preloaded;});};InputMethodDatabaseConfig.prototype.isAllDataPreloaded=function(){return this._configPromise.then(function(layouts){if(!layouts){return true;}
|
||
return layouts.every(function(layout){return layout.preloaded;});});};InputMethodDatabaseConfig.prototype._getConfig=function(){this._configPromise=new Promise(function(resolve,reject){var xhr=new XMLHttpRequest();xhr.open('GET',this.CONFIG_FILE_PATH);xhr.responseType='json';xhr.onload=function(){if(xhr.response){resolve(xhr.response);}else{resolve(null);}};xhr.onerror=function(){reject();};xhr.send();}.bind(this)).catch(function(e){e&&console.error(e);return null;});};var InputMethodDatabaseLoader=function InputMethodDatabaseLoader(){this.config=null;this._loadDBStorePromise=null;this.dbStore=null;};InputMethodDatabaseLoader.prototype.DATABASE_NAME='imEngineData';InputMethodDatabaseLoader.prototype.SOURCE_DIR='./js/imes/';InputMethodDatabaseLoader.prototype.start=function(){this.config=new InputMethodDatabaseConfig();this.config.start();this._loadDBStorePromise=this.config.isAllDataPreloaded().then(function(allDataPreloaded){if(allDataPreloaded){return;}
|
||
this.dbStore=new PromiseStorage(this.DATABASE_NAME);this.dbStore.start();}.bind(this)).catch(function(e){e&&console.error(e);});};InputMethodDatabaseLoader.prototype.stop=function(){this.config.stop();this.config=null;return this._loadDBStorePromise.then(function(){if(this.dbStore){this.dbStore.stop();this.dbStore=null;}
|
||
this._loadDBStorePromise=null;}.bind(this));};InputMethodDatabaseLoader.prototype.load=function(imEngineName,dataPath){var p=this.config.isDataPreloaded(imEngineName,dataPath).then(function(isDataPreloaded){if(isDataPreloaded){var url=this.SOURCE_DIR+imEngineName+'/'+dataPath;return this._loadPreloadData(url);}else{var databaseId=imEngineName+'/'+dataPath;return this._loadDBStoreData(databaseId);}}.bind(this)).catch(function(e){e&&console.error('InputMethodDatabaseLoader: Failed to load data.','imEngineName=',imEngineName,'dataPath=',dataPath,'error=',e);throw e;});return p;};InputMethodDatabaseLoader.prototype._loadPreloadData=function(url){return new Promise(function(resolve,reject){var xhr=new XMLHttpRequest();xhr.open('GET',url,true);xhr.responseType='arraybuffer';xhr.onload=function(){if(xhr.status!==404&&xhr.response&&xhr.response.byteLength){resolve(xhr.response);}else{reject(xhr.statusText);}};xhr.send();}.bind(this));};InputMethodDatabaseLoader.prototype._loadDBStoreData=function(databaseId){return this._loadDBStorePromise.then(function(){if(!this.dbStore){console.error('InputMethodDatabaseLoader:'+'Asked to load data from IndexedDB but build config indicates'+' otherwise.');throw undefined;}
|
||
return this.dbStore.getItem(databaseId);}.bind(this));};exports.InputMethodDatabaseConfig=InputMethodDatabaseConfig;exports.InputMethodDatabaseLoader=InputMethodDatabaseLoader;})(window);;'use strict';(function(exports){var PromiseStorage=function(name){this.name=name;if(typeof this.name!=='string'||this.name===''){throw new Error('PromiseStorage: Need a storage name.');}
|
||
this._openPromise=null;};PromiseStorage.prototype.DB_VERSION=1;PromiseStorage.prototype.STORE_NAME='keyvaluepairs';PromiseStorage.prototype.start=function(){return this._getDatabase().catch(function(e){this._openPromise=null;throw e;}.bind(this));};PromiseStorage.prototype.stop=function(){if(!this._openPromise){return Promise.resolve();}
|
||
return this._getDatabase().then(function(db){db.close();this._openPromise=null;});};PromiseStorage.prototype._getDatabase=function(){if(this._openPromise){return this._openPromise;}
|
||
var p=new Promise(function(resolve,reject){var req=window.indexedDB.open(this.name,this.DB_VERSION);req.onerror=function(){reject(req.error);};req.onsuccess=function(evt){resolve(req.result);};req.onupgradeneeded=function(evt){var db=req.result;if(evt.oldVersion<1){db.createObjectStore(this.STORE_NAME);}}.bind(this);}.bind(this));this._openPromise=p;return p;};PromiseStorage.prototype._getTxn=function(type,callback){return this._getDatabase().then(function(db){var txn=db.transaction(this.STORE_NAME,type);return callback(txn);}.bind(this));};PromiseStorage.prototype.getItems=function(names){return this._getTxn('readonly',function(txn){var store=txn.objectStore(this.STORE_NAME);var reqPromises=names.map(function(name){return new Promise(function(resolve,reject){var req=store.get(name);req.onerror=function(e){reject(req.error);};req.onsuccess=function(){resolve(req.result);};});},this);return new Promise(function(resolve){txn.oncomplete=function(){resolve(Promise.all(reqPromises));};});}.bind(this)).catch(function(e){e&&console.error(e);return Promise.reject(e);});};PromiseStorage.prototype.getItem=function(name){return this._getTxn('readonly',function(txn){return new Promise(function(resolve,reject){var req=txn.objectStore(this.STORE_NAME).get(name);req.onerror=function(e){reject(req.error);};txn.oncomplete=function(){resolve(req.result);};}.bind(this));}.bind(this)).catch(function(e){e&&console.error(e);return Promise.reject(e);});};PromiseStorage.prototype.setItem=function(name,data){return this._getTxn('readwrite',function(txn){return new Promise(function(resolve,reject){var store=txn.objectStore(this.STORE_NAME);var req=store.put(data,name);req.onerror=function(e){reject(req.error);};txn.oncomplete=function(){resolve(req.result);};}.bind(this));}.bind(this)).catch(function(e){e&&console.error(e);return Promise.reject(e);});};PromiseStorage.prototype.setItems=function(items){return this._getTxn('readwrite',function(txn){var store=txn.objectStore(this.STORE_NAME);var reqPromises=Object.keys(items).map(function(name){var data=items[name];return new Promise(function(resolve,reject){var req=store.put(data,name);req.onerror=function(e){reject(req.error);};req.onsuccess=function(){resolve(req.result);};});},this);return new Promise(function(resolve){txn.oncomplete=function(){resolve(Promise.all(reqPromises));};});}.bind(this)).catch(function(e){e&&console.error(e);return Promise.reject(e);});};PromiseStorage.prototype.deleteItem=function(name){return this._getTxn('readwrite',function(txn){return new Promise(function(resolve,reject){var req=txn.objectStore(this.STORE_NAME).delete(name);req.onerror=function(e){reject(req.error);};txn.oncomplete=function(){resolve();};}.bind(this));}.bind(this)).catch(function(e){e&&console.error(e);return Promise.reject(e);});};exports.PromiseStorage=PromiseStorage;}(window));;'use strict';(function(exports){var SettingsPromiseManager=function SettingsPromiseManager(){this._readLock=null;this._writeLock=null;};SettingsPromiseManager.prototype._cleanLock=function(type){var propName;switch(type){case'read':propName='_readLock';break;case'write':propName='_writeLock';break;default:throw new Error('SettingsPromiseManager: Not such type.');}
|
||
if(this[propName]&&this[propName].closed){this[propName]=null;}};SettingsPromiseManager.prototype._getLock=function(type){var propName;switch(type){case'read':propName='_readLock';break;case'write':propName='_writeLock';break;default:throw new Error('SettingsPromiseManager: Not such type.');}
|
||
if(this[propName]&&!this[propName].closed){return this[propName];}
|
||
var settings=window.navigator.mozSettings;this[propName]=settings.createLock();return this[propName];};SettingsPromiseManager.prototype._getReadLock=function(){return this._getLock('read');};SettingsPromiseManager.prototype._getWriteLock=function(){return this._getLock('write');};SettingsPromiseManager.prototype.get=function(obj){if(typeof obj==='string'){return this.getOne(obj);}
|
||
if(typeof obj!=='object'){throw new Error('SettingsPromiseManager.get: '+'require object, array, or string.');}
|
||
var arr=Array.isArray(obj)?obj:Object.keys(obj);var promise=Promise.all(arr.map(function(key){return this.getOne(key);},this));return promise;};SettingsPromiseManager.prototype.getOne=function(key){var promise=new Promise(function(resolve,reject){var req=this._getReadLock().get(key);req.onsuccess=function(){this._cleanLock('read');resolve(req.result[key]);}.bind(this);req.onerror=function(){this._cleanLock('read');reject();}.bind(this);}.bind(this));return promise;};SettingsPromiseManager.prototype.set=function(obj,value){if(typeof obj==='string'){return this.setOne(obj,value);}
|
||
if(typeof obj!=='object'){throw new Error('SettingsPromiseManager.set: require object.');}
|
||
var promise=new Promise(function(resolve,reject){var req=this._getWriteLock().set(obj);req.onsuccess=function(){this._cleanLock('write');resolve();}.bind(this);req.onerror=function(){this._cleanLock('write');reject();}.bind(this);}.bind(this));return promise;};SettingsPromiseManager.prototype.setOne=function(key,value){var obj={};obj[key]=value;return this.set(obj);};SettingsPromiseManager.prototype.updateOne=function(key,callback){var promise=new Promise(function(resolve,reject){var lock=this._getWriteLock();var req=lock.get(key);req.onsuccess=function(){var newValue=callback(req.result[key]);var obj={};obj[key]=newValue;resolve(lock.set(obj));}.bind(this);req.onerror=function(){reject(req.error);}.bind(this);}.bind(this)).then(function(){this._cleanLock('write');}.bind(this),function(e){this._cleanLock('write');throw e;}.bind(this));return promise;};var SettingsManagerBase=function(){this.initialized=false;this._callbacks=null;this._values={};this._initPromise=null;};SettingsManagerBase.prototype.onsettingchange=null;SettingsManagerBase.prototype.KEYS=[];SettingsManagerBase.prototype.PROPERTIES=[];SettingsManagerBase.prototype.getSettingsSync=function(){return this._values;};SettingsManagerBase.prototype.initSettings=function(){if(this._initPromise){return this._initPromise;}
|
||
var promise=this.promiseManager.get(this.KEYS).then(function(results){results.forEach(function(value,i){this._values[this.PROPERTIES[i]]=value;},this);this.startObserve();this.initialized=true;return this._values;}.bind(this),function(error){this._initPromise=null;return Promise.reject(error);}.bind(this));this._initPromise=promise;return promise;};SettingsManagerBase.prototype.startObserve=function(){if(this._callbacks){return;}
|
||
var callbacks=this._callbacks=[];this.KEYS.forEach(function(key,i){var callback=function(e){this._values[this.PROPERTIES[i]]=e.settingValue;if(typeof this.onsettingchange==='function'){this.onsettingchange(this._values);}}.bind(this);navigator.mozSettings.addObserver(key,callback);callbacks.push(callback);},this);};SettingsManagerBase.prototype.stopObserve=function(){if(!this._callbacks){return;}
|
||
var callbacks=this._callbacks;this.KEYS.forEach(function(key,i){navigator.mozSettings.removeObserver(key,callbacks[i]);},this);this._callbacks=null;};var SoundFeedbackSettings=function(){};SoundFeedbackSettings.prototype=new SettingsManagerBase();SoundFeedbackSettings.prototype.KEYS=['keyboard.clicksound','audio.volume.notification'];SoundFeedbackSettings.prototype.PROPERTIES=['clickEnabled','isSoundEnabled'];var VibrationFeedbackSettings=function(){};VibrationFeedbackSettings.prototype=new SettingsManagerBase();VibrationFeedbackSettings.prototype.KEYS=['keyboard.vibration'];VibrationFeedbackSettings.prototype.PROPERTIES=['vibrationEnabled'];var IMEngineSettings=function(){};IMEngineSettings.prototype=new SettingsManagerBase();IMEngineSettings.prototype.KEYS=['keyboard.wordsuggestion','keyboard.autocorrect'];IMEngineSettings.prototype.PROPERTIES=['suggestionsEnabled','correctionsEnabled'];var HandwritingPadSettings=function(){};HandwritingPadSettings.prototype=new SettingsManagerBase();HandwritingPadSettings.prototype.KEYS=['keyboard.handwriting.strokeWidth','keyboard.handwriting.responseTime'];HandwritingPadSettings.prototype.PROPERTIES=['strokeWidth','responseTime'];var UserPressManagerSettings=function(){};UserPressManagerSettings.prototype=new SettingsManagerBase();UserPressManagerSettings.prototype.KEYS=['deviceinfo.hardware','deviceinfo.product_model'];UserPressManagerSettings.prototype.PROPERTIES=['deviceinfoHardware','deviceinfoProductModel'];exports.SettingsPromiseManager=SettingsPromiseManager;exports.SettingsManagerBase=SettingsManagerBase;exports.SoundFeedbackSettings=SoundFeedbackSettings;exports.VibrationFeedbackSettings=VibrationFeedbackSettings;exports.IMEngineSettings=IMEngineSettings;exports.HandwritingPadSettings=HandwritingPadSettings;exports.UserPressManagerSettings=UserPressManagerSettings;})(window);;'use strict';(function(exports){var SoundFeedbackPlayer=function(){this._audioCtx=null;this._clickerAudioBuf=null;this._specialClickerAudioBuf=null;};SoundFeedbackPlayer.prototype.CLICK_SOUND_URL='./resources/sounds/key.wav';SoundFeedbackPlayer.prototype.SPECIAL_SOUND_URL='./resources/sounds/special.wav';SoundFeedbackPlayer.prototype.activate=function(){if(this._audioCtx){return;}
|
||
this._audioCtx=new AudioContext('system');};SoundFeedbackPlayer.prototype.deactivate=function(){this._audioCtx=null;};SoundFeedbackPlayer.prototype.prepare=function(){if(typeof AudioContext==='undefined'||typeof OfflineAudioContext==='undefined'){console.error('SoundFeedbackPlayer: No Web Audio API on this platform.');return;}
|
||
var clickerPromise=this._getAudioFileAsArrayBuffer(this.CLICK_SOUND_URL).then(this._decodeAudioData.bind(this)).then(function(audioBuffer){this._clickerAudioBuf=audioBuffer;}.bind(this));var specialClickerPromise=this._getAudioFileAsArrayBuffer(this.SPECIAL_SOUND_URL).then(this._decodeAudioData.bind(this)).then(function(audioBuffer){this._specialClickerAudioBuf=audioBuffer;}.bind(this));return Promise.all([clickerPromise,specialClickerPromise]).catch(function(e){console.error(e);throw e;});};SoundFeedbackPlayer.prototype._getAudioFileAsArrayBuffer=function(url){return new Promise(function(resolve,reject){var xhr=new XMLHttpRequest();xhr.open('GET',url);xhr.responseType='arraybuffer';xhr.onload=function(){if(!xhr.response){reject('SoundFeedbackPlayer: Cannot load file: '+url);return;}
|
||
resolve(xhr.response);};xhr.send();});};SoundFeedbackPlayer.prototype._decodeAudioData=function(arrayBuffer){return new Promise(function(resolve,reject){var ctx=new OfflineAudioContext(2,1,44100);ctx.decodeAudioData(arrayBuffer,function(audioBuffer){resolve(audioBuffer);},function(){reject('SoundFeedbackPlayer: decodeAudioData failed.');});}.bind(this));};SoundFeedbackPlayer.prototype.play=function(isSpecialKey){if(!this._clickerAudioBuf||!this._specialClickerAudioBuf){console.warn('SoundFeedbackPlayer: '+'Sound feedback needed but audio buffer is not available yet.');return;}
|
||
if(!this._audioCtx){console.error('SoundFeedbackPlayer: play() is called but not activated?');return;}
|
||
var ctx=this._audioCtx;var source=ctx.createBufferSource();source.buffer=isSpecialKey?this._specialClickerAudioBuf:this._clickerAudioBuf;source.connect(ctx.destination);source.start(0);};exports.SoundFeedbackPlayer=SoundFeedbackPlayer;})(window);;'use strict';(function(exports){var VibrationFeedback=function(app){this.app=app;this.settings=null;};VibrationFeedback.prototype.VIBRATE_MS=50;VibrationFeedback.prototype.start=function(){var settings=this.settings=new VibrationFeedbackSettings();settings.promiseManager=this.app.settingsPromiseManager;settings.initSettings().catch(function rejected(){console.warn('VibrationFeedback: Failed to get initial settings.');});};VibrationFeedback.prototype.stop=function(){this.settings=null;};VibrationFeedback.prototype.triggerFeedback=function(){if(!this.settings.initialized){console.warn('VibrationFeedback: '+'Sound feedback needed but settings is not available yet.');return;}
|
||
if(typeof window.navigator.vibrate!=='function'){console.warn('VibrationFeedback: '+'No navigator.vibrate() on this platform.');return;}
|
||
var vibrationFeedbackSettingsValues=this.settings.getSettingsSync();if(!vibrationFeedbackSettingsValues.vibrationEnabled){return;}
|
||
window.navigator.vibrate(this.VIBRATE_MS);};var SoundFeedback=function(app){this.app=app;this.activated=false;this.settings=null;this.clicker=null;this.specialClicker=null;};SoundFeedback.prototype.start=function(){var settings=this.settings=new SoundFeedbackSettings();settings.promiseManager=this.app.settingsPromiseManager;settings.onsettingchange=this._handleSettingsChange.bind(this);settings.initSettings().then(this._handleSettingsChange.bind(this),function rejected(){console.warn('SoundFeedback: Failed to get initial settings.');});};SoundFeedback.prototype.stop=function(){this.settings=null;this.player=null;};SoundFeedback.prototype.activate=function(){this.activated=true;if(this.player){this.player.activate();}};SoundFeedback.prototype.deactivate=function(){this.activated=false;if(this.player){this.player.deactivate();}};SoundFeedback.prototype._handleSettingsChange=function(settings){if(settings.clickEnabled&&!!settings.isSoundEnabled){this.player=new SoundFeedbackPlayer();this.player.prepare();if(this.activated){this.player.activate();}}else{this.player=null;}};SoundFeedback.prototype.triggerFeedback=function(target){if(!this.settings.initialized){console.warn('SoundFeedback: '+'Sound feedback needed but settings is not available yet.');return;}
|
||
if(!this.player){return;}
|
||
this.player.play(target.isSpecialKey);};var FeedbackManager=function(app){this.app=app;this.vibrationFeedback=null;this.soundFeedback=null;};FeedbackManager.prototype.start=function(){this.vibrationFeedback=new VibrationFeedback(this.app);this.vibrationFeedback.start();this.soundFeedback=new SoundFeedback(this.app);this.soundFeedback.start();};FeedbackManager.prototype.stop=function(){this.settings=null;this.vibrationFeedback.stop();this.soundFeedback.stop();this.vibrationFeedback=null;this.soundFeedback=null;};FeedbackManager.prototype.activate=function(){this.soundFeedback.activate();};FeedbackManager.prototype.deactivate=function(){this.soundFeedback.deactivate();};FeedbackManager.prototype.triggerFeedback=function(target){this.vibrationFeedback.triggerFeedback(target);this.soundFeedback.triggerFeedback(target);};exports.VibrationFeedback=VibrationFeedback;exports.SoundFeedback=SoundFeedback;exports.FeedbackManager=FeedbackManager;})(window);;'use strict';(function(exports){var UpperCaseStateManager=function(){this.isUpperCase=undefined;this.isUpperCaseLocked=undefined;};UpperCaseStateManager.prototype.onstatechange=null;UpperCaseStateManager.prototype.start=UpperCaseStateManager.prototype.reset=function(){this.isUpperCase=false;this.isUpperCaseLocked=false;};UpperCaseStateManager.prototype.stop=function(){this.isUpperCase=undefined;this.isUpperCaseLocked=undefined;};UpperCaseStateManager.prototype.switchUpperCaseState=function(state){if(!state){return;}
|
||
var newIsUpperCase=(typeof state.isUpperCase==='boolean')?state.isUpperCase:this.isUpperCase;var newIsUpperCaseLocked=(typeof state.isUpperCaseLocked==='boolean')?state.isUpperCaseLocked:this.isUpperCaseLocked;if(newIsUpperCaseLocked){newIsUpperCase=true;}
|
||
var statechanged=(this.isUpperCase!==newIsUpperCase)||(this.isUpperCaseLocked!==newIsUpperCaseLocked);if(!statechanged){return;}
|
||
this.isUpperCase=newIsUpperCase;this.isUpperCaseLocked=newIsUpperCaseLocked;if(typeof this.onstatechange==='function'){this.onstatechange();}};exports.UpperCaseStateManager=UpperCaseStateManager;})(window);;'use strict';(function(exports){var CandidatePanelScrollingMonitor=function(app){this.app=app;this.scrollTimer=undefined;};CandidatePanelScrollingMonitor.prototype.SCROLL_END_WAIT_MS=200;CandidatePanelScrollingMonitor.prototype.onneedcandidates=null;CandidatePanelScrollingMonitor.prototype.start=function(){};CandidatePanelScrollingMonitor.prototype.stop=function(){clearTimeout(this.scrollTimer);var candidatePanel=this.app.viewManager.candidatePanel;if(candidatePanel){var suggestionsContainer=candidatePanel.querySelector('.suggestions-container');suggestionsContainer.removeEventListener('scroll',this);}};CandidatePanelScrollingMonitor.prototype.handleEvent=function(evt){var panel=evt.target;clearTimeout(this.scrollTimer);if(panel.scrollTop===0||(panel.scrollHeight-panel.clientHeight-panel.scrollTop)>=5){return;}
|
||
this.scrollTimer=setTimeout(function(){if(typeof this.onneedcandidates==='function'){this.onneedcandidates();}}.bind(this),this.SCROLL_END_WAIT_MS);};CandidatePanelScrollingMonitor.prototype.startMonitoring=function(){var candidatePanel=this.app.viewManager.candidatePanel;if('truncated'in candidatePanel.dataset){var suggestionsContainer=candidatePanel.querySelector('.suggestions-container');suggestionsContainer.addEventListener('scroll',this);}};CandidatePanelScrollingMonitor.prototype.stopMonitoring=function(){clearTimeout(this.scrollTimer);var suggestionsContainer=this.app.viewManager.candidatePanel.querySelector('.suggestions-container');suggestionsContainer.removeEventListener('scroll',this);};var CandidatePanelManager=function(app){this.app=app;this.currentCandidates=null;this.isFullPanelShown=undefined;this.scrollingMonitor=null;};CandidatePanelManager.prototype.FIRST_PAGE_ROWS=11;CandidatePanelManager.prototype.PAGE_ROWS=12;CandidatePanelManager.prototype.oncandidateschange=null;CandidatePanelManager.prototype.start=function(){this.currentCandidates=[];this.isFullPanelShown=false;this.scrollingMonitor=new CandidatePanelScrollingMonitor(this.app);this.scrollingMonitor.start();this.scrollingMonitor.onneedcandidates=this.showNextCandidatePage.bind(this);};CandidatePanelManager.prototype.stop=function(){this.scrollingMonitor.stop();this.scrollingMonitor=null;this.isFullPanelShown=undefined;};CandidatePanelManager.prototype.showNextCandidatePage=function(){var numberOfCandidatesPerRow=this.app.viewManager.getNumberOfCandidatesPerRow();var candidatePanel=this.app.viewManager.candidatePanel;var candidateIndicator=parseInt(candidatePanel.dataset.candidateIndicator,10);var engine=this.app.inputMethodManager.currentIMEngine;if(typeof engine.getMoreCandidates==='function'){engine.getMoreCandidates(candidateIndicator,this.PAGE_ROWS*numberOfCandidatesPerRow+1,this.app.viewManager.showMoreCandidates.bind(this.app.viewManager,this.PAGE_ROWS));}else{var list=this.currentCandidates.slice(candidateIndicator,candidateIndicator+this.PAGE_ROWS*numberOfCandidatesPerRow+1);this.app.viewManager.showMoreCandidates(this.PAGE_ROWS,list);}};CandidatePanelManager.prototype.toggleFullPanel=function(fullPanel){if(this.isFullPanelShown){this.hideFullPanel();}else{this.showFullPanel();}};CandidatePanelManager.prototype.showFullPanel=function(){if(this.isFullPanelShown){return;}
|
||
this.isFullPanelShown=true;var candidatePanel=this.app.viewManager.candidatePanel;if(candidatePanel.dataset.rowCount==1){var numberOfCandidatesPerRow=this.app.viewManager.getNumberOfCandidatesPerRow();var candidateIndicator=parseInt(candidatePanel.dataset.candidateIndicator,10);var engine=this.app.inputMethodManager.currentIMEngine;if(typeof engine.getMoreCandidates==='function'){engine.getMoreCandidates(candidateIndicator,this.FIRST_PAGE_ROWS*numberOfCandidatesPerRow+1,function gotMoreCandidates(list){if(candidatePanel.dataset.rowCount!=1){return;}
|
||
this.app.viewManager.showMoreCandidates(this.FIRST_PAGE_ROWS,list);this.scrollingMonitor.startMonitoring();this.app.viewManager.toggleCandidatePanel(true);}.bind(this));}else{var list=this.currentCandidates.slice(candidateIndicator,candidateIndicator+
|
||
this.FIRST_PAGE_ROWS*numberOfCandidatesPerRow+1);this.app.viewManager.showMoreCandidates(this.FIRST_PAGE_ROWS,list);this.scrollingMonitor.startMonitoring();this.app.viewManager.toggleCandidatePanel(true);}}else{this.scrollingMonitor.startMonitoring();this.app.viewManager.toggleCandidatePanel(true);}};CandidatePanelManager.prototype.hideFullPanel=function(){if(!this.isFullPanelShown){return;}
|
||
this.isFullPanelShown=false;this.scrollingMonitor.stopMonitoring();this.app.viewManager.toggleCandidatePanel(false);};CandidatePanelManager.prototype.reset=function(){this.hideFullPanel();this.currentCandidates=[];};CandidatePanelManager.prototype.updateCandidates=function(candidates){this.currentCandidates=candidates;if(typeof this.oncandidateschange==='function'){this.oncandidateschange();}};exports.CandidatePanelScrollingMonitor=CandidatePanelScrollingMonitor;exports.CandidatePanelManager=CandidatePanelManager;})(window);;'use strict';(function(exports){var LayoutRenderingManager=function(app){this.app=app;this._currentRenderingPage=null;this._resizeListenerTimer=undefined;this.domObjectMap=null;};LayoutRenderingManager.prototype.start=function(){this.app.console.log('LayoutRenderingManager.start()');this._resizeListenerTimer=setTimeout(function attachResizeListener(){this.app.console.log('LayoutRenderingManager.attachResizeListener()');window.addEventListener('resize',this);}.bind(this),2000);this.domObjectMap=new WeakMap();};LayoutRenderingManager.prototype.stop=function(){clearTimeout(this._resizeListenerTimer);this._resizeListenerTimer=undefined;window.removeEventListener('resize',this);this.domObjectMap=null;};LayoutRenderingManager.prototype.handleEvent=function(){this.app.console.log('LayoutRenderingManager.handleEvent()');if(document.hidden){this.app.console.log('LayoutRenderingManager: Ignore resizing call since '+'document is hidden.');return;}
|
||
if(this._currentRenderingPage!==this.app.layoutManager.currentPage){this.app.console.log('LayoutRenderingManager: Ignore resizing call since '+'layout is not ready yet.');return;}
|
||
this.app.viewManager.resize();this._updateHeight();this._updateLayoutParams();};LayoutRenderingManager.prototype.updateCandidatesRendering=function(){if(this._currentRenderingPage!==this.app.layoutManager.currentPage){this.app.console.log('LayoutRenderingManager: Ignore updateCandidatesRendering() call since '+'layout is not ready yet.');return;}
|
||
this.app.viewManager.showCandidates(this.app.candidatePanelManager.currentCandidates);};LayoutRenderingManager.prototype.updateUpperCaseRendering=function(){this.app.console.log('LayoutRenderingManager.updateUpperCaseRendering()');if(this._currentRenderingPage!==this.app.layoutManager.currentPage){this.app.console.log('LayoutRenderingManager: Ignore updateUpperCaseRendering() call since '+'layout is not ready yet.');return;}
|
||
window.requestAnimationFrame(function(){this.app.console.log('LayoutRenderingManager.updateUpperCaseRendering()::'+'requestAnimationFrame');this.app.viewManager.setUpperCaseLock(this.app.upperCaseStateManager);}.bind(this));};LayoutRenderingManager.prototype.updateLayoutRendering=function(){this.app.console.log('LayoutRenderingManager.updateLayoutRendering()');this.app.console.time('LayoutRenderingManager.updateLayoutRendering()');var currentPage=this._currentRenderingPage=this.app.layoutManager.currentPage;var currentIMEngine=this.app.inputMethodManager.currentIMEngine;this.app.console.log('needsCandidatePanel',currentPage.autoCorrectLanguage,currentPage.needsCandidatePanel,typeof currentIMEngine.displaysCandidates!=='function',(currentIMEngine.displaysCandidates&¤tIMEngine.displaysCandidates()));var needsCandidatePanel=!!((currentPage.autoCorrectLanguage||currentPage.needsCandidatePanel)&&((typeof currentIMEngine.displaysCandidates!=='function')||currentIMEngine.displaysCandidates()));if(currentPage.updateByIMEngine){if(typeof currentIMEngine.updatePageKeys!=='function'){throw new Error('LayoutRenderingManager: unable to update '+'page keys by IMEngine');}
|
||
currentIMEngine.updatePageKeys(currentPage);}
|
||
var p=new Promise(function(resolve){this.app.viewManager.render(currentPage,{uppercase:this.app.upperCaseStateManager.isUpperCase,inputType:this.app.getBasicInputType(),showCandidatePanel:needsCandidatePanel},resolve);}.bind(this)).then(this._afterRenderDrew.bind(this));p.catch(function(e){console.error(e);});this._updateHeight();this.app.console.timeEnd('LayoutRenderingManager.updateLayoutRendering()');return p;};LayoutRenderingManager.prototype.drawHandwritingPad=function(press,start,strokeWidth){return this.app.viewManager.drawHandwritingPad(press,start,strokeWidth);};LayoutRenderingManager.prototype.clearHandwritingPad=function(target){this.app.viewManager.clearHandwritingPad(target);};LayoutRenderingManager.prototype._afterRenderDrew=function(){this.app.console.log('LayoutRenderingManager._afterRenderDrew()');this.app.console.time('LayoutRenderingManager._afterRenderDrew()');this.app.viewManager.setUpperCaseLock(this.app.upperCaseStateManager);this.app.viewManager.showCandidates(this.app.candidatePanelManager.currentCandidates);this._updateLayoutParams();this.app.console.timeEnd('LayoutRenderingManager._afterRenderDrew()');};LayoutRenderingManager.prototype._updateLayoutParams=function(){this.app.console.log('LayoutRenderingManager._updateLayoutParams()');var currentIMEngine=this.app.inputMethodManager.currentIMEngine;var layoutManager=this.app.layoutManager;if((typeof currentIMEngine.setLayoutParams!=='function')||layoutManager.currentPageIndex!==layoutManager.PAGE_INDEX_DEFAULT){return;}
|
||
var candidatePanel=this.app.viewManager.candidatePanel;var yBias=candidatePanel?candidatePanel.clientHeight:0;currentIMEngine.setLayoutParams({keyboardWidth:this.app.viewManager.getWidth(),keyboardHeight:(this.app.viewManager.getHeight()-yBias),keyArray:this.app.viewManager.getKeyArray(),keyWidth:this.app.viewManager.getKeyWidth(),keyHeight:this.app.viewManager.getKeyHeight()});};LayoutRenderingManager.prototype._updateHeight=function(){this.app.console.log('LayoutRenderingManager._updateHeight()');this.app.console.time('LayoutRenderingManager._updateHeight()');var imeHeight=this.app.viewManager.getHeight();var imeWidth=this.app.viewManager.getWidth();imeHeight=Math.floor(imeHeight*window.devicePixelRatio)/window.devicePixelRatio;this.app.console.timeEnd('LayoutRenderingManager._updateHeight()');this.app.console.timeEnd('activate');this.app.console.timeEnd('domLoading');window.resizeTo(imeWidth,imeHeight);};LayoutRenderingManager.prototype.getTargetObject=function(elem){this.app.console.log('LayoutRenderingManager.getTargetObject()',elem);if(!elem){return{};}
|
||
var target=this.domObjectMap.get(elem);this.app.console.log('target=',target,'prototype=',target&&Object.getPrototypeOf(target));return target||{};};exports.LayoutRenderingManager=LayoutRenderingManager;})(window);;'use strict';(function(exports){var AbortablePromiseQueueError=function(currentId,expectedId){this.currentId=currentId;this.expectedId=expectedId;};AbortablePromiseQueueError.prototype.name='AbortablePromiseQueueError';AbortablePromiseQueueError.prototype.message='The current task group ID does not match.';var AbortablePromiseQueue=function AbortablePromiseQueue(){this._started=false;this._taskGroupId=0;this._queuedTasks=null;};AbortablePromiseQueue.prototype.start=function(){if(this._started){throw new Error('AbortablePromiseQueue: Should not be start()\'ed twice.');}
|
||
this._started=true;this._queuedTasks=Promise.resolve();};AbortablePromiseQueue.prototype.stop=function(){if(!this._started){throw new Error('AbortablePromiseQueue: '+'Was not start()\'ed but stop() is called.');}
|
||
this._started=false;this.abort();this._queuedTasks=null;this._taskGroupId=0;};AbortablePromiseQueue.prototype.run=function(tasks){this.abort();var idCheck=this._getIdCheckFunction();tasks.forEach(function(task){this._queuedTasks=this._queuedTasks.then(idCheck).then(task);},this);this._queuedTasks=this._queuedTasks.catch(function(e){if(e instanceof AbortablePromiseQueueError){return;}
|
||
(e!==undefined)&&console.error(e);});return this._queuedTasks;};AbortablePromiseQueue.prototype.abort=function(){this._taskGroupId++;};AbortablePromiseQueue.prototype._getIdCheckFunction=function(){var id=this._taskGroupId;return function __taskGroupIdCheck(value){if(id!==this._taskGroupId){return Promise.reject(new AbortablePromiseQueueError(this._taskGroupId,id));}
|
||
return value;}.bind(this);};exports.AbortablePromiseQueue=AbortablePromiseQueue;})(window);;'use strict';(function(exports){var StateManager=function(app){this.app=app;this._started=false;this._isActive=undefined;this._layoutName=undefined;};StateManager.prototype.start=function(){this.app.console.log('StateManager.start()');if(this._started){throw new Error('StateManager: Should not be start()\'ed twice.');}
|
||
this._started=true;this._isActive=false;this._queue=new AbortablePromiseQueue();this._queue.start();window.addEventListener('hashchange',this);window.addEventListener('visibilitychange',this);navigator.mozInputMethod.addEventListener('inputcontextchange',this);this.app.setInputContext(navigator.mozInputMethod.inputcontext);this._layoutName=window.location.hash.substr(1);var active=(!document.hidden&&!!this.app.inputContext);if(!active){this._queue.run([this._preloadLayout.bind(this),this._preloadInputMethod.bind(this),this.app.l10nLoader.load.bind(this.app.l10nLoader)]);}
|
||
this._updateActiveState(active);};StateManager.prototype.stop=function(){this.app.console.log('StateManager.stop()');if(!this._started){throw new Error('StateManager: Was not start()\'ed but stop() is called.');}
|
||
this._started=false;this._queue.stop();this._queue=null;window.removeEventListener('hashchange',this);window.removeEventListener('visibilitychange',this);navigator.mozInputMethod.removeEventListener('inputcontextchange',this);this._isActive=undefined;this._layoutName=undefined;};StateManager.prototype.handleEvent=function(evt){var active=(!document.hidden&&!!navigator.mozInputMethod.inputcontext);this.app.console.info('StateManager.handleEvent()',evt,active);switch(evt.type){case'hashchange':this._layoutName=window.location.hash.substr(1);if(!active){this._queue.run([this._preloadLayout.bind(this),this._preloadInputMethod.bind(this)]);}
|
||
break;case'visibilitychange':break;case'inputcontextchange':this.app.setInputContext(navigator.mozInputMethod.inputcontext);break;}
|
||
this._updateActiveState(active);};StateManager.prototype._updateActiveState=function(active){this.app.console.log('StateManager._updateActiveState()',active);if(active){this.app.console.time('activate');this._queue.run([function(){this.app.candidatePanelManager.hideFullPanel();this.app.candidatePanelManager.updateCandidates([]);this.app.inputMethodManager.deactivateIMEngine();this.app.feedbackManager.activate();}.bind(this),this.app.layoutManager.switchCurrentLayout.bind(this.app.layoutManager,this._layoutName),this._activateIMEngineForCurrentPage.bind(this),this.app.layoutRenderingManager.updateLayoutRendering.bind(this.app.layoutRenderingManager),this.app.l10nLoader.load.bind(this.app.l10nLoader)]);}else{if(active===this._isActive){return;}
|
||
this._queue.run([function(){this.app.candidatePanelManager.hideFullPanel();this.app.candidatePanelManager.updateCandidates([]);this.app.targetHandlersManager.activeTargetsManager.clearAllTargets();this.app.feedbackManager.deactivate();}.bind(this),this.app.inputMethodManager.deactivateIMEngine.bind(this.app.inputMethodManager)]);}
|
||
this._isActive=active;};StateManager.prototype._preloadLayout=function(){this.app.console.log('StateManager._preloadLayout()');var layoutLoader=this.app.layoutManager.loader;return layoutLoader.getLayoutAsync(this._layoutName);};StateManager.prototype._preloadInputMethod=function(layout){this.app.console.log('StateManager._preloadInputMethod()');var imEngineName=layout.imEngine;var imEngineLoader=this.app.inputMethodManager.loader;if(imEngineName){var p=imEngineLoader.getInputMethodAsync(imEngineName);return p;}};StateManager.prototype._activateIMEngineForCurrentPage=function(){this.app.console.log('StateManager._activateIMEngineForCurrentPage()');var page=this.app.layoutManager.currentPage;var imEngineName=page.imEngine||'default';this.app.upperCaseStateManager.reset();this.app.candidatePanelManager.reset();var p=this.app.inputMethodManager.activateIMEngine(imEngineName);return p;};exports.StateManager=StateManager;})(window);;'use strict';(function(exports){var KeyboardApp=function(){this.console=null;this.inputMethodManager=null;this.inputMethodDatabaseLoader=null;this.layoutManager=null;this.settingsPromiseManager=null;this.l10nLoader=null;this.targetHandlersManager=null;this.handwritingPadsManager=null;this.feedbackManager=null;this.visualHighlightManager=null;this.candidatePanelManager=null;this.upperCaseStateManager=null;this.layoutRenderingManager=null;this.stateManager=null;this.viewManager=null;this.inputContext=null;};KeyboardApp.prototype.CONATINER_ELEMENT_ID='keyboard';KeyboardApp.prototype.start=function(){this._startComponents();};KeyboardApp.prototype._startComponents=function(){this.console=new KeyboardConsole();this.console.start();this.console.log('KeyboardApp._startComponents()');this.console.trace();this.console.time('KeyboardApp._startComponents()');this.settingsPromiseManager=new SettingsPromiseManager();this.inputMethodManager=new InputMethodManager(this);this.inputMethodManager.start();this.inputMethodDatabaseLoader=new InputMethodDatabaseLoader(this);this.inputMethodDatabaseLoader.start();this.layoutManager=new LayoutManager(this);this.layoutManager.start();this.l10nLoader=new L10nLoader();this.targetHandlersManager=new TargetHandlersManager(this);this.targetHandlersManager.start();this.handwritingPadsManager=new HandwritingPadsManager(this);this.handwritingPadsManager.start();this.feedbackManager=new FeedbackManager(this);this.feedbackManager.start();this.visualHighlightManager=new VisualHighlightManager(this);this.visualHighlightManager.start();this.viewManager=new ViewManager(this);this.viewManager.start();var renderingManager=this.layoutRenderingManager=new LayoutRenderingManager(this);renderingManager.start();this.upperCaseStateManager=new UpperCaseStateManager();this.upperCaseStateManager.onstatechange=renderingManager.updateUpperCaseRendering.bind(renderingManager);this.upperCaseStateManager.start();this.candidatePanelManager=new CandidatePanelManager(this);this.candidatePanelManager.oncandidateschange=renderingManager.updateCandidatesRendering.bind(renderingManager);this.candidatePanelManager.start();this.stateManager=new StateManager(this);this.stateManager.start();this.console.timeEnd('KeyboardApp._startComponents()');};KeyboardApp.prototype.stop=function(){this.console.log('KeyboardApp.stop()');this._stopComponents();this.inputContext=null;};KeyboardApp.prototype._stopComponents=function(){this.console=null;this.inputMethodManager=null;this.inputMethodDatabaseLoader.stop();this.inputMethodDatabaseLoader=null;this.layoutManager=null;this.settingsPromiseManager=null;this.l10nLoader=null;this.targetHandlersManager.stop();this.targetHandlersManager=null;this.handwritingPadsManager.stop();this.handwritingPadsManager=null;this.feedbackManager.stop();this.feedbackManager=null;this.visualHighlightManager.stop();this.visualHighlightManager=null;this.candidatePanelManager.stop();this.candidatePanelManager=null;this.upperCaseStateManager.onstatechange=null;this.upperCaseStateManager.stop();this.upperCaseStateManager=null;this.layoutRenderingManager.stop();this.layoutRenderingManager=null;this.stateManager.stop();this.stateManager=null;this.viewManager.stop();this.viewManager=null;};KeyboardApp.prototype.getContainer=function(){return document.getElementById(this.CONATINER_ELEMENT_ID);};KeyboardApp.prototype.setInputContext=function(inputContext){this.console.log('KeyboardApp.setInputContext()',inputContext);this.inputContext=inputContext;};KeyboardApp.prototype.getBasicInputType=function(){if(!this.inputContext){return'text';}
|
||
var type=this.inputContext.inputType;switch(type){case'url':case'tel':case'email':case'text':case'search':break;case'password':default:type='text';break;case'number':case'range':type='number';break;}
|
||
return type;};KeyboardApp.prototype.supportsSwitching=function(){return navigator.mozInputMethod.mgmt.supportsSwitching();};KeyboardApp.prototype.setLayoutPage=function setLayoutPage(page){this.console.log('KeyboardApp.setLayoutPage()',page);this.layoutManager.updateLayoutPage(page);this.layoutRenderingManager.updateLayoutRendering();var engine=this.inputMethodManager.currentIMEngine;if(typeof engine.setLayoutPage==='function'){engine.setLayoutPage(this.layoutManager.currentPageIndex);}};exports.KeyboardApp=KeyboardApp;})(window);;'use strict';(function(exports){var app=new KeyboardApp();app.start();exports.app=app;})(window); |