Share Gaia assets and adapters, keep private profiles and development documents local, and update both public READMEs.
1282 lines
No EOL
268 KiB
JavaScript
1282 lines
No EOL
268 KiB
JavaScript
;var _createClass=(function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if('value'in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};})();function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError('Cannot call a class as a function');}}
|
||
(function(){'use strict';function emit(listeners,...args){const type=args.shift();if(listeners['*']){listeners['*'].slice().forEach(listener=>listener.apply(this,args));}
|
||
if(listeners[type]){listeners[type].slice().forEach(listener=>listener.apply(this,args));}}
|
||
function addEventListener(listeners,type,listener){if(!(type in listeners)){listeners[type]=[];}
|
||
listeners[type].push(listener);}
|
||
function removeEventListener(listeners,type,listener){const typeListeners=listeners[type];const pos=typeListeners.indexOf(listener);if(pos===-1){return;}
|
||
typeListeners.splice(pos,1);}
|
||
let Client=(function(){function Client(remote){_classCallCheck(this,Client);this.id=this;this.remote=remote;const listeners={};this.on=(...args)=>addEventListener(listeners,...args);this.emit=(...args)=>emit(listeners,...args);}
|
||
_createClass(Client,[{key:'method',value:function method(name,...args){return this.remote[name](...args);}}]);return Client;})();function broadcast(type,data){Array.from(this.ctxs.keys()).forEach(client=>client.emit(type,data));}
|
||
function L10nError(message,id,lang){this.name='L10nError';this.message=message;this.id=id;this.lang=lang;}
|
||
L10nError.prototype=Object.create(Error.prototype);L10nError.prototype.constructor=L10nError;function load(type,url){return new Promise(function(resolve,reject){const xhr=new XMLHttpRequest();if(xhr.overrideMimeType){xhr.overrideMimeType(type);}
|
||
xhr.open('GET',url,true);if(type==='application/json'){xhr.responseType='json';}
|
||
xhr.addEventListener('load',function io_onload(e){if(e.target.status===200||e.target.status===0){resolve(e.target.response||e.target.responseText);}else{reject(new L10nError('Not found: '+url));}});xhr.addEventListener('error',reject);xhr.addEventListener('timeout',reject);try{xhr.send(null);}catch(e){if(e.name==='NS_ERROR_FILE_NOT_FOUND'){reject(new L10nError('Not found: '+url));}else{throw e;}}});}
|
||
const io={extra:function(code,ver,path,type){return navigator.mozApps.getLocalizationResource(code,ver,path,type);},app:function(code,ver,path,type){switch(type){case'text':return load('text/plain',path);case'json':return load('application/json',path);default:throw new L10nError('Unknown file type: '+type);}}};function fetchResource(res,{code,src,ver}){const url=res.replace('{locale}',code);const type=res.endsWith('.json')?'json':'text';return io[src](code,ver,url,type);}
|
||
const KNOWN_MACROS=['plural'];const MAX_PLACEABLE_LENGTH=2500;const FSI='';const PDI='';const resolutionChain=new WeakSet();function format(ctx,lang,args,entity){if(typeof entity==='string'){return[{},entity];}
|
||
if(resolutionChain.has(entity)){throw new L10nError('Cyclic reference detected');}
|
||
resolutionChain.add(entity);let rv;try{rv=resolveValue({},ctx,lang,args,entity.value,entity.index);}finally{resolutionChain.delete(entity);}
|
||
return rv;}
|
||
function resolveIdentifier(ctx,lang,args,id){if(KNOWN_MACROS.indexOf(id)>-1){return[{},ctx._getMacro(lang,id)];}
|
||
if(args&&args.hasOwnProperty(id)){if(typeof args[id]==='string'||typeof args[id]==='number'&&!isNaN(args[id])){return[{},args[id]];}else{throw new L10nError('Arg must be a string or a number: '+id);}}
|
||
if(id==='__proto__'){throw new L10nError('Illegal id: '+id);}
|
||
const entity=ctx._getEntity(lang,id);if(entity){return format(ctx,lang,args,entity);}
|
||
throw new L10nError('Unknown reference: '+id);}
|
||
function subPlaceable(locals,ctx,lang,args,id){let newLocals,value;try{[newLocals,value]=resolveIdentifier(ctx,lang,args,id);}catch(err){return[{error:err},FSI+'{{ '+id+' }}'+PDI];}
|
||
if(typeof value==='number'){const formatter=ctx._getNumberFormatter(lang);return[newLocals,formatter.format(value)];}
|
||
if(typeof value==='string'){if(value.length>=MAX_PLACEABLE_LENGTH){throw new L10nError('Too many characters in placeable ('+value.length+', max allowed is '+MAX_PLACEABLE_LENGTH+')');}
|
||
return[newLocals,FSI+value+PDI];}
|
||
return[{},FSI+'{{ '+id+' }}'+PDI];}
|
||
function interpolate(locals,ctx,lang,args,arr){return arr.reduce(function([localsSeq,valueSeq],cur){if(typeof cur==='string'){return[localsSeq,valueSeq+cur];}else{const[,value]=subPlaceable(locals,ctx,lang,args,cur.name);return[localsSeq,valueSeq+value];}},[locals,'']);}
|
||
function resolveSelector(ctx,lang,args,expr,index){let selectorName;if(index[0].type==='call'&&index[0].expr.type==='prop'&&index[0].expr.expr.name==='cldr'){selectorName='plural';}else{selectorName=index[0].name;}
|
||
const selector=resolveIdentifier(ctx,lang,args,selectorName)[1];if(typeof selector!=='function'){return selector;}
|
||
const argValue=index[0].args?resolveIdentifier(ctx,lang,args,index[0].args[0].name)[1]:undefined;if(selectorName==='plural'){if(argValue===0&&'zero'in expr){return'zero';}
|
||
if(argValue===1&&'one'in expr){return'one';}
|
||
if(argValue===2&&'two'in expr){return'two';}}
|
||
return selector(argValue);}
|
||
function resolveValue(locals,ctx,lang,args,expr,index){if(!expr){return[locals,expr];}
|
||
if(typeof expr==='string'||typeof expr==='boolean'||typeof expr==='number'){return[locals,expr];}
|
||
if(Array.isArray(expr)){return interpolate(locals,ctx,lang,args,expr);}
|
||
if(index){const selector=resolveSelector(ctx,lang,args,expr,index);if(selector in expr){return resolveValue(locals,ctx,lang,args,expr[selector]);}}
|
||
const defaultKey=expr.__default||'other';if(defaultKey in expr){return resolveValue(locals,ctx,lang,args,expr[defaultKey]);}
|
||
throw new L10nError('Unresolvable value');}
|
||
const locales2rules={'af':3,'ak':4,'am':4,'ar':1,'asa':3,'az':0,'be':11,'bem':3,'bez':3,'bg':3,'bh':4,'bm':0,'bn':3,'bo':0,'br':20,'brx':3,'bs':11,'ca':3,'cgg':3,'chr':3,'cs':12,'cy':17,'da':3,'de':3,'dv':3,'dz':0,'ee':3,'el':3,'en':3,'eo':3,'es':3,'et':3,'eu':3,'fa':0,'ff':5,'fi':3,'fil':4,'fo':3,'fr':5,'fur':3,'fy':3,'ga':8,'gd':24,'gl':3,'gsw':3,'gu':3,'guw':4,'gv':23,'ha':3,'haw':3,'he':2,'hi':4,'hr':11,'hu':0,'id':0,'ig':0,'ii':0,'is':3,'it':3,'iu':7,'ja':0,'jmc':3,'jv':0,'ka':0,'kab':5,'kaj':3,'kcg':3,'kde':0,'kea':0,'kk':3,'kl':3,'km':0,'kn':0,'ko':0,'ksb':3,'ksh':21,'ku':3,'kw':7,'lag':18,'lb':3,'lg':3,'ln':4,'lo':0,'lt':10,'lv':6,'mas':3,'mg':4,'mk':16,'ml':3,'mn':3,'mo':9,'mr':3,'ms':0,'mt':15,'my':0,'nah':3,'naq':7,'nb':3,'nd':3,'ne':3,'nl':3,'nn':3,'no':3,'nr':3,'nso':4,'ny':3,'nyn':3,'om':3,'or':3,'pa':3,'pap':3,'pl':13,'ps':3,'pt':3,'rm':3,'ro':9,'rof':3,'ru':11,'rwk':3,'sah':0,'saq':3,'se':7,'seh':3,'ses':0,'sg':0,'sh':11,'shi':19,'sk':12,'sl':14,'sma':7,'smi':7,'smj':7,'smn':7,'sms':7,'sn':3,'so':3,'sq':3,'sr':11,'ss':3,'ssy':3,'st':3,'sv':3,'sw':3,'syr':3,'ta':3,'te':3,'teo':3,'th':0,'ti':4,'tig':3,'tk':3,'tl':4,'tn':3,'to':0,'tr':0,'ts':3,'tzm':22,'uk':11,'ur':3,'ve':3,'vi':0,'vun':3,'wa':4,'wae':3,'wo':0,'xh':3,'xog':3,'yo':0,'zh':0,'zu':3};function isIn(n,list){return list.indexOf(n)!==-1;}
|
||
function isBetween(n,start,end){return typeof n===typeof start&&start<=n&&n<=end;}
|
||
const pluralRules={'0':function(){return'other';},'1':function(n){if(isBetween(n%100,3,10)){return'few';}
|
||
if(n===0){return'zero';}
|
||
if(isBetween(n%100,11,99)){return'many';}
|
||
if(n===2){return'two';}
|
||
if(n===1){return'one';}
|
||
return'other';},'2':function(n){if(n!==0&&n%10===0){return'many';}
|
||
if(n===2){return'two';}
|
||
if(n===1){return'one';}
|
||
return'other';},'3':function(n){if(n===1){return'one';}
|
||
return'other';},'4':function(n){if(isBetween(n,0,1)){return'one';}
|
||
return'other';},'5':function(n){if(isBetween(n,0,2)&&n!==2){return'one';}
|
||
return'other';},'6':function(n){if(n===0){return'zero';}
|
||
if(n%10===1&&n%100!==11){return'one';}
|
||
return'other';},'7':function(n){if(n===2){return'two';}
|
||
if(n===1){return'one';}
|
||
return'other';},'8':function(n){if(isBetween(n,3,6)){return'few';}
|
||
if(isBetween(n,7,10)){return'many';}
|
||
if(n===2){return'two';}
|
||
if(n===1){return'one';}
|
||
return'other';},'9':function(n){if(n===0||n!==1&&isBetween(n%100,1,19)){return'few';}
|
||
if(n===1){return'one';}
|
||
return'other';},'10':function(n){if(isBetween(n%10,2,9)&&!isBetween(n%100,11,19)){return'few';}
|
||
if(n%10===1&&!isBetween(n%100,11,19)){return'one';}
|
||
return'other';},'11':function(n){if(isBetween(n%10,2,4)&&!isBetween(n%100,12,14)){return'few';}
|
||
if(n%10===0||isBetween(n%10,5,9)||isBetween(n%100,11,14)){return'many';}
|
||
if(n%10===1&&n%100!==11){return'one';}
|
||
return'other';},'12':function(n){if(isBetween(n,2,4)){return'few';}
|
||
if(n===1){return'one';}
|
||
return'other';},'13':function(n){if(isBetween(n%10,2,4)&&!isBetween(n%100,12,14)){return'few';}
|
||
if(n!==1&&isBetween(n%10,0,1)||isBetween(n%10,5,9)||isBetween(n%100,12,14)){return'many';}
|
||
if(n===1){return'one';}
|
||
return'other';},'14':function(n){if(isBetween(n%100,3,4)){return'few';}
|
||
if(n%100===2){return'two';}
|
||
if(n%100===1){return'one';}
|
||
return'other';},'15':function(n){if(n===0||isBetween(n%100,2,10)){return'few';}
|
||
if(isBetween(n%100,11,19)){return'many';}
|
||
if(n===1){return'one';}
|
||
return'other';},'16':function(n){if(n%10===1&&n!==11){return'one';}
|
||
return'other';},'17':function(n){if(n===3){return'few';}
|
||
if(n===0){return'zero';}
|
||
if(n===6){return'many';}
|
||
if(n===2){return'two';}
|
||
if(n===1){return'one';}
|
||
return'other';},'18':function(n){if(n===0){return'zero';}
|
||
if(isBetween(n,0,2)&&n!==0&&n!==2){return'one';}
|
||
return'other';},'19':function(n){if(isBetween(n,2,10)){return'few';}
|
||
if(isBetween(n,0,1)){return'one';}
|
||
return'other';},'20':function(n){if((isBetween(n%10,3,4)||n%10===9)&&!(isBetween(n%100,10,19)||isBetween(n%100,70,79)||isBetween(n%100,90,99))){return'few';}
|
||
if(n%1000000===0&&n!==0){return'many';}
|
||
if(n%10===2&&!isIn(n%100,[12,72,92])){return'two';}
|
||
if(n%10===1&&!isIn(n%100,[11,71,91])){return'one';}
|
||
return'other';},'21':function(n){if(n===0){return'zero';}
|
||
if(n===1){return'one';}
|
||
return'other';},'22':function(n){if(isBetween(n,0,1)||isBetween(n,11,99)){return'one';}
|
||
return'other';},'23':function(n){if(isBetween(n%10,1,2)||n%20===0){return'one';}
|
||
return'other';},'24':function(n){if(isBetween(n,3,10)||isBetween(n,13,19)){return'few';}
|
||
if(isIn(n,[2,12])){return'two';}
|
||
if(isIn(n,[1,11])){return'one';}
|
||
return'other';}};function getPluralRule(code){const index=locales2rules[code.replace(/-.*$/,'')];if(!(index in pluralRules)){return function(){return'other';};}
|
||
return pluralRules[index];}
|
||
const L20nIntl=typeof Intl!=='undefined'?Intl:{NumberFormat:function(){return{format:function(v){return v;}};}};let Context=(function(){function Context(env,langs,resIds){_classCallCheck(this,Context);this.langs=langs;this.resIds=resIds;this.env=env;this.emit=(type,evt)=>env.emit(type,evt,this);}
|
||
_createClass(Context,[{key:'_formatTuple',value:function _formatTuple(lang,args,entity,id,key){try{return format(this,lang,args,entity);}catch(err){err.id=key?id+'::'+key:id;err.lang=lang;this.emit('resolveerror',err);return[{error:err},err.id];}}},{key:'_formatEntity',value:function _formatEntity(lang,args,entity,id){const[,value]=this._formatTuple(lang,args,entity,id);const formatted={value,attrs:null};if(entity.attrs){formatted.attrs=Object.create(null);for(let key in entity.attrs){const[,attrValue]=this._formatTuple(lang,args,entity.attrs[key],id,key);formatted.attrs[key]=attrValue;}}
|
||
return formatted;}},{key:'_formatValue',value:function _formatValue(lang,args,entity,id){return this._formatTuple(lang,args,entity,id)[1];}},{key:'fetch',value:function fetch(langs=this.langs){if(langs.length===0){return Promise.resolve(langs);}
|
||
return Promise.all(this.resIds.map(resId=>this.env._getResource(langs[0],resId))).then(()=>langs);}},{key:'_resolve',value:function _resolve(langs,keys,formatter,prevResolved){const lang=langs[0];if(!lang){return reportMissing.call(this,keys,formatter,prevResolved);}
|
||
let hasUnresolved=false;const resolved=keys.map((key,i)=>{if(prevResolved&&prevResolved[i]!==undefined){return prevResolved[i];}
|
||
const[id,args]=Array.isArray(key)?key:[key,undefined];const entity=this._getEntity(lang,id);if(entity){return formatter.call(this,lang,args,entity,id);}
|
||
this.emit('notfounderror',new L10nError('"'+id+'"'+' not found in '+lang.code,id,lang));hasUnresolved=true;});if(!hasUnresolved){return resolved;}
|
||
return this.fetch(langs.slice(1)).then(nextLangs=>this._resolve(nextLangs,keys,formatter,resolved));}},{key:'formatEntities',value:function formatEntities(...keys){return this.fetch().then(langs=>this._resolve(langs,keys,this._formatEntity));}},{key:'formatValues',value:function formatValues(...keys){return this.fetch().then(langs=>this._resolve(langs,keys,this._formatValue));}},{key:'_getEntity',value:function _getEntity(lang,id){const cache=this.env.resCache;for(let i=0,resId;resId=this.resIds[i];i++){const resource=cache.get(resId+lang.code+lang.src);if(resource instanceof L10nError){continue;}
|
||
if(id in resource){return resource[id];}}
|
||
return undefined;}},{key:'_getNumberFormatter',value:function _getNumberFormatter(lang){if(!this.env.numberFormatters){this.env.numberFormatters=new Map();}
|
||
if(!this.env.numberFormatters.has(lang)){const formatter=L20nIntl.NumberFormat(lang);this.env.numberFormatters.set(lang,formatter);return formatter;}
|
||
return this.env.numberFormatters.get(lang);}},{key:'_getMacro',value:function _getMacro(lang,id){switch(id){case'plural':return getPluralRule(lang.code);default:return undefined;}}}]);return Context;})();function reportMissing(keys,formatter,resolved){const missingIds=new Set();keys.forEach((key,i)=>{if(resolved&&resolved[i]!==undefined){return;}
|
||
const id=Array.isArray(key)?key[0]:key;missingIds.add(id);resolved[i]=formatter===this._formatValue?id:{value:id,attrs:null};});this.emit('notfounderror',new L10nError('"'+Array.from(missingIds).join(', ')+'"'+' not found in any language',missingIds));return resolved;}
|
||
var MAX_PLACEABLES=100;var PropertiesParser={patterns:null,entryIds:null,emit:null,init:function(){this.patterns={comment:/^\s*#|^\s*$/,entity:/^([^=\s]+)\s*=\s*(.*)$/,multiline:/[^\\]\\$/,index:/\{\[\s*(\w+)(?:\(([^\)]*)\))?\s*\]\}/i,unicode:/\\u([0-9a-fA-F]{1,4})/g,entries:/[^\r\n]+/g,controlChars:/\\([\\\n\r\t\b\f\{\}\"\'])/g,placeables:/\{\{\s*([^\s]*?)\s*\}\}/};},parse:function(emit,source){if(!this.patterns){this.init();}
|
||
this.emit=emit;var entries={};var lines=source.match(this.patterns.entries);if(!lines){return entries;}
|
||
for(var i=0;i<lines.length;i++){var line=lines[i];if(this.patterns.comment.test(line)){continue;}
|
||
while(this.patterns.multiline.test(line)&&i<lines.length){line=line.slice(0,-1)+lines[++i].trim();}
|
||
var entityMatch=line.match(this.patterns.entity);if(entityMatch){try{this.parseEntity(entityMatch[1],entityMatch[2],entries);}catch(e){if(!this.emit){throw e;}}}}
|
||
return entries;},parseEntity:function(id,value,entries){var name,key;var pos=id.indexOf('[');if(pos!==-1){name=id.substr(0,pos);key=id.substring(pos+1,id.length-1);}else{name=id;key=null;}
|
||
var nameElements=name.split('.');if(nameElements.length>2){throw this.error('Error in ID: "'+name+'".'+' Nested attributes are not supported.');}
|
||
var attr;if(nameElements.length>1){name=nameElements[0];attr=nameElements[1];if(attr[0]==='$'){throw this.error('Attribute can\'t start with "$"');}}else{attr=null;}
|
||
this.setEntityValue(name,attr,key,this.unescapeString(value),entries);},setEntityValue:function(id,attr,key,rawValue,entries){var value=rawValue.indexOf('{{')>-1?this.parseString(rawValue):rawValue;var isSimpleValue=typeof value==='string';var root=entries;var isSimpleNode=typeof entries[id]==='string';if(!entries[id]&&(attr||key||!isSimpleValue)){entries[id]=Object.create(null);isSimpleNode=false;}
|
||
if(attr){if(isSimpleNode){const val=entries[id];entries[id]=Object.create(null);entries[id].value=val;}
|
||
if(!entries[id].attrs){entries[id].attrs=Object.create(null);}
|
||
if(!entries[id].attrs&&!isSimpleValue){entries[id].attrs[attr]=Object.create(null);}
|
||
root=entries[id].attrs;id=attr;}
|
||
if(key){isSimpleNode=false;if(typeof root[id]==='string'){const val=root[id];root[id]=Object.create(null);root[id].index=this.parseIndex(val);root[id].value=Object.create(null);}
|
||
root=root[id].value;id=key;isSimpleValue=true;}
|
||
if(isSimpleValue){if(id in root){throw this.error('Duplicated id: '+id);}
|
||
root[id]=value;}else{if(!root[id]){root[id]=Object.create(null);}
|
||
root[id].value=value;}},parseString:function(str){var chunks=str.split(this.patterns.placeables);var complexStr=[];var len=chunks.length;var placeablesCount=(len-1)/2;if(placeablesCount>=MAX_PLACEABLES){throw this.error('Too many placeables ('+placeablesCount+', max allowed is '+MAX_PLACEABLES+')');}
|
||
for(var i=0;i<chunks.length;i++){if(chunks[i].length===0){continue;}
|
||
if(i%2===1){complexStr.push({type:'idOrVar',name:chunks[i]});}else{complexStr.push(chunks[i]);}}
|
||
return complexStr;},unescapeString:function(str){if(str.lastIndexOf('\\')!==-1){str=str.replace(this.patterns.controlChars,'$1');}
|
||
return str.replace(this.patterns.unicode,function(match,token){return String.fromCodePoint(parseInt(token,16));});},parseIndex:function(str){var match=str.match(this.patterns.index);if(!match){throw new L10nError('Malformed index');}
|
||
if(match[2]){return[{type:'call',expr:{type:'prop',expr:{type:'glob',name:'cldr'},prop:'plural',cmpt:false},args:[{type:'idOrVar',name:match[2]}]}];}else{return[{type:'idOrVar',name:match[1]}];}},error:function(msg,type='parsererror'){const err=new L10nError(msg);if(this.emit){this.emit(type,err);}
|
||
return err;}};const MAX_PLACEABLES$1=100;var L20nParser={parse:function(emit,string){this._source=string;this._index=0;this._length=string.length;this.entries=Object.create(null);this.emit=emit;return this.getResource();},getResource:function(){this.getWS();while(this._index<this._length){try{this.getEntry();}catch(e){if(e instanceof L10nError){this.getJunkEntry();if(!this.emit){throw e;}}else{throw e;}}
|
||
if(this._index<this._length){this.getWS();}}
|
||
return this.entries;},getEntry:function(){if(this._source[this._index]==='<'){++this._index;const id=this.getIdentifier();if(this._source[this._index]==='['){++this._index;return this.getEntity(id,this.getItemList(this.getExpression,']'));}
|
||
return this.getEntity(id);}
|
||
if(this._source.startsWith('/*',this._index)){return this.getComment();}
|
||
throw this.error('Invalid entry');},getEntity:function(id,index){if(!this.getRequiredWS()){throw this.error('Expected white space');}
|
||
const ch=this._source[this._index];const hasIndex=index!==undefined;const value=this.getValue(ch,hasIndex,hasIndex);let attrs;if(value===undefined){if(ch==='>'){throw this.error('Expected ">"');}
|
||
attrs=this.getAttributes();}else{const ws1=this.getRequiredWS();if(this._source[this._index]!=='>'){if(!ws1){throw this.error('Expected ">"');}
|
||
attrs=this.getAttributes();}}
|
||
++this._index;if(id in this.entries){throw this.error('Duplicate entry ID "'+id,'duplicateerror');}
|
||
if(!attrs&&!index&&typeof value==='string'){this.entries[id]=value;}else{this.entries[id]={value,attrs,index};}},getValue:function(ch=this._source[this._index],index=false,required=true){switch(ch){case'\'':case'"':return this.getString(ch,1);case'{':return this.getHash(index);}
|
||
if(required){throw this.error('Unknown value type');}
|
||
return;},getWS:function(){let cc=this._source.charCodeAt(this._index);while(cc===32||cc===10||cc===9||cc===13){cc=this._source.charCodeAt(++this._index);}},getRequiredWS:function(){const pos=this._index;let cc=this._source.charCodeAt(pos);while(cc===32||cc===10||cc===9||cc===13){cc=this._source.charCodeAt(++this._index);}
|
||
return this._index!==pos;},getIdentifier:function(){const start=this._index;let cc=this._source.charCodeAt(this._index);if(cc>=97&&cc<=122||cc>=65&&cc<=90||cc===95){cc=this._source.charCodeAt(++this._index);}else{throw this.error('Identifier has to start with [a-zA-Z_]');}
|
||
while(cc>=97&&cc<=122||cc>=65&&cc<=90||cc>=48&&cc<=57||cc===95){cc=this._source.charCodeAt(++this._index);}
|
||
return this._source.slice(start,this._index);},getUnicodeChar:function(){for(let i=0;i<4;i++){let cc=this._source.charCodeAt(++this._index);if(cc>96&&cc<103||cc>64&&cc<71||cc>47&&cc<58){continue;}
|
||
throw this.error('Illegal unicode escape sequence');}
|
||
this._index++;return String.fromCharCode(parseInt(this._source.slice(this._index-4,this._index),16));},stringRe:/"|'|{{|\\/g,getString:function(opchar,opcharLen){const body=[];let placeables=0;this._index+=opcharLen;const start=this._index;let bufStart=start;let buf='';while(true){this.stringRe.lastIndex=this._index;const match=this.stringRe.exec(this._source);if(!match){throw this.error('Unclosed string literal');}
|
||
if(match[0]==='"'||match[0]==='\''){if(match[0]!==opchar){this._index+=opcharLen;continue;}
|
||
this._index=match.index+opcharLen;break;}
|
||
if(match[0]==='{{'){if(placeables>MAX_PLACEABLES$1-1){throw this.error('Too many placeables, maximum allowed is '+MAX_PLACEABLES$1);}
|
||
placeables++;if(match.index>bufStart||buf.length>0){body.push(buf+this._source.slice(bufStart,match.index));buf='';}
|
||
this._index=match.index+2;this.getWS();body.push(this.getExpression());this.getWS();this._index+=2;bufStart=this._index;continue;}
|
||
if(match[0]==='\\'){this._index=match.index+1;const ch2=this._source[this._index];if(ch2==='u'){buf+=this._source.slice(bufStart,match.index)+this.getUnicodeChar();}else if(ch2===opchar||ch2==='\\'){buf+=this._source.slice(bufStart,match.index)+ch2;this._index++;}else if(this._source.startsWith('{{',this._index)){buf+=this._source.slice(bufStart,match.index)+'{{';this._index+=2;}else{throw this.error('Illegal escape sequence');}
|
||
bufStart=this._index;}}
|
||
if(body.length===0){return buf+this._source.slice(bufStart,this._index-opcharLen);}
|
||
if(this._index-opcharLen>bufStart||buf.length>0){body.push(buf+this._source.slice(bufStart,this._index-opcharLen));}
|
||
return body;},getAttributes:function(){const attrs=Object.create(null);while(true){this.getAttribute(attrs);const ws1=this.getRequiredWS();const ch=this._source.charAt(this._index);if(ch==='>'){break;}else if(!ws1){throw this.error('Expected ">"');}}
|
||
return attrs;},getAttribute:function(attrs){const key=this.getIdentifier();let index;if(this._source[this._index]==='['){++this._index;this.getWS();index=this.getItemList(this.getExpression,']');}
|
||
this.getWS();if(this._source[this._index]!==':'){throw this.error('Expected ":"');}
|
||
++this._index;this.getWS();const hasIndex=index!==undefined;const value=this.getValue(undefined,hasIndex);if(key in attrs){throw this.error('Duplicate attribute "'+key,'duplicateerror');}
|
||
if(!index&&typeof value==='string'){attrs[key]=value;}else{attrs[key]={value,index};}},getHash:function(index){const items=Object.create(null);++this._index;this.getWS();let defKey;while(true){const[key,value,def]=this.getHashItem();items[key]=value;if(def){if(defKey){throw this.error('Default item redefinition forbidden');}
|
||
defKey=key;}
|
||
this.getWS();const comma=this._source[this._index]===',';if(comma){++this._index;this.getWS();}
|
||
if(this._source[this._index]==='}'){++this._index;break;}
|
||
if(!comma){throw this.error('Expected "}"');}}
|
||
if(defKey){items.__default=defKey;}else if(!index){throw this.error('Unresolvable Hash Value');}
|
||
return items;},getHashItem:function(){let defItem=false;if(this._source[this._index]==='*'){++this._index;defItem=true;}
|
||
const key=this.getIdentifier();this.getWS();if(this._source[this._index]!==':'){throw this.error('Expected ":"');}
|
||
++this._index;this.getWS();return[key,this.getValue(),defItem];},getComment:function(){this._index+=2;const start=this._index;const end=this._source.indexOf('*/',start);if(end===-1){throw this.error('Comment without a closing tag');}
|
||
this._index=end+2;},getExpression:function(){let exp=this.getPrimaryExpression();while(true){let ch=this._source[this._index];if(ch==='.'||ch==='['){++this._index;exp=this.getPropertyExpression(exp,ch==='[');}else if(ch==='('){++this._index;exp=this.getCallExpression(exp);}else{break;}}
|
||
return exp;},getPropertyExpression:function(idref,computed){let exp;if(computed){this.getWS();exp=this.getExpression();this.getWS();if(this._source[this._index]!==']'){throw this.error('Expected "]"');}
|
||
++this._index;}else{exp=this.getIdentifier();}
|
||
return{type:'prop',expr:idref,prop:exp,cmpt:computed};},getCallExpression:function(callee){this.getWS();return{type:'call',expr:callee,args:this.getItemList(this.getExpression,')')};},getPrimaryExpression:function(){const ch=this._source[this._index];switch(ch){case'$':++this._index;return{type:'var',name:this.getIdentifier()};case'@':++this._index;return{type:'glob',name:this.getIdentifier()};default:return{type:'id',name:this.getIdentifier()};}},getItemList:function(callback,closeChar){const items=[];let closed=false;this.getWS();if(this._source[this._index]===closeChar){++this._index;closed=true;}
|
||
while(!closed){items.push(callback.call(this));this.getWS();let ch=this._source.charAt(this._index);switch(ch){case',':++this._index;this.getWS();break;case closeChar:++this._index;closed=true;break;default:throw this.error('Expected "," or "'+closeChar+'"');}}
|
||
return items;},getJunkEntry:function(){const pos=this._index;let nextEntity=this._source.indexOf('<',pos);let nextComment=this._source.indexOf('/*',pos);if(nextEntity===-1){nextEntity=this._length;}
|
||
if(nextComment===-1){nextComment=this._length;}
|
||
let nextEntry=Math.min(nextEntity,nextComment);this._index=nextEntry;},error:function(message,type='parsererror'){const pos=this._index;let start=this._source.lastIndexOf('<',pos-1);const lastClose=this._source.lastIndexOf('>',pos-1);start=lastClose>start?lastClose+1:start;const context=this._source.slice(start,pos+10);const msg=message+' at pos '+pos+': `'+context+'`';const err=new L10nError(msg);if(this.emit){this.emit(type,err);}
|
||
return err;}};function walkEntry(entry,fn){if(typeof entry==='string'){return fn(entry);}
|
||
const newEntry=Object.create(null);if(entry.value){newEntry.value=walkValue(entry.value,fn);}
|
||
if(entry.index){newEntry.index=entry.index;}
|
||
if(entry.attrs){newEntry.attrs=Object.create(null);for(let key in entry.attrs){newEntry.attrs[key]=walkEntry(entry.attrs[key],fn);}}
|
||
return newEntry;}
|
||
function walkValue(value,fn){if(typeof value==='string'){return fn(value);}
|
||
if(value.type){return value;}
|
||
const newValue=Array.isArray(value)?[]:Object.create(null);const keys=Object.keys(value);for(let i=0,key;key=keys[i];i++){newValue[key]=walkValue(value[key],fn);}
|
||
return newValue;}
|
||
function createGetter(id,name){let _pseudo=null;return function getPseudo(){if(_pseudo){return _pseudo;}
|
||
const reAlphas=/[a-zA-Z]/g;const reVowels=/[aeiouAEIOU]/g;const reWords=/[^\W0-9_]+/g;const reExcluded=/(%[EO]?\w|\{\s*.+?\s*\}|&[#\w]+;|<\s*.+?\s*>)/;const charMaps={'fr-x-psaccent':'ȦƁƇḒḖƑƓĦĪĴĶĿḾȠǾƤɊŘŞŦŬṼẆẊẎẐ[\\]^_`ȧƀƈḓḗƒɠħīĵķŀḿƞǿƥɋřşŧŭṽẇẋẏẑ','ar-x-psbidi':'∀ԐↃpƎɟפHIſӼ˥WNOԀÒᴚS⊥∩ɅMXʎZ[\\]ᵥ_,ɐqɔpǝɟƃɥıɾʞʅɯuodbɹsʇnʌʍxʎz'};const mods={'fr-x-psaccent':val=>val.replace(reVowels,match=>match+match.toLowerCase()),'ar-x-psbidi':val=>val.replace(reWords,match=>''+match+'')};const replaceChars=(map,val)=>val.replace(reAlphas,match=>map.charAt(match.charCodeAt(0)-65));const transform=val=>replaceChars(charMaps[id],mods[id](val));const apply=(fn,val)=>{if(!val){return val;}
|
||
const parts=val.split(reExcluded);const modified=parts.map(function(part){if(reExcluded.test(part)){return part;}
|
||
return fn(part);});return modified.join('');};return _pseudo={name:transform(name),process:str=>apply(transform,str)};};}
|
||
const pseudo=Object.defineProperties(Object.create(null),{'fr-x-psaccent':{enumerable:true,get:createGetter('fr-x-psaccent','Runtime Accented')},'ar-x-psbidi':{enumerable:true,get:createGetter('ar-x-psbidi','Runtime Bidi')}});let Env=(function(){function Env(fetchResource){_classCallCheck(this,Env);this.fetchResource=fetchResource;this.resCache=new Map();this.resRefs=new Map();this.numberFormatters=null;this.parsers={properties:PropertiesParser,l20n:L20nParser};const listeners={};this.emit=emit.bind(this,listeners);this.addEventListener=addEventListener.bind(this,listeners);this.removeEventListener=removeEventListener.bind(this,listeners);}
|
||
_createClass(Env,[{key:'createContext',value:function createContext(langs,resIds){const ctx=new Context(this,langs,resIds);resIds.forEach(resId=>{const usedBy=this.resRefs.get(resId)||0;this.resRefs.set(resId,usedBy+1);});return ctx;}},{key:'destroyContext',value:function destroyContext(ctx){ctx.resIds.forEach(resId=>{const usedBy=this.resRefs.get(resId)||0;if(usedBy>1){return this.resRefs.set(resId,usedBy-1);}
|
||
this.resRefs.delete(resId);this.resCache.forEach((val,key)=>key.startsWith(resId)?this.resCache.delete(key):null);});}},{key:'_parse',value:function _parse(syntax,lang,data){const parser=this.parsers[syntax];if(!parser){return data;}
|
||
const emit=(type,err)=>this.emit(type,amendError(lang,err));return parser.parse.call(parser,emit,data);}},{key:'_create',value:function _create(lang,entries){if(lang.src!=='pseudo'){return entries;}
|
||
const pseudoentries=Object.create(null);for(let key in entries){pseudoentries[key]=walkEntry(entries[key],pseudo[lang.code].process);}
|
||
return pseudoentries;}},{key:'_getResource',value:function _getResource(lang,res){const cache=this.resCache;const id=res+lang.code+lang.src;if(cache.has(id)){return cache.get(id);}
|
||
const syntax=res.substr(res.lastIndexOf('.')+1);const saveEntries=data=>{const entries=this._parse(syntax,lang,data);cache.set(id,this._create(lang,entries));};const recover=err=>{err.lang=lang;this.emit('fetcherror',err);cache.set(id,err);};const langToFetch=lang.src==='pseudo'?{code:'en-US',src:'app',ver:lang.ver}:lang;const resource=this.fetchResource(res,langToFetch).then(saveEntries,recover);cache.set(id,resource);return resource;}}]);return Env;})();function amendError(lang,err){err.lang=lang;return err;}
|
||
function prioritizeLocales(def,availableLangs,requested){let supportedLocale;for(let i=0;i<requested.length;i++){const locale=requested[i];if(availableLangs.indexOf(locale)!==-1){supportedLocale=locale;break;}}
|
||
if(!supportedLocale||supportedLocale===def){return[def];}
|
||
return[supportedLocale,def];}
|
||
function negotiateLanguages({appVersion,defaultLang,availableLangs},additionalLangs,prevLangs,requestedLangs){const allAvailableLangs=Object.keys(availableLangs).concat(Object.keys(additionalLangs)).concat(Object.keys(pseudo));const newLangs=prioritizeLocales(defaultLang,allAvailableLangs,requestedLangs);const langs=newLangs.map(code=>({code:code,src:getLangSource(appVersion,availableLangs,additionalLangs,code),ver:appVersion}));return{langs,haveChanged:!arrEqual(prevLangs,newLangs)};}
|
||
function arrEqual(arr1,arr2){return arr1.length===arr2.length&&arr1.every((elem,i)=>elem===arr2[i]);}
|
||
function getMatchingLangpack(appVersion,langpacks){for(let i=0,langpack;langpack=langpacks[i];i++){if(langpack.target===appVersion){return langpack;}}
|
||
return null;}
|
||
function getLangSource(appVersion,availableLangs,additionalLangs,code){if(additionalLangs&&additionalLangs[code]){const lp=getMatchingLangpack(appVersion,additionalLangs[code]);if(lp&&(!(code in availableLangs)||parseInt(lp.revision)>availableLangs[code])){return'extra';}}
|
||
if(code in pseudo&&!(code in availableLangs)){return'pseudo';}
|
||
return'app';}
|
||
let Remote=(function(){function Remote(fetchResource,broadcast){_classCallCheck(this,Remote);this.broadcast=broadcast;this.env=new Env(fetchResource);this.ctxs=new Map();}
|
||
_createClass(Remote,[{key:'registerView',value:function registerView(view,resources,meta,additionalLangs,requestedLangs){const{langs}=negotiateLanguages(meta,additionalLangs,[],requestedLangs);this.ctxs.set(view,this.env.createContext(langs,resources));return langs;}},{key:'unregisterView',value:function unregisterView(view){this.ctxs.delete(view);return true;}},{key:'formatEntities',value:function formatEntities(view,keys){return this.ctxs.get(view).formatEntities(...keys);}},{key:'formatValues',value:function formatValues(view,keys){return this.ctxs.get(view).formatValues(...keys);}},{key:'changeLanguages',value:function changeLanguages(view,meta,additionalLangs,requestedLangs){const oldCtx=this.ctxs.get(view);const prevLangs=oldCtx.langs;const newLangs=negotiateLanguages(meta,additionalLangs,prevLangs,requestedLangs);this.ctxs.set(view,this.env.createContext(newLangs.langs,oldCtx.resIds));return newLangs;}},{key:'requestLanguages',value:function requestLanguages(requestedLangs){this.broadcast('languageschangerequest',requestedLangs);}},{key:'getName',value:function getName(code){return pseudo[code].name;}},{key:'processString',value:function processString(code,str){return pseudo[code].process(str);}}]);return Remote;})();const observerConfig={attributes:true,characterData:false,childList:true,subtree:true,attributeFilter:['data-l10n-id','data-l10n-args']};const observers=new WeakMap();function initMutationObserver(view){observers.set(view,{roots:new Set(),observer:new MutationObserver(mutations=>translateMutations(view,mutations))});}
|
||
function translateRoots(view){return Promise.all([...observers.get(view).roots].map(root=>_translateFragment(view,root)));}
|
||
function observe(view,root){const obs=observers.get(view);if(obs){obs.roots.add(root);obs.observer.observe(root,observerConfig);}}
|
||
function disconnect(view,root,allRoots){const obs=observers.get(view);if(obs){obs.observer.disconnect();if(allRoots){return;}
|
||
obs.roots.delete(root);obs.roots.forEach(other=>obs.observer.observe(other,observerConfig));}}
|
||
function reconnect(view){const obs=observers.get(view);if(obs){obs.roots.forEach(root=>obs.observer.observe(root,observerConfig));}}
|
||
const reOverlay=/<|&#?\w+;/;const allowed={elements:['a','em','strong','small','s','cite','q','dfn','abbr','data','time','code','var','samp','kbd','sub','sup','i','b','u','mark','ruby','rt','rp','bdi','bdo','span','br','wbr'],attributes:{global:['title','aria-label','aria-valuetext','aria-moz-hint'],a:['download'],area:['download','alt'],input:['alt','placeholder'],menuitem:['label'],menu:['label'],optgroup:['label'],option:['label'],track:['label'],img:['alt'],textarea:['placeholder'],th:['abbr']}};function overlayElement(element,translation){const value=translation.value;if(typeof value==='string'){if(!reOverlay.test(value)){element.textContent=value;}else{const tmpl=element.ownerDocument.createElement('template');tmpl.innerHTML=value;overlay(element,tmpl.content);}}
|
||
for(let key in translation.attrs){const attrName=camelCaseToDashed(key);if(isAttrAllowed({name:attrName},element)){element.setAttribute(attrName,translation.attrs[key]);}}}
|
||
function overlay(sourceElement,translationElement){const result=translationElement.ownerDocument.createDocumentFragment();let k,attr;let childElement;while(childElement=translationElement.childNodes[0]){translationElement.removeChild(childElement);if(childElement.nodeType===childElement.TEXT_NODE){result.appendChild(childElement);continue;}
|
||
const index=getIndexOfType(childElement);const sourceChild=getNthElementOfType(sourceElement,childElement,index);if(sourceChild){overlay(sourceChild,childElement);result.appendChild(sourceChild);continue;}
|
||
if(isElementAllowed(childElement)){const sanitizedChild=childElement.ownerDocument.createElement(childElement.nodeName);overlay(sanitizedChild,childElement);result.appendChild(sanitizedChild);continue;}
|
||
result.appendChild(translationElement.ownerDocument.createTextNode(childElement.textContent));}
|
||
sourceElement.textContent='';sourceElement.appendChild(result);if(translationElement.attributes){for(k=0,attr;attr=translationElement.attributes[k];k++){if(isAttrAllowed(attr,sourceElement)){sourceElement.setAttribute(attr.name,attr.value);}}}}
|
||
function isElementAllowed(element){return allowed.elements.indexOf(element.tagName.toLowerCase())!==-1;}
|
||
function isAttrAllowed(attr,element){const attrName=attr.name.toLowerCase();const tagName=element.tagName.toLowerCase();if(allowed.attributes.global.indexOf(attrName)!==-1){return true;}
|
||
if(!allowed.attributes[tagName]){return false;}
|
||
if(allowed.attributes[tagName].indexOf(attrName)!==-1){return true;}
|
||
if(tagName==='input'&&attrName==='value'){const type=element.type.toLowerCase();if(type==='submit'||type==='button'||type==='reset'){return true;}}
|
||
return false;}
|
||
function getNthElementOfType(context,element,index){let nthOfType=0;for(let i=0,child;child=context.children[i];i++){if(child.nodeType===child.ELEMENT_NODE&&child.tagName===element.tagName){if(nthOfType===index){return child;}
|
||
nthOfType++;}}
|
||
return null;}
|
||
function getIndexOfType(element){let index=0;let child;while(child=element.previousElementSibling){if(child.tagName===element.tagName){index++;}}
|
||
return index;}
|
||
function camelCaseToDashed(string){if(string==='ariaValueText'){return'aria-valuetext';}
|
||
return string.replace(/[A-Z]/g,function(match){return'-'+match.toLowerCase();}).replace(/^-/,'');}
|
||
const reHtml=/[&<>]/g;const htmlEntities={'&':'&','<':'<','>':'>'};function setAttributes(element,id,args){element.setAttribute('data-l10n-id',id);if(args){element.setAttribute('data-l10n-args',JSON.stringify(args));}}
|
||
function getAttributes(element){return{id:element.getAttribute('data-l10n-id'),args:JSON.parse(element.getAttribute('data-l10n-args'))};}
|
||
function getTranslatables(element){const nodes=Array.from(element.querySelectorAll('[data-l10n-id]'));if(typeof element.hasAttribute==='function'&&element.hasAttribute('data-l10n-id')){nodes.push(element);}
|
||
return nodes;}
|
||
function translateMutations(view,mutations){const targets=new Set();for(let mutation of mutations){switch(mutation.type){case'attributes':targets.add(mutation.target);break;case'childList':for(let addedNode of mutation.addedNodes){if(addedNode.nodeType===addedNode.ELEMENT_NODE){if(addedNode.childElementCount){getTranslatables(addedNode).forEach(targets.add.bind(targets));}else{if(addedNode.hasAttribute('data-l10n-id')){targets.add(addedNode);}}}}
|
||
break;}}
|
||
if(targets.size===0){return;}
|
||
translateElements(view,Array.from(targets));}
|
||
function _translateFragment(view,frag){return translateElements(view,getTranslatables(frag));}
|
||
function getElementsTranslation(view,elems){const keys=elems.map(elem=>{const id=elem.getAttribute('data-l10n-id');const args=elem.getAttribute('data-l10n-args');return args?[id,JSON.parse(args.replace(reHtml,match=>htmlEntities[match]))]:id;});return view.formatEntities(...keys);}
|
||
function translateElements(view,elements){return getElementsTranslation(view,elements).then(translations=>applyTranslations(view,elements,translations));}
|
||
function applyTranslations(view,elems,translations){disconnect(view,null,true);for(let i=0;i<elems.length;i++){overlayElement(elems[i],translations[i]);}
|
||
reconnect(view);}
|
||
if(typeof NodeList==='function'&&!NodeList.prototype[Symbol.iterator]){NodeList.prototype[Symbol.iterator]=Array.prototype[Symbol.iterator];}
|
||
function documentReady(){if(document.readyState!=='loading'){return Promise.resolve();}
|
||
return new Promise(resolve=>{document.addEventListener('readystatechange',function onrsc(){document.removeEventListener('readystatechange',onrsc);resolve();});});}
|
||
function getDirection(code){const tag=code.split('-')[0];return['ar','he','fa','ps','ur'].indexOf(tag)>=0?'rtl':'ltr';}
|
||
if(navigator.languages===undefined){navigator.languages=[navigator.language];}
|
||
function getResourceLinks(head){return Array.prototype.map.call(head.querySelectorAll('link[rel="localization"]'),el=>el.getAttribute('href'));}
|
||
function getMeta(head){let availableLangs=Object.create(null);let defaultLang=null;let appVersion=null;const metas=Array.from(head.querySelectorAll('meta[name="availableLanguages"],'+'meta[name="defaultLanguage"],'+'meta[name="appVersion"]'));for(let meta of metas){const name=meta.getAttribute('name');const content=meta.getAttribute('content').trim();switch(name){case'availableLanguages':availableLangs=getLangRevisionMap(availableLangs,content);break;case'defaultLanguage':const[lang,rev]=getLangRevisionTuple(content);defaultLang=lang;if(!(lang in availableLangs)){availableLangs[lang]=rev;}
|
||
break;case'appVersion':appVersion=content;}}
|
||
return{defaultLang,availableLangs,appVersion};}
|
||
function getLangRevisionMap(seq,str){return str.split(',').reduce((seq,cur)=>{const[lang,rev]=getLangRevisionTuple(cur);seq[lang]=rev;return seq;},seq);}
|
||
function getLangRevisionTuple(str){const[lang,rev]=str.trim().split(':');return[lang,parseInt(rev)];}
|
||
const viewProps=new WeakMap();let View=(function(){function View(client,doc){_classCallCheck(this,View);this.pseudo={'fr-x-psaccent':createPseudo(this,'fr-x-psaccent'),'ar-x-psbidi':createPseudo(this,'ar-x-psbidi')};const initialized=documentReady().then(()=>init(this,client));this._interactive=initialized.then(()=>client);this.ready=initialized.then(langs=>translateView(this,langs));initMutationObserver(this);viewProps.set(this,{doc:doc,ready:false});client.on('languageschangerequest',requestedLangs=>this.requestLanguages(requestedLangs));}
|
||
_createClass(View,[{key:'requestLanguages',value:function requestLanguages(requestedLangs,isGlobal){const method=isGlobal?client=>client.method('requestLanguages',requestedLangs):client=>changeLanguages(this,client,requestedLangs);return this._interactive.then(method);}},{key:'handleEvent',value:function handleEvent(){return this.requestLanguages(navigator.languages);}},{key:'formatEntities',value:function formatEntities(...keys){return this._interactive.then(client=>client.method('formatEntities',client.id,keys));}},{key:'formatValue',value:function formatValue(id,args){return this._interactive.then(client=>client.method('formatValues',client.id,[[id,args]])).then(values=>values[0]);}},{key:'formatValues',value:function formatValues(...keys){return this._interactive.then(client=>client.method('formatValues',client.id,keys));}},{key:'translateFragment',value:function translateFragment(frag){return _translateFragment(this,frag);}},{key:'observeRoot',value:function observeRoot(root){observe(this,root);}},{key:'disconnectRoot',value:function disconnectRoot(root){disconnect(this,root);}}]);return View;})();View.prototype.setAttributes=setAttributes;View.prototype.getAttributes=getAttributes;function createPseudo(view,code){return{getName:()=>view._interactive.then(client=>client.method('getName',code)),processString:str=>view._interactive.then(client=>client.method('processString',code,str))};}
|
||
function init(view,client){const doc=viewProps.get(view).doc;const resources=getResourceLinks(doc.head);const meta=getMeta(doc.head);view.observeRoot(doc.documentElement);return getAdditionalLanguages().then(additionalLangs=>client.method('registerView',client.id,resources,meta,additionalLangs,navigator.languages));}
|
||
function changeLanguages(view,client,requestedLangs){const doc=viewProps.get(view).doc;const meta=getMeta(doc.head);return getAdditionalLanguages().then(additionalLangs=>client.method('changeLanguages',client.id,meta,additionalLangs,requestedLangs)).then(({langs,haveChanged})=>haveChanged?translateView(view,langs):undefined);}
|
||
function getAdditionalLanguages(){if(navigator.mozApps&&navigator.mozApps.getAdditionalLanguages){return navigator.mozApps.getAdditionalLanguages().catch(()=>Object.create(null));}
|
||
return Promise.resolve(Object.create(null));}
|
||
function translateView(view,langs){const props=viewProps.get(view);const html=props.doc.documentElement;if(props.ready){return translateRoots(view).then(()=>setAllAndEmit(html,langs));}
|
||
const translated=langs[0].code===html.getAttribute('lang')?Promise.resolve():translateRoots(view).then(()=>setLangDir(html,langs));return translated.then(()=>{setLangs(html,langs);props.ready=true;});}
|
||
function setLangs(html,langs){const codes=langs.map(lang=>lang.code);html.setAttribute('langs',codes.join(' '));}
|
||
function setLangDir(html,langs){const code=langs[0].code;html.setAttribute('lang',code);html.setAttribute('dir',getDirection(code));}
|
||
function setAllAndEmit(html,langs){setLangDir(html,langs);setLangs(html,langs);html.parentNode.dispatchEvent(new CustomEvent('DOMRetranslated',{bubbles:false,cancelable:false}));}
|
||
const remote=new Remote(fetchResource,broadcast);const client=new Client(remote);document.l10n=new View(client,document);window.addEventListener('languagechange',document.l10n);document.addEventListener('additionallanguageschange',document.l10n);navigator.mozL10n={setAttributes:document.l10n.setAttributes,getAttributes:document.l10n.getAttributes,formatValue:(...args)=>document.l10n.formatValue(...args),translateFragment:(...args)=>document.l10n.translateFragment(...args),once:cb=>document.l10n.ready.then(cb),ready:cb=>document.l10n.ready.then(()=>{document.addEventListener('DOMRetranslated',cb);cb();})};})();;'use strict';function tzSelect(regionSelector,citySelector,onchange,onload){const TIMEZONE_FILE='/shared/resources/tz.json';const APN_TZ_FILE='/shared/resources/apn_tz.json';const TIMEZONE_NONE='NONE';const TIMEZONE_NETWORK='NETWORK';const TIMEZONE_SIM='SIM';const TIMEZONE_USER='USER';const TIMEZONE_PREVIOUS_SETTING='PREVIOUS_SETTING';function loadJSON(href,callback){var xhr=new XMLHttpRequest();xhr.open('GET',href,true);xhr.responseType='json';xhr.onerror=callback;xhr.onload=function(){callback(xhr.response);};xhr.onerror=function(){console.error('Error getting file');callback(xhr.response);};xhr.send();}
|
||
function getDefaultTimezoneID(callback){if(!callback){return;}
|
||
var tzDefault='America/New_York';var source=TIMEZONE_NONE;var mcc,mnc;var connections=window.navigator.mozMobileConnections||[];for(var i=0;i<connections.length;++i){var conn=connections[i];if(conn&&conn.voice&&conn.voice.network&&conn.voice.connected){mcc=conn.voice.network.mcc;mnc=conn.voice.network.mnc;source=TIMEZONE_NETWORK;break;}}
|
||
if(!mcc&&IccHelper&&IccHelper.iccInfo){mcc=IccHelper.iccInfo.mcc;mnc=IccHelper.iccInfo.mnc;source=TIMEZONE_SIM;if(IccHelper.cardState!=='ready'){IccHelper.addEventListener('iccinfochange',function simReady(){if(IccHelper.iccInfo.mcc){IccHelper.removeEventListener('iccinfochange',simReady);}
|
||
getDefaultTimezoneID(callback);});}}
|
||
if(!mcc){callback(tzDefault,TIMEZONE_NONE);return;}
|
||
loadJSON(APN_TZ_FILE,function(response){if(response){var tz=response[mcc];if(typeof(tz)==='string'){callback(tz,source);return;}else if(tz&&(mnc in tz)){callback(tz[mnc],source);return;}}
|
||
callback(tzDefault,TIMEZONE_NONE);});}
|
||
function newTZSelector(onchangeTZ,currentID,source){var gRegion=currentID.replace(/\/.*/,'');var gCity=currentID.replace(/.*?\//,'');var gTZ=null;function fillSelectElement(selector,options){selector.innerHTML='';options.sort(function(a,b){return(a.text>b.text);});for(var i=0;i<options.length;i++){var option=document.createElement('option');option.textContent=options[i].text;option.selected=options[i].selected;option.value=options[i].value;selector.appendChild(option);}}
|
||
function fillSelectL10nElement(selector,options){selector.innerHTML='';const collator=Intl.Collator(navigator.languages,{usage:'sort',});const frag=document.createDocumentFragment();const items=options.map(option=>{const item=document.createElement('option');item.setAttribute('data-l10n-id',option.l10nId);item.selected=option.selected;item.value=option.value;frag.appendChild(item);return item;});return document.l10n.translateFragment(frag).then(()=>{items.sort((a,b)=>collator.compare(a.textContent,b.textContent));items.forEach(item=>frag.appendChild(item));selector.appendChild(frag);});}
|
||
function getSelectedText(selector){var options=selector.querySelectorAll('option');return options[selector.selectedIndex].textContent;}
|
||
function fillRegions(){var options=[];for(var c in gTZ){options.push({l10nId:'tzRegion-'+c,value:c,selected:(c===gRegion)});}
|
||
fillSelectL10nElement(regionSelector,options).then(fillCities);}
|
||
function fillCities(){gRegion=regionSelector.value;var list=gTZ[gRegion];var options=[];for(var i=0;i<list.length;i++){options.push({text:list[i].name||list[i].city.replace(/_/g,' '),value:i,selected:(list[i].city===gCity)});}
|
||
fillSelectElement(citySelector,options);setTimezone();}
|
||
function setTimezone(){if(source===TIMEZONE_PREVIOUS_SETTING){onload&&onload(getTZInfo(),true);return;}
|
||
onchangeTZ(getTZInfo(),{'changedByUser':source===TIMEZONE_USER,'needsConfirmation':source!==TIMEZONE_USER&&source!==TIMEZONE_NETWORK});}
|
||
function getTZInfo(){var res=gTZ[gRegion][citySelector.value];gCity=res.city;var offset=res.offset.split(',');return{id:res.id||gRegion+'/'+res.city,region:getSelectedText(regionSelector),city:getSelectedText(citySelector),cc:res.cc,utcOffset:offset[0],dstOffset:offset[1]};}
|
||
regionSelector.onchange=function(){source=TIMEZONE_USER;fillCities();};citySelector.onchange=function(){source=TIMEZONE_USER;setTimezone();};loadJSON(TIMEZONE_FILE,function loadTZ(response){gTZ=response;fillRegions();});}
|
||
function newTZObserver(){var settings=window.navigator.mozSettings;if(!settings){return;}
|
||
settings.addObserver('time.timezone',function(event){setTimezoneDescription(event.settingValue);});var systemTimeChanged=function(){onchange(systemTimeChanged.tz,systemTimeChanged.needsConfirmation);};function updateTZ(tz,options){systemTimeChanged.tz=tz;systemTimeChanged.needsConfirmation=options.needsConfirmation;var req=settings.createLock().set({'time.timezone':tz.id});req.onsuccess=function updateTZ_callback(){if(options.changedByUser){settings.createLock().set({'time.timezone.user-selected':tz.id});}else{onload&&onload(tz,options.needsConfirmation);}};}
|
||
function initSelector(initialValue,source){onchange&&window.addEventListener('moztimechange',systemTimeChanged);onchange&&window.addEventListener('unload',function(){window.removeEventListener('moztimechange',systemTimeChanged);});newTZSelector(updateTZ,initialValue,source);}
|
||
var reqTimezone=settings.createLock().get('time.timezone');reqTimezone.onsuccess=function dt_getStatusSuccess(){var reqUserTZ=settings.createLock().get('time.timezone.user-selected');reqUserTZ.onsuccess=function dt_getUserTimezoneSuccess(){var userSelTimezone=reqUserTZ.result['time.timezone.user-selected'];if(userSelTimezone){initSelector(userSelTimezone,TIMEZONE_PREVIOUS_SETTING);}else{getDefaultTimezoneID(initSelector);}};};function setTimezoneDescription(timezoneID){var oldSelectedIndex=regionSelector.selectedIndex;regionSelector.value=timezoneID.replace(/\/.*/,'');if(regionSelector.selectedIndex==-1){regionSelector.selectedIndex=oldSelectedIndex;}
|
||
oldSelectedIndex=citySelector.selectedIndex;citySelector.value=timezoneID.replace(/.*?\//,'');if(citySelector.selectedIndex==-1){citySelector.selectedIndex=oldSelectedIndex;}}}
|
||
newTZObserver();};(function(root,factory){'use strict';if(typeof define==='function'&&define.amd){define(factory);}else if(typeof exports==='object'){module.exports=factory();}else{root.Sanitizer=factory();}}(this,function(){'use strict';var Sanitizer={_entity:/[&<>"'/]/g,_entities:{'&':'&','<':'<','>':'>','"':'"','\'':''','/':'/'},getEntity:function(s){return Sanitizer._entities[s];},escapeHTML:function(strings,...values){var result='';for(var i=0;i<strings.length;i++){result+=strings[i];if(i<values.length){result+=String(values[i]).replace(Sanitizer._entity,Sanitizer.getEntity);}}
|
||
return result;},createSafeHTML:function(strings,...values){var escaped=Sanitizer.escapeHTML(strings,...values);return{__html:escaped,toString:function(){return'[object WrappedHTMLObject]';},info:'This is a wrapped HTML object. See https://developer.mozilla.or'+'g/en-US/Firefox_OS/Security/Security_Automation for more.'};},unwrapSafeHTML:function(...htmlObjects){var markupList=htmlObjects.map(function(obj){return obj.__html;});return markupList.join('');}};return Sanitizer;}));;'use strict';(function(exports){var InputApp=function(domApp,dynamicInputs){this.domApp=domApp;this.dynamicInputs=dynamicInputs||{};if(!this.domApp.manifest){throw new Error('InputApp: should not be constructed before DOMApplication '+'has manifest ready.');}};InputApp.prototype.getInputs=function(){var dict={};var inputId;for(inputId in this.domApp.manifest.inputs){dict[inputId]=this.domApp.manifest.inputs[inputId];delete dict[inputId].nameL10nId;}
|
||
for(inputId in this.dynamicInputs){if(inputId in dict){break;}
|
||
dict[inputId]=this.dynamicInputs[inputId];dict[inputId].isDynamic=true;}
|
||
if(this.domApp.manifest.type==='certified'){if('emoji'in dict){dict.emoji.nameL10nId='keyboard-layout-emoji';}}
|
||
return dict;};var InputAppListSettings=function(){this._values={enable3rdPartyApps:undefined,dynamicInputs:undefined};this._bindCallback=null;this.ready=false;this._promise=null;};InputAppListSettings.prototype.onchange=null;InputAppListSettings.prototype.SETTINGS_KEY_THIRD_PARTY_APP_ENABLED='keyboard.3rd-party-app.enabled';InputAppListSettings.prototype.SETTINGS_KEY_DYNAMIC_INPUTS='keyboard.dynamic-inputs';InputAppListSettings.prototype.start=function(){if(navigator.mozSettings){this._bindCallback=this.callback.bind(this);navigator.mozSettings.addObserver(this.SETTINGS_KEY_THIRD_PARTY_APP_ENABLED,this._bindCallback);navigator.mozSettings.addObserver(this.SETTINGS_KEY_DYNAMIC_INPUTS,this._bindCallback);}
|
||
this.getSettings().then(function(){this.ready=true;}.bind(this));};InputAppListSettings.prototype.getSettings=function(){if(this.ready){return this.getSettingsSync();}
|
||
return this.getSettingsAsync();};InputAppListSettings.prototype.getSettingsSync=function(){if(!this.ready){console.warn('getSettingsSync: getSettingsSync called before ready.');}
|
||
return this._values;};InputAppListSettings.prototype.getSettingsAsync=function(){if(this._promise){return this._promise;}
|
||
var lock=navigator.mozSettings.createLock();var p=this._promise=Promise.all([lock.get(this.SETTINGS_KEY_THIRD_PARTY_APP_ENABLED),lock.get(this.SETTINGS_KEY_DYNAMIC_INPUTS)]).then(function(values){this._values.enable3rdPartyApps=values[0][this.SETTINGS_KEY_THIRD_PARTY_APP_ENABLED];this._values.dynamicInputs=values[1][this.SETTINGS_KEY_DYNAMIC_INPUTS];return this._values;}.bind(this)).catch(function(e){console.error('InputAppListSettings: Fail to get setting.',e);this._promise=null;this._values.enable3rdPartyApps=false;this._values.dynamicInputs={};return this._values;}.bind(this));return p;};InputAppListSettings.prototype.callback=function(obj){switch(obj.settingName){case this.SETTINGS_KEY_THIRD_PARTY_APP_ENABLED:this._values.enable3rdPartyApps=obj.settingValue;break;case this.SETTINGS_KEY_DYNAMIC_INPUTS:this._values.dynamicInputs=obj.settingValue;break;}
|
||
if(typeof this.onchange==='function'){this.onchange(this._values);}};InputAppListSettings.prototype.stop=function(){this._values={enable3rdPartyApps:undefined,dynamicInputs:undefined};this.ready=false;this._promise=null;if(navigator.mozSettings){navigator.mozSettings.removeObserver(this.SETTINGS_KEY_THIRD_PARTY_APP_ENABLED,this._bindCallback);navigator.mozSettings.removeObserver(this.SETTINGS_KEY_DYNAMIC_INPUTS,this._bindCallback);this._bindCallback=null;}};var InputAppList=function(){this.ready=false;this._inputApps=null;this.settings=null;this._getListPromise=null;};InputAppList.prototype.onready=null;InputAppList.prototype.onupdate=null;InputAppList.prototype.SETTINGS_KEY_THIRD_PARTY_APP_ENABLED='keyboard.3rd-party-app.enabled';InputAppList.prototype.start=function(){if(navigator.mozApps&&navigator.mozApps.mgmt){navigator.mozApps.mgmt.addEventListener('install',this);navigator.mozApps.mgmt.addEventListener('uninstall',this);}
|
||
this.settings=new InputAppListSettings();this.settings.onchange=this._refresh.bind(this);this.settings.start();this.getList().then(function(){this.ready=true;if(typeof this.onready==='function'){return this.onready(this._inputApps);}}.bind(this)).catch(function(e){console.error(e);});};InputAppList.prototype.getList=function(){if(this._getListPromise){return this._getListPromise;}
|
||
var p=this._getListPromise=Promise.all([this.settings.getSettings(),this._getAllApps()]).then(this._setInputApps.bind(this)).then(function(){return this._inputApps;}.bind(this)).catch(function(e){this._getListPromise=null;console.error(e);}.bind(this));return p;};InputAppList.prototype.getListSync=function(){if(!this.ready){console.warn('InputAppList: getListSync called when list is not ready.');}
|
||
return this._inputApps;};InputAppList.prototype.handleEvent=function(evt){var updated=false;switch(evt.type){case'install':var app=evt.application;if(app.downloading){app.addEventListener('downloadsuccess',this);return;}
|
||
updated=this._addInputApp(app);break;case'downloadsuccess':updated=this._addInputApp(evt.target);break;case'uninstall':updated=this._removeInputApp(evt.application);break;}
|
||
if(updated&&typeof this.onupdate==='function'){this.onupdate(this._inputApps);}};InputAppList.prototype.stop=function(){this.ready=false;this._inputApps=null;this.settings=null;this._getListPromise=null;if(navigator.mozApps&&navigator.mozApps.mgmt){navigator.mozApps.mgmt.removeEventListener('install',this);navigator.mozApps.mgmt.removeEventListener('uninstall',this);}};InputAppList.prototype._getAllApps=function(){if(!navigator.mozApps||!navigator.mozApps.mgmt){console.error('InputAppList: mozApps.mgmt not available.');return[];}
|
||
return Promise.resolve(navigator.mozApps.mgmt.getAll()).catch(function(e){console.error('InputAppList: Fail to get app list.',e);return[];});};InputAppList.prototype._setInputApps=function(values){var apps=values[1];var dynamicInputs=this.settings.getSettingsSync().dynamicInputs||{};var inputApps=apps.filter(this._isInputApp,this).map(function(domApp){var inputApp=new InputApp(domApp,dynamicInputs[domApp.manifestURL]);return inputApp;});if(inputApps.length===0){console.error('InputAppList: No input apps installed?');}
|
||
this._inputApps=inputApps;};InputAppList.prototype._addInputApp=function(domApp){if(!this._isInputApp(domApp)){return false;}
|
||
this._inputApps.push(new InputApp(domApp));return true;};InputAppList.prototype._removeInputApp=function(domApp){var index=this._inputApps.findIndex(function(appInList){return(appInList.domApp.manifestURL===domApp.manifestURL);});if(index===-1){return false;}
|
||
this._inputApps.splice(index,1);return true;};InputAppList.prototype._isInputApp=function(domApp){if(!domApp.manifest||'input'!==domApp.manifest.role){return false;}
|
||
if(domApp.manifest.type!=='certified'&&domApp.manifest.type!=='privileged'){return false;}
|
||
var settingValues=this.settings.getSettingsSync();if(!settingValues.enable3rdPartyApps&&domApp.manifest.type!=='certified'){console.warn('InputAppList: '+'A 3rd-party input app is installed but the feature is not enabled.',domApp.manifestURL);return false;}
|
||
if(domApp.manifest.permissions&&(typeof domApp.manifest.permissions.input!=='object')){return false;}
|
||
if(typeof domApp.manifest.inputs!=='object'){return false;}
|
||
return true;};InputAppList.prototype._refresh=function(){this._getListPromise=null;this.getList().then(function(){if(typeof this.onupdate==='function'){return this.onupdate(this._inputApps);}}.bind(this)).catch(function(e){console.error(e);});};exports.InputAppListSettings=InputAppListSettings;exports.InputAppList=InputAppList;exports.InputApp=InputApp;}(window));;'use strict';(function(exports){var BASE_TYPES=new Set(['text','url','email','password','number','option']);var SETTINGS_KEYS={ENABLED:'keyboard.enabled-layouts',DEFAULT:'keyboard.default-layouts'};var DEPRECATE_KEYBOARD_SETTINGS={en:'keyboard.layouts.english','en-Dvorak':'keyboard.layouts.dvorak',cs:'keyboard.layouts.czech',fr:'keyboard.layouts.french',de:'keyboard.layouts.german',hu:'keyboard.layouts.hungarian',nb:'keyboard.layouts.norwegian',my:'keyboard.layouts.myanmar',sl:'keyboard.layouts.slovak',tr:'keyboard.layouts.turkish',ro:'keyboard.layouts.romanian',ru:'keyboard.layouts.russian',ar:'keyboard.layouts.arabic',he:'keyboard.layouts.hebrew','zh-Hant-Zhuyin':'keyboard.layouts.zhuyin','zh-Hans-Pinyin':'keyboard.layouts.pinyin',el:'keyboard.layouts.greek','jp-kanji':'keyboard.layouts.japanese',pl:'keyboard.layouts.polish','pt-BR':'keyboard.layouts.portuguese',sr:'keyboard.layouts.serbian',es:'keyboard.layouts.spanish',ca:'keyboard.layouts.catalan'};var MULTI_LAYOUT_MAP={sr:['sr-Cyrl','sr-Latn']};var defaultKeyboardManifestURL='app://keyboard.gaiamobile.org/manifest.webapp';var currentSettings={defaultLayouts:{}};currentSettings.defaultLayouts[defaultKeyboardManifestURL]={en:true,number:true};currentSettings.enabledLayouts=map2dClone(currentSettings.defaultLayouts);function map2dIs(manifestURL,layoutId){return!!(this[manifestURL]&&this[manifestURL][layoutId]);}
|
||
function map2dSet(manifestURL,layoutId){if(!this[manifestURL]){this[manifestURL]={};}
|
||
this[manifestURL][layoutId]=true;}
|
||
function map2dUnset(manifestURL,layoutId){if(!this[manifestURL]){return;}
|
||
delete this[manifestURL][layoutId];if(!Object.keys(this[manifestURL]).length){delete this[manifestURL];}}
|
||
function map2dClone(obj){var result={};for(var key1 in obj){result[key1]={};for(var key2 in obj[key1]){result[key1][key2]=obj[key1][key2];}}
|
||
return result;}
|
||
var watchQueries=[];var defaultLayoutConfig;function kh_updateWatchers(reason){if(watchQueries.length){KeyboardHelper.getApps(function withApps(){watchQueries.forEach(function eachWatchQuery(watch){KeyboardHelper.getLayouts(watch.query,function withLayouts(layouts){watch.callback(layouts,reason);});});});}}
|
||
var waitingForSettings=[];var loadedSettings=new Set();function kh_loadedSetting(setting){loadedSettings.add(setting);if(loadedSettings.size>=Object.keys(SETTINGS_KEYS).length){waitingForSettings.forEach(function(callback){callback();});waitingForSettings=[];kh_updateWatchers({settings:true});}}
|
||
function kh_withSettings(callback){if(loadedSettings.size>=Object.keys(SETTINGS_KEYS).length){callback();}else{waitingForSettings.push(callback);}}
|
||
function kh_getSettings(){loadedSettings=new Set();var lock=window.navigator.mozSettings.createLock();lock.get(SETTINGS_KEYS.DEFAULT).onsuccess=kh_parseDefault;lock.get(SETTINGS_KEYS.ENABLED).onsuccess=kh_parseEnabled;}
|
||
function kh_parseDefault(){var value=this.result[SETTINGS_KEYS.DEFAULT];if(value){currentSettings.defaultLayouts=value;}
|
||
kh_loadedSetting(SETTINGS_KEYS.DEFAULT);}
|
||
function kh_parseEnabled(){var value=this.result[SETTINGS_KEYS.ENABLED];var needsSave=false;if(!value){currentSettings.enabledLayouts=map2dClone(currentSettings.defaultLayouts);needsSave=true;}else{var type=typeof value;if(type==='string'){try{currentSettings.enabledLayouts={};var oldSettings=JSON.parse(value);oldSettings.forEach(function(layout){if(layout.enabled){var manifestURL=layout.manifestURL;if(!manifestURL){manifestURL=layout.appOrigin+'/manifest.webapp';}
|
||
map2dSet.call(currentSettings.enabledLayouts,manifestURL,layout.layoutId);}});}catch(e){currentSettings.enabledLayouts=map2dClone(currentSettings.defaultLayouts);needsSave=true;}}else{currentSettings.enabledLayouts=value;}}
|
||
kh_loadedSetting(SETTINGS_KEYS.ENABLED);if(needsSave){KeyboardHelper.saveToSettings();}}
|
||
function kh_migrateDeprecatedSettings(deprecatedSettings){var settingEntry=DEPRECATE_KEYBOARD_SETTINGS.en;if(deprecatedSettings[settingEntry]===undefined){return;}
|
||
currentSettings.enabledLayouts[defaultKeyboardManifestURL]={number:true};var hasEnabledLayout=false;for(var key in DEPRECATE_KEYBOARD_SETTINGS){settingEntry=DEPRECATE_KEYBOARD_SETTINGS[key];if(deprecatedSettings[settingEntry]){hasEnabledLayout=true;if(key in MULTI_LAYOUT_MAP){MULTI_LAYOUT_MAP[key].forEach(function enableLayout(layoutId){map2dSet.call(currentSettings.enabledLayouts,defaultKeyboardManifestURL,layoutId);});}else{map2dSet.call(currentSettings.enabledLayouts,defaultKeyboardManifestURL,key);}}}
|
||
if(!hasEnabledLayout){map2dSet.call(currentSettings.enabledLayouts,defaultKeyboardManifestURL,'en');}
|
||
var deprecatedSettingsQuery={};for(key in DEPRECATE_KEYBOARD_SETTINGS){settingEntry=DEPRECATE_KEYBOARD_SETTINGS[key];deprecatedSettingsQuery[settingEntry]=null;}
|
||
window.navigator.mozSettings.createLock().set(deprecatedSettingsQuery);KeyboardHelper.saveToSettings();}
|
||
function kh_loadJSON(href,callback){if(!callback){return;}
|
||
var xhr=new XMLHttpRequest();xhr.onerror=function(){console.error('Failed to fetch file: '+href,xhr.statusText);};xhr.onload=function(){callback(xhr.response);};xhr.open('GET',href,true);xhr.responseType='json';xhr.send();}
|
||
function kh_getMultiSettings(settings,callback){var results={};try{var lock=navigator.mozSettings.createLock();}
|
||
catch(e){console.warn('Exception in mozSettings.createLock():',e,'\nUsing default values');for(var p in settings){results[p]=settings[p];}
|
||
callback(results);}
|
||
var settingNames=Object.keys(settings);var numSettings=settingNames.length;var numResults=0;for(var i=0;i<numSettings;i++){requestSetting(settingNames[i]);}
|
||
function requestSetting(name){var request;try{request=lock.get(name);}
|
||
catch(e){console.warn('Exception querying setting',name,':',e,'\nUsing default value');recordResult(name,settings[name]);return;}
|
||
request.onsuccess=function(){var value=request.result[name];if(value===undefined){value=settings[name];}
|
||
recordResult(name,value);};request.onerror=function(evt){console.warn('Error querying setting',name,':',evt.error);recordResult(name,settings[name]);};}
|
||
function recordResult(name,value){results[name]=value;numResults++;if(numResults===numSettings){callback(results);}}}
|
||
function KeyboardLayout(options){for(var key in options){this[key]=options[key];}}
|
||
Object.defineProperties(KeyboardLayout.prototype,{'default':{get:function kh_getLayoutIsDefault(){return map2dIs.call(currentSettings.defaultLayouts,this.app.manifestURL,this.layoutId);}},enabled:{get:function kh_getLayoutIsEnabled(){return map2dIs.call(currentSettings.enabledLayouts,this.app.manifestURL,this.layoutId);},set:function kh_setLayoutIsDefault(value){var method=value?map2dSet:map2dUnset;method.call(currentSettings.enabledLayouts,this.app.manifestURL,this.layoutId);}}});var kh_SettingsHelper={};Object.defineProperties(kh_SettingsHelper,{'default':{get:function(){return map2dClone(currentSettings.defaultLayouts);},set:function(value){currentSettings.defaultLayouts=map2dClone(value);},enumerable:true},'enabled':{get:function(){return map2dClone(currentSettings.enabledLayouts);},set:function(value){currentSettings.enabledLayouts=map2dClone(value);},enumerable:true}});var KeyboardHelper=exports.KeyboardHelper={settings:kh_SettingsHelper,fallbackLayoutNames:{password:'en'},fallbackLayouts:{},inputAppList:null,init:function kh_init(){watchQueries=[];this.inputAppList=new InputAppList();this.inputAppList.onupdate=kh_updateWatchers.bind(undefined,{apps:true});this.inputAppList.start();var settings=window.navigator.mozSettings;if(settings){kh_getSettings();settings.addObserver(SETTINGS_KEYS.ENABLED,kh_getSettings);settings.addObserver(SETTINGS_KEYS.DEFAULT,kh_getSettings);var deprecatedSettingsQuery={};for(var key in DEPRECATE_KEYBOARD_SETTINGS){var settingEntry=DEPRECATE_KEYBOARD_SETTINGS[key];deprecatedSettingsQuery[settingEntry]=undefined;}
|
||
kh_getMultiSettings(deprecatedSettingsQuery,kh_migrateDeprecatedSettings);}
|
||
window.addEventListener('applicationinstallsuccess',this);},handleEvent:function(event){kh_updateWatchers({apps:true});},isKeyboardType:function kh_isKeyboardType(type){return BASE_TYPES.has(type);},setLayoutEnabled:function kh_setLayoutEnabled(manifestURL,layoutId,enabled){var method=enabled?map2dSet:map2dUnset;method.call(currentSettings.enabledLayouts,manifestURL,layoutId);},getLayoutEnabled:function kh_getLayoutEnabled(manifestURL,layoutId){return map2dIs.call(currentSettings.enabledLayouts,manifestURL,layoutId);},setLayoutIsDefault:function kh_setLayoutIsDefault(manifestURL,layoutId,enabled){var method=enabled?map2dSet:map2dUnset;method.call(currentSettings.defaultLayouts,manifestURL,layoutId);},getLayoutIsDefault:function kh_getLayoutIsDefault(manifestURL,layoutId){return map2dIs.call(currentSettings.defaultLayouts,manifestURL,layoutId);},checkDefaults:function kh_checkDefaults(callback){var layoutsEnabled=[];var missingTypes=[];['text','url','number'].forEach(function eachType(type){var enabled;this.getLayouts({type:type,enabled:true},function(layouts){enabled=layouts.length;});if(!enabled){missingTypes.push(type);this.getLayouts({type:type,'default':true},function(layouts){if(layouts[0]){layouts[0].enabled=true;layoutsEnabled.push(layouts[0]);}});}},this);if(layoutsEnabled.length){if(callback){callback(layoutsEnabled,missingTypes);}}},saveToSettings:function ke_saveToSettings(){var toSet={};toSet[SETTINGS_KEYS.ENABLED]=currentSettings.enabledLayouts;toSet[SETTINGS_KEYS.DEFAULT]=currentSettings.defaultLayouts;window.navigator.mozSettings.createLock().set(toSet);},getApps:function kh_getApps(callback){var cleanupSettings=function(inputApps){Object.keys(currentSettings.enabledLayouts).concat(Object.keys(currentSettings.defaultLayouts)).forEach(function(manifestURL){if(!inputApps.some(function(inputApp){return(inputApp.domApp.manifestURL===manifestURL);})){delete currentSettings.enabledLayouts[manifestURL];delete currentSettings.defaultLayouts[manifestURL];}});};if(this.inputAppList.ready){var inputApps=this.inputAppList.getListSync();cleanupSettings(inputApps);callback(inputApps);return;}
|
||
this.inputAppList.getList().then(function(inputApps){cleanupSettings(inputApps);callback(inputApps);})['catch'](function(e){console.error(e);});},getLayouts:function kh_getLayouts(options,callback){if(typeof options==='function'){callback=options;options={};}
|
||
function withApps(inputApps){var fallbackLayoutNames={};for(var group in this.fallbackLayoutNames){fallbackLayoutNames[group]=this.fallbackLayoutNames[group];}
|
||
this.fallbackLayouts={};var layouts=inputApps.reduce(function eachApp(result,inputApp){var domApp=inputApp.domApp;var manifest=new ManifestHelper(domApp.manifest);var inputs=inputApp.getInputs();for(var layoutId in inputs){var inputManifest=inputs[layoutId];if(!inputManifest.types){console.warn(domApp.manifestURL,layoutId,'did not declare type.');continue;}
|
||
var layout=new KeyboardLayout({app:domApp,inputApp:inputApp,manifest:manifest,inputManifest:inputManifest,layoutId:layoutId});if(domApp.manifestURL===defaultKeyboardManifestURL){for(var group in fallbackLayoutNames){if(layoutId===fallbackLayoutNames[group]){this.fallbackLayouts[group]=layout;delete fallbackLayoutNames[group];}}}
|
||
if(options['default']&&!layout['default']){continue;}
|
||
if(options.enabled&&!layout.enabled){continue;}
|
||
if(options.type){options.type=[].concat(options.type);if(!options.type.some(function(type){return inputManifest.types.indexOf(type)!==-1;})){continue;}}
|
||
result.push(layout);}
|
||
if(options['default']){result.sort(function(a,b){return a.inputManifest.types.length-b.inputManifest.types.length;});}
|
||
return result;}.bind(this),[]);kh_withSettings(callback.bind(null,layouts));}
|
||
this.getApps(withApps.bind(this));},stopWatching:function(){watchQueries=[];},watchLayouts:function(query,callback){if(typeof query==='function'){callback=query;query={};}
|
||
var watch={query:query,callback:callback};watchQueries.push(watch);this.getLayouts(query,function initialCall(layouts){watch.layouts=layouts;callback(layouts,{apps:true,settings:true});});},getDefaultLayoutConfig:function kh_getDefaultLayoutConfig(callback){if(!callback){return;}
|
||
if(defaultLayoutConfig){callback(defaultLayoutConfig);}else{var KEYBOARDS='/shared/resources/keyboard_layouts.json';kh_loadJSON(KEYBOARDS,function loadKeyboardLayouts(data){if(data){defaultLayoutConfig=data;callback(defaultLayoutConfig);}});}},changeDefaultLayouts:function kh_changeDefaultLayouts(language,reset){this.getDefaultLayoutConfig(function gotDefaultLayouts(keyboards){var newKbLayouts=keyboards.layout[language];var kbManifestURL=defaultKeyboardManifestURL;currentSettings.defaultLayouts={};var langIndependentLayouts=keyboards.langIndependentLayouts;for(var i=langIndependentLayouts.length-1;i>=0;i--){this.setLayoutIsDefault(kbManifestURL,langIndependentLayouts[i].layoutId,true);}
|
||
if(reset){currentSettings.enabledLayouts=map2dClone(currentSettings.defaultLayouts);}
|
||
for(i=newKbLayouts.length-1;i>=0;i--){this.setLayoutIsDefault(kbManifestURL,newKbLayouts[i].layoutId,true);this.setLayoutEnabled(kbManifestURL,newKbLayouts[i].layoutId,true);}
|
||
this.saveToSettings();}.bind(this));}};KeyboardHelper.init();}(window));;'use strict';(function(exports){var LOCALES_FILE='/shared/resources/languages.json';function readFile(file,callback){return new Promise(function(resolve,reject){var xhr=new XMLHttpRequest();xhr.onreadystatechange=function loadFile(){if(xhr.readyState===4){if(xhr.status===0||xhr.status===200){resolve(xhr.response);}else{reject(xhr.statusText);}}};xhr.open('GET',file,true);xhr.responseType='json';xhr.send();});}
|
||
function onError(name){console.error('Error checking setting '+name);}
|
||
function readSetting(name,callback){var settings=window.navigator.mozSettings;if(!settings||!settings.createLock){return callback(null);}
|
||
return settings.createLock().get(name).then(function(res){return res[name];},onError.bind(null,name));}
|
||
exports.LanguageList={_languages:null,_readFile:readFile,_readSetting:readSetting,_extendPseudo:function(languages,currentLang,pseudoEnabled){if(!pseudoEnabled){for(var code in languages){var isCurrent=(code===currentLang);if(code.indexOf('-x-ps')>-1&&!isCurrent){delete languages[code];}}}
|
||
if(!document.l10n){return Promise.resolve(languages);}
|
||
var runtimePseudoCodes=Object.keys(document.l10n.pseudo).filter(code=>!(code in languages)&&(code===currentLang||pseudoEnabled));function obj(arr1,arr2){const zipped=[];arr1.forEach(x=>{arr2.forEach(y=>{zipped.push([x,y]);});});return zipped.reduce((obj,[x,y])=>Object.assign(obj,{[x]:y}),{});}
|
||
return Promise.all(runtimePseudoCodes.map(code=>document.l10n.pseudo[code].getName())).then(names=>Object.assign(languages,obj(runtimePseudoCodes,names)));},_extendAdditional:function(languages,ver,additional){for(var lang in additional){for(var i=0,locale;locale=additional[lang][i];i++){if(locale.target===ver){languages[lang]=locale.name;break;}}}},_removeWithNoSpeech:function(languages,srEnabled){if(srEnabled){var speechLangs=new Set(window.speechSynthesis.getVoices().map(v=>v.lang.split('-')[0]));for(var langName in languages){if(!speechLangs.has(langName.split('-')[0])){delete languages[langName];}}}},_copyObj:function(obj){var copy=Object.create(null);for(var prop in obj){copy[prop]=obj[prop];}
|
||
return copy;},_parseVersion:function(ver){return ver.split('.').slice(0,2).join('.');},_build:function(){return Promise.all([this._languages||(this._languages=this._readFile(LOCALES_FILE)),this._readSetting('language.current'),this._readSetting('devtools.pseudolocalization.enabled')]).then(([langsFromFile,current,pseudoEnabled])=>{var langs=this._copyObj(langsFromFile);return Promise.all([this._extendPseudo(langs,current,pseudoEnabled),this._readSetting('langpack.channel'),current,this._readSetting('accessibility.screenreader'),navigator.mozApps.getAdditionalLanguages()]);}).then(([langs,ver,current,srEnabled,addl])=>{this._extendAdditional(langs,this._parseVersion(ver),addl);this._removeWithNoSpeech(langs,srEnabled);return[langs,current];});},get:function(callback){if(!callback){return;}
|
||
this._build().then(Function.prototype.apply.bind(callback,null));},wrapBidi:function(langCode,langName){var rtlList=['ar','he','fa','ps','ar-x-psbidi','ur'];var lEmbedBegin=(rtlList.indexOf(langCode)>=0)?'\u202b':'\u202a';var lEmbedEnd='\u202c';return lEmbedBegin+langName+lEmbedEnd;}};}(window));;'use strict';var SettingsListener={_lock:null,_observers:[],getSettingsLock:function sl_getSettingsLock(){if(this._lock&&!this._lock.closed){return this._lock;}
|
||
var settings=window.navigator.mozSettings;return(this._lock=settings.createLock());},observe:function sl_observe(name,defaultValue,callback){var settings=window.navigator.mozSettings;if(!settings){window.setTimeout(function(){callback(defaultValue);});return;}
|
||
var req;try{req=this.getSettingsLock().get(name);}catch(e){console.warn('Stale lock in settings_listener.js.','See https://bugzilla.mozilla.org/show_bug.cgi?id=793239');this._lock=null;req=this.getSettingsLock().get(name);}
|
||
req.addEventListener('success',(function onsuccess(){callback(typeof(req.result[name])!='undefined'?req.result[name]:defaultValue);}));var settingChanged=function settingChanged(evt){callback(evt.settingValue);};settings.addObserver(name,settingChanged);this._observers.push({name:name,callback:callback,observer:settingChanged});},unobserve:function sl_unobserve(name,callback){var settings=window.navigator.mozSettings;var that=this;this._observers.forEach(function(value,index){if(value.name===name&&value.callback===callback){settings.removeObserver(name,value.observer);that._observers.splice(index,1);}});}};;'use strict';(function(exports){function Version(str){str=str||'0.0';var parts=str.split('.');this.major=parts[0];this.minor=parts[1];this.toString=function(){return''+str;};}
|
||
function InfoResult(current,previous){this.current=current;this.previous=previous;}
|
||
InfoResult.prototype.isUpgrade=function(){var prev=this.previous,curr=this.current,isUpgrade=false;if(prev&&curr){isUpgrade=curr.major>prev.major||curr.minor>prev.minor;}
|
||
return isUpgrade;};InfoResult.prototype.delta=function(){var prev=this.previous,curr=this.current;var delta='';if(prev){delta+=prev.major+'.'+prev.minor;}
|
||
delta+='..';if(curr){delta+=curr.major+'.'+curr.minor;}
|
||
return delta;};function getSetting(setting,cb,errback){var req=navigator.mozSettings.createLock().get(setting);req.onsuccess=function(){var value=req.result[setting];if(typeof cb==='function'){cb(value);}};req.onerror=function(){if(typeof errback==='function'){errback(req.error);}};}
|
||
function getCurrent(){return new Promise(function(resolve,reject){getSetting('deviceinfo.os',function(value){resolve(value?new Version(value):null);},function(err){reject(err);});});}
|
||
function getPrevious(){return new Promise(function(resolve,reject){getSetting('deviceinfo.previous_os',function(value){resolve(value?new Version(value):null);},function(err){resolve(null);});});}
|
||
function updatePrevious(str){var currentPromise=str?Promise.resolve(new Version(str)):getCurrent();var setPromise=new Promise(function(resolve,reject){currentPromise.then(function(version){if(version){var req=navigator.mozSettings.createLock().set({'deviceinfo.previous_os':version.toString()});req.onsuccess=function(){resolve(version);};req.onerror=function(){var reason=req.error;reject(reason);};}else{resolve(null);}},function(err){reject('Error getting previous version: ',err);});});return setPromise;}
|
||
function getVersionInfo(){var info=new InfoResult();var infoPromise=new Promise(function(resolve,reject){Promise.all([getCurrent().then(function(version){info.current=version;}),getPrevious().then(function(version){info.previous=version;})]).then(function(){resolve(info);},reject);});return infoPromise;}
|
||
exports.VersionHelper={updatePrevious:updatePrevious,getVersionInfo:getVersionInfo};})(window);;'use strict';function eventSafety(obj,event,callback,timeout){if(typeof callback==='number'){timeout=callback;callback=null;}
|
||
if(!timeout){throw new Error('You must pass a valid timeout value to `eventSafety`.');}
|
||
return new Promise((resolve)=>{var finishTimeout;function done(e){if(e&&e.target!==obj&&(e.type==='transitionend'||e.type==='animationend')){return;}
|
||
clearTimeout(finishTimeout);obj.removeEventListener(event,done);if(callback){resolve(callback.apply(this,arguments));}else{resolve(e);}}
|
||
finishTimeout=setTimeout(done,timeout);obj.addEventListener(event,done);});};(function(){'use strict';if(window.navigator.mozHour12||window.navigator.hour12){return;}
|
||
window.navigator.mozHour12=undefined;var _setMozHour12=function(result){if(result===null){result=undefined;}
|
||
if(window.navigator.mozHour12!==result){window.navigator.mozHour12=result;window.dispatchEvent(new CustomEvent('timeformatchange'));}};var _hour12Handler=function(event){_setMozHour12(event.settingValue);};var _kLocaleTime='locale.hour12';var req=window.navigator.mozSettings.createLock().get(_kLocaleTime);req.onsuccess=function(){_setMozHour12(req.result[_kLocaleTime]);};window.navigator.mozSettings.addObserver(_kLocaleTime,_hour12Handler);})();;'use strict';var utils=window.utils||{};utils.status=(function(){var STATUS_TIME=2000;var statusMsg=document.querySelector('#statusMsg');var hidingTimeout;var transitionEndTimeout;var additionalLine;var hideAnimationDone=function(){statusMsg.removeEventListener('transitionend',hideAnimationDone);statusMsg.classList.add('hidden');};var showAnimationDone=function(){if(transitionEndTimeout){clearTimeout(transitionEndTimeout);}
|
||
statusMsg.removeEventListener('transitionend',showAnimationDone);hidingTimeout=setTimeout(utils.status.hide,STATUS_TIME);};var hideStatus=function(){statusMsg.addEventListener('transitionend',hideAnimationDone);statusMsg.classList.remove('opening');statusMsg.classList.remove('bannerStart');statusMsg.querySelector('p').removeAttribute('data-l10n-id');if(additionalLine){statusMsg.removeChild(additionalLine);additionalLine=null;}};var setL10nAttributes=function(node,l10n){if(l10n&&l10n.id){navigator.mozL10n.setAttributes(node,l10n.id,l10n.args);return true;}else{console.error('Status arguments must be objects');return false;}};var showStatus=function(mainMessage,extra){statusMsg.removeEventListener('transitionend',showAnimationDone);statusMsg.removeEventListener('transitionend',hideAnimationDone);LazyLoader.load([statusMsg],function _loaded(){if(!setL10nAttributes(statusMsg.querySelector('p'),mainMessage)){return;}
|
||
if(extra){additionalLine=document.createElement('p');statusMsg.appendChild(additionalLine);setL10nAttributes(additionalLine,extra);}
|
||
if(statusMsg.classList.contains('opening')){clearTimeout(hidingTimeout);hidingTimeout=setTimeout(hideStatus,STATUS_TIME);return;}
|
||
statusMsg.classList.remove('hidden');statusMsg.addEventListener('transitionend',showAnimationDone);setTimeout(function displaying(){statusMsg.classList.add('opening');statusMsg.classList.add('bannerStart');transitionEndTimeout=setTimeout(showAnimationDone,STATUS_TIME);},10);});};return{show:showStatus,hide:hideStatus};})();;'use strict';var utils=window.utils||{};(function(){utils.overlay={};var overlay=document.querySelector('#loading-overlay'),statusContainer=overlay.querySelector('p[role="status"]'),progressActivity=document.querySelector('#progress-activity'),progressTitle=document.querySelector('#progress-title'),progressElement=document.querySelector('#progress-element'),progressMsg=document.querySelector('#progress-msg'),menu=document.querySelector('#loading-overlay menu'),cancelButton=document.querySelector('#cancel-overlay');function ProgressBar(pMsgId,pClass){var counter=0;var total=0;var progressTextId=pMsgId||'genericProgress';var clazz=pClass;progressElement.setAttribute('value',0);function showMessage(){var attributes=progressTextId=='infiniteProgress'?{n:counter}:{current:counter,total:total};document.l10n.setAttributes(progressMsg,progressTextId,attributes);}
|
||
this.update=function(value){if(value&&value<=total&&value>=counter){counter=value;}else{counter++;}
|
||
progressElement.setAttribute('value',((counter*100)/total).toFixed());showMessage();};this.setTotal=function(ptotal){total=ptotal;};this.setClass=function(clazzName){setClass(clazzName);clazz=clazzName;if(clazzName==='activityBar'||clazzName==='spinner'){progressMsg.removeAttribute('data-l10n-id');}};this.setHeaderMsg=function(headerMsgId){progressTitle.setAttribute('data-l10n-id',headerMsgId);};}
|
||
utils.overlay.isAnimationPlaying=false;utils.overlay.isShown=false;utils.overlay._show=function _show(messageId,progressClass,textId){progressActivity.classList.remove('hide');if(typeof messageId==='string'){progressTitle.setAttribute('data-l10n-id',messageId);}else{document.l10n.setAttributes(progressTitle,messageId.id,messageId.args);}
|
||
progressMsg.textContent=null;progressMsg.removeAttribute('data-l10n-id');if(utils.overlay.isShown){return;}
|
||
overlay.classList.remove('hide');overlay.classList.remove('fade-out');overlay.classList.add('fade-in');utils.overlay.isAnimationPlaying=true;window.dispatchEvent(new CustomEvent('loadingoverlayshowing'));overlay.addEventListener('animationend',function ov_onFadeIn(ev){utils.overlay.isAnimationPlaying=false;overlay.removeEventListener('animationend',ov_onFadeIn);overlay.classList.remove('no-opacity');utils.overlay.isShown=true;});};utils.overlay.show=function show(messageId,progressClass,textId){var out;out=new ProgressBar(textId,progressClass);setClass(progressClass);utils.overlay.hideMenu();if(!utils.overlay.isAnimationPlaying){utils.overlay._show(messageId,progressClass,textId);return out;}
|
||
overlay.addEventListener('animationend',function ov_showWhenFinished(ev){overlay.removeEventListener('animationend',ov_showWhenFinished);utils.overlay._show(messageId,progressClass,textId);});return out;};utils.overlay.showMenu=function showMenu(){menu.classList.add('showed');};utils.overlay.hideMenu=function hideMenu(){menu.classList.remove('showed');};Object.defineProperty(utils.overlay,'oncancel',{set:function(cancelCb){if(typeof cancelCb==='function'){cancelButton.disabled=false;cancelButton.onclick=function on_cancel(e){delete cancelButton.onclick;cancelCb();return false;};}}});function setAsProgress(){statusContainer.classList.remove('loading-icon');progressElement.setAttribute('max','100');progressElement.setAttribute('value','0');}
|
||
function setClass(clazzName){switch(clazzName){case'spinner':progressElement.classList.remove('pack-activity');statusContainer.classList.add('loading-icon');progressElement.removeAttribute('max');progressElement.removeAttribute('value');break;case'activityBar':case'progressActivity':progressElement.classList.add('pack-activity');setAsProgress();break;case'progressBar':progressElement.classList.remove('pack-activity');setAsProgress();break;}}
|
||
utils.overlay._hide=function ov__hide(){if(!utils.overlay.isShown){return;}
|
||
overlay.classList.remove('fade-in');overlay.classList.add('fade-out');utils.overlay.isAnimationPlaying=true;window.dispatchEvent(new CustomEvent('loadingoverlayhiding'));overlay.addEventListener('animationend',function ov_onFadeOut(ev){utils.overlay.isAnimationPlaying=false;overlay.removeEventListener('animationend',ov_onFadeOut);progressActivity.classList.add('hide');overlay.classList.add('no-opacity');overlay.classList.add('hide');utils.overlay.isShown=false;});};utils.overlay.hide=function ov_hide(){if(!utils.overlay.isAnimationPlaying){utils.overlay._hide();return;}
|
||
overlay.addEventListener('animationend',function ov_hideWhenFinished(ev){overlay.removeEventListener('animationend',ov_hideWhenFinished);utils.overlay._hide();});};})();;'use strict';var utils=window.utils||{};if(typeof utils.config==='undefined'){(function(){var configs={};var initializing={};var initialized={};var EVENT_INITIALIZED='config_initialized';utils.config=utils.config||{};utils.config.reset=function(){configs={};initializing={};initialized={};};function onLoad(xhr,file,resolveCb){configs[file]=xhr.response;delete initializing[file];initialized[file]=true;document.dispatchEvent(new CustomEvent(EVENT_INITIALIZED,{detail:{file:file,success:true}}));resolveCb(configs[file]);}
|
||
utils.config.load=function(file){return new Promise(function(resolve,reject){var isInitialized=initialized[file];if(isInitialized===true){resolve(configs[file]);return;}
|
||
var isInitializing=initializing[file];if(isInitializing){var handler=function(expectedFile,e){document.removeEventListener(EVENT_INITIALIZED,handler);var file=e.detail.file;if(expectedFile!==file){return;}
|
||
if(e.detail.success){resolve(configs[file]);}
|
||
else{reject();}}.bind(null,file);document.addEventListener(EVENT_INITIALIZED,handler);return;}
|
||
initializing[file]=true;var xhr=new XMLHttpRequest();xhr.open('GET',file,true);xhr.responseType='json';xhr.onload=function(){var resolvedCb=resolve;if(xhr.status!==200){resolvedCb=reject;}
|
||
onLoad(xhr,file,resolvedCb);};xhr.onerror=function(){document.dispatchEvent(new CustomEvent(EVENT_INITIALIZED,{detail:{file:file,success:false}}));delete initializing[file];reject(xhr.error);};try{xhr.send(null);}
|
||
catch(e){console.error('Error while loading config file: ',e.message);onLoad({status:404},file,reject);}});};})();};'use strict';var utils=window.utils||{};var SCALE_RATIO=window.devicePixelRatio||1;var LAST_IMPORT_TIMESTAMP_SUFFIX='_last_import_timestamp';function scale(size){return Math.round(SCALE_RATIO*size);}
|
||
if(!utils.misc){utils.misc={};utils.misc.toMozContact=function(contact){var outContact=contact;if(!(contact instanceof mozContact)){outContact=new mozContact(contact);outContact.id=contact.id||outContact.id;}
|
||
return outContact;};const FLAG_YEAR_IGNORED=9996;utils.misc.FLAG_YEAR_IGNORED=FLAG_YEAR_IGNORED;utils.misc.formatDate=function(date,customFormat){var dateString=null;try{var format=customFormat||{month:'short',day:'numeric'};var offset=date.getTimezoneOffset()*60*1000;var normalizedDate=new Date(date.getTime()+offset);var year=normalizedDate.getFullYear();if(year!==FLAG_YEAR_IGNORED){format.year='numeric';}
|
||
var f=new Intl.DateTimeFormat(navigator.languages,format);dateString=f.format(normalizedDate);}catch(err){console.error('Error parsing date: ',err);throw err;}
|
||
return dateString;};utils.misc.parseName=function(nameString){var MIN_LENGHT_SIGNIFICATIVE=3;var MIN_LENGHT_FN=2;var out={givenName:'',familyName:''};if(!nameString){return out;}
|
||
var str=nameString.trim();if(!str){return out;}
|
||
function startsWithUpper(str){var firstLetter=str.charAt(0);var capFirstLetter=firstLetter.toLocaleUpperCase();return(capFirstLetter===firstLetter);}
|
||
var tokens=nameString.split(/\s+/);var significativeTokens={};for(var j=0;j<tokens.length;j++){var token=tokens[j];if(token.length>MIN_LENGHT_SIGNIFICATIVE||startsWithUpper(token)){significativeTokens[token]=true;}}
|
||
var totalTokens=tokens.length;var lastToken=totalTokens-1;var rolePrevToken;var remainingTokens=Object.keys(significativeTokens).length;var outGivenNames=[],outFamilyNames=[];var numFns=0;while(lastToken>=0){if(significativeTokens[tokens[lastToken]]){remainingTokens--;}
|
||
var currToken=tokens[lastToken],nextToken=tokens[lastToken+1],prevToken=tokens[lastToken-1];if(!nextToken&&prevToken){outFamilyNames.push(currToken);numFns++;rolePrevToken='FN';}
|
||
else if(!prevToken){outGivenNames.push(currToken);rolePrevToken='GN';}
|
||
else if(nextToken){if(!significativeTokens[currToken]){if(rolePrevToken==='FN'){outFamilyNames.push(currToken);}
|
||
else{outGivenNames.push(currToken);}}
|
||
else if(currToken.length<MIN_LENGHT_FN){outGivenNames.push(currToken);rolePrevToken='GN';}
|
||
else{if(remainingTokens>=2&&numFns<2){outFamilyNames.push(currToken);numFns++;rolePrevToken='FN';}
|
||
else{outGivenNames.push(currToken);rolePrevToken='GN';}}}
|
||
lastToken--;}
|
||
out.givenName=outGivenNames.reverse().join(' ').trim();out.familyName=outFamilyNames.reverse().join(' ').trim();return out;};utils.misc.getPreferredPictureBox=function(){var imgThumbSize=oauthflow.params.facebook.imgThumbSize;var out={width:scale(imgThumbSize)};out.height=out.width;return out;};utils.misc.getPreferredPictureDetail=function(){var imgDetailWidth=oauthflow.params.facebook.imgDetailWidth;return scale(imgDetailWidth);};utils.misc.setTimestamp=function(type,callback){ImportStatusData.put(type+LAST_IMPORT_TIMESTAMP_SUFFIX,Date.now()).then(callback);};utils.misc.getTimestamp=function(type,callback){ImportStatusData.get(type+LAST_IMPORT_TIMESTAMP_SUFFIX).then(callback);};};'use strict';var utils=window.utils||{};if(!utils.sdcard){var SdCard=utils.sdcard={NOT_INITIALIZED:0,NOT_AVAILABLE:1,AVAILABLE:2,SHARED:3,observers:{}};SdCard.status=SdCard.NOT_INITIALIZED;SdCard.deviceStorages=navigator.getDeviceStorages('sdcard');SdCard.deviceStorage=Array.isArray(SdCard.deviceStorages)&&SdCard.deviceStorages[0];SdCard._toStatus=function toStatus(state){switch(state){case'available':SdCard.status=SdCard.AVAILABLE;break;case'shared':SdCard.status=SdCard.SHARED;break;case'unavailable':case'deleted':SdCard.status=SdCard.NOT_AVAILABLE;break;}};SdCard.updateStorageState=function sd_updateStorageState(state){SdCard._toStatus(state);Object.keys(this.observers).forEach(function onObserver(name){if(typeof(SdCard.observers[name])==='function'){SdCard.observers[name].call(null,state);}});};if(SdCard.deviceStorage){SdCard.deviceStorage.addEventListener('change',function sd_deviceStorageChangeHandler(e){SdCard.updateStorageState(e.reason);});if(SdCard.status===SdCard.NOT_INITIALIZED){SdCard.deviceStorage.available().onsuccess=(function(e){SdCard.updateStorageState(e.target.result);});}}
|
||
SdCard.checkStorageCard=function sd_checkStorageCard(){return SdCard.status===SdCard.AVAILABLE;};SdCard.getStatus=function(cb){if(!SdCard.deviceStorage){SdCard._toStatus('unavailable');cb(SdCard.status);return;}
|
||
var req=SdCard.deviceStorage.available();req.onsuccess=function(){SdCard._toStatus(req.result);cb(SdCard.status);};req.onerror=function(){console.error('Error while determining SD Status',req.error.name);cb(SdCard.status);};};SdCard.retrieveFiles=function retrieveFilesContent(mimes,exts,cb){var fileArray=[];var forbiddenDirectories=['.Trash'];var storages=navigator.getDeviceStorages('sdcard');var numberOfStorages=storages.length;var currentStorage=0;var cursorOnError=function(){cb(this.error.name);};var reExt=new RegExp('.('+exts.join('|')+')$');var cursorOnSuccess=function(e){var file=e.target.result;if(!file){if(++currentStorage<numberOfStorages){cursor=storages[currentStorage].enumerate();cursor.onsuccess=cursorOnSuccess;cursor.onerror=cursorOnError;}else{cb(null,fileArray);}}else{if((mimes.indexOf(file.type)===-1)&&!reExt.test(file.name)){cursor.continue();}else{if(forbiddenDirectories.indexOf(file.name)===-1){fileArray.push(file);cursor.continue();}}}};var cursor=storages[currentStorage].enumerate();cursor.onsuccess=cursorOnSuccess;cursor.onerror=cursorOnError;};SdCard.getTextFromFile=function(file,cb){if(!file){return Promise.reject();}
|
||
return new Promise((resolve,reject)=>{const END_VCARD='end:vcard';const CHUNK_SIZE=1*1024*1024;var fileReader=new FileReader();var result=0;(function readChunk(offset,buffer){if(offset>=file.size){resolve(result);return;}
|
||
var chunk=file.slice(offset,offset+CHUNK_SIZE);offset+=CHUNK_SIZE;fileReader.readAsText(chunk);fileReader.onload=function(){buffer+=fileReader.result;if(!buffer.match(/end:vcard/gi)){readChunk(offset,buffer);return;}
|
||
var lastContactInChunk=buffer.toLowerCase().lastIndexOf(END_VCARD)+END_VCARD.length;cb(buffer.substr(0,lastContactInChunk)).then(partialResult=>{result+=partialResult;readChunk(offset,buffer.substr(lastContactInChunk+1));}).catch(error=>{console.warn(error);});};})(0,'');});};SdCard.subscribeToChanges=function(name,func,force){if(this.observers[name]!==undefined&&!force){return false;}
|
||
this.observers[name]=func;return true;};SdCard.unsubscribeToChanges=function(name){if(this.observers[name]){delete this.observers[name];return true;}else{return false;}};};'use strict';function parseDataUri(str){var re=/^data:(.+);(charset=([^;]+))?;?base64,(.*)$/;var matches=re.exec(str);if(matches){return{mime:matches[1],charset:matches[3],value:matches[4]};}
|
||
return null;}
|
||
function ensureMimeType(type){type=type.toLowerCase();if(!MimeMapper.isSupportedType(type)){type=MimeMapper.guessTypeFromExtension(type)||type;}
|
||
return type||'';}
|
||
function b64toBlob(b64Data,contentType,sliceSize){if(!b64Data){console.error('No b64 data provided to convert to blob.');return;}
|
||
contentType=contentType||'';sliceSize=sliceSize||1024;function charCodeFromCharacter(c){return c.charCodeAt(0);}
|
||
var blob;try{var byteCharacters=atob(b64Data);var byteArrays=[];for(var offset=0;offset<byteCharacters.length;offset+=sliceSize){var slice=byteCharacters.slice(offset,offset+sliceSize);var byteNumbers=[];for(var i=0,l=slice.length;i<l;i++){byteNumbers.push(charCodeFromCharacter(slice[i]));}
|
||
var byteArray=new Uint8Array(byteNumbers);byteArrays.push(byteArray);}
|
||
blob=new Blob(byteArrays,{type:contentType});}catch(e){console.error('Error parsing base64 data');}
|
||
return blob;}
|
||
var VCFReader=(function _VCFReader(){var ReBasic=/^([^:]+):(.+)$/;var ReTuple=/([a-zA-Z]+)=(.+)/;var WHITE_SPACE=' ';var DEFAULT_PHONE_TYPE='other';var VCARD_SIMPLE_TYPES={'fax':'faxOther','faxother':'faxOther','home':'home','internet':'internet','cell':'mobile','pager':'pager','personal':'home','pref':'pref','text':'text','textphone':'textphone','voice':'voice','work':'work'};var VCARD_COMPLEX_TYPES={'fax,work':'faxOffice','fax,home':'faxHome','voice,work':'work','voice,home':'home'};var REST_TIMEOUT=5000;function _parseTuple(p){var match=p.match(ReTuple);return match?[match[1].toLowerCase(),match[2]]:['type',p];}
|
||
function _parseLine(line){var parsed=ReBasic.exec(line);if(!parsed){return null;}
|
||
var tuples=parsed[1].split(/[;,]/);var fieldName=tuples.shift().toLowerCase();var fieldValue=/[^\s;]/.test(parsed[2])?parsed[2].split(';'):[];var meta={type:[]};var len=tuples.length;for(var i=0;i<len;i++){var tuple=_parseTuple(tuples[i]);if(tuple[0]==='type'){meta.type.push(tuple[1]);}else{meta[tuple[0]]=tuple[1];}}
|
||
if(fieldName==='photo'){if(meta.type.length){meta.type=ensureMimeType(meta.type[0]);}
|
||
fieldValue=parsed[2];if(meta.encoding&&(meta.encoding.toLowerCase()==='b'||meta.encoding.toLowerCase()==='base64')){meta.encoding='base64';}else{var parsedUri=parseDataUri(fieldValue);if(parsedUri){meta.type=ensureMimeType(parsedUri.mime);meta.encoding='base64';fieldValue=parsedUri.value;}}}
|
||
return{key:fieldName,data:{meta:meta,value:fieldValue}};}
|
||
var _parseEntries=function(cardArray,cb){var parsedCards=[];function sendIfFinished(contactObj){parsedCards.push(contactObj);if(parsedCards.length===cardArray.length){cb(parsedCards);}}
|
||
for(var i=0;i<cardArray.length;i++){var lines=cardArray[i];if(!lines){sendIfFinished(null);continue;}
|
||
var fields={};var len=lines.length;for(var j=0;j<len;j++){var line=lines[j];var parsedLine=_parseLine(line);if(!parsedLine){continue;}
|
||
if(!fields[parsedLine.key]){fields[parsedLine.key]=[];}
|
||
fields[parsedLine.key].push(parsedLine.data);}
|
||
if(!fields.fn&&!fields.n){sendIfFinished(null);continue;}
|
||
vcardToContact(fields,sendIfFinished);}};var qpRegexp=/=([a-zA-Z0-9]{2})/g;var _decodeQuoted=function(str){return decodeURIComponent(str.replace(qpRegexp,'%$1'));};function _decodeQP(metaObj,value){var isQP=metaObj&&metaObj.encoding&&(/quoted-printable/i).test(metaObj.encoding);if(isQP){value=_decodeQuoted(value);}
|
||
return value;}
|
||
var NAME_PARTS=['familyName','givenName','additionalName','honorificPrefix','honorificSuffix'];function _processName(vcardObj,contactObj){if(vcardObj.fn&&vcardObj.fn.length){var fnMeta=vcardObj.fn[0].meta;var fnValue=vcardObj.fn[0].value[0];contactObj.name=[_decodeQP(fnMeta,fnValue)];}
|
||
if(vcardObj.n&&vcardObj.n.length){var values=vcardObj.n[0].value;var meta=vcardObj.n[0].meta;for(var i=0;i<values.length;i++){var namePart=values[i];if(namePart&&NAME_PARTS[i]){contactObj[NAME_PARTS[i]]=_decodeQP(meta,namePart).split(',');}}
|
||
if(!contactObj.name){contactObj.name=[_decodeQP(meta,values.join(' ').trim())];}}
|
||
contactObj.givenName=contactObj.givenName||contactObj.name;return contactObj;}
|
||
var ADDR_PARTS=[null,null,'streetAddress','locality','region','postalCode','countryName'];function _processAddr(vcardObj,contactObj){if(!vcardObj.adr){return contactObj;}
|
||
contactObj.adr=[];for(var i=0;i<vcardObj.adr.length;i++){var cur={};var adr=vcardObj.adr[i];if(adr.meta&&adr.meta.type){cur.type=adr.meta.type;}
|
||
for(var j=2;j<adr.value.length;j++){var decoded=_decodeQP(adr.meta,adr.value[j]);if(decoded!==''){cur[ADDR_PARTS[j]]=decoded;}}
|
||
contactObj.adr.push(cur);}
|
||
return contactObj;}
|
||
function _processComm(vcardObj,contactObj){contactObj.tel=[];['tel','email','url'].forEach(function field2field(field){if(!vcardObj[field]){return;}
|
||
var len=vcardObj[field].length;var hasTypeMapper=function(x){return x.trim().toLowerCase();};var notTypeMapper=function(v,key){return v.meta[key].trim().toLowerCase();};var noType=function(field){return field!=='type';};var noPref=function(field){return field!=='pref';};var typeFilter=function(metaValue){return!!VCARD_SIMPLE_TYPES[metaValue];};for(var i=0;i<len;i++){var v=vcardObj[field][i];var metaValues;var cur={};if(v.meta){if(v.value){cur.value=_decodeQP(v.meta,v.value[0]);cur.value=cur.value.replace(/^tel:/i,'');}
|
||
if(v.meta.type){metaValues=([].slice.call(v.meta.type)).map(hasTypeMapper);}else{metaValues=Object.keys(v.meta).filter(noType).map(notTypeMapper.bind(null,v));}
|
||
if(metaValues.indexOf('pref')!==-1){cur.pref=true;metaValues=metaValues.filter(noPref);}
|
||
switch(metaValues.length){case 0:cur.type=[DEFAULT_PHONE_TYPE];break;case 1:cur.type=[VCARD_SIMPLE_TYPES[metaValues[0]]||DEFAULT_PHONE_TYPE];break;case 2:var complexType1=metaValues[0]+','+metaValues[1];var complexType2=metaValues[1]+','+metaValues[0];cur.type=[VCARD_COMPLEX_TYPES[complexType1]||VCARD_COMPLEX_TYPES[complexType2]||VCARD_SIMPLE_TYPES[metaValues[0]]||VCARD_SIMPLE_TYPES[metaValues[1]]||DEFAULT_PHONE_TYPE];break;default:cur.type=[VCARD_SIMPLE_TYPES[metaValues.filter(typeFilter).shift()]||DEFAULT_PHONE_TYPE];}}
|
||
if(!contactObj[field]){contactObj[field]=[];}
|
||
contactObj[field].push(cur);}});return contactObj;}
|
||
function _isValidDate(dateValue){return!isNaN(Date.parse(dateValue));}
|
||
function _processFields(vcardObj,contactObj){['org','title','bday','anniversary'].forEach(function(field){if(!vcardObj[field]){return;}
|
||
var v=vcardObj[field][0];if(!v||!Array.isArray(v.value)||v.value.length===0){return;}
|
||
var dateValue;if(field==='bday'){dateValue=v.value[0];if(_isValidDate(dateValue)){contactObj.bday=new Date(dateValue);}
|
||
return;}
|
||
if(field==='anniversary'){dateValue=v.value[0];if(_isValidDate(dateValue)){contactObj.anniversary=new Date(dateValue);}
|
||
return;}
|
||
if(!v){return;}
|
||
if(field==='title'){field='jobTitle';}
|
||
switch(typeof v){case'object':contactObj[field]=[_decodeQP(v.meta,v.value[0])];break;case'string':contactObj[field]=[v];break;}});return contactObj;}
|
||
function _processPhoto(vcardObj,contactObj,cb){if(!Array.isArray(vcardObj.photo)||vcardObj.photo.length===0||!vcardObj.photo[0]||!vcardObj.photo[0].value){return cb(contactObj);}
|
||
var photo=vcardObj.photo[0];var photoContents=photo.value.trim();if(!photoContents){return cb(contactObj);}
|
||
if(photoContents&&photo.meta&&photo.meta.encoding==='base64'){var blob=b64toBlob(photoContents,photo.meta.type);if(blob){utils.thumbnailImage(blob,function gotThumbnail(thumbnail){if(blob!==thumbnail){contactObj.photo=[blob,thumbnail];}else{contactObj.photo=[blob];}
|
||
cb(contactObj);});}else{cb(contactObj);}}
|
||
else{var callbacks={success:function(blobPic){if(blobPic){contactObj.photo=[blobPic];}
|
||
cb(contactObj);},error:function(){console.error('Error getting photo for contact');cb(contactObj);},timeout:function(){console.error('Timeout getting photo for contact');cb(contactObj);}};Rest.get(photoContents,callbacks,{responseType:'blob',operationsTimeout:REST_TIMEOUT});}}
|
||
var vcardToContact=function(vcard,cb){if(!vcard){return null;}
|
||
var obj={};_processName(vcard,obj);_processAddr(vcard,obj);_processComm(vcard,obj);_processFields(vcard,obj);_processPhoto(vcard,obj,function(contactObj){cb(utils.misc.toMozContact(contactObj));});};var VCFReader=function(contents){this.contents=contents;this.processed=0;this.finished=false;this.currentChar=0;this.numDupsMerged=0;};VCFReader.CONCURRENCY=5;VCFReader.prototype.finish=function(){this.finished=true;};VCFReader.prototype.process=function(cb){var self=this;var match=this.contents.match(/end:vcard/gi);if(!match){if(cb){cb();}
|
||
return;}
|
||
this.importedContacts=[];this.total=match.length;this.onread&&this.onread(this.total);this.ondone=function(numImported){cb(numImported,self.numDupsMerged);};LazyLoader.load(['/shared/js/simple_phone_matcher.js','/shared/js/mime_mapper.js','/shared/js/contact_photo_helper.js','/shared/js/contacts/import/utilities/misc.js','/shared/js/contacts/contacts_matcher.js','/shared/js/contacts/contacts_merger.js','/shared/js/contacts/utilities/image_thumbnail.js','/shared/js/contacts/merger_adapter.js','/shared/js/contacts/utilities/http_rest.js'],function(){this.splitLines();}.bind(this));};VCFReader.prototype.onParsed=function(err,ct){this.processed+=1;this.importedContacts.push(ct);this.onimported&&this.onimported(ct&&ct.name);if(this.finished||this.processed===this.total){this.ondone(this.importedContacts);return;}
|
||
var processed=this.processed;if(processed<this.total&&processed%VCFReader.CONCURRENCY===0){this.splitLines();}};VCFReader.prototype.post=function(contactObjects){var _onParsed=this.onParsed.bind(this);var cursor=0;var self=this;function afterSave(ct,e){_onParsed(e,ct);cursor+=1;if(cursor<contactObjects.length){saveContact(contactObjects[cursor]);}}
|
||
function saveContact(ct){if(!ct){afterSave(null,null);return;}
|
||
var contact=utils.misc.toMozContact(ct);var afterSaveFn=afterSave.bind(null,contact);var matchCbs={onmatch:function(matches){var callbacks={success:function(mergedContact){self.numDupsMerged++;afterSave(mergedContact,null);},error:afterSaveFn};contacts.adaptAndMerge(contact,matches,callbacks);},onmismatch:function(){VCFReader._save(contact,afterSaveFn);}};Matcher.match(contact,'passive',matchCbs);}
|
||
saveContact(contactObjects[cursor]);};VCFReader._save=function(item,cb){var req=navigator.mozContacts.save(utils.misc.toMozContact(item));req.onsuccess=cb;req.onerror=cb;};var reBeginCard=/begin:vcard$/i;var reEndCard=/end:vcard$/i;var reVersion=/^VERSION:([\d\.]*)/i;VCFReader.prototype.splitLines=function(){var currentLine='';var currentVersion=0;var inLabel=false;var multiline=false;var cardArray=[[]];var cardsProcessed=0;var i=this.currentChar;var callPost=this.post.bind(this);for(var l=this.contents.length;i<l;i++){this.currentChar=i;var ch=this.contents[i];if(currentVersion>=4&&ch==='"'){inLabel=!inLabel;currentLine+=ch;continue;}
|
||
if(multiline===true){if((/[\r\t\s\n]/).test(ch)){continue;}else{multiline=false;}}
|
||
var next=this.contents[i+1];if(inLabel||(ch!=='\n'&&ch!=='\r')){if(!(/^PHOTO/i).test(currentLine)&&ch==='='&&next&&next.search(/(\r|\n)/)!==-1){multiline=true;continue;}
|
||
currentLine+=ch;if(i!==l-1){continue;}}
|
||
var firstCharNextLine=this.contents[i+2];if((firstCharNextLine===WHITE_SPACE)&&(/[\r\t\s\n]/).test(next)&&(/^PHOTO/i).test(currentLine)){multiline=true;continue;}
|
||
if(next&&(next===WHITE_SPACE||next==='\t')){multiline=true;continue;}
|
||
if(reBeginCard.test(currentLine)){currentLine='';currentVersion=0;continue;}
|
||
if(reEndCard.test(currentLine)){cardsProcessed+=1;if(cardsProcessed===VCFReader.CONCURRENCY||(cardsProcessed+this.processed)===this.total){_parseEntries(cardArray,callPost);break;}
|
||
currentLine='';cardArray.push([]);continue;}
|
||
if(currentLine){var matches=reVersion.exec(currentLine);if(matches===null){cardArray[cardArray.length-1].push(currentLine);}else{currentVersion=parseFloat(matches[1]||'0');}}
|
||
currentLine='';}};VCFReader._decodeQuoted=_decodeQuoted;VCFReader.processAddr=_processAddr;VCFReader.processName=_processName;VCFReader.vcardToContact=vcardToContact;VCFReader.utils={parseDataUri:parseDataUri,b64toBlob:b64toBlob};return VCFReader;})();;'use strict';var utils=window.utils||{};utils.importFromVcard=function(file,callback){var MERGE_DEPENDENCIES=['/shared/js/simple_phone_matcher.js','/shared/js/contacts/merger_adapter.js','/shared/js/contacts/contacts_merger.js','/shared/js/contacts/contacts_matcher.js'];Loader.utility('Overlay',function(){LazyLoader.load(MERGE_DEPENDENCIES,_loaded);});function _loaded(){var importedContacts=0;var cancelled=false;var importer=null;var text=null;var progress=utils.overlay.show('memoryCardContacts-reading','activityBar');utils.overlay.showMenu();utils.overlay.oncancel=function oncancel(){cancelled=true;if(importer){importer.finish();}else{utils.overlay.hide();}};readVCard(function(vcardText){if(vcardText){processTextFromFile(vcardText);}else{callback();}});function readVCard(cb){var reader;if(typeof file==='string'){cb(file);}else{reader=new FileReader();reader.onloadend=function(){text=reader.result;if(text){cb(text);}};try{reader.readAsText(file);}
|
||
catch(ex){console.error('Error reading the file '+ex.message);import_error();cb();}}}
|
||
function processTextFromFile(textFromFile){if(cancelled){return;}
|
||
var reader=new VCardReader(textFromFile);var match=textFromFile&&textFromFile.match(/END:VCARD/g);var cursor=reader.getAll();var numContacts=match?match.length:0;var numDupsMerged=0;var firstContact=null;var _doContinue=function(savedContact){if(savedContact){if(!firstContact){firstContact=savedContact;}
|
||
imported_contact();}
|
||
if(!cancelled){cursor.continue();}};cursor.onsuccess=function(evt){if(evt.target.result){var contact=evt.target.result;Matcher.match(contact,'passive',{onmatch:function(matches){var callbacks={success:function(mergedContact){numDupsMerged++;_doContinue(mergedContact);},error:_doContinue};contacts.adaptAndMerge(contact,matches,callbacks);},onmismatch:function(){var req=navigator.mozContacts.save(contact);req.onsuccess=function(){_doContinue(contact);};}});}else{utils.overlay.hide();if(!cancelled){var msgImported={id:'memoryCardContacts-imported3',args:{n:importedContacts}};var msgDupsMerged=numDupsMerged?{id:'contactsMerged',args:{numDups:numDupsMerged}}:null;utils.status.show(msgImported,msgDupsMerged);}
|
||
if(importedContacts>0){callback(importedContacts,firstContact.id);}else{callback(importedContacts);}}};import_read(numContacts);}
|
||
function import_read(n){progress.setClass('progressBar');progress.setHeaderMsg('memoryCardContacts-importing');progress.setTotal(n);}
|
||
function imported_contact(){importedContacts++;if(!cancelled){progress.update();}}
|
||
function import_error(e){console.error('Error importing from vcard: '+e.message);var cancel={title:'cancel',callback:function(){ConfirmDialog.hide();}};var retry={title:'retry',isRecommend:true,callback:function(){ConfirmDialog.hide();processTextFromFile(text);}};ConfirmDialog.show(null,'memoryCardContacts-error',cancel,retry);utils.overlay.hide();}}};;'use strict';function SimContactsImporter(targetIcc){if(targetIcc===null){throw new Error('We need an icc to continue with this operation');}
|
||
var pointer=0;var CHUNK_SIZE=5;var numResponses=0;var self=this;var mustFinish=false;var loadedMatch=false;var DEFAULT_TEL_TYPE='other';var icc=targetIcc;var iccId=icc.iccInfo&&icc.iccInfo.iccid;var numDupsMerged=0;function generateIccContactUrl(contactid){var urlValue='urn:'+'uuid:'+(iccId||'iccId')+'-'+contactid;return[{type:['source','sim'],value:urlValue}];}
|
||
function notifyFinish(){if(typeof self.onfinish==='function'){window.setTimeout(self.onfinish,0,numDupsMerged,iccId);}}
|
||
function notifyImported(){if(typeof self.onimported==='function'){window.setTimeout(self.onimported,0);}}
|
||
function continueCb(){numResponses++;pointer++;notifyImported();if(pointer<self.items.length&&numResponses===CHUNK_SIZE){numResponses=0;mustFinish?notifyFinish():importSlice(pointer);}
|
||
else if(pointer>=self.items.length){notifyFinish();}}
|
||
function startMigration(){if(!mustFinish&&Array.isArray(self.items)&&self.items.length>0){importSlice(0);}
|
||
else{notifyFinish();}}
|
||
function onContactsReadyForImport(){if(typeof self.onread==='function'){self.onread(self.items.length);}
|
||
if(loadedMatch){startMigration();}
|
||
else{document.addEventListener('matchLoaded',function mloaded(){document.removeEventListener('matchLoaded',mloaded);startMigration();});}}
|
||
this.start=function(){numDupsMerged=0;if(mustFinish){notifyFinish();return;}
|
||
LazyLoader.load(['/shared/js/simple_phone_matcher.js','/shared/js/contacts/contacts_matcher.js','/shared/js/contacts/contacts_merger.js','/shared/js/contacts/utilities/image_thumbnail.js','/shared/js/contacts/merger_adapter.js'],function loaded(){loadedMatch=true;document.dispatchEvent(new CustomEvent('matchLoaded'));});var requestAdn,requestSdn;if(icc&&icc.readContacts){requestAdn=icc.readContacts('adn');}else{throw new Error('Not able to obtain a SIM import function from platform');}
|
||
requestAdn.onsuccess=function onsuccess(){if(mustFinish){notifyFinish();return;}
|
||
self.items=requestAdn.result||[];requestSdn=icc.readContacts('sdn');requestSdn.onsuccess=function onsuccess(){if(mustFinish){notifyFinish();return;}
|
||
if(Array.isArray(requestSdn.result)){self.items=self.items.concat(requestSdn.result);}
|
||
onContactsReadyForImport();};requestSdn.onerror=function error(){if(mustFinish){notifyFinish();return;}
|
||
console.warn('Could not read SDN Contacts from SIM Card',error.name);onContactsReadyForImport();};};requestAdn.onerror=function error(){if(typeof self.onerror==='function'){self.onerror(requestAdn.error);}};};this.finish=function(){mustFinish=true;};function importSlice(from){for(var i=from;i<from+CHUNK_SIZE&&i<self.items.length;i++){var item=self.items[i];var parsedName=utils.misc.parseName(item.name[0]);item.givenName=[parsedName.givenName];item.familyName=[parsedName.familyName];if(Array.isArray(item.tel)){var telItems=[];for(var j=0;j<item.tel.length;j++){var aTel=item.tel[j];if(aTel.value&&aTel.value.trim()){aTel.type=[DEFAULT_TEL_TYPE];telItems.push(aTel);}}
|
||
item.tel=telItems;}
|
||
item.category=['sim'];item.url=generateIccContactUrl(item.id);var contact=item;var cbs={onmatch:function(results){var mergeCbs={success:function(){numDupsMerged++;continueCb();},error:function(e){window.console.error('Error while merging: ',e.name);continueCb();}};contacts.adaptAndMerge(this,results,mergeCbs);}.bind(contact),onmismatch:function(){saveContact(this);}.bind(contact)};Matcher.match(item,'passive',cbs);}}
|
||
function saveContact(contact){var req=window.navigator.mozContacts.save(new mozContact(contact));req.onsuccess=function saveSuccess(){continueCb();};req.onerror=function saveError(){console.error('SIM Import: Error importing ',contact.id,req.error.name);continueCb();};}};'use strict';var ScreenLayout={defaultQueries:{tiny:'(max-width: 767px)',small:'(min-width: 768px) and (max-width: 991px)',medium:'(min-width: 992px) and (max-width: 1200px)',large:'(min-width: 1201px)',hardwareHomeButton:window.VulpesCompat?'(min-width: 0px)':'(-moz-physical-home-button)'},init:function sl_init(){this.queries=(function(qs){var result={};for(var key in qs){result[key]=window.matchMedia(qs[key]);}
|
||
return result;})(this.defaultQueries);},_isOnRealDevice:undefined,isOnRealDevice:function sl_isOnRealDevice(){if(typeof(this._isOnRealDevice)!=='undefined'){return this._isOnRealDevice;}
|
||
if(window.innerWidth===screen.availWidth){this._isOnRealDevice=true;}else{this._isOnRealDevice=false;}
|
||
return this._isOnRealDevice;},getCurrentLayout:function sl_getCurrentLayout(type){if(type===undefined){for(var name in this.defaultQueries){if(this.queries[name]&&this.queries[name].matches){return name;}}}
|
||
if(typeof this.queries[type]!=='undefined'){return this.queries[type].matches;}
|
||
return false;},watch:function sl_watch(name,media){var mediaString=media||this.queries[name].media;if(!mediaString){return;}
|
||
this.unwatch(name);this.queries[name]=window.matchMedia(mediaString);this.boundHandleChange=this.handleChange.bind(this);this.queries[name].addListener(this.boundHandleChange);},unwatch:function sl_unwatch(name){if(this.queries[name]){this.queries[name].removeListener(this.boundHandleChange);}},handleChange:function sl_handleChange(evt){for(var key in this.queries){if(this.queries[key].media!==evt.media){continue;}
|
||
window.dispatchEvent(new CustomEvent('screenlayoutchange',{detail:{name:key,status:evt.matches}}));}}};ScreenLayout.init();;'use strict';var Normalizer={initAsciiNormalizer:function normalizer_init(){var equivalentChars={'a':'áăǎâäȧạȁàảȃāąåḁⱥãǽǣæ','A':'ÁĂǍÂÄȦẠȀÀẢȂĀĄÅḀȺÃǼǢÆ','b':'ḃḅɓḇƀƃ','B':'ḂḄƁḆɃƂ','c':'ćčçĉċƈȼ','C':'ĆČÇĈĊƇȻ','d':'ďḑḓḋḍɗḏđƌð','D':'ĎḐḒḊḌƊḎĐƋ','e':'éĕěȩêḙëėẹȅèẻȇēę','E':'ÉĔĚȨÊḘËĖẸȄÈẺȆĒĘ','f':'ḟƒ','F':'ḞƑ','g':'ǵğǧģĝġɠḡǥ','G':'ǴĞǦĢĜĠƓḠǤ','h':'ḫȟḩĥⱨḧḣḥħ','H':'ḪȞḨĤⱧḦḢḤĦ','i':'íĭǐîïịȉìỉȋīįɨĩḭı','I':'ÍĬǏÎÏỊȈÌỈȊĪĮƗĨḬ','j':'ĵɉ','J':'ĴɈ','k':'ḱǩķⱪꝃḳƙḵꝁ','K':'ḰǨĶⱩꝂḲƘḴꝀ','l':'ĺƚľļḽḷⱡꝉḻŀɫł','L':'ĹȽĽĻḼḶⱠꝈḺĿⱢŁ','m':'ḿṁṃɱ','M':'ḾṀṂⱮ','n':'ńňņṋṅṇǹɲṉƞñ','N':'ŃŇŅṊṄṆǸƝṈȠÑ','o':'óŏǒôöȯọőȍòỏơȏꝋꝍōǫøõœ','O':'ÓŎǑÔÖȮỌŐȌÒỎƠȎꝊꝌŌǪØÕŒ','p':'ṕṗꝓƥᵽꝑ','P':'ṔṖꝒƤⱣꝐ','q':'ꝗ','Q':'Ꝗ','r':'ŕřŗṙṛȑȓṟɍɽ','R':'ŔŘŖṘṚȐȒṞɌⱤ','s':'śšşŝșṡṣß','S':'ŚŠŞŜȘṠṢ','t':'ťţṱțⱦṫṭƭṯʈŧ','T':'ŤŢṰȚȾṪṬƬṮƮŦ','u':'úŭǔûṷüṳụűȕùủưȗūųůũṵ','U':'ÚŬǓÛṶÜṲỤŰȔÙỦƯȖŪŲŮŨṴ','v':'ṿʋṽ','V':'ṾƲṼ','w':'ẃŵẅẇẉẁⱳ','W':'ẂŴẄẆẈẀⱲ','x':'ẍẋ','X':'ẌẊ','y':'ýŷÿẏỵỳƴỷỿȳɏỹ','Y':'ÝŶŸẎỴỲƳỶỾȲɎỸ','z':'źžẑⱬżẓȥẕƶ','Z':'ŹŽẐⱫŻẒȤẔƵ'};this._toAsciiForm={};for(var letter in equivalentChars){var accentedForms=equivalentChars[letter];for(var i=accentedForms.length-1;i>=0;i--){this._toAsciiForm[accentedForms[i]]=letter;}}},toAscii:function normalizer_toAscii(str){if(!str||typeof str!='string'){return'';}
|
||
if(!this._toAsciiForm){Normalizer.initAsciiNormalizer();}
|
||
var result='';for(var i=0,len=str.length;i<len;i++){result+=this._toAsciiForm[str.charAt(i)]||str.charAt(i);}
|
||
return result;},escapeHTML:function normalizer_escapeHTML(str,escapeQuotes){if(Array.isArray(str)){return Normalizer.escapeHTML(str.join(' '),escapeQuotes);}
|
||
if(!str||typeof str!='string'){return'';}
|
||
var escaped=str.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');if(escapeQuotes){return escaped.replace(/"/g,'"').replace(/'/g,''');}
|
||
return escaped;},unescapeHTML:function normalizer_unescapeHTML(text){return text.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"').replace(/'/g,'\'');},escapeRegExp:function normalizer_escapeRegExp(str){return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,'\\$&');}};;'use strict';var LazyLoader=(function(){function LazyLoader(){this._loaded={};this._isLoading={};}
|
||
LazyLoader.prototype={_js:function(file,callback){var script=document.createElement('script');script.src=file;script.async=false;script.addEventListener('load',callback);document.head.appendChild(script);this._isLoading[file]=script;},_css:function(file,callback){var style=document.createElement('link');style.type='text/css';style.rel='stylesheet';style.href=file;document.head.appendChild(style);callback();},_html:function(domNode,callback){if(domNode.getAttribute('is')){this.load(['/shared/js/html_imports.js'],function(){HtmlImports.populate(callback);}.bind(this));return;}
|
||
for(var i=0;i<domNode.childNodes.length;i++){if(domNode.childNodes[i].nodeType==document.COMMENT_NODE){domNode.innerHTML=domNode.childNodes[i].nodeValue;break;}}
|
||
window.dispatchEvent(new CustomEvent('lazyload',{detail:domNode}));callback();},getJSON:function(file,mozSystem){return new Promise(function(resolve,reject){var xhr;if(mozSystem){xhr=new XMLHttpRequest({mozSystem:true});}else{xhr=new XMLHttpRequest();}
|
||
xhr.open('GET',file,true);xhr.responseType='json';xhr.onerror=function(error){reject(error);};xhr.onload=function(){if(xhr.response!==null){resolve(xhr.response);}else{reject(new Error('No valid JSON object was found ('+
|
||
xhr.status+' '+xhr.statusText+')'));}};xhr.send();});},load:function(files,callback){var deferred={};deferred.promise=new Promise(resolve=>{deferred.resolve=resolve;});if(!Array.isArray(files)){files=[files];}
|
||
var loadsRemaining=files.length,self=this;function perFileCallback(file){if(self._isLoading[file]){delete self._isLoading[file];}
|
||
self._loaded[file]=true;if(--loadsRemaining===0){deferred.resolve();if(callback){callback();}}}
|
||
for(var i=0;i<files.length;i++){var file=files[i];if(this._loaded[file.id||file]){perFileCallback(file);}else if(this._isLoading[file]){this._isLoading[file].addEventListener('load',perFileCallback.bind(null,file));}else{var method,idx;if(typeof file==='string'){method=file.match(/\.([^.]+)$/)[1];idx=file;}else{method='html';idx=file.id;}
|
||
this['_'+method](file,perFileCallback.bind(null,idx));}}
|
||
return deferred.promise;}};return new LazyLoader();}());;'use strict';var Basket={DATASTORE_NAME:'Basket_Newsletter',basketUrl:'https://basket.mozilla.org/news/subscribe/',newsletterId:'firefox-os',callback:null,xhr:null,errors:{NETWORK_FAILURE:1,INVALID_EMAIL:2,UNKNOWN_EMAIL:3,UNKNOWN_TOKEN:4,USAGE_ERROR:5,EMAIL_PROVIDER_AUTH_FAILURE:6,AUTH_ERROR:7,SSL_REQUIRED:8,INVALID_NEWSLETTER:9,INVALID_LANGUAGE:10,EMAIL_NOT_CHANGED:11,CHANGE_REQUEST_NOT_FOUND:12,UNKNOWN_ERROR:99},responseHandler:function b_responseHandler(){if(this.xhr.readyState===4){if(this.xhr.status===200){if(typeof this.callback==='function'){this.callback(null,JSON.parse(this.xhr.responseText));}}else{if(typeof this.callback==='function'){if(this.xhr.responseText){this.callback(JSON.parse(this.xhr.responseText));}else{this.callback('Unknown error');}}}}},timeoutHandler:function b_timeoutHandler(){this.callback('Timeout');},send:function b_send(email,callback){var self=this;var params='email='+encodeURIComponent(email)+'&newsletters='+self.newsletterId;self.callback=callback;self.xhr=new XMLHttpRequest({mozSystem:true});self.xhr.onreadystatechange=self.responseHandler.bind(self);self.xhr.open('POST',self.basketUrl,true);self.xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');self.xhr.setRequestHeader('Connection','close');self.xhr.timeout=5000;self.xhr.ontimeout=self.timeoutHandler.bind(self);self.getLanguage(function do_send(language){if(language){params+='&lang='+language;}
|
||
self.xhr.setRequestHeader('Content-length',params.length);self.xhr.send(params);});},getDataStore:function(){var self=this;return new Promise(function(resolve,reject){navigator.getDataStores(self.DATASTORE_NAME).then(function(stores){if(!stores.length){reject(new Error('DataStore not loaded'));}else{var dataStore=stores[0];if(dataStore.owner==='app://ftu.gaiamobile.org/manifest.webapp'){resolve(dataStore);}else{reject(new Error('Wrong DataStore'));}}});});},store:function b_store(email,callback){this.getDataStore().then(function loaded(store){store.add({'newsletter_email':email}).then(function(id){if(callback){callback(false,id);}});}).catch(function error(err){console.error('Something went wrong: '+err);callback(err);});},getLanguage:function b_getLanguage(callback){var settings=window.navigator.mozSettings;if(!settings||!settings.createLock){callback();return;}
|
||
var s_name='language.current';var req=settings.createLock().get(s_name);req.onsuccess=function _onsuccess(){callback(req.result[s_name]);};req.onerror=function _onerror(){console.error('Error getting setting: '+s_name);callback();};}};;'use strict';var FTU_APP_ORIGIN=document.location.protocol+'//'+
|
||
document.location.host;var ServicesLauncher=(function(document){var extensionFrame=document.querySelector('#iframe_extensions');var oauthFrame=document.querySelector('#iframe_oauth');var BASE_IMPORT='/shared/pages/import/import.html?ftu=1';function getServiceURI(service){return BASE_IMPORT+'&service='+service;}
|
||
var access_token,currentURI,currentService;function open(){extensionFrame.className='opening';}
|
||
function load(targetService){currentService=targetService;currentURI=getServiceURI(targetService);window.addEventListener('message',messageHandler);oauthFrame.contentWindow.postMessage({type:'start',data:{from:'friends',service:targetService}},FTU_APP_ORIGIN);}
|
||
function unload(){window.removeEventListener('message',messageHandler);extensionFrame.src=null;}
|
||
function close(messageId){extensionFrame.addEventListener('transitionend',function tclose(){extensionFrame.removeEventListener('transitionend',tclose);extensionFrame.src=null;if(messageId){utils.status.show(messageId);}});extensionFrame.className='closing';window.removeEventListener('message',messageHandler);}
|
||
function messageHandler(e){if(e.origin!==FTU_APP_ORIGIN){return;}
|
||
var data=e.data;switch(data.type){case'ready':open();break;case'abort':unload();break;case'window_close':close(data.messageId);break;case'authenticated':extensionFrame.src=currentURI;access_token=data.data;break;case'messaging_ready':extensionFrame.contentWindow.postMessage({type:'token',data:access_token},FTU_APP_ORIGIN);break;}}
|
||
return{start:load};})(document);;'use strict';if(!window.ImportStatusData){var ImportStatusData=(function(){var store=null;var DS_NAME='Import_Status_Data';var datastoreLoading=false;var datastoreLoaded=false;var DS_LOADED_EVENT='datastore_loaded';var getDatastore=function getDatastore(){return new Promise(function(resolve,reject){if(!navigator.getDataStores){reject({name:'DatastoreNotEnabled'});return;}
|
||
if(datastoreLoaded){resolve(store);return;}
|
||
if(datastoreLoading){document.addEventListener(DS_LOADED_EVENT,function loadedHandler(){document.removeEventListener(DS_LOADED_EVENT,loadedHandler);resolve(store);});}
|
||
datastoreLoading=true;navigator.getDataStores(DS_NAME).then(function(stores){store=stores[0];},reject).then(function(){datastoreLoading=false;datastoreLoaded=true;document.dispatchEvent(new CustomEvent(DS_LOADED_EVENT));resolve(store);},reject);});};var put=function put(key,obj){return new Promise(function(resolve,reject){getDatastore().then(function success(store){store.put(obj,key).then(resolve,reject);},reject);});};var remove=function remove(key){return new Promise(function(resolve,reject){getDatastore().then(function success(store){store.remove(key).then(resolve,reject);},reject);});};var get=function get(key){return new Promise(function(resolve,reject){getDatastore().then(function success(store){store.get(key).then(resolve,reject);},reject);});};var clear=function clear(){return new Promise(function(resolve,reject){getDatastore().then(function success(store){store.clear().then(resolve,reject);},reject);});};return{put:put,remove:remove,get:get,clear:clear};})();};this.asyncStorage=(function(){'use strict';var DBNAME='asyncStorage';var DBVERSION=1;var STORENAME='keyvaluepairs';var db=null;function withDatabase(f){if(db){f();}else{var openreq=indexedDB.open(DBNAME,DBVERSION);openreq.onerror=function withStoreOnError(){console.error('asyncStorage: can\'t open database:',openreq.error.name);};openreq.onupgradeneeded=function withStoreOnUpgradeNeeded(){openreq.result.createObjectStore(STORENAME);};openreq.onsuccess=function withStoreOnSuccess(){db=openreq.result;f();};}}
|
||
function withStore(type,callback,oncomplete){withDatabase(function(){var transaction=db.transaction(STORENAME,type);if(oncomplete){transaction.oncomplete=oncomplete;}
|
||
callback(transaction.objectStore(STORENAME));});}
|
||
function getItem(key,callback){var req;withStore('readonly',function getItemBody(store){req=store.get(key);req.onerror=function getItemOnError(){console.error('Error in asyncStorage.getItem(): ',req.error.name);};},function onComplete(){var value=req.result;if(value===undefined){value=null;}
|
||
callback(value);});}
|
||
function setItem(key,value,callback){withStore('readwrite',function setItemBody(store){var req=store.put(value,key);req.onerror=function setItemOnError(){console.error('Error in asyncStorage.setItem(): ',req.error.name);};},callback);}
|
||
function removeItem(key,callback){withStore('readwrite',function removeItemBody(store){var req=store.delete(key);req.onerror=function removeItemOnError(){console.error('Error in asyncStorage.removeItem(): ',req.error.name);};},callback);}
|
||
function clear(callback){withStore('readwrite',function clearBody(store){var req=store.clear();req.onerror=function clearOnError(){console.error('Error in asyncStorage.clear(): ',req.error.name);};},callback);}
|
||
function length(callback){var req;withStore('readonly',function lengthBody(store){req=store.count();req.onerror=function lengthOnError(){console.error('Error in asyncStorage.length(): ',req.error.name);};},function onComplete(){callback(req.result);});}
|
||
function key(n,callback){if(n<0){callback(null);return;}
|
||
var req;withStore('readonly',function keyBody(store){var advanced=false;req=store.openCursor();req.onsuccess=function keyOnSuccess(){var cursor=req.result;if(!cursor){return;}
|
||
if(n===0||advanced){return;}
|
||
advanced=true;cursor.advance(n);};req.onerror=function keyOnError(){console.error('Error in asyncStorage.key(): ',req.error.name);};},function onComplete(){var cursor=req.result;callback(cursor?cursor.key:null);});}
|
||
return{getItem:getItem,setItem:setItem,removeItem:removeItem,clear:clear,length:length,key:key};}());;'use strict';var MobileInfo={brazil:{carriers:{'00':'NEXTEL','02':'TIM','03':'TIM','04':'TIM','05':'CLARO','06':'VIVO','07':'CTBC','08':'TIM','10':'VIVO','11':'VIVO','15':'SERCOMTEL','16':'OI','23':'VIVO','24':'OI','31':'OI','32':'CTBC','33':'CTBC','34':'CTBC','37':'AEIOU'},regions:{'11':'SP','12':'SP','13':'SP','14':'SP','15':'SP','16':'SP','17':'SP','18':'SP','19':'SP','21':'RJ','22':'RJ','24':'RJ','27':'ES','28':'ES','31':'MG','32':'MG','33':'MG','34':'MG','35':'MG','37':'MG','38':'MG','41':'PR','42':'PR','43':'PR','44':'PR','45':'PR','46':'PR','47':'SC','48':'SC','49':'SC','51':'RS','53':'RS','54':'RS','55':'RS','61':'DF','62':'GO','63':'TO','64':'GO','65':'MT','66':'MT','67':'MS','68':'AC','69':'RO','71':'BA','73':'BA','74':'BA','75':'BA','77':'BA','79':'SE','81':'PE','82':'AL','83':'PB','84':'RN','85':'CE','86':'PI','87':'PE','88':'CE','89':'PI','91':'PA','92':'AM','93':'PA','94':'PA','95':'RR','96':'AP','97':'AM','98':'MA','99':'MA'}}};var MobileOperator={BRAZIL_MCC:'724',BRAZIL_CELLBROADCAST_CHANNEL:50,userFacingInfo:function mo_userFacingInfo(mobileConnection){var network=mobileConnection.voice.network;var iccid=mobileConnection.iccId;var iccObj=navigator.mozIccManager.getIccById(iccid);var iccInfo=iccObj?iccObj.iccInfo:null;var operator=network?(network.shortName||network.longName):null;if(operator&&iccInfo&&iccInfo.isDisplaySpnRequired&&iccInfo.spn){if(iccInfo.isDisplayNetworkNameRequired&&operator!==iccInfo.spn){operator=operator+' '+iccInfo.spn;}else{operator=iccInfo.spn;}}
|
||
var carrier,region;if(this.isBrazil(mobileConnection)){var lac=mobileConnection.voice.cell.gsmLocationAreaCode%100;var carriers=MobileInfo.brazil.carriers;var regions=MobileInfo.brazil.regions;carrier=carriers[network.mnc]||(this.BRAZIL_MCC+network.mnc);region=(regions[lac]?regions[lac]+' '+lac:'');}
|
||
return{'operator':operator,'carrier':carrier,'region':region};},isBrazil:function mo_isBrazil(mobileConnection){var cell=mobileConnection.voice.cell;var net=mobileConnection.voice.network;return net?(net.mcc===this.BRAZIL_MCC&&cell&&cell.gsmLocationAreaCode):null;}};;'use strict';(function(exports){var _iccManager=navigator.mozIccManager;var _iccProxy=null;Object.defineProperty(exports,'IccHelper',{configurable:true,get:function(){return _iccProxy;},set:function(value){_iccProxy=value;}});if(_iccManager&&_iccManager.getIccById){var activeIccObj=null;var eventListeners={};var cachedEventListeners={};var events=['cardstatechange','iccinfochange','stkcommand','stksessionend'];var getters=['iccInfo','cardState'];var methods=['sendStkResponse','sendStkMenuSelection','sendStkTimerExpiration','sendStkEventDownload'];var domRequests=['getCardLock','unlockCardLock','setCardLock','getCardLockRetryCount','readContacts','updateContact','iccOpenChannel','iccExchangeAPDU','iccCloseChannel'];var getterTemplate=function(name){return function(){if(activeIccObj){return activeIccObj[name];}else{return null;}};};var methodTemplate=function(name){return function(){if(activeIccObj){return activeIccObj[name].apply(activeIccObj,arguments);}};};var createIccProxy=function(){var iccProxy={addEventListener:function(eventName,callback){if(typeof callback!=='function'){return;}
|
||
if(events.indexOf(eventName)===-1){return;}
|
||
var listeners=eventListeners[eventName];if(listeners==null){listeners=eventListeners[eventName]=[];}
|
||
if(listeners.indexOf(callback)===-1){listeners.push(callback);}},removeEventListener:function(eventName,callback){var listeners=eventListeners[eventName];if(listeners){var index=listeners.indexOf(callback);if(index!==-1){listeners.splice(index,1);}}}};getters.forEach(function(getter){Object.defineProperty(iccProxy,getter,{enumerable:true,get:getterTemplate(getter)});});methods.forEach(function(method){iccProxy[method]=methodTemplate(method);});domRequests.forEach(function(request){iccProxy[request]=methodTemplate(request);});events.forEach(function(eventName){Object.defineProperty(iccProxy,'on'+eventName,{enumerable:true,set:function(newListener){var oldListener=cachedEventListeners[eventName];if(oldListener){iccProxy.removeEventListener(eventName,oldListener);}
|
||
cachedEventListeners[eventName]=newListener;if(newListener){iccProxy.addEventListener(eventName,newListener);}},get:function(){return cachedEventListeners[eventName];}});});return iccProxy;};_iccProxy=createIccProxy();if(_iccManager.iccIds&&_iccManager.iccIds.length){activeIccObj=_iccManager.getIccById(_iccManager.iccIds[0]);if(activeIccObj){events.forEach(function(eventName){activeIccObj.addEventListener(eventName,function(event){var listeners=eventListeners[eventName];if(listeners){listeners.forEach(function(listener){listener(event);});}});});}}
|
||
_iccManager.oniccdetected=function(event){if(_iccProxy.cardState==null){activeIccObj=_iccManager.getIccById(event.iccId);if(activeIccObj){events.forEach(function(eventName){activeIccObj.addEventListener(eventName,function(event){var listeners=eventListeners[eventName];if(listeners){listeners.forEach(function(listener){listener(event);});}});});['cardstatechange','iccinfochange'].forEach(function(eventName){if(eventListeners[eventName]){eventListeners[eventName].forEach(function(listener){listener();});}});}}};}else{_iccProxy=_iccManager;}})(window);;'use strict';var WifiHelper={getWifiManager:function(){return this.wifiManager();},wifiManager:function(){return navigator.mozWifiManager;},setPassword:function(network,password,identity,eap,phase2,certificate){var encType=this.getKeyManagement(network);switch(encType){case'WPA-PSK':network.psk=password;break;case'WPA-EAP':network.eap=eap;switch(eap){case'SIM':break;case'PEAP':case'TLS':case'TTLS':if(password&&password.length){network.password=password;}
|
||
if(identity&&identity.length){network.identity=identity;}
|
||
if(phase2!='No'){network.phase2=phase2;}
|
||
if(certificate!='none'){network.serverCertificate=certificate;}
|
||
break;default:break;}
|
||
break;case'WEP':network.wep=password;break;default:return;}
|
||
network.keyManagement=encType;},setSecurity:function(network,encryptions){network.security=encryptions;},getSecurity:function(network){return network.security;},getCapabilities:function(network){return network.capabilities===undefined||network.capabilities===null?[]:network.capabilities;},getKeyManagement:function(network){var key=this.getSecurity(network)[0];if(/WEP$/.test(key)){return'WEP';}
|
||
if(/PSK$/.test(key)){return'WPA-PSK';}
|
||
if(/EAP$/.test(key)){return'WPA-EAP';}
|
||
return'';},isConnected:function(network){return'connected'===this.getNetworkStatus(network);},getNetworkStatus:function(network){var currentConnection=this.getWifiManager().connection;var currentNetwork=currentConnection.network;if(!currentNetwork||!network){return false;}
|
||
var key=network.ssid+'+'+this.getSecurity(network).join('+');var curkey=currentNetwork.ssid+'+'+
|
||
this.getSecurity(currentNetwork).join('+');return(key===curkey?currentConnection.status:'disconnected');},isValidInput:function(key,password,identity,eap){function isValidWepKey(password){switch(password.length){case 5:case 13:case 16:case 29:return true;case 10:case 26:case 32:case 58:return!/[^a-fA-F0-9]/.test(password);default:return false;}}
|
||
switch(key){case'WPA-PSK':if(!password||password.length<8){return false;}
|
||
break;case'WPA-EAP':switch(eap){case'SIM':break;case'PEAP':case'TLS':case'TTLS':default:if(!password||password.length<1||!identity||identity.length<1){return false;}
|
||
break;}
|
||
break;case'WEP':if(!password||!isValidWepKey(password)){return false;}
|
||
break;}
|
||
return true;},isSSIDValid:function(ssid){return!!ssid&&ssid.length>0;},isWpsAvailable:function(network){var capabilities=this.getCapabilities(network);for(var i=0;i<capabilities.length;i++){if(/WPS/.test(capabilities[i])){return true;}}
|
||
return false;},isOpen:function(network){return this.getKeyManagement(network)==='';},isEap:function(network){return this.getKeyManagement(network).indexOf('EAP')!==-1;},_unionOfNetworks:function(available,known){var allNetworks=available||{};var result=[];Object.keys(known).forEach(function(key){if(!allNetworks[key]){allNetworks[key]=known[key];}});Object.keys(allNetworks).forEach(function(key){result.push(allNetworks[key]);});return result;},_networksArrayToObject:function(allNetworks){var self=this;var networksObject={};[].forEach.call(allNetworks,function(network){var key=network.ssid+'+'+
|
||
self.getSecurity(network).join('+');if(!networksObject[key]||network.relSignalStrength>networksObject[key].relSignalStrength){networksObject[key]=network;}});return networksObject;},_onReqProxySuccess:function(reqProxy,availableNetworks,knownNetworks){reqProxy.result=this._unionOfNetworks(availableNetworks,knownNetworks);reqProxy.onsuccess();},getAvailableAndKnownNetworks:function(){var self=this;var reqProxy={onsuccess:function(){},onerror:function(){}};var knownNetworks={};var availableNetworks={};var knownNetworksReq=null;var availableNetworksReq=this.getWifiManager().getNetworks();availableNetworksReq.onsuccess=function anrOnSuccess(){availableNetworks=self._networksArrayToObject(availableNetworksReq.result);knownNetworksReq=self.getWifiManager().getKnownNetworks();knownNetworksReq.onsuccess=function knrOnSuccess(){knownNetworks=self._networksArrayToObject(knownNetworksReq.result);self._onReqProxySuccess(reqProxy,availableNetworks,knownNetworks);};knownNetworksReq.onerror=function knrOnError(){self._onReqProxySuccess(reqProxy,availableNetworks,knownNetworks);};};availableNetworksReq.onerror=function anrOnError(){reqProxy.error=availableNetworksReq.error;reqProxy.onerror();};return reqProxy;},getSignalLevel:function(network){return Math.min(Math.floor(network.relSignalStrength/20),4);}};;'use strict';var FxAccountsIACHelper=function FxAccountsIACHelper(){var DEFAULT_CONNECTION_STRING='fxa-mgmt';var default_rules={'manifestURLs':['app://system.gaiamobile.org/manifest.webapp','app://smart-system.gaiamobile.org/manifest.webapp']};var CONNECTION_STRING=DEFAULT_CONNECTION_STRING;var rules=default_rules;var port;var callbacks={};var eventListeners={};var init=function init(options){if(!options){return;}
|
||
if(options.keyword&&typeof(options.keyword)=='string'&&options.keyword.length>0){CONNECTION_STRING=options.keyword;}
|
||
if(options.rules&&typeof(options.rules)=='object'){rules=options.rules;}};var addEventListener=function addEventListener(eventName,listener){if(!eventListeners[eventName]){eventListeners[eventName]=[];}
|
||
eventListeners[eventName].push(listener);};var removeEventListener=function removeEventListener(eventName,listener){var listeners=eventListeners[eventName];if(!listeners){return;}
|
||
var index=listeners.indexOf(listener);if(index===-1){return;}
|
||
listeners.splice(index,1);};var reset=function reset(){CONNECTION_STRING=DEFAULT_CONNECTION_STRING;rules=default_rules;eventListeners={};callbacks={};port=null;};var onMessage=function onMessage(evt){if(evt&&evt.data){var message=evt.data;if(message.eventName){var listeners=eventListeners[message.eventName];if(!listeners){return;}
|
||
for(var listener in listeners){if(listeners[listener]&&typeof listeners[listener]==='function'){listeners[listener]();}}
|
||
return;}
|
||
var cbs,cb;if(message.methodName){cbs=callbacks[message.methodName];if(!cbs||!cbs.length){console.warn('No callbacks for method '+message.methodName);return;}
|
||
while(cbs.length){cb=cbs.shift();if(!message.error){cb.successCb(message.data);}else{cb.errorCb(message.error);}}}}else{console.error('Unknown');}};var getSelf=function getSelf(cb,error){var request=navigator.mozApps.getSelf();request.onsuccess=function onSuccess(evt){cb(evt.target.result);};request.onerror=function onError(){if(error&&typeof(error)==='function'){error();}};};var requestQueue=[];var isConnecting=false;var connect=function connect(cb){if(isConnecting){return requestQueue.push(cb);}
|
||
isConnecting=true;_connect(function onConnect(err){var next;isConnecting=false;if(typeof cb==='function'){cb(err);}
|
||
while(!!(next=requestQueue.shift())){next&&next(err);}});};var _connect=function _connect(callback){getSelf(function onApp(app){if(!app){return;}
|
||
app.connect(CONNECTION_STRING,rules).then(function(ports){if(!ports||ports.length!==1){return;}
|
||
port=ports[0];callback&&callback();});});};var sendMessage=function sendMessage(message,successCb,errorCb){if(port){_sendMessage(message,successCb,errorCb);return;}
|
||
connect(function(){_sendMessage(message,successCb,errorCb);});};var _sendMessage=function _sendMessage(message,successCb,errorCb){var name=message.name;if(!name){return;}
|
||
if(!callbacks[name]){callbacks[name]=[];}
|
||
callbacks[name].push({successCb:successCb,errorCb:errorCb});port.onmessage=onMessage;port.postMessage(message);};var getAccount=function getAccount(successCb,errorCb){sendMessage({'name':'getAccount'},successCb,errorCb);};var openFlow=function openFlow(successCb,errorCb){sendMessage({'name':'openFlow'},successCb,errorCb);};var logout=function logout(successCb,errorCb){sendMessage({'name':'logout'},successCb,errorCb);};var refreshAuthentication=function refreshAuthentication(email,successCb,errorCb){sendMessage({'name':'refreshAuthentication','email':email},successCb,errorCb);};var resendVerificationEmail=function resendVerificationEmail(email,successCb,errorCb){sendMessage({'name':'resendVerificationEmail','email':email},successCb,errorCb);};connect();return{'addEventListener':addEventListener,'getAccount':getAccount,'init':init,'logout':logout,'openFlow':openFlow,'refreshAuthentication':refreshAuthentication,'removeEventListener':removeEventListener,'resendVerificationEmail':resendVerificationEmail,'reset':reset};}();;'use strict';var SimManager=(function(){function Icc(mozIcc){this.mozIcc=mozIcc;}
|
||
Icc.prototype={skipped:false,unlocked:false,alreadyImported:false,mozIcc:null,isLocked:function(){return!this.unlocked&&lockStates.indexOf(this.mozIcc.cardState)!==-1;}};function showRetryCount(icc,lockType,uiElement){var request=icc.mozIcc.getCardLockRetryCount(lockType);request.onsuccess=function(){var retryCount=request.result.retryCount;if(retryCount){var l10nArgs={n:retryCount};document.l10n.setAttributes(uiElement,'inputCodeRetriesLeft',l10nArgs);uiElement.classList.remove('hidden');}};request.onerror=function(){console.error('Could not fetch CardLockRetryCount',request.error.name);};}
|
||
var lockStates=['pinRequired','pukRequired','networkLocked','corporateLocked','serviceProviderLocked','network1Locked','network2Locked','hrpdNetworkLocked','ruimCorporateLocked','ruimServiceProviderLocked'];return{icc0:null,icc1:null,simSlots:window.navigator.mozMobileConnections?window.navigator.mozMobileConnections.length:0,_unlockingIcc:null,init:function sm_init(){this.mobConn=window.navigator.mozMobileConnections;if(!this.mobConn){return;}
|
||
this.iccManager=window.navigator.mozIccManager;if(!this.iccManager){return;}
|
||
this.icc0=null;this.icc1=null;if(this.iccManager.iccIds[0]){this.updateIccState(this.iccManager.iccIds[0]);}
|
||
if(this.iccManager.iccIds[1]){this.updateIccState(this.iccManager.iccIds[1]);}
|
||
this.iccManager.addEventListener('iccdetected',this.handleIccState.bind(this));this.alreadyImported=false;},handleUnlockError:function sm_handleUnlockError(lockType,retryCount){var l10nArgs={n:retryCount};switch(lockType){case'pin':if(retryCount===0){this.showPukScreen(this._unlockingIcc);break;}
|
||
UIManager.pinInput.value='';UIManager.pinInput.classList.add('onerror');UIManager.pinError.classList.remove('hidden');document.l10n.setAttributes(UIManager.pinRetriesLeft,'inputCodeRetriesLeft',l10nArgs);UIManager.pinRetriesLeft.classList.remove('hidden');if(retryCount===1){UIManager.pinError.querySelector('.lastchance').classList.remove('hidden');}else{document.l10n.setAttributes(UIManager.pinError.querySelector('.main'),'pinAttemptMsg2',l10nArgs);UIManager.pinError.querySelector('.main').classList.remove('hidden');}
|
||
break;case'puk':UIManager.pukInput.value='';UIManager.pukInput.classList.add('onerror');UIManager.pukError.classList.remove('hidden');UIManager.pukInfo.classList.add('hidden');document.l10n.setAttributes(UIManager.pukRetriesLeft,'inputCodeRetriesLeft',l10nArgs);UIManager.pukRetriesLeft.classList.remove('hidden');if(retryCount===1){UIManager.pukError.querySelector('.lastchance').classList.remove('hidden');}else{document.l10n.setAttributes(UIManager.pukError.querySelector('.main'),'pukAttemptMsg2',l10nArgs);UIManager.pukError.querySelector('.main').classList.remove('hidden');}
|
||
break;case'nck':case'cck':case'spck':UIManager.xckInput.value='';UIManager.xckInput.classList.add('onerror');UIManager.xckError.classList.remove('hidden');document.l10n.setAttributes(UIManager.xckRetriesLeft,'inputCodeRetriesLeft',l10nArgs);UIManager.xckRetriesLeft.classList.remove('hidden');if(retryCount==1){UIManager.xckError.querySelector('.lastchance').classList.remove('hidden');}else{document.l10n.setAttributes(UIManager.xckError.querySelector('.main'),'nckAttemptMsg2',l10nArgs);UIManager.xckError.querySelector('.main').classList.remove('hidden');}
|
||
break;}},available:function sm_available(){var icc=this.guessIcc();return(icc&&icc.cardState==='ready');},handleIccState:function sm_handleIccState(event){this.updateIccState(event.iccId);},updateIccState:function(iccId){var iccInfo=this.iccManager.getIccById(iccId);if(!iccInfo){throw new Error('Unrecognized iccID: '+iccId);}
|
||
if(this.mobConn[0]&&iccId===this.mobConn[0].iccId){this.icc0=new Icc(iccInfo);}else if(this.mobConn[1]&&iccId===this.mobConn[1].iccId){this.icc1=new Icc(iccInfo);}else{console.warn('ICC detected in unsupported slot',iccId);}},handleCardState:function sm_handleCardState(callback,skipUnlockScreen){this._unlockingIcc=null;SimManager.checkSIMButton();if(typeof callback==='function'){this.finishCallback=callback;}
|
||
if(this.shouldShowUnlockScreen(this.icc0)&&!skipUnlockScreen){this.showUnlockScreen(this.icc0);}else if(this.shouldShowUnlockScreen(this.icc1)&&!skipUnlockScreen){this.showUnlockScreen(this.icc1);}else if(this.shouldShowSIMInfoScreen()){this.resetSkipped();this.showSIMInfoScreen();}else{this.resetSkipped();this.finish();}},finish:function(){this.hideScreen();this.hideSIMInfoScreen();var showCellData=(this.icc0&&!this.icc0.isLocked())||(this.icc1&&!this.icc1.isLocked());this.finishCallback&&this.finishCallback(showCellData);},shouldShowUnlockScreen:function sm_shouldShowLockScreen(icc){return icc&&!icc.skipped&&icc.isLocked();},shouldShowSIMInfoScreen:function sm_shouldShowSIMInfoScreen(){return(this.icc0&&this.icc1);},showUnlockScreen:function sm_showUnlockScreen(icc){if(icc.unlocked){return;}
|
||
this._unlockingIcc=icc;switch(icc.mozIcc.cardState){case'pinRequired':this.showPinScreen(icc);break;case'pukRequired':this.showPukScreen(icc);break;case'networkLocked':case'corporateLocked':case'serviceProviderLocked':case'network1Locked':case'network2Locked':case'hrpdNetworkLocked':case'ruimCorporateLocked':case'ruimServiceProviderLocked':this.showXckScreen(icc);break;default:throw new Error('Cannot show SIM unlock screen, unknown cardState '+
|
||
icc.mozIcc.cardState);}},voiceChangeListeners:[],updateSIMInfoText:function sm_updateSIMInfoText(icc){var iccNumber=(icc===this.icc0)?1:2;if(icc&&icc.isLocked()){UIManager['simInfo'+iccNumber].classList.add('locked');UIManager['simCarrier'+iccNumber].setAttribute('data-l10n-id','simPinLocked');UIManager['simNumber'+iccNumber].removeAttribute('data-l10n-id');UIManager['simNumber'+iccNumber].textContent='';}else{UIManager['simInfo'+iccNumber].classList.remove('locked');var mobConn=this.mobConn[iccNumber-1];var operator=MobileOperator.userFacingInfo(mobConn).operator;if(!operator&&!this.voiceChangeListeners[iccNumber-1]){this.voiceChangeListeners[iccNumber-1]=function(evt){var operator=MobileOperator.userFacingInfo(mobConn).operator;if(operator){UIManager['simCarrier'+iccNumber].removeAttribute('data-l10n-id');UIManager['simCarrier'+iccNumber].textContent=operator;mobConn.removeEventListener('voicechange',this.voiceChangeListeners[iccNumber-1]);this.voiceChangeListeners[iccNumber-1]=null;}}.bind(this);mobConn.addEventListener('voicechange',this.voiceChangeListeners[iccNumber-1]);}
|
||
if(operator){UIManager['simCarrier'+iccNumber].removeAttribute('data-l10n-id');UIManager['simCarrier'+iccNumber].textContent=operator;}else{UIManager['simCarrier'+iccNumber].setAttribute('data-l10n-id','searchingOperator');}
|
||
var number=icc.mozIcc.iccInfo.msisdn||icc.mozIcc.iccInfo.mdn||'';if(number){UIManager['simNumber'+iccNumber].textContent=number;UIManager['simInfo'+iccNumber].classList.remove('no-number');}else{UIManager['simInfo'+iccNumber].classList.add('no-number');}}},showSIMInfoScreen:function sm_showSIMInfoScreen(){this.updateSIMInfoText(this.icc0);this.updateSIMInfoText(this.icc1);UIManager.activationScreen.classList.remove('show');UIManager.simInfoScreen.classList.add('show');},hideSIMInfoScreen:function sm_hidescreen(){UIManager.simInfoScreen.classList.remove('show');UIManager.activationScreen.classList.add('show');},checkSIMButton:function sm_checkSIMButton(){if(!this.mobConn){UIManager.simImport.classList.add('hidden');return;}
|
||
var simOption=UIManager.simImportButton;if(!SimManager.alreadyImported&&SimManager.available()){simOption.removeAttribute('disabled');UIManager.noSim.classList.add('hidden');}else{simOption.setAttribute('disabled','disabled');if(!SimManager.alreadyImported){UIManager.noSim.classList.remove('hidden');}}},showPinScreen:function sm_showPinScreen(icc){showRetryCount(icc,'pin',UIManager.pinRetriesLeft);UIManager.unlockSimButton.disabled=true;UIManager.pinInput.addEventListener('input',function sm_checkInput(event){UIManager.unlockSimButton.disabled=(event.target.value.length<4);});UIManager.activationScreen.classList.remove('show');UIManager.unlockSimScreen.classList.add('show');UIManager.pincodeScreen.classList.add('show');UIManager.xckcodeScreen.classList.remove('show');UIManager.unlockSimHeader.setAttribute('data-l10n-id','pincode2');if(this.simSlots>1){var simNumber=icc===this.icc0?1:2;document.l10n.setAttributes(UIManager.pinLabel,'pincodeLabel',{n:simNumber});}else{UIManager.pinLabel.setAttribute('data-l10n-id','type_pin');}
|
||
UIManager.pinInput.focus();},showPukScreen:function sm_showPukScreen(icc){showRetryCount(icc,'puk',UIManager.pukRetriesLeft);UIManager.unlockSimScreen.classList.add('show');UIManager.activationScreen.classList.remove('show');UIManager.pincodeScreen.classList.remove('show');UIManager.pukcodeScreen.classList.add('show');UIManager.xckcodeScreen.classList.remove('show');UIManager.unlockSimHeader.setAttribute('data-l10n-id','pukcode');if(this.simSlots>1){var simNumber=icc===this.icc0?1:2;document.l10n.setAttributes(UIManager.pukLabel,'pukcodeLabel',{n:simNumber});}else{UIManager.pukLabel.setAttribute('data-l10n-id','type_puk');}
|
||
UIManager.pukInput.focus();},showXckScreen:function sm_showXckScreen(icc){var lockType;switch(icc.mozIcc.cardState){case'networkLocked':lockType='nck';break;case'corporateLocked':lockType='cck';break;case'serviceProviderLocked':lockType='spck';break;case'network1Locked':lockType='nck1';break;case'network2Locked':lockType='nck2';break;case'hrpdNetworkLocked':lockType='hnck';break;case'ruimCorporateLocked':lockType='rcck';break;case'ruimServiceProviderLocked':lockType='rspck';break;default:return;}
|
||
showRetryCount(icc,lockType,UIManager.xckRetriesLeft);UIManager.unlockSimScreen.classList.add('show');UIManager.activationScreen.classList.remove('show');UIManager.pincodeScreen.classList.remove('show');UIManager.pukcodeScreen.classList.remove('show');UIManager.xckcodeScreen.classList.add('show');var simNumber=icc===this.icc0?1:2;switch(icc.mozIcc.cardState){case'networkLocked':document.l10n.setAttributes(UIManager.unlockSimHeader,'nckcodeTitle',{n:simNumber});document.l10n.setAttributes(UIManager.xckLabel,'nckcodeLabel',{n:simNumber});break;case'corporateLocked':document.l10n.setAttributes(UIManager.unlockSimHeader,'cckcodeTitle',{n:simNumber});document.l10n.setAttributes(UIManager.xckLabel,'cckcodeLabel',{n:simNumber});break;case'serviceProviderLocked':document.l10n.setAttributes(UIManager.unlockSimHeader,'spckcodeTitle',{n:simNumber});document.l10n.setAttributes(UIManager.xckLabel,'spckcodeLabel',{n:simNumber});break;case'network1Locked':document.l10n.setAttributes(UIManager.unlockSimHeader,'nck1codeTitle',{n:simNumber});document.l10n.setAttributes(UIManager.xckLabel,'nck1codeLabel',{n:simNumber});break;case'network2Locked':document.l10n.setAttributes(UIManager.unlockSimHeader,'nck2codeTitle',{n:simNumber});document.l10n.setAttributes(UIManager.xckLabel,'nck2codeLabel',{n:simNumber});break;case'hrpdNetworkLocked':document.l10n.setAttributes(UIManager.unlockSimHeader,'hnckcodeTitle',{n:simNumber});document.l10n.setAttributes(UIManager.xckLabel,'hnckcodeLabel',{n:simNumber});break;case'ruimCorporateLocked':document.l10n.setAttributes(UIManager.unlockSimHeader,'rcckcodeTitle',{n:simNumber});document.l10n.setAttributes(UIManager.xckLabel,'rcckcodeLabel',{n:simNumber});break;case'ruimServiceProviderLocked':document.l10n.setAttributes(UIManager.unlockSimHeader,'rspckcodeTitle',{n:simNumber});document.l10n.setAttributes(UIManager.xckLabel,'rspckcodeLabel',{n:simNumber});break;}
|
||
UIManager.xckInput.focus();},resetForm:function sm_clearInputs(){this.clearFields();UIManager.newpinInput.value='';UIManager.confirmNewpinInput.value='';UIManager.pinInput.value='';UIManager.pukInput.value='';UIManager.pukInfo.classList.remove('hidden');UIManager.xckInput.value='';UIManager.unlockSimButton.disabled=false;},hideScreen:function sm_hideScreen(){UIManager.unlockSimScreen.classList.remove('show');UIManager.pincodeScreen.classList.remove('show');UIManager.pukcodeScreen.classList.remove('show');UIManager.xckcodeScreen.classList.remove('show');UIManager.activationScreen.classList.add('show');},skip:function sm_skip(){if(this._unlockingIcc){this._unlockingIcc.skipped=true;}
|
||
this.resetForm();this.hideScreen();this.handleCardState();},resetSkipped:function sm_resetSkipped(){if(this.icc0){this.icc0.skipped=false;}
|
||
if(this.icc1){this.icc1.skipped=false;}},back:function sm_back(){this.resetForm();this.resetSkipped();this.hideScreen();this.hideSIMInfoScreen();Navigation.back();},simUnlockBack:function sm_simUnlockBack(){if(this.icc0&&this.icc0.skipped){this.icc0.skipped=false;this.hideScreen();this.handleCardState();}else{this.back();}},unlock:function sm_unlock(){var icc=this._unlockingIcc;if(!icc){throw new Error('Cannot unlock SIM, no current ICC');}
|
||
this.clearFields();switch(icc.mozIcc.cardState){case'pinRequired':this.unlockPin(icc);break;case'pukRequired':this.unlockPuk(icc);break;case'networkLocked':case'corporateLocked':case'serviceProviderLocked':case'network1Locked':case'network2Locked':case'hrpdNetworkLocked':case'ruimCorporateLocked':case'ruimServiceProviderLocked':this.unlockXck(icc);break;}},unlockPin:function sm_unlockPin(icc){var pin=UIManager.pinInput.value;if(pin.length<4||pin.length>8){UIManager.pinError.querySelector('.main').setAttribute('data-l10n-id','pinValidation');UIManager.pinInput.classList.add('onerror');UIManager.pinError.classList.remove('hidden');UIManager.pinInput.focus();return;}else{UIManager.pinInput.classList.remove('onerror');UIManager.pinError.classList.add('hidden');}
|
||
this.attemptUnlock(icc,{lockType:'pin',pin:pin});},clearFields:function sm_clearFields(){UIManager.pukInput.classList.remove('onerror');UIManager.pukError.classList.add('hidden');UIManager.newpinInput.classList.remove('onerror');UIManager.newpinError.classList.add('hidden');UIManager.confirmNewpinInput.classList.remove('onerror');UIManager.confirmNewpinError.classList.add('hidden');UIManager.pinError.classList.add('hidden');UIManager.pinError.querySelector('.main').classList.add('hidden');UIManager.pinError.querySelector('.lastchance').classList.add('hidden');UIManager.pinRetriesLeft.classList.add('hidden');UIManager.pukError.classList.add('hidden');UIManager.pukError.querySelector('.main').classList.add('hidden');UIManager.pukError.querySelector('.lastchance').classList.add('hidden');UIManager.pukRetriesLeft.classList.add('hidden');UIManager.xckError.classList.add('hidden');UIManager.xckError.querySelector('.main').classList.add('hidden');UIManager.xckError.querySelector('.lastchance').classList.add('hidden');UIManager.xckRetriesLeft.classList.add('hidden');},unlockPuk:function sm_unlockPuk(icc){var pukCode=UIManager.pukInput.value;if(pukCode.length!==8){UIManager.pukError.querySelector('.main').setAttribute('data-l10n-id','pukValidation');UIManager.pukError.classList.remove('hidden');UIManager.pukInfo.classList.add('hidden');UIManager.pukInput.classList.add('onerror');UIManager.pukError.focus();return;}
|
||
var newpinCode=UIManager.newpinInput.value;var confirmNewpin=UIManager.confirmNewpinInput.value;if(newpinCode.length<4||newpinCode.length>8){UIManager.newpinError.setAttribute('data-l10n-id','pinValidation');UIManager.newpinError.classList.remove('hidden');UIManager.newpinInput.classList.add('onerror');UIManager.newpinError.focus();return;}
|
||
if(newpinCode!=confirmNewpin){UIManager.confirmNewpinError.setAttribute('data-l10n-id','newpinConfirmation');UIManager.confirmNewpinError.classList.remove('hidden');UIManager.newpinInput.classList.add('onerror');UIManager.confirmNewpinInput.classList.add('onerror');UIManager.confirmNewpinError.focus();return;}
|
||
var options={lockType:'puk',puk:pukCode,newPin:newpinCode};this.attemptUnlock(icc,options);},unlockXck:function sm_unlockXck(icc){var xck=UIManager.xckInput.value;var lockType;switch(icc.mozIcc.cardState){case'networkLocked':lockType='nck';break;case'corporateLocked':lockType='cck';break;case'serviceProviderLocked':lockType='spck';break;case'network1Locked':lockType='nck1';break;case'network2Locked':lockType='nck2';break;case'hrpdNetworkLocked':lockType='hnck';break;case'ruimCorporateLocked':lockType='rcck';break;case'ruimServiceProviderLocked':lockType='rspck';break;}
|
||
if(xck.length<8||xck.length>16){UIManager.xckInput.classList.add('onerror');UIManager.xckError.classList.remove('hidden');UIManager.xckError.querySelector('.main').setAttribute('data-l10n-id',lockType+'Validation');UIManager.xckInput.focus();return;}else{UIManager.pinInput.classList.remove('onerror');UIManager.pinError.classList.add('hidden');}
|
||
var options={lockType:lockType,pin:xck};this.attemptUnlock(icc,options);},attemptUnlock:function sm_attemptUnlock(icc,options){var req=icc.mozIcc.unlockCardLock(options);req.onsuccess=(function sm_unlockSuccess(){icc.unlocked=true;this.resetForm();this.hideScreen();this.handleCardState();}).bind(this);req.onerror=(function sm_unlockError(){this.handleUnlockError(options.lockType,req.error.retryCount);}).bind(this);},guessIcc:function guessIcc(){var tempIcc=null;if(navigator.mozMobileConnections){for(var i=0;i<navigator.mozMobileConnections.length&&tempIcc===null;i++){if(navigator.mozMobileConnections[i]!==null&&navigator.mozMobileConnections[i].iccId!==null){tempIcc=navigator.mozIccManager.getIccById(navigator.mozMobileConnections[i].iccId);}}}else{tempIcc=navigator.mozIccManager;}
|
||
return tempIcc;},importContacts:function sm_importContacts(){var DELAY_FEEDBACK=300;UIManager.navBar.setAttribute('aria-disabled','true');var progress=utils.overlay.show('simContacts-reading','activityBar');var importButton=UIManager.simImportButton;var cancelled=false,contactsRead=false;var importer=new SimContactsImporter(SimManager.guessIcc());utils.overlay.showMenu();utils.overlay.oncancel=function oncancel(){cancelled=true;importer.finish();if(contactsRead){progress.setClass('activityBar');utils.overlay.hideMenu();progress.setHeaderMsg('messageCanceling');}else{importer.onfinish();}};var importedContacts=0;importer.onread=function sim_import_read(n){contactsRead=true;if(n>0){progress.setClass('progressBar');progress.setHeaderMsg('simContacts-importing');progress.setTotal(n);}};importer.onimported=function imported_contact(){importedContacts++;if(!cancelled){progress.update();}};importer.onfinish=function sim_import_finish(numDupsMerged,iccId){window.setTimeout(function do_sim_import_finish(){UIManager.navBar.removeAttribute('aria-disabled');utils.overlay.hide();if(importedContacts>0){utils.misc.setTimestamp('sim-'+iccId);}
|
||
if(!cancelled){SimManager.alreadyImported=true;importButton.setAttribute('disabled','disabled');utils.status.show({id:'simContacts-imported3',args:{n:importedContacts}});}},DELAY_FEEDBACK);importer.onfinish=null;};importer.onerror=function sim_import_error(){UIManager.navBar.removeAttribute('aria-disabled');utils.overlay.hide();importButton.removeAttribute('disabled');var cancel={title:'cancel',callback:function(){ConfirmDialog.hide();}};var retry={title:'retry',isRecommend:true,callback:function(){ConfirmDialog.hide();importButton.click();}};ConfirmDialog.show(null,'simContacts-error',cancel,retry);};importer.start();}};})();;'use strict';var SdManager={available:function(){return utils.sdcard.checkStorageCard();},checkSDButton:function sm_checkSDButton(){var sdOption=UIManager.sdImportButton;if(!SdManager.alreadyImported&&SdManager.available()){sdOption.removeAttribute('disabled');UIManager.noMemorycard.classList.add('hidden');}else{sdOption.setAttribute('disabled','disabled');if(!SdManager.alreadyImported){UIManager.noMemorycard.classList.remove('hidden');}}},importContacts:function sm_importContacts(){var importedContacts=0;UIManager.navBar.setAttribute('aria-disabled','true');var cancelled=false;var importer=null;var importButton;var progress=utils.overlay.show('memoryCardContacts-importing','activityBar','infiniteProgress');utils.overlay.showMenu();return new Promise((resolve,reject)=>{utils.overlay.oncancel=()=>{cancelled=true;if(importer){importer.finish();}else{UIManager.navBar.removeAttribute('aria-disabled');utils.overlay.hide();}
|
||
resolve();};importButton=UIManager.sdImportButton;utils.sdcard.retrieveFiles(['text/vcard','text/directory;profile=vCard','text/directory'],['vcf','vcard'],(error,fileArray)=>{if(!error&&!fileArray.length){error='No contacts were found';}
|
||
if(error){reject(error);return import_error(error);}
|
||
if(cancelled){resolve();return;}
|
||
var promises=[];fileArray.forEach(file=>{promises.push(utils.sdcard.getTextFromFile(file,onContacts));});Promise.all(promises).then(()=>{utils.misc.setTimestamp('sd');UIManager.navBar.removeAttribute('aria-disabled');utils.overlay.hide();if(cancelled){resolve();return;}
|
||
SdManager.alreadyImported=true;importButton.setAttribute('disabled','disabled');utils.status.show({id:'memoryCardContacts-imported3',args:{n:importedContacts}});resolve();}).catch(reject);});});function onContacts(text){if(cancelled){return Promise.reject();}
|
||
return new Promise((resolve,reject)=>{importer=new VCFReader(text);if(!text||!importer){var error='No contacts were found';import_error(error);reject(error);return;}
|
||
importer.onimported=imported_contact;importer.onerror=error=>{import_error(error);reject(error);};importer.process(()=>{if(cancelled){reject('Cancelled');utils.overlay.hide();return;}
|
||
resolve();});});}
|
||
function imported_contact(){importedContacts++;progress.update();}
|
||
function import_error(e){UIManager.navBar.removeAttribute('aria-disabled');utils.overlay.hide();importButton.removeAttribute('disabled');var cancel={title:'cancel',callback:function(){ConfirmDialog.hide();}};var retry={title:'retry',isRecommend:true,callback:function(){ConfirmDialog.hide();importButton.click();}};ConfirmDialog.show(null,'memoryCardContacts-error',cancel,retry);}}};;(function(exports){'use strict';const WIFI_STATUS={connecting:'connecting',associated:'associated',connected:'connected',connectingfailed:'connectingfailed',disconnected:'disconnected'};var WifiManager={STATUS:Object.freeze(WIFI_STATUS),init:function wn_init(){this.api=WifiHelper.getWifiManager();this.changeStatus();if(navigator.mozSettings){var lock=window.navigator.mozSettings.createLock();this.enable(lock);this.enableDebugging(lock);}
|
||
this.gCurrentNetwork=this.api?this.api.connection.network:null;if(this.gCurrentNetwork!==null){this.api.forget(this.gCurrentNetwork);this.gCurrentNetwork=null;}},getNetworks:function wn_getNetworks(callback){this.networks?callback(this.networks):this.scan(callback);},scan:function wn_scan(callback){if(this._scanning){return;}
|
||
this._scanning=true;utils.overlay.show('scanningNetworks','spinner');var SCAN_TIMEOUT=10000;var self=this;self.onScan=callback;var req=this.api?this.api.getNetworks():null;if(!req){setTimeout(function(){self._scanning=false;callback();});return;}
|
||
var handleRequest=function handleRequest(){self._scanning=false;clearTimeout(self.scanTimeout);self.scanTimeout=null;self.onScan(self.networks);self.onScan=null;};req.onsuccess=function onScanSuccess(){self.networks=req.result;handleRequest();};req.onerror=function onScanError(){console.error('Error reading networks: '+req.error.name);self.networks=[];handleRequest();};if(!self.scanTimeout){self.scanTimeout=setTimeout(function(){self._scanning=false;console.warn('Timeout while reading networks');self.onScan();},SCAN_TIMEOUT);}},enable:function wn_enable(lock){lock.set({'wifi.enabled':true});},enableDebugging:function wn_enableDebugging(lock){this._prevDebuggingValue=false;var req=lock.get('wifi.debugging.enabled');req.onsuccess=function wn_getDebuggingSuccess(){this._prevDebuggingValue=req.result['wifi.debugging.enabled'];};lock.set({'wifi.debugging.enabled':true});},finish:function wn_finish(){if(!this._prevDebuggingValue&&navigator.mozSettings){var resetLock=window.navigator.mozSettings.createLock();resetLock.set({'wifi.debugging.enabled':false});}},getNetwork:function wm_gn(ssid){var list=this.networks;for(var i=0;i<list.length;i++){if(list[i].ssid===ssid){return list[i];}}
|
||
return null;},connect:function wn_connect(ssid,password,user){var network=this.getNetwork(ssid);if(!network){console.error('Network not found');return;}
|
||
this.ssid=ssid;WifiHelper.setPassword(network,password,user,'PEAP');this.gCurrentNetwork=network;this.api.associate(network);},changeStatus:function wn_cs(callback){var self=this;if(WifiManager.api){WifiManager.api.onstatuschange=function(event){if(event.status===WifiManager.STATUS.disconnected&&self.onScan){self.scan(self.onScan);}else{WifiUI.updateNetworkStatus(event.network.ssid,event.status);}};}}};var WifiUI={joinNetwork:function wui_jn(){var password=document.getElementById('wifi_password').value;var user=document.getElementById('wifi_user').value;var ssid=document.getElementById('wifi_ssid').value;WifiUI.connect(ssid,password,user);window.history.back();},joinHiddenNetwork:function wui_jhn(){var password=UIManager.hiddenWifiPassword.value;var user=UIManager.hiddenWifiIdentity.value;var ssid=UIManager.hiddenWifiSsid.value;var security=UIManager.hiddenWifiSecurity.value;var network;if(ssid.length){if(!Array.isArray(WifiManager.networks)){WifiManager.networks=[];}
|
||
network=new window.MozWifiNetwork({ssid:ssid,capabilities:[],security:[security],relSignalStrength:0,hidden:true});WifiManager.networks.push(network);this.renderNetworks(WifiManager.networks);WifiUI.connect(ssid,password,user);}
|
||
window.history.back();},_selectNetworkItem:function(ssid,isSelected=true){var elem=document.getElementById(ssid);if(!elem){return;}
|
||
if(isSelected){elem.setAttribute('data-wifi-selected',true);}else{var icon=elem.querySelector('aside');elem.removeAttribute('data-wifi-selected');elem.classList.remove('connected');icon.classList.remove('connecting');icon.classList.remove('connected');var security=elem.dataset.security;var securityLevelDOM=elem.querySelector('p[data-security-level]');securityLevelDOM.setAttribute('data-l10n-id',security?security:'securityOpen');}},connect:function wui_connect(ssid,password,user){var newWifi=document.getElementById(ssid);Array.from(document.querySelectorAll('li[data-wifi-selected]')).forEach((networkSelected)=>{this._selectNetworkItem(networkSelected,networkSelected===newWifi);});WifiManager.connect(ssid,password,user);},chooseNetwork:function wui_cn(event){var ssid=event.target.dataset.ssid;var selectedNetwork=WifiManager.getNetwork(ssid);if(!selectedNetwork){console.error('Network not found');return;}
|
||
if(WifiHelper.isOpen(selectedNetwork)){WifiUI.connect(ssid);return;}
|
||
UIManager.activationScreen.classList.add('no-options');UIManager.mainTitle.textContent=ssid;var ssidHeader=document.getElementById('wifi_ssid');var userInput=document.getElementById('wifi_user');var passwordInput=document.getElementById('wifi_password');var showPassword=document.querySelector('gaia-checkbox[name=show_password]');var joinButton=UIManager.wifiJoinButton;joinButton.disabled=true;passwordInput.addEventListener('input',function validatePassword(){joinButton.disabled=!WifiHelper.isValidInput(WifiHelper.getKeyManagement(selectedNetwork),passwordInput.value,userInput.value);});passwordInput.type='password';passwordInput.value='';showPassword.checked=false;showPassword.addEventListener('change',e=>{passwordInput.type=e.target.checked?'text':'password';});passwordInput.value='';ssidHeader.value=ssid;UIManager.navBar.classList.add('secondary-menu');if(WifiHelper.isEap(selectedNetwork)){userInput.parentNode.classList.remove('hidden');}else{userInput.parentNode.classList.add('hidden');}
|
||
window.location.hash='#configure_network';},addHiddenNetwork:function wui_addHiddenNetwork(){UIManager.activationScreen.classList.add('no-options');UIManager.mainTitle.setAttribute('data-l10n-id','authentication');UIManager.navBar.classList.add('secondary-menu');UIManager.hiddenWifiSsid.value='';UIManager.hiddenWifiPassword.value='';UIManager.hiddenWifiIdentity.value='';UIManager.wifiJoinButton.disabled=true;window.location.hash='#hidden-wifi-authentication';},handleHiddenWifiSecurity:function wui_handleSecurity(securityType){if(securityType===''){UIManager.hiddenWifiPasswordBox.classList.add('hidden');}else{UIManager.hiddenWifiPasswordBox.classList.remove('hidden');}
|
||
if(securityType.indexOf('EAP')!==-1){UIManager.hiddenWifiIdentityBox.classList.remove('hidden');}else{UIManager.hiddenWifiIdentityBox.classList.add('hidden');}},renderNetworks:function wui_rn(networks){var networksDOM=document.getElementById('networks');networksDOM.innerHTML='';var networksList;if(!networks||networks.length===0){var noResult='<div id="no-result-container">'+' <div id="no-result-message">'+' <p data-l10n-id="noWifiFound3"></p>'+' </div>'+'</div>';networksDOM.innerHTML=noResult;}else{networksList=document.createElement('ul');networksList.id='networks-list';networksList.setAttribute('role','listbox');networksList.setAttribute('data-l10n-id','networksList');var networksShown=[];networks.sort(function(a,b){return b.relSignalStrength-a.relSignalStrength;});for(var i=0,max=networks.length;i<max;i++){var network=networks[i];if(networksShown.indexOf(network.ssid)===-1){var li=document.createElement('li');var icon=document.createElement('aside');var ssidp=document.createElement('p');ssidp.setAttribute('dir','auto');var small=document.createElement('p');small.dataset.securityLevel=true;icon.classList.add('pack-end');icon.classList.add('wifi-icon');var level=Math.min(Math.floor(network.relSignalStrength/20),4);icon.classList.add('level-'+level);document.l10n.setAttributes(icon,'wifiLevel',{level:level});icon.setAttribute('role','presentation');ssidp.textContent=network.ssid;li.dataset.ssid=network.ssid;var keys=WifiHelper.getSecurity(network);li.dataset.security=keys;if(!WifiHelper.isOpen(network)){small.textContent=keys.join(', ');icon.classList.add('secured');}else{small.setAttribute('data-l10n-id','securityOpen');}
|
||
icon.classList.add('wifi-signal');var connectionStatus=WifiHelper.getNetworkStatus(network)||WifiManager.STATUS.disconnected;li.dataset.status=connectionStatus;if(connectionStatus===WifiManager.STATUS.connected){small.setAttribute('data-l10n-id','shortStatus-connected');small.removeAttribute('aria-label');icon.classList.add('connected');li.classList.add('connected');li.dataset.wifiSelected=true;}
|
||
networksShown.push(network.ssid);li.setAttribute('id',network.ssid);li.setAttribute('role','option');li.setAttribute('aria-live',true);li.setAttribute('aria-relevant','text');li.appendChild(ssidp);li.appendChild(small);li.appendChild(icon);if(WifiHelper.isConnected(network)){networksList.insertBefore(li,networksList.firstChild);}else{networksList.appendChild(li);}}}
|
||
networksList.dataset.type='list';networksDOM.appendChild(networksList);}
|
||
utils.overlay.hide();},updateNetworkStatus:function wui_uns(ssid,status){var element=document.getElementById(ssid);if(!element){return;}
|
||
if(status===WifiManager.STATUS.connecting&&ssid!==WifiManager.ssid){return;}
|
||
element.dataset.status=status;if(status!==WifiManager.STATUS.disconnected){element.querySelector('p[data-security-level]').setAttribute('data-l10n-id','shortStatus-'+status);}else{var security=element.dataset.security||'Open';element.querySelector('p[data-security-level]').setAttribute('data-l10n-id','security'+security);element.classList.remove('connected');}
|
||
var icon=element.querySelector('aside');switch(status){case WifiManager.STATUS.connecting:case WifiManager.STATUS.associated:icon.classList.add('connecting');break;case WifiManager.STATUS.connected:icon.classList.remove('connecting');var networksList=document.getElementById('networks-list');icon.classList.add('connected');element.classList.add('connected');networksList.removeChild(element);networksList.insertBefore(element,networksList.firstChild);break;default:icon.classList.remove('connecting');icon.classList.remove('connected');break;}}};exports.WifiManager=WifiManager;exports.WifiUI=WifiUI;})(window);;'use strict';var ImportIntegration={get liveImportButton(){delete this.liveImportButton;return(this.liveImportButton=document.getElementById('live-import-button'));},get gmailImportButton(){delete this.gmailImportButton;return(this.gmailImportButton=document.getElementById('gmail-import-button'));},init:function(){this.liveImportButton.addEventListener('click',this);this.gmailImportButton.addEventListener('click',this);},handleEvent:function(event){switch(event.type){case'click':if(event.target===this.liveImportButton){ServicesLauncher.start('live');}
|
||
else if(event.target===this.gmailImportButton){ServicesLauncher.start('gmail');}
|
||
break;}},checkImport:function(nextState){if(nextState==='disabled'){this.gmailImportButton.setAttribute('disabled','disabled');this.liveImportButton.setAttribute('disabled','disabled');}
|
||
else if(nextState==='enabled'){this.gmailImportButton.removeAttribute('disabled');this.liveImportButton.removeAttribute('disabled');}}};;(function(exports){'use strict';var rdashes=/-(.)/g;var Utils={camelCase:function ut_camelCase(str){return str.replace(rdashes,function(str,p1){return p1.toUpperCase();});}};exports.Utils=Utils;}(this));;(function(exports){'use strict';var currentLayout='tiny';var elementIDs=['tutorialFinished','enjoyYourPhone','enjoyYourPhoneUpdated'];var dom={};var initialized=false;var FinishScreen={init:function(isUpgrade){if(initialized){return;}
|
||
if(ScreenLayout.getCurrentLayout()!=='tiny'){currentLayout='large';}
|
||
var panelSelector='tutorial-finish-'+currentLayout;var finishPanel=document.getElementById(panelSelector);finishPanel.classList.add('show');elementIDs.forEach(function(name){dom[Utils.camelCase(name)]=document.getElementById(name);},this);if(isUpgrade){dom.enjoyYourPhone.hidden=true;dom.enjoyYourPhoneUpdated.hidden=false;}
|
||
if(currentLayout==='tiny'){dom.tutorialFinished.addEventListener('click',function ftuEnd(){window.close();});}else{navigator.mozApps.getSelf().onsuccess=function(evt){var app=evt.target.result;app.connect('ftucomms').then(function onConnAccepted(ports){ports.forEach(function(port){port.postMessage('done');});},function onConnRejected(reason){console.warn('FTU is rejected due to '+reason);});};}
|
||
initialized=true;}};exports.FinishScreen=FinishScreen;}(this));;(function(exports){'use strict';var TutorialUtils={loadMedia:function(mediaElement,src){console.log('loadMedia, got mediaElement: ',mediaElement);var isVideo=(mediaElement.nodeName==='VIDEO');console.log('TutorialUtils.loadMedia, isVideo: ',isVideo,mediaElement.nodeName);return new Promise(function(resolve,reject){function onMediaLoadOrError(evt){console.log('TutorialUtils.loadMedia, onMediaLoadOrError for '+'evt.type: '+(evt&&evt.type));evt.target.removeEventListener('error',onMediaLoadOrError);if(isVideo){evt.target.removeEventListener('canplay',onMediaLoadOrError);evt.target.removeEventListener('abort',onMediaLoadOrError);}else{evt.target.removeEventListener('load',onMediaLoadOrError);}
|
||
if(evt.type==='error'){console.error('Failed to load tutorial media: '+src);}else if(evt.type==='abort'){console.error('Loading of tutorial media aborted: '+src);}
|
||
resolve(evt);}
|
||
function onVideoUnloaded(evt){console.log('TutorialUtils.loadMedia, onVideoUnloaded for evt.type: '+
|
||
(evt&&evt.type));mediaElement.removeEventListener('emptied',onVideoUnloaded);mediaElement.addEventListener('canplay',onMediaLoadOrError);mediaElement.addEventListener('abort',onMediaLoadOrError);mediaElement.addEventListener('error',onMediaLoadOrError);console.log('TutorialUtils.loadMedia, onVideoUnloaded, '+'assigning src: '+src);mediaElement.src=src;mediaElement.load();}
|
||
if(isVideo){if(mediaElement.src){console.log('TutorialUtils.loadMedia, removing src attribute');mediaElement.removeAttribute('src');mediaElement.addEventListener('emptied',onVideoUnloaded,false);console.log('TutorialUtils.loadMedia, calling load');mediaElement.load();}else{console.log('TutorialUtils.loadMedia, no src, '+'just calling onVideoUnloaded');onVideoUnloaded();}}else{console.log('TutorialUtils.loadMedia, not a video, '+'listen for load/error only');mediaElement.addEventListener('load',onMediaLoadOrError,false);mediaElement.addEventListener('error',onMediaLoadOrError,false);mediaElement.src=src;}});},loadAndPlayMedia:function(mediaElement,src){return this.loadMedia(mediaElement,src).then((evt)=>{if(evt.type!=='error'&&mediaElement.nodeName==='VIDEO'){mediaElement.play();}});},fileExists:function(src){return new Promise((resolve)=>{window.fetch(src,{method:'HEAD'}).then((response)=>{resolve(response.ok);}).catch(()=>{resolve(false);});});},getBestAssetForDirection:function(src){var dir=document.dir||'ltr';var re=/(-rtl|ltr)?\.(png|gif|jpg|webm|mp4|m4v|ogg|ogv)$/;var directionSrc=src.replace(re,'-'+dir+'.$2');return this.fileExists(directionSrc).then((result)=>{return result?directionSrc:src;}).catch((e)=>{console.log('Exception from getBestAssetForDirection: ',e);});},Sequence:function(){var sequence=Array.slice(arguments);var aborted=false;sequence.abort=function(){aborted=true;this.length=0;if(typeof this.onabort==='function'){this.onabort();}};sequence.complete=function(result){if(!aborted&&typeof this.oncomplete==='function'){this.oncomplete(result);}};sequence.fail=function(reason){this.complete(reason);};sequence.next=function(previousTaskResult){var result,exception;if(aborted){return;}
|
||
var task=this.shift();if(task){try{result=task.apply(null,arguments);}catch(e){exception=e;}
|
||
if(exception){this.fail(exception);}else if(result&&typeof result.then==='function'){result.then(this.next.bind(this),this.fail.bind(this));}else{this.next(result);}}else{this.complete(previousTaskResult);}};return sequence;}};exports.TutorialUtils=TutorialUtils;})(window);;(function(exports){'use strict';var currentLayout='tiny';var dom={};var elementIDs=['tutorial','tutorial-step-title','tutorial-step-media','tutorial-step-image','tutorial-step-video','forward-tutorial','back-tutorial'];var Tutorial={config:null,_stepsConfig:{},_stepsKey:'',_currentStep:1,_initialized:false,init:function(stepsKey,onLoaded){if(this._initialized||this._initialization){return;}
|
||
var initTasks=this._initialization=new TutorialUtils.Sequence(this.loadConfig.bind(this),this._initWithConfig.bind(this,stepsKey));initTasks.onabort=this._onAbortInitialization.bind(this);initTasks.oncomplete=this._onCompleteInitialization.bind(this,onLoaded);elementIDs.forEach(function(name){dom[Utils.camelCase(name)]=document.getElementById(name);if(!dom[Utils.camelCase(name)]){console.error('Cache DOM elements: couldnt cache: '+name);}},this);initTasks.next();var mediaEvents=this._mediaEvents=['abort','canplay','canplaythrough','durationchange','emptied','ended','error','interruptbegin','interruptend','loadeddata','loadedmetadata','loadstart','mozaudioavailable','pause','play','playing','stalled','suspend','waiting'];this._debugEventHandler={handleEvent:function(evt){var errCodes={'1':'MEDIA_ERR_ABORTED','2':'MEDIA_ERR_NETWORK','3':'MEDIA_ERR_DECODE','4':'MEDIA_ERR_SRC_NOT_SUPPORTED'};console.log('TUTORIAL: media-event: '+evt.type);if(evt.type=='error'){var errtype=errCodes[evt.target.error.code]||'unknown';console.log('TUTORIAL: media-event, '+errtype+' error');}}};mediaEvents.forEach(name=>{dom.tutorialStepVideo.addEventListener(name,this._debugEventHandler);});},start:function(onReady){var sequence;var initInProgress=false;if(this._initialization){sequence=this._initialization;initInProgress=true;}else{this._initialization=sequence=new TutorialUtils.Sequence();sequence.onabort=this._onAbortInitialization.bind(this);sequence.oncomplete=this._onCompleteInitialization.bind(this);}
|
||
sequence.push(function setInitialStep(){console.log('TUTORIAL: setInitialStep');return this._setStep();}.bind(this));sequence.push(function showTutorialAndFinishInit(){dom.tutorial.classList.add('show');console.log('TUTORIAL: dispatching tutorialinitialized');window.dispatchEvent(new CustomEvent('tutorialinitialized'));});if(typeof onReady==='function'){sequence.push(onReady);}
|
||
if(!initInProgress){sequence.next();}},_initWithConfig:function(stepsKey){stepsKey=stepsKey||'default';this._stepsKey=stepsKey;this._stepsConfig=this.config[stepsKey]||this.config['default'];dom.forwardTutorial.addEventListener('click',this);dom.backTutorial.addEventListener('click',this);this._currentStep=1;},_onAbortInitialization:function(){this._initialization=null;},_onCompleteInitialization:function(onReady){this._initialization=null;this._initialized=true;if(typeof onReady==='function'){onReady();}},_setStep:function(value){value=(typeof value==='number')?value:this._currentStep;var stepIndex=value-1;if(stepIndex>=this._stepsConfig.steps.length){return Promise.resolve().then(function(){Tutorial.done();});}
|
||
var stepData=this._stepsConfig.steps[stepIndex];if(!stepData){return Promise.reject('No data for step: '+value);}
|
||
dom.tutorial.dataset.step=this._currentStep;document.l10n.setAttributes(dom.tutorialStepTitle,stepData.l10nKey);var imgElement=dom.tutorialStepImage,videoElement=dom.tutorialStepVideo;var stepPromise;if(stepData.video){stepPromise=TutorialUtils.getBestAssetForDirection(stepData.video).then((bestSrc)=>{return TutorialUtils.loadAndPlayMedia(videoElement,bestSrc);});videoElement.hidden=false;imgElement.hidden=true;}else{imgElement.hidden=false;stepPromise=TutorialUtils.loadMedia(imgElement,stepData.image);imgElement.hidden=false;videoElement.hidden=true;}
|
||
return stepPromise;},handleEvent:function(evt){if(evt.type==='click'){switch(evt.target){case dom.forwardTutorial:this.next(evt);break;case dom.backTutorial:this.back(evt);break;}}},next:function(){return this._setStep(++this._currentStep);},back:function(){return this._setStep(--this._currentStep);},done:function(){var isUpgrade=this._stepsKey&&this._stepsKey!=='default';FinishScreen.init(isUpgrade);dom.tutorial.classList.remove('show');dom.tutorialStepVideo.removeAttribute('src');dom.tutorialStepImage.removeAttribute('src');},loadConfig:function(){if(!this._configPromise){currentLayout=ScreenLayout.getCurrentLayout()==='tiny'?'tiny':'large';var configUrl='/config/'+currentLayout+'.json';this._configPromise=LazyLoader.getJSON(configUrl).then(function(json){Tutorial.config=json;return Tutorial.config;},function(){return new Error('Tutorial config failed to load from: '+configUrl);});}
|
||
return this._configPromise;},reset:function(){var resetPromise=Promise.resolve();if(dom.tutorialStepVideo){this._mediaEvents.forEach(name=>{dom.tutorialStepVideo.removeEventListener(name,this._debugEventHandler);});dom.tutorialStepVideo.hidden=true;if(dom.tutorialStepVideo.src){resetPromise=new Promise((resolve,reject)=>{dom.tutorialStepVideo.addEventListener('emptied',()=>{resolve();});dom.tutorialStepVideo.removeAttribute('src');dom.tutorialStepVideo.load();});}}
|
||
if(this._initialization){this._initialization.abort();this._initialization=null;}
|
||
this._configPromise=null;this._currentStep=1;this._stepsConfig=this.config=null;if(this._initialized){dom.tutorial.classList.remove('show');this._initialized=false;}
|
||
document.getElementById('tutorial').classList.remove('show');return resetPromise;}};exports.Tutorial=Tutorial;})(this);;(function(exports){'use strict';const DOGFOODSETTING='debug.performance_data.dogfooding';const METRICSSETTING='metrics.selectedMetrics.level';var steps=[{onlyForward:true,hash:'#languages',requireSIM:false},{onlyForward:false,hash:'#data_3g',requireSIM:true},{onlyForward:false,hash:'#wifi',requireSIM:false},{onlyForward:false,hash:'#date_and_time',requireSIM:false},{onlyForward:false,hash:'#geolocation',requireSIM:false},{onlyForward:false,hash:'#import_contacts',requireSIM:false},{onlyForward:false,hash:'#firefox_accounts',requireSIM:false},{onlyForward:false,hash:'#welcome_browser',requireSIM:false},{onlyForward:false,hash:'#browser_privacy',requireSIM:false}];exports.Navigation={get stepCount(){return this._stepOrder?this._stepOrder.length:0;},currentStepIndex:0,previousStepIndex:0,simMandatory:false,skipMobileDataScreen:false,skipDateTimeScreen:false,tzInitialized:false,_stepsById:null,_stepOrder:null,init:function n_init(){this._stepOrder=[];this._stepsById={};var settings=navigator.mozSettings;var forward=document.getElementById('forward');var back=document.getElementById('back');this._onForwardClick=this.forward.bind(this);this._onBackClick=this.back.bind(this);forward.addEventListener('click',this._onForwardClick);back.addEventListener('click',this._onBackClick);window.addEventListener('hashchange',this);this._onActivationScreenClick=this.handleExternalLinksClick.bind(this);UIManager.activationScreen.addEventListener('click',this._onActivationScreenClick);steps.forEach(step=>{this.registerStep(step);});var self=this;var reqSIM=settings&&settings.createLock().get('ftu.sim.mandatory')||{};reqSIM.onsuccess=function onSuccess(){self.simMandatory=reqSIM.result['ftu.sim.mandatory']||false;};navigator.mozApps.getSelf().onsuccess=function(evt){var app=evt.target.result;app.connect('ftucomms').then(function onConnAccepted(ports){self.ports=ports;ports.forEach(port=>port.postMessage('started'));},function onConnRejected(reason){console.warn('FTU navigation cannot use IAC: '+reason);});};},uninit:function(){this._stepOrder=null;this._stepsById=null;this.currentStepIndex=0;this.previousStepIndex=0;this.ports=null;var forward=document.getElementById('forward');var back=document.getElementById('back');var activationScreen=UIManager&&UIManager.activationScreen;if(forward&&this._onForwardClick){forward.removeEventListener('click',this._onForwardClick);}
|
||
if(back&&this._onBackClick){back.removeEventListener('click',this._onBackClick);}
|
||
if(activationScreen&&this._onActivationScreenClick){activationScreen.removeEventListener('click',this._onActivationScreenClick);}
|
||
window.removeEventListener('hashchange',this);},registerStep:function(step){if(!step.id){step.id=step.hash.substring(1);}
|
||
var id=step.id;this._stepsById[id]=step;var beforeStepIdx=step.hasOwnProperty('beforeStep')?this._stepOrder.indexOf(step.beforeStep):-1;var afterStepIdx=step.hasOwnProperty('afterStep')?this._stepOrder.indexOf(step.afterStep):-1;if(beforeStepIdx>-1){this._stepOrder.splice(beforeStepIdx,0,id);}else if(afterStepIdx>-1){this._stepOrder.splice(afterStepIdx+1,0,id);}else{this._stepOrder.push(id);}},stepAt:function(idx){var stepId=this._stepOrder[idx];if(stepId){return this._stepsById[stepId];}},indexOfStep:function(step){var id=(typeof id==='string')?step.id:step;return this._stepOrder.indexOf(id);},back:function n_back(event){var currentStep=this.stepAt(this.currentStepIndex);var actualHash=window.location.hash;if(actualHash!=currentStep.hash){window.history.back();}else{var self=this;var goToStep=function(){self.previousStepIndex=self.currentStepIndex;self.currentStepIndex--;if(self.currentStepIndex>=0){self.manageStep();}};goToStep();}},forward:function n_forward(event){var self=this;var goToStepForward=function(){self.previousStepIndex=self.currentStepIndex;self.currentStepIndex++;if(self.currentStepIndex>=self.stepCount){UIManager.sendNewsletter(function newsletterSent(result){if(result){UIManager.activationScreen.classList.remove('show');UIManager.changeStatusBarColor(UIManager.DARK_THEME);UIManager.finishScreen.classList.add('show');UIManager.hideActivationScreenFromScreenReader();}else{self.currentStepIndex--;}});return;}
|
||
self.manageStep();};goToStepForward();},handleExternalLinksClick:function n_handleExternalLinksClick(e){var link=e.target;if(!link.mozMatchesSelector('a.external')){return;}
|
||
e.preventDefault();var href=link.href,title=link.getAttribute('title')||link.textContent;if(navigator.onLine){this.displayExternalLink(href,title);}else{UIManager.displayOfflineDialog(href,title);}},displayExternalLink:function n_displayExternalLink(href,title){window.open(href,'','dialog');},ensureTZInitialized:function(){if(!this.tzInitialized){return UIManager.initTZ().then(()=>{this.skipDateTimeScreen=!UIManager.timeZoneNeedsConfirmation;this.tzInitialized=true;});}else{return Promise.resolve();}},handleEvent:function n_handleEvent(event){var actualHash=window.location.hash;switch(actualHash){case'#languages':UIManager.mainTitle.setAttribute('data-l10n-id','language');break;case'#data_3g':UIManager.mainTitle.setAttribute('data-l10n-id','3g');DataMobile.getStatus(UIManager.updateDataConnectionStatus.bind(UIManager));break;case'#wifi':DataMobile.removeSVStatusObserver();UIManager.mainTitle.setAttribute('data-l10n-id','selectNetwork');UIManager.activationScreen.classList.remove('no-options');if(UIManager.navBar.classList.contains('secondary-menu')){UIManager.navBar.classList.remove('secondary-menu');return;}
|
||
WifiManager.getNetworks(networks=>{this.ensureTZInitialized().then(()=>{WifiUI.renderNetworks(networks);});});break;case'#date_and_time':UIManager.mainTitle.setAttribute('data-l10n-id','dateAndTime');break;case'#geolocation':UIManager.mainTitle.setAttribute('data-l10n-id','geolocation');break;case'#import_contacts':UIManager.mainTitle.setAttribute('data-l10n-id','importContacts3');SimManager.checkSIMButton();SdManager.checkSDButton();var onlineState;if(!WifiManager.api){ImportIntegration.checkImport('enabled');break;}
|
||
onlineState=window.navigator.onLine?'enabled':'disabled';ImportIntegration.checkImport(onlineState);break;case'#firefox_accounts':UIManager.mainTitle.setAttribute('data-l10n-id','firefox-accounts');break;case'#welcome_browser':UIManager.mainTitle.setAttribute('data-l10n-id','aboutBrowser');var settings=navigator.mozSettings;var basicMetrics=document.getElementById('metrics-basic');var enhancedMetrics=document.getElementById('metrics-enhanced');var noneMetrics=document.getElementById('metrics-none');var defaultLevel=settings&&settings.createLock().get(METRICSSETTING);if(defaultLevel){defaultLevel.onsuccess=function(){var result=defaultLevel.result[METRICSSETTING];if(result==='Basic'){basicMetrics.checked=true;}else if(result==='Enhanced'){enhancedMetrics.checked=true;}else if(result==='None'){noneMetrics.checked=true;}};}
|
||
var dogfood=settings&&settings.createLock().get(DOGFOODSETTING);if(dogfood){dogfood.onsuccess=function(){if(dogfood.result[DOGFOODSETTING]){basicMetrics.setAttribute('disabled','true');enhancedMetrics.setAttribute('disabled','true');noneMetrics.setAttribute('disabled','true');}else{basicMetrics.removeAttribute('disabled');enhancedMetrics.removeAttribute('disabled');noneMetrics.removeAttribute('disabled');}};}
|
||
break;case'#browser_privacy':UIManager.mainTitle.setAttribute('data-l10n-id','aboutBrowser');break;case'#SIM_mandatory':UIManager.mainTitle.setAttribute('data-l10n-id','SIM_mandatory');break;case'#about-your-rights':case'#about-your-privacy':UIManager.mainTitle.setAttribute('data-l10n-id','aboutBrowser');UIManager.navBar.classList.add('back-only');break;case'#sharing-performance-data':UIManager.mainTitle.setAttribute('data-l10n-id','aboutBrowser');UIManager.navBar.classList.add('back-only');break;}
|
||
if(this.simMandatory){UIManager.skipPinButton.classList.add('hidden');UIManager.backSimButton.classList.remove('hidden');}else{UIManager.skipPinButton.classList.remove('hidden');UIManager.backSimButton.classList.add('hidden');}
|
||
var lastIndex=this.stepCount-1;if(this.currentStepIndex<=lastIndex&&(this.stepAt(this.currentStepIndex).hash!=='#wifi')){UIManager.activationScreen.classList.add('no-options');}
|
||
if(this.currentStepIndex<=lastIndex&&this.stepAt(this.currentStepIndex).hash===actualHash){UIManager.navBar.classList.remove('back-only');}},postStepMessage:function n_postStepMessage(stepIndex){if(!this.ports){return;}
|
||
var step=this.stepAt(stepIndex);this.ports.forEach(function(port){port.postMessage({type:'step',hash:step.hash});});},skipStep:function n_skipStep(){var stepIndex=this.currentStepIndex;stepIndex+=stepIndex>this.previousStepIndex?1:-1;if(stepIndex<=0){this.previousStepIndex=stepIndex=0;}
|
||
if(stepIndex>this.stepCount){this.previousStepIndex=stepIndex=this.stepCount;}
|
||
this.currentStepIndex=stepIndex;this.manageStep();},manageStep:function n_manageStep(){var self=this;if(self.currentStepIndex>self.previousStepIndex){self.postStepMessage(self.previousStepIndex);}
|
||
if(self.currentStepIndex>=self.stepCount){OperatorVariant.setSIMOnFirstBootState();}
|
||
if(self.currentStepIndex===0){self.skipMobileDataScreen=false;}
|
||
var futureLocation=this.stepAt(self.currentStepIndex);if(this.simMandatory&&!IccHelper.cardState&&futureLocation.requireSIM){futureLocation.hash='#SIM_mandatory';futureLocation.requireSIM=false;futureLocation.onlyBackward=true;}
|
||
if(this.stepAt(this.currentStepIndex).onlyForward){UIManager.navBar.classList.add('forward-only');}else{UIManager.navBar.classList.remove('forward-only');}
|
||
var nextButton=document.getElementById('forward');if(this.stepAt(this.currentStepIndex).onlyBackward){nextButton.setAttribute('disabled','disabled');}else{nextButton.removeAttribute('disabled');}
|
||
if(this.currentStepIndex===this.stepCount){nextButton.setAttribute('data-l10n-id','done');}else{nextButton.setAttribute('data-l10n-id','navbar-next');}
|
||
if(futureLocation.hash==='#firefox_accounts'){nextButton.setAttribute('data-l10n-id','skip');}
|
||
window.location.hash=futureLocation.hash;if(futureLocation.requireSIM){var check_cardState=function(response){if(!response||(!SimManager.available()&&futureLocation.hash!=='#data_3g')){self.skipStep();if(self.currentStepIndex>self.previousStepIndex){self.skipMobileDataScreen=true;}}};var skipUnlockScreens=this.currentStepIndex<this.previousStepIndex;SimManager.handleCardState(check_cardState,skipUnlockScreens);}
|
||
if(this.stepAt(this.currentStepIndex).hash==='#date_and_time'){if(!self.tzInitialized){self.skipDateTimeScreen=!UIManager.timeZoneNeedsConfirmation;}
|
||
if(self.skipDateTimeScreen){self.postStepMessage(self.currentStepIndex);if(navigator.onLine){UIManager.updateSetting('time.timezone.automatic-update.enabled',true);UIManager.updateSetting('time.clock.automatic-update.enabled',true);}
|
||
self.skipStep();}}
|
||
if((futureLocation.hash==='#firefox_accounts'&&!navigator.onLine)||(futureLocation.hash==='#firefox_accounts'&&UIManager.skipFxA)){self.postStepMessage(self.currentStepIndex);self.skipStep();}}};})(window);;'use strict';var DataMobile={key:'ril.data.enabled',keySV:'ftu.ril.data.enabled',STEP_DATA_3G:2,apnRetrieved:false,init:function dm_init(){var settings=navigator.mozSettings;if(!settings){console.log('Settings is not available');return;}
|
||
this.settings=settings;},removeSVStatusObserver:function dm_removeSVStatusObserver(){this.settings.removeObserver(this.keySV,this.getStatus);},getStatus:function dm_getStatus(aCallback){var self=this;var reqSV=this.settings.createLock().get(this.keySV);reqSV.onsuccess=function gst_svsuccess(){var svStatus=reqSV.result[self.keySV];if(svStatus!==undefined&&!UIManager.dataConnectionChangedByUsr){self.settings.removeObserver(self.keySV,self.getStatus);if(Navigation.currentStep===self.STEP_DATA_3G){self.toggle(svStatus);if(typeof aCallback==='function'){aCallback(svStatus);}}else{self.getRealStatus(aCallback);}}else{self.getRealStatus(aCallback);}};reqSV.onerror=function gst_error(){console.log('Error retrieving '+self.keySV);};this.settings.addObserver(this.keySV,this.getStatus.bind(this,aCallback));},getRealStatus:function dm_getRealStatus(callback){var request=this.settings.createLock().get(this.key);var self=this;request.onsuccess=function gst_success(){var currentStatus=request.result[self.key];self.isDataAvailable=currentStatus;callback(currentStatus);};request.onerror=function gst_error(){console.log('Error retrieving '+self.key);};},toggle:function dm_toggle(status,callback){var options={};options[this.key]=status;if(!this.apnRetrieved){var self=this;this.getAPN(function apn_recovered(){self.settings.createLock().set(options);self.apnRetrieved=true;self.isDataAvailable=status;if(callback){callback();}});return;}
|
||
this.settings.createLock().set(options);this.apnRetrieved=true;this.isDataAvailable=status;if(callback){callback();}},getAPN:function dm_getapn(callback){var _self=this;function ensureApnSettings(){var req=_self.settings.createLock().get('ril.data.apnSettings');req.onsuccess=function loadApn(){var apnSettings=req.result['ril.data.apnSettings'];if(apnSettings){if(callback){callback(req.result);}
|
||
_self.settings.removeObserver('ril.data.apnSettings',ensureApnSettings);}};}
|
||
ensureApnSettings();this.settings.addObserver('ril.data.apnSettings',ensureApnSettings);}};;'use strict';var TimeManager={elementIDs:['tz-region','tz-city','date-configuration','time-configuration'],init:function tm_init(){if(window.navigator.mozTime){this.time=window.navigator.mozTime;}else{console.log('There is no mozTime available in window');}
|
||
this.elementIDs.forEach(function(elementID){document.getElementById(elementID+'-button').addEventListener('click',function(evt){evt.preventDefault();var input=document.getElementById(elementID);setTimeout(input.focus.bind(input),10);});});},set:function tm_set(date){this.time.set(date);}};;'use strict';var UIManager={domSelectors:['container','splash-screen','activation-screen','finish-screen','update-screen','nav-bar','main-title','unlock-sim-screen','unlock-sim-header','unlock-sim-action','pincode-screen','pin-label','pin-retries-left','pin-input','back-sim-button','pin-error','skip-pin-button','unlock-sim-button','pukcode-screen','puk-label','puk-retries-left','puk-input','puk-info','puk-error','newpin-input','newpin-error','confirm-newpin-input','confirm-newpin-error','xckcode-screen','xck-label','xck-retries-left','xck-input','xck-error','sim-info-screen','sim-info-back','sim-info-forward','sim-info-1','sim-info-2','sim-number-1','sim-number-2','sim-carrier-1','sim-carrier-2','sim-import','sim-import-button','no-sim','sd-import-button','no-memorycard','fxa-create-account','fxa-intro','networks','wifi-refresh-button','wifi-join-button','join-hidden-button','hidden-wifi-authentication','hidden-wifi-ssid','hidden-wifi-security','hidden-wifi-password','hidden-wifi-password-box','hidden-wifi-identity','hidden-wifi-identity-box','hidden-wifi-show-password','date-configuration','time-configuration','date-configuration-label','time-configuration-label','time-form','data-connection-switch','geolocation-switch','lets-go-button','update-lets-go-button','skip-tutorial-button','update-skip-tutorial-button','metrics-basic','metrics-enhanced','metrics-none','offline-error-dialog','newsletter-form','newsletter-input','newsletter-success-screen','offline-newsletter-error-dialog','invalid-email-error-dialog'],dataConnectionChangedByUsr:false,timeZoneNeedsConfirmation:true,DARK_THEME:'#242d33',LIGHT_THEME:'#eeeeee',init:function ui_init(){this.domSelectors.forEach(function createElementRef(name){this[toCamelCase(name)]=document.getElementById(name);}.bind(this));this._settingsObserveHandler={'geolocation.enabled':{defaultValue:this.geolocationSwitch.checked,callback:function(value){var isEnabled=!!value;if(this.geolocationSwitch.checked!==isEnabled){this.geolocationSwitch.checked=isEnabled;}}.bind(this)}};for(var name in this._settingsObserveHandler){SettingsListener.observe(name,this._settingsObserveHandler[name].defaultValue,this._settingsObserveHandler[name].callback);}
|
||
var currentDate=new Date();this.timeConfigurationLabel.textContent=currentDate.toLocaleString(navigator.languages,{hour12:navigator.mozHour12,hour:'numeric',minute:'numeric',second:'numeric'});this.dateConfigurationLabel.textContent=currentDate.toLocaleString(navigator.languages,{year:'numeric',month:'numeric',day:'numeric'});this.simImportButton.addEventListener('click',this);this.sdImportButton.addEventListener('click',this);this.skipPinButton.addEventListener('click',this);this.backSimButton.addEventListener('click',this);this.unlockSimButton.addEventListener('click',this);this.unlockSimAction.addEventListener('action',this);this.simInfoBack.addEventListener('click',this);this.simInfoForward.addEventListener('click',this);this.dataConnectionSwitch.addEventListener('change',this);this.wifiRefreshButton.addEventListener('click',this);this.wifiJoinButton.addEventListener('click',this);this.networks.addEventListener('click',this);this.joinHiddenButton.addEventListener('click',this);this.hiddenWifiSecurity.addEventListener('change',this);this.wifiJoinButton.disabled=true;var checkHiddenWifiJoin=function(){this.wifiJoinButton.disabled=this.hiddenWifiSsid.value===''||!WifiHelper.isValidInput(this.hiddenWifiSecurity.value,this.hiddenWifiPassword.value,this.hiddenWifiIdentity.value);}.bind(this);this.hiddenWifiSsid.addEventListener('keyup',checkHiddenWifiJoin);this.hiddenWifiIdentity.addEventListener('keyup',checkHiddenWifiJoin);this.hiddenWifiPassword.addEventListener('keyup',checkHiddenWifiJoin);this.hiddenWifiSecurity.addEventListener('change',checkHiddenWifiJoin);this.hiddenWifiShowPassword.onchange=function togglePasswordVisibility(){UIManager.hiddenWifiPassword.type=this.checked?'text':'password';};this.timeConfiguration.addEventListener('input',this);this.dateConfiguration.addEventListener('input',this);this.geolocationSwitch.addEventListener('change',this);this.fxaCreateAccount.addEventListener('click',this);this.timeForm.addEventListener('submit',function(event){event.preventDefault();});this.newsletterInput.addEventListener('focus',function(){window.addEventListener('resize',function resize(){window.removeEventListener('resize',resize);setTimeout(function(){var page=document.getElementById('browser_privacy');UIManager.scrollToElement(page,UIManager.newsletterInput);},30);});});this.offlineNewsletterErrorDialog.querySelector('button').addEventListener('click',function offlineDialogClick(){this.offlineNewsletterErrorDialog.classList.remove('visible');}.bind(this));this.invalidEmailErrorDialog.querySelector('button').addEventListener('click',function invalidEmailDialogClick(){this.invalidEmailErrorDialog.classList.remove('visible');}.bind(this));var skipTutorialAction=function(){WifiManager.finish();if(ScreenLayout.getCurrentLayout()==='tiny'){window.close();}else{FinishScreen.init();}};var startTutorialAction=function(evt){WifiManager.finish();Tutorial.start(function onTutorialLoaded(){UIManager.activationScreen.classList.remove('show');UIManager.updateScreen.classList.remove('show');UIManager.finishScreen.classList.remove('show');});};this.skipTutorialButton.addEventListener('click',skipTutorialAction);this.updateSkipTutorialButton.addEventListener('click',skipTutorialAction);this.letsGoButton.addEventListener('click',startTutorialAction);this.updateLetsGoButton.addEventListener('click',startTutorialAction);this.metricsBasic.addEventListener('change',this);this.metricsEnhanced.addEventListener('change',this);this.metricsNone.addEventListener('change',this);var button=this.offlineErrorDialog.querySelector('button');button.addEventListener('click',this.onOfflineDialogButtonClick.bind(this));['confirmdialogshowing','loadingoverlayshowing','tutorialinitialized'].forEach(function(event){window.addEventListener(event,this.hideActivationScreenFromScreenReader.bind(this));},this);['confirmdialoghiding','loadingoverlayhiding'].forEach(function(event){window.addEventListener(event,this.showActivationScreenToScreenReader.bind(this));},this);this.checkInitialFxAStatus();},scrollToElement:function ui_scrollToElement(container,element){container.scrollTop=element.offsetTop;},sendNewsletter:function ui_sendNewsletter(callback){var self=this;var emailValue=self.newsletterInput.value;if(emailValue===''){return callback(true);}else{utils.overlay.show('email-loading','spinner');if(self.newsletterInput.checkValidity()){if(window.navigator.onLine){Basket.send(emailValue,function emailSent(err,data){if(err){if(err.code&&err.code===Basket.errors.INVALID_EMAIL){ConfirmDialog.show('invalid-email-dialog-title','invalid-email-dialog-text',{title:'cancel',callback:function ok(){ConfirmDialog.hide();}});utils.overlay.hide();return callback(false);}else{Basket.store(emailValue);}}
|
||
utils.overlay.hide();return callback(true);});}else{Basket.store(emailValue,function stored(errorStoring){utils.overlay.hide();return callback(!errorStoring);});}}else{utils.overlay.hide();ConfirmDialog.show('invalid-email-dialog-title','invalid-email-dialog-text',{title:'cancel',callback:function ok(){ConfirmDialog.hide();}});return callback(false);}}},initTZ:function ui_initTZ(){var self=this;var tzRegion=document.getElementById('tz-region');var tzCity=document.getElementById('tz-city');return new Promise(function(resolve){var onchange=self.setTimeZone.bind(self);var onload=function(){self.setTimeZone.apply(self,arguments);resolve();};tzSelect(tzRegion,tzCity,onchange,onload);});},handleEvent:function ui_handleEvent(event){switch(event.target.id){case'skip-pin-button':SimManager.skip();break;case'back-sim-button':case'sim-info-back':SimManager.back();break;case'unlock-sim-button':SimManager.unlock();break;case'unlock-sim-action':SimManager.simUnlockBack();break;case'sim-info-forward':SimManager.finish();break;case'sim-import-button':window.setTimeout(SimManager.importContacts,0);break;case'sd-import-button':window.setTimeout(SdManager.importContacts,0);break;case'data-connection-switch':this.dataConnectionChangedByUsr=true;var status=event.target.checked;DataMobile.toggle(status);break;case'wifi-refresh-button':WifiManager.scan(WifiUI.renderNetworks);break;case'wifi-join-button':if(window.location.hash==='#hidden-wifi-authentication'){WifiUI.joinHiddenNetwork();}else{WifiUI.joinNetwork();}
|
||
break;case'join-hidden-button':WifiUI.addHiddenNetwork();break;case'hidden-wifi-security':var securityType=event.target.selectedIndex?event.target.value:'';WifiUI.handleHiddenWifiSecurity(securityType);break;case'time-configuration':this.setTime();break;case'date-configuration':this.setDate();break;case'geolocation-switch':this.updateSetting(event.target.name,event.target.checked);break;case'metrics-enhanced':this.updateSetting('hud.hide',(event.target.value==='Enhanced'));this.updateSetting('devtools.overlay',(event.target.value==='Enhanced'));case'metrics-basic':case'metrics-none':this.updateSetting('metrics.selectedMetrics.level',event.target.value);break;case'fxa-create-account':this.createFirefoxAccount();break;default:if(event.target.parentNode.id==='networks-list'){WifiUI.chooseNetwork(event);}
|
||
break;}},updateSetting:function ui_updateSetting(name,value){if(!name){return;}
|
||
var cset={};cset[name]=value;return SettingsListener.getSettingsLock().set(cset);},setForwardButtonLabel:function ui_setForwardButtonLabel(label){var nextButton=document.getElementById('forward');nextButton.setAttribute('data-l10n-id',label);},checkInitialFxAStatus:function ui_checkInitialFxAStatus(){this.skipFxA=true;FxAccountsIACHelper.getAccount((account)=>{this.skipFxA=false;this.onFxALogin(account);},()=>{FxAccountsIACHelper.logout(()=>{this.skipFxA=false;});});},createFirefoxAccount:function ui_createFirefoxAccount(){FxAccountsIACHelper.openFlow(UIManager.onFxAFlowDone,UIManager.onFxAError);},onFxAFlowDone:function ui_onFxAFlowDone(){FxAccountsIACHelper.getAccount((account)=>{if(!account){return;}
|
||
UIManager.onFxALogin(account);UIManager.setForwardButtonLabel('navbar-next');},UIManager.onFxAError);},onFxALogin:function ui_onFxALogin(account){if(!account){return;}
|
||
UIManager.newsletterInput.value=account.email;UIManager.fxaIntro.innerHTML='';document.l10n.setAttributes(UIManager.fxaIntro,account.verified?'fxa-signed-in':'fxa-email-sent',{email:account.email});UIManager.fxaCreateAccount.disabled=true;},onFxAError:function ui_onFxAError(response){console.error('Create FxA Error: '+JSON.stringify(response));UIManager.newsletterInput.value='';document.l10n.setAttributes(UIManager.fxaIntro,'fxa-upsell');UIManager.fxaCreateAccount.disabled=false;UIManager.setForwardButtonLabel('skip');},displayOfflineDialog:function ui_displayOfflineDialog(href,title){var dialog=this.offlineErrorDialog;document.l10n.setAttributes(dialog.querySelector('small'),'offline-dialog-text',{url:href});dialog.classList.add('visible');this.hideActivationScreenFromScreenReader();},onOfflineDialogButtonClick:function ui_onOfflineDialogButtonClick(e){this.offlineErrorDialog.classList.remove('visible');this.showActivationScreenToScreenReader();},hideActivationScreenFromScreenReader:function ui_hideActivationScreenFromScreenReader(){this.activationScreen.setAttribute('aria-hidden',true);},showActivationScreenToScreenReader:function ui_showActivationScreenToScreenReader(){this.activationScreen.setAttribute('aria-hidden',false);},setDate:function ui_sd(){if(!!this.lock){return;}
|
||
var now=new Date();var currentDate=this.dateConfiguration.value;var currentTime=now.toLocaleFormat('%H:%M');var timeToSet=new Date(currentDate+'T'+currentTime);TimeManager.set(timeToSet);this.dateConfigurationLabel.textContent=timeToSet.toLocaleString(navigator.languages,{year:'numeric',month:'numeric',day:'numeric'});},setTime:function ui_st(){if(!!this.lock){return;}
|
||
var timeLabel=document.getElementById('time-configuration-label');var now=new Date();var currentTime=document.getElementById('time-configuration').value;if(currentTime.indexOf(':')===1){currentTime='0'+currentTime;}
|
||
var currentDate=now.toLocaleFormat('%Y-%m-%d');var timeToSet=new Date(currentDate+'T'+currentTime);TimeManager.set(timeToSet);timeLabel.textContent=timeToSet.toLocaleString(navigator.languages,{hour12:navigator.mozHour12,hour:'numeric',minute:'numeric',second:'numeric'});},setTimeZone:function ui_stz(timezone,needsConfirmation){this.timeZoneNeedsConfirmation=!!needsConfirmation;var utcOffset=timezone.utcOffset;document.getElementById('time_zone_overlay').className='UTC'+utcOffset.replace(/[+:]/g,'');var timezoneTitle=document.getElementById('time-zone-title');document.l10n.setAttributes(timezoneTitle,'timezoneTitle',{utcOffset:utcOffset,region:timezone.region,city:timezone.city});document.getElementById('tz-region-label').textContent=timezone.region;document.getElementById('tz-city-label').textContent=timezone.city;var now=new Date();var timeLabel=document.getElementById('time-configuration-label');timeLabel.textContent=now.toLocaleString(navigator.languages,{hour12:navigator.mozHour12,hour:'numeric',minute:'numeric',second:'numeric'});},updateDataConnectionStatus:function ui_udcs(status){this.dataConnectionSwitch.checked=status;},changeStatusBarColor:function ui_csbc(color){var themeMeta=document.head.querySelector('meta[name="theme-color"]');themeMeta.setAttribute('content',color);}};function toCamelCase(str){return str.replace(/\-(.)/g,function replacer(str,p1){return p1.toUpperCase();});};'use strict';var LanguageManager={settings:window.navigator.mozSettings,init:function init(){this.buildLanguageList();document.getElementById('languages').addEventListener('change',this);var onSettingChange=this._boundHandleSettingChange=this.handleSettingChange.bind(this);this.settings.addObserver('language.current',onSettingChange);this.settings.addObserver('accessibility.screenreader',onSettingChange);},uninit:function uninit(){if(this._boundHandleSettingChange){this.settings.removeObserver('language.current',this._boundHandleSettingChange);this.settings.removeObserver('accessibility.screenreader',this._boundHandleSettingChange);}},handleSettingChange:function(evt){switch(evt.settingName){case'accessibility.screenreader':this.buildLanguageList();break;case'language.current':KeyboardHelper.changeDefaultLayouts(evt.settingValue,true);break;}},handleEvent:function handleEvent(evt){if(!this.settings||evt.target.name!='language.current'){return true;}
|
||
this.setLanguage(evt.target.value);return false;},setLanguage:function settings_setLanguage(language){this.settings.createLock().set({'language.current':language});},buildLanguageList:function settings_buildLanguageList(){var panel=document.querySelector('#languages');var container=panel.querySelector('ul');container.innerHTML='';LanguageList.get(function fillLanguageList(allLanguages,currentLanguage){for(var lang in allLanguages){var label=document.createElement('label');label.textContent=LanguageList.wrapBidi(lang,allLanguages[lang]);var radio=document.createElement('gaia-radio');radio.className='checkone';radio.setAttribute('name','language.current');radio.setAttribute('value',lang);radio.checked=(lang===currentLanguage);radio.appendChild(label);radio.configureClass();var li=document.createElement('li');li.dataset.value=lang;li.appendChild(radio);container.appendChild(li);}
|
||
panel.dataset.languagesReady=true;window.dispatchEvent(new CustomEvent('languagelistready'));});}};;'use strict';var AppManager={EVENT_PREFIX:'ftu-',init:function init(versionInfo){window.performance.mark('initialize');this.isInitialized=true;LanguageManager.init();UIManager.init();Navigation.init();window.performance.mark('navigationLoaded');this.publish('setup');var splashTimeout=1025;var splashScreenHidden=this.whenEvent(UIManager.splashScreen,'transitionend',splashTimeout).then(()=>{UIManager.container.removeAttribute('aria-hidden');window.performance.mark('visuallyLoaded');});var languageListReady=this.whenEvent(window,'languagelistready');Promise.all([splashScreenHidden,languageListReady]).then(()=>{window.performance.mark('fullyLoaded');});if(versionInfo&&versionInfo.isUpgrade()){var stepsKey=versionInfo.delta();UIManager.changeStatusBarColor(UIManager.DARK_THEME);UIManager.splashScreen.classList.remove('show');UIManager.activationScreen.classList.remove('show');UIManager.updateScreen.classList.add('show');Tutorial.init(stepsKey,function(){Tutorial.start();});return;}
|
||
SimManager.init();WifiManager.init();ImportIntegration.init();TimeManager.init();DataMobile.init();Tutorial.init();var kSplashTimeout=700;var conn=window.navigator.mozMobileConnections&&window.navigator.mozMobileConnections[0];if(!conn){setTimeout(function(){window.location.hash='#';UIManager.activationScreen.classList.add('show');window.location.hash='#languages';UIManager.splashScreen.classList.remove('show');window.performance.mark('navigationInteractive');window.performance.mark('contentInteractive');},kSplashTimeout);return;}
|
||
setTimeout(function(){Navigation.manageStep();UIManager.activationScreen.classList.add('show');UIManager.splashScreen.classList.remove('show');window.performance.mark('navigationInteractive');window.performance.mark('contentInteractive');},kSplashTimeout);},whenEvent:function(target,name,timeoutMs){return new Promise((resolve,reject)=>{eventSafety(target,name,resolve,timeoutMs||1000);});},publish:function(name,detail){var evt=new CustomEvent(this.EVENT_PREFIX+name,{bubbles:true,detail:detail||this});window.dispatchEvent(evt);}};function init(){VersionHelper.getVersionInfo().then(function(versionInfo){if(!AppManager.isInitialized){AppManager.init(versionInfo);}else{UIManager.initTZ();if(!UIManager.mainTitle.hasAttribute('data-l10n-id')){UIManager.mainTitle.setAttribute('data-l10n-id','language');}}});}
|
||
init();document.addEventListener('DOMRetranslated',init);document.l10n.ready.then(()=>{window.performance.mark('l10nready');});;'use strict';var OperatorVariant=(function(){var NO_SIM='000-000';function setSIMOnFirstBootState(){var cardValue;function normalizeCode(aCode){var ncode=''+aCode;while(ncode.length<3){ncode='0'+ncode;}
|
||
return ncode;}
|
||
try{if(!IccHelper||!IccHelper.cardState){cardValue=NO_SIM;}else{var mcc=IccHelper.iccInfo.mcc;var mnc=IccHelper.iccInfo.mnc;if((mcc!==undefined)&&(mcc!==null)&&(mnc!==undefined)&&(mnc!==null)){cardValue=normalizeCode(mcc)+'-'+normalizeCode(mnc);}else{cardValue=NO_SIM;}}
|
||
var settings=navigator.mozSettings;if(!settings){console.log('Settings is not available');return;}
|
||
var req=settings.createLock().get('ftu.simPresentOnFirstBoot');req.onsuccess=function ov_onsuccess(){var currentStatus=req.result['ftu.simPresentOnFirstBoot'];if(currentStatus===undefined||currentStatus===null){var result=navigator.mozSettings.createLock().set({'ftu.simPresentOnFirstBoot':cardValue});result.onerror=function ov_error(){console.error('An error occurre setting '+'ftu.simPresentOnFirstBoot: '+cardValue);};}
|
||
cardValue=null;};req.onerror=function ov_error(){console.error('Error retrieving ftu.simPresentOnFirstBoot');};}catch(e){console.error('Error setSIMOnFirstBootState. '+e);}}
|
||
return{setSIMOnFirstBootState:setSIMOnFirstBootState};})();;'use strict';var ConfirmDialog=(function(){var isAnimationPlaying=false;var isShown=false;var doc=document;try{if(!document.getElementById("confirmation-message"))doc=parent.document;}catch(_){}var screen=doc.getElementById('confirmation-message');var titleNode=screen.querySelector('h1');var messageNode=screen.querySelector('p');var action1Node=screen.querySelector('button:nth-of-type(1)');var action1Callback;var action2Node=screen.querySelector('button:nth-of-type(2)');var action2Callback;var oldzIndex;var callBackAndPreventDefault=function callBackAndPreventDefault(ev){if(ev.target===action1Node){action1Callback();ev.preventDefault();return false;}else if(ev.target===action2Node){action2Callback();ev.preventDefault();return false;}};var _hide=function _hide(){if(!isShown){return;}
|
||
titleNode.removeAttribute('data-l10n-id');titleNode.className='';messageNode.removeAttribute('data-l10n-id');messageNode.className='';action1Node.removeAttribute('data-l10n-id');action1Node.onclick=null;action2Node.removeAttribute('data-l10n-id');action2Node.onclick=null;screen.classList.remove('fade-in');screen.classList.add('fade-out');isAnimationPlaying=true;window.dispatchEvent(new CustomEvent('confirmdialoghiding'));screen.addEventListener('animationend',function cd_fadeOut(ev){action1Node.className='';action2Node.className='';isAnimationPlaying=false;screen.removeEventListener('animationend',cd_fadeOut);screen.classList.add('no-opacity');screen.classList.add('hide');isShown=false;});};var _show=function _show(title,msg,action1,action2,options){var setL10nAttributes=function(element,options){if('string'===typeof options){document.l10n.setAttributes(element,options);}
|
||
if(options.id){document.l10n.setAttributes(element,options.id,options.args);}};if(options&&options.zIndex){oldzIndex=screen.style.zIndex;screen.style.zIndex=options.zIndex;}
|
||
else{oldzIndex=null;}
|
||
if(title){setL10nAttributes(titleNode,title);}else{titleNode.classList.add('hide');}
|
||
if(msg){setL10nAttributes(messageNode,msg);}else{messageNode.classList.add('hide');}
|
||
if(action1){if(action1.title){setL10nAttributes(action1Node,action1.title);}
|
||
if(action1.isDanger){action1Node.classList.add('danger');}
|
||
if(action1.isRecommend){action1Node.classList.add('recommend');}
|
||
if(action1.callback){action1Callback=action1.callback;action1Node.onclick=callBackAndPreventDefault;}
|
||
if(!action2){action2Node.classList.add('hide');action1Node.classList.add('full');}}
|
||
if(action2){if(action2.title){setL10nAttributes(action2Node,action2.title);}
|
||
if(action2.isDanger){action2Node.classList.add('danger');}
|
||
if(action2.isRecommend){action2Node.classList.add('recommend');}
|
||
if(action2.callback){action2Callback=action2.callback;action2Node.onclick=callBackAndPreventDefault;}
|
||
if(!action1){action1Node.classList.add('hide');action2Node.classList.add('full');}}
|
||
if(isShown){return;}
|
||
screen.classList.remove('hide');screen.classList.remove('fade-out');screen.classList.add('fade-in');isAnimationPlaying=true;window.dispatchEvent(new CustomEvent('confirmdialogshowing'));screen.addEventListener('animationend',function cd_fadeIn(ev){isAnimationPlaying=false;screen.removeEventListener('animationend',cd_fadeIn);screen.classList.remove('no-opacity');isShown=true;});};return{hide:function dialog_hide(){if(oldzIndex){screen.style.zIndex=oldzIndex;oldzIndex=null;}
|
||
if(!isAnimationPlaying){_hide();return;}
|
||
screen.addEventListener('animationend',function cd_hideWhenFinished(ev){screen.removeEventListener('animationend',cd_hideWhenFinished);_hide();});},show:function dialog_show(title,msg,action1,action2,options){if(!isAnimationPlaying){_show(title,msg,action1,action2,options);return;}
|
||
screen.addEventListener('animationend',function cd_showWhenFinished(ev){screen.removeEventListener('animationend',cd_showWhenFinished);_show(title,msg,action1,action2,options);});}};}());;(function(exports){'use strict';exports.ComponentUtils={style:function(baseUrl){if(window.VulpesCompat){window.VulpesCompat.componentStyle(this,baseUrl).catch(console.error);return;}var style=document.createElement('style');var url=baseUrl+'style.css';var self=this;style.setAttribute('scoped','');style.innerHTML='@import url('+url+');';this.appendChild(style);this.style.visibility='hidden';style.addEventListener('load',function(){if(self.shadowRoot){self.shadowRoot.appendChild(style.cloneNode(true));}
|
||
self.style.visibility='';});}};}(window));;'use strict';window.GaiaSwitch=(function(win){var proto=Object.create(HTMLElement.prototype);var baseurl=window.GaiaSwitchBaseurl||'/shared/elements/gaia_switch/';proto.createdCallback=function(){var shadow=this.createShadowRoot();this._template=template.content.cloneNode(true);this._input=this._template.querySelector('input[type="checkbox"]');var checked=this.getAttribute('checked');if(checked!==null){this._input.checked=true;}
|
||
var wrapper=this._template.getElementById('switch');wrapper.addEventListener('click',this.handleClick.bind(this));shadow.appendChild(this._template);ComponentUtils.style.call(this,baseurl);var dirObserver=new MutationObserver(this.updateInternalDir.bind(this));dirObserver.observe(document.documentElement,{attributeFilter:['dir'],attributes:true});this.updateInternalDir();};proto.updateInternalDir=function(){var internal=this.shadowRoot.firstElementChild;if(document.documentElement.dir==='rtl'){internal.setAttribute('dir','rtl');}else{internal.removeAttribute('dir');}};proto.handleClick=function(e){if(e&&e.target.tagName==='A'){return;}
|
||
e&&e.preventDefault();e&&e.stopImmediatePropagation();var event=new MouseEvent('click',{view:window,bubbles:true,cancelable:true});this.dispatchEvent(event);if(!event.defaultPrevented){this.checked=!this.checked;}
|
||
this.dispatchEvent(new CustomEvent('change',{bubbles:true,cancelable:false}));};proto.click=function(){this.handleClick();};Object.defineProperty(proto,'checked',{get:function(){return this._input.checked;},set:function(value){this._input.checked=value;}});Object.defineProperty(proto,'disabled',{get:function(){return this.hasAttribute('disabled');},set:function(value){if(value){this.setAttribute('disabled',true);}else{this.removeAttribute('disabled');}}});Object.defineProperty(proto,'name',{get:function(){return this.getAttribute('name');},set:function(value){this.setAttribute('name',value);}});Object.defineProperty(proto,'type',{get:function(){return'gaia-switch';}});var template=document.createElement('template');template.innerHTML=`<span id="switch">
|
||
<input type="checkbox">
|
||
<span><content select="label"></content></span>
|
||
<div class="details"><content select="details"></content></div>
|
||
<content select="a"></content>
|
||
</span>`;return document.registerElement('gaia-switch',{prototype:proto});})(window);;'use strict';window.GaiaCheckbox=(function(win){var proto=Object.create(HTMLElement.prototype);var baseurl=window.GaiaCheckboxBaseurl||'/shared/elements/gaia_checkbox/';proto.createdCallback=function(){this.lastClick=0;this.throttleTime=250;var shadow=this.createShadowRoot();this._template=template.content.cloneNode(true);this._wrapper=this._template.getElementById('checkbox');this._wrapper.addEventListener('click',this.handleClick.bind(this));this.configureClass();this.checked=this.hasAttribute('checked');this._wrapper.setAttribute('aria-checked',this.checked);this.setAttribute('role','presentation');shadow.appendChild(this._template);ComponentUtils.style.call(this,baseurl);};proto.handleClick=function(e){e.preventDefault();e.stopImmediatePropagation();if(this.lastClick+this.throttleTime>Date.now()){return;}
|
||
this.lastClick=Date.now();var event=new MouseEvent('click',{view:window,bubbles:true,cancelable:true});this.dispatchEvent(event);if(!event.defaultPrevented){this.checked=!this.checked;this._wrapper.setAttribute('aria-checked',this.checked);}
|
||
this.dispatchEvent(new CustomEvent('change',{bubbles:true,cancelable:false}));};proto.configureClass=function(){this._wrapper.className=this.className;};proto.attributeChangedCallback=function(name,from,to){if(name==='class'){this._wrapper.className=to;}};Object.defineProperty(proto,'checked',{get:function(){return this._checked||false;},set:function(value){this._wrapper.classList.toggle('checked',value);this._checked=value;}});Object.defineProperty(proto,'name',{get:function(){return this.getAttribute('name');},set:function(value){this.setAttribute('name',value);}});var template=document.createElement('template');template.innerHTML=`<span id="checkbox" role="checkbox">
|
||
<span role="presentation"><content select="label"></content></span>
|
||
</span>`;return document.registerElement('gaia-checkbox',{prototype:proto});})(window);;'use strict';window.GaiaRadio=(function(win){var proto=Object.create(HTMLElement.prototype);var baseurl=window.GaiaRadioBaseurl||'/shared/elements/gaia_radio/';proto.createdCallback=function(){var shadow=this.createShadowRoot();this._template=template.content.cloneNode(true);this._wrapper=this._template.getElementById('radio');this._wrapper.addEventListener('click',this.handleClick.bind(this));if(this.dataset.role){this._wrapper.setAttribute('role',this.dataset.role);}
|
||
if(!this.hasAttribute('role')){this.setAttribute('role','presentation');}
|
||
this.configureClass();shadow.appendChild(this._template);this.checked=this.hasAttribute('checked');this._wrapper.setAttribute('aria-checked',this.checked);setTimeout(function nextTick(){var label=this.querySelector('label, p');if(!label){return;}
|
||
label.addEventListener('click',this.handleClick.bind(this));}.bind(this));ComponentUtils.style.call(this,baseurl);var dirObserver=new MutationObserver(this.updateInternalDir.bind(this));dirObserver.observe(document.documentElement,{attributeFilter:['dir'],attributes:true});this.updateInternalDir();};proto.updateInternalDir=function(){var internal=this.shadowRoot.firstElementChild;if(document.documentElement.dir==='rtl'){internal.setAttribute('dir','rtl');}else{internal.removeAttribute('dir');}};proto.handleClick=function(e){e.stopImmediatePropagation();var event=new MouseEvent('click',{view:window,bubbles:true,cancelable:true});this.dispatchEvent(event);if(this.checked){return;}
|
||
if(!event.defaultPrevented){this.checked=!this.checked;}
|
||
this.dispatchEvent(new CustomEvent('change',{bubbles:true,cancelable:false}));};proto.configureClass=function(){this._wrapper.className=this.className;this._wrapper.classList.toggle('checked',this._checked);};proto.hideDetails=function(){this.shadowRoot.querySelector('.details').style.display='none';};proto.attributeChangedCallback=function(name,from,to){if(name==='class'){this._wrapper.className=to;}};Object.defineProperty(proto,'checked',{get:function(){return this._checked;},set:function(value){if(!this._template){return;}
|
||
if(value){var relevant=document.querySelectorAll('gaia-radio[name="'+this.getAttribute('name')+'"]');for(var i=0,iLen=relevant.length;i<iLen;i++){relevant[i].checked=false;}
|
||
this.setAttribute('checked',true);}else{this.removeAttribute('checked');}
|
||
this._wrapper.classList.toggle('checked',value);this._wrapper.setAttribute('aria-checked',value);this._checked=value;}});Object.defineProperty(proto,'name',{get:function(){return this.getAttribute('name');},set:function(value){this.setAttribute('name',value);}});Object.defineProperty(proto,'value',{get:function(){return this.getAttribute('value');},set:function(value){this.setAttribute('value',value);}});Object.defineProperty(proto,'type',{get:function(){return'gaia-radio';}});var template=document.createElement('template');template.innerHTML='<span role="radio" id="radio">'+'<span><content select="p,label"></content></span>'+'<div class="details"><content select="details"></content></div>'+'<div class="divider"></div>'+'</span>';return document.registerElement('gaia-radio',{prototype:proto});})(window);;'use strict';window.GaiaButtons=(function(win){var proto=Object.create(HTMLElement.prototype);var baseurl=window.GaiaButtonsBaseurl||'/shared/elements/gaia_buttons/';proto.createdCallback=function(){ComponentUtils.style.call(this,baseurl);};return document.registerElement('gaia-buttons',{prototype:proto});})(window);;'use strict';window.GaiaSubheader=(function(win){var proto=Object.create(HTMLElement.prototype);var baseurl=window.GaiaSubheaderBaseurl||'/shared/elements/gaia_subheader/';proto.createdCallback=function(){ComponentUtils.style.call(this,baseurl);};return document.registerElement('gaia-subheader',{prototype:proto});})(window);;window.COMPONENTS_BASE_URL='/shared/elements/';;(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.GaiaHeader=f()}})(function(){var define,module,exports;return(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){;(function(define){define(function(require,exports,module){'use strict';var debug=0?console.log.bind(console):function(){};var cache={};var MIN=16;var MAX=24;var BUFFER=3;module.exports=function(config){debug('font fit',config);var space=config.space-BUFFER;var min=config.min||MIN;var max=config.max||MAX;var text=trim(config.text);var fontSize=max;var textWidth;var font;do{font=config.font.replace(/\d+px/,fontSize+'px');textWidth=getTextWidth(text,font);}while(textWidth>space&&fontSize!==min&&fontSize--);return{textWidth:textWidth,fontSize:fontSize,overflowing:textWidth>space};};function getTextWidth(text,font){var ctx=getCanvasContext(font);var width=ctx.measureText(text).width;debug('got text width',width);return width;}
|
||
function getCanvasContext(font){debug('get canvas context',font);var cached=cache[font];if(cached){return cached;}
|
||
var canvas=document.createElement('canvas');canvas.setAttribute('moz-opaque','true');canvas.setAttribute('width','1px');canvas.setAttribute('height','1px');debug('created canvas',canvas);var ctx=canvas.getContext('2d',{willReadFrequently:true});ctx.font=font;return cache[font]=ctx;}
|
||
function trim(text){return text.replace(/\s+/g,' ').trim();}});})(typeof define=='function'&&define.amd?define:(function(n,w){'use strict';return typeof module=='object'?function(c){c(require,exports,module);}:function(c){var m={exports:{}};c(function(n){return w[n];},m.exports,m);w[n]=m.exports;};})('font-fit',this));},{}],2:[function(require,module,exports){;(function(define){'use strict';define(function(require,exports,module){var textContent=Object.getOwnPropertyDescriptor(Node.prototype,'textContent');var innerHTML=Object.getOwnPropertyDescriptor(Element.prototype,'innerHTML');var removeAttribute=Element.prototype.removeAttribute;var setAttribute=Element.prototype.setAttribute;var noop=function(){};exports.register=function(name,props){var baseProto=getBaseProto(props.extends);var template=props.template||baseProto.templateString;var extensible=props.extensible=props.hasOwnProperty('extensible')?props.extensible:true;delete props.extends;if(template){if(extensible&&props.template){props.templateString=props.template;}
|
||
var output=processCss(template,name);props.template=document.createElement('template');props.template.innerHTML=output.template;props.lightCss=output.lightCss;props.globalCss=props.globalCss||'';props.globalCss+=output.globalCss;}
|
||
injectGlobalCss(props.globalCss);delete props.globalCss;var descriptors=mixin(props.attrs||{},base.descriptors);props._attrs=props.attrs;delete props.attrs;var proto=createProto(baseProto,props);Object.defineProperties(proto,descriptors);try{return document.registerElement(name,{prototype:proto});}catch(e){if(e.name!=='NotSupportedError'){throw e;}}};var base={properties:{GaiaComponent:true,attributeChanged:noop,attached:noop,detached:noop,created:noop,createdCallback:function(){if(this.dirObserver){addDirObserver();}
|
||
injectLightCss(this);this.created();},attributeChangedCallback:function(name,from,to){var prop=toCamelCase(name);if(this._attrs&&this._attrs[prop]){this[prop]=to;}
|
||
this.attributeChanged(name,from,to);},attachedCallback:function(){if(this.dirObserver){this.setInnerDirAttributes=setInnerDirAttributes.bind(null,this);document.addEventListener('dirchanged',this.setInnerDirAttributes);}
|
||
this.attached();},detachedCallback:function(){if(this.dirObserver){document.removeEventListener('dirchanged',this.setInnerDirAttributes);}
|
||
this.detached();},setupShadowRoot:function(){if(!this.template){return;}
|
||
var node=document.importNode(this.template.content,true);this.createShadowRoot().appendChild(node);if(this.dirObserver){setInnerDirAttributes(this);}
|
||
return this.shadowRoot;},setAttr:function(name,value){var internal=this.shadowRoot.firstElementChild;setAttribute.call(internal,name,value);setAttribute.call(this,name,value);},removeAttr:function(name){var internal=this.shadowRoot.firstElementChild;removeAttribute.call(internal,name);removeAttribute.call(this,name);}},descriptors:{textContent:{set:function(value){textContent.set.call(this,value);if(this.lightStyle){this.appendChild(this.lightStyle);}},get:function(){return textContent.get();}},innerHTML:{set:function(value){innerHTML.set.call(this,value);if(this.lightStyle){this.appendChild(this.lightStyle);}},get:innerHTML.get}}};var defaultPrototype=createProto(HTMLElement.prototype,base.properties);function getBaseProto(proto){if(!proto){return defaultPrototype;}
|
||
proto=proto.prototype||proto;return!proto.GaiaComponent?createProto(proto,base.properties):proto;}
|
||
function createProto(proto,props){return mixin(Object.create(proto),props);}
|
||
var hasShadowCSS=(function(){var div=document.createElement('div');try{div.querySelector(':host');div.querySelector('::content');return true;}
|
||
catch(e){return false;}})();var regex={shadowCss:/(?:\:host|\:\:content)[^{]*\{[^}]*\}/g,':host':/(?:\:host)/g,':host()':/\:host\((.+)\)(?: \:\:content)?/g,':host-context':/\:host-context\((.+)\)([^{,]+)?/g,'::content':/(?:\:\:content)/g};function processCss(template,name){var globalCss='';var lightCss='';if(!hasShadowCSS){template=template.replace(regex.shadowCss,function(match){var hostContext=regex[':host-context'].exec(match);if(hostContext){globalCss+=match.replace(regex['::content'],'').replace(regex[':host-context'],'$1 '+name+'$2').replace(/ +/g,' ');}else{lightCss+=match.replace(regex[':host()'],name+'$1').replace(regex[':host'],name).replace(regex['::content'],name);}
|
||
return'';});}
|
||
return{template:template,lightCss:lightCss,globalCss:globalCss};}
|
||
function injectGlobalCss(css){if(!css){return;}
|
||
var style=document.createElement('style');style.innerHTML=css.trim();headReady().then(function(){document.head.appendChild(style);});}
|
||
function headReady(){return new Promise(function(resolve){if(document.head){return resolve();}
|
||
window.addEventListener('load',function fn(){window.removeEventListener('load',fn);resolve();});});}
|
||
function injectLightCss(el){if(hasShadowCSS){return;}
|
||
var stylesheet=el.querySelector('style');if(!stylesheet){stylesheet=document.createElement('style');stylesheet.setAttribute('scoped','');stylesheet.appendChild(document.createTextNode(el.lightCss));el.appendChild(stylesheet);}
|
||
el.lightStyle=stylesheet;}
|
||
function toCamelCase(string){return string.replace(/-(.)/g,function replacer(string,p1){return p1.toUpperCase();});}
|
||
var dirObserver;function setInnerDirAttributes(component){var dir=component.dir||document.dir;Array.from(component.shadowRoot.children).forEach(element=>{if(element.nodeName!=='STYLE'){element.dir=dir;}});}
|
||
function addDirObserver(){if(dirObserver){return;}
|
||
dirObserver=new MutationObserver(onChanged);dirObserver.observe(document.documentElement,{attributeFilter:['dir'],attributes:true});function onChanged(mutations){document.dispatchEvent(new Event('dirchanged'));}}
|
||
function mixin(target,source){for(var key in source){target[key]=source[key];}
|
||
return target;}});})(typeof define=='function'&&define.amd?define:(function(n,w){'use strict';return typeof module=='object'?function(c){c(require,exports,module);}:function(c){var m={exports:{}};c(function(n){return w[n];},m.exports,m);w[n]=m.exports;};})('gaia-component',this));},{}],3:[function(require,module,exports){(function(define){'use strict';define(function(require,exports,module){var base=window.GAIA_ICONS_BASE_URL||window.COMPONENTS_BASE_URL||'bower_components/';if(!document.documentElement){window.addEventListener('load',load);}else{load();}
|
||
function load(){if(isLoaded()){return;}
|
||
var link=document.createElement('link');link.rel='stylesheet';link.type='text/css';link.href=base+'gaia-icons/gaia-icons.css';document.head.appendChild(link);exports.loaded=true;}
|
||
function isLoaded(){return exports.loaded||document.querySelector('link[href*=gaia-icons]')||document.documentElement.classList.contains('gaia-icons-loaded');}});})(typeof define=='function'&&define.amd?define:(function(n,w){'use strict';return typeof module=='object'?function(c){c(require,exports,module);}:function(c){var m={exports:{}};c(function(n){return w[n];},m.exports,m);w[n]=m.exports;};})('gaia-icons',this));},{}],4:[function(require,module,exports){;(function(define){'use strict';define(function(require,exports,module){var component=require('gaia-component');var fontFit=require('font-fit');require('gaia-icons');var debug=0?console.log.bind(console):function(){};const KNOWN_ACTIONS={menu:'menu',back:'back',close:'close'};const TITLE_FONT='italic 300 24px FiraSans';const TITLE_PADDING=10;const MINIMUM_FONT_SIZE_CENTERED=20;const MINIMUM_FONT_SIZE_UNCENTERED=16;const MAXIMUM_FONT_SIZE=23;module.exports=component.register('gaia-header',{extensible:false,dirObserver:true,created:function(){debug('created');this.setupShadowRoot();this.els={actionButton:this.shadowRoot.querySelector('.action-button'),titles:this.getElementsByTagName('h1')};this.els.actionButton.addEventListener('click',e=>this.onActionButtonClick(e));this.observer=new MutationObserver(this.onMutation.bind(this));this.ignoreDir=this.hasAttribute('ignore-dir');this.titleEnd=this.getAttribute('title-end');this.titleStart=this.getAttribute('title-start');this.noFontFit=this.getAttribute('no-font-fit');this.notFlush=this.hasAttribute('not-flush');this.action=this.getAttribute('action');this.unresolved={};this.pending={};this._resizeThrottlingId=null;this.onResize=this.onResize.bind(this);},attached:function(){debug('attached');this.runFontFitSoon();this.observerStart();window.addEventListener('resize',this.onResize);},detached:function(){debug('detached');window.removeEventListener('resize',this.onResize);this.observerStop();this.clearPending();},clearPending:function(){for(var key in this.pending){this.pending[key].clear();delete this.pending[key];}
|
||
window.cancelAnimationFrame(this._resizeThrottlingId);this._resizeThrottlingId=null;},runFontFit:function(){debug('run font-fit');if(this.noFontFit){return Promise.resolve();}
|
||
var titles=this.els.titles;var space=this.getTitleSpace();var styles=[].map.call(titles,el=>this.getTitleStyle(el,space));return this.setTitleStylesSoon(styles);},runFontFitSoon:function(){debug('run font-fit soon');if(this.pending.runFontFitSoon){return;}
|
||
this.pending.runFontFitSoon=this.nextTick(()=>{delete this.pending.runFontFitSoon;this.runFontFit();});},getTitleStyle:function(el,space){debug('get el style',el,space);var text=el.textContent;var styleId=space.start+text+space.end+'#'+space.value;if(!text||!text.trim()){return debug('exit: no text');}
|
||
if(getStyleId(el)===styleId){return debug('exit: no change');}
|
||
var marginStart=this.getTitleMarginStart();var textSpace=space.value-Math.abs(marginStart);var fontFitResult=this.fontFit(text,textSpace,{min:MINIMUM_FONT_SIZE_CENTERED});var overflowing=fontFitResult.overflowing;var padding={start:0,end:0};if(overflowing){debug('title overflowing');padding.start=!space.start?TITLE_PADDING:0;padding.end=!space.end?TITLE_PADDING:0;textSpace=space.value-padding.start-padding.end;fontFitResult=this.fontFit(text,textSpace);marginStart=0;}
|
||
return{id:styleId,fontSize:fontFitResult.fontSize,marginStart:marginStart,overflowing:overflowing,padding:padding};},setTitleStylesSoon:function(styles){debug('set title styles soon',styles);var key='setStyleTitlesSoon';this._titleStyles=styles;if(this.unresolved[key]){return this.unresolved[key];}
|
||
this.unresolved[key]=new Promise((resolve)=>{this.pending[key]=this.nextTick(()=>{var styles=this._titleStyles;var els=this.els.titles;[].forEach.call(els,(el,i)=>{if(!styles[i]){return debug('exit');}
|
||
this.setTitleStyle(el,styles[i]);});delete this._titleStyles;delete this.unresolved[key];delete this.pending[key];resolve();});});},setTitleStyle:function(el,style){debug('set title style',style);this.observerStop();if(this.ignoreDir){el.style.marginLeft=style.marginStart+'px';el.style.paddingLeft=style.padding.start+'px';el.style.paddingRight=style.padding.end+'px';}else{el.style.marginInlineStart=style.marginStart+'px';el.style.paddingInlineStart=style.padding.start+'px';el.style.paddingInlineEnd=style.padding.end+'px';}
|
||
el.style.fontSize=style.fontSize+'px';setStyleId(el,style.id);this.observerStart();},fontFit:function(text,space,opts={}){debug('font fit:',text,space,opts);var fontFitArgs={font:TITLE_FONT,min:opts.min||MINIMUM_FONT_SIZE_UNCENTERED,max:MAXIMUM_FONT_SIZE,text:text,space:space};return fontFit(fontFitArgs);},observerStart:function(){if(this.observing){return;}
|
||
this.observer.observe(this,{childList:true,attributes:true,subtree:true});this.observing=true;debug('observer started');},observerStop:function(){if(!this.observing){return;}
|
||
this.observer.disconnect();this.observing=false;debug('observer stopped');},onResize:function(e){debug('onResize',this._resizeThrottlingId);if(this._resizeThrottlingId!==null){return;}
|
||
this._resizeThrottlingId=window.requestAnimationFrame(()=>{this._resizeThrottlingId=null;this.runFontFitSoon();});},onMutation:function(mutations){debug('on mutation',mutations);if(!this.pending.runFontFitSoon){this.runFontFit();}},getTitleSpace:function(){var start=this.titleStart;var end=this.titleEnd;var space=this.getWidth()-start-end;var result={value:space,start:start,end:end};debug('get title space',result);return result;},getWidth:function(){var value=this.notFlush?this.clientWidth:window.innerWidth;debug('get width',value);return value;},triggerAction:function(){if(this.action){this.els.actionButton.click();}},onActionButtonClick:function(){debug('action button click');var config={detail:{type:this.action}};var e=new CustomEvent('action',config);setTimeout(()=>this.dispatchEvent(e));},getTitleMarginStart:function(){var start=this.titleStart;var end=this.titleEnd;var marginStart=end-start;debug('get title margin start',marginStart);return marginStart;},getButtonsBeforeTitle:function(){var children=this.children;var l=children.length;var els=[];for(var i=0;i<l;i++){var el=children[i];if(el.tagName==='H1'){break;}
|
||
if(!contributesToLayout(el)){continue;}
|
||
els.push(el);}
|
||
if(this.action){els.push(this.els.actionButton);}
|
||
return els;},getButtonsAfterTitle:function(){var children=this.children;var els=[];for(var i=children.length-1;i>=0;i--){var el=children[i];if(el.tagName==='H1'){break;}
|
||
if(!contributesToLayout(el)){continue;}
|
||
els.push(el);}
|
||
return els;},sumButtonWidths:function(buttons){var defaultWidth=50;var sum=buttons.reduce((prev,button)=>{var isStandardButton=button===this.els.actionButton;var width=isStandardButton?defaultWidth:button.clientWidth;return prev+width;},0);debug('sum button widths',buttons,sum);return sum;},attrs:{action:{get:function(){return this._action;},set:function(value){var action=KNOWN_ACTIONS[value];if(action===this._action){return;}
|
||
this.setAttr('action',action);this._action=action;}},titleStart:{get:function(){debug('get title-start');if('_titleStart'in this){return this._titleStart;}
|
||
var buttons=this.getButtonsBeforeTitle();var value=this.sumButtonWidths(buttons);debug('get title-start',buttons,value);return value;},set:function(value){debug('set title-start',value);value=parseInt(value,10);if(value===this._titleStart||isNaN(value)){return;}
|
||
this.setAttr('title-start',value);this._titleStart=value;debug('set');}},titleEnd:{get:function(){debug('get title-end');if('_titleEnd'in this){return this._titleEnd;}
|
||
var buttons=this.getButtonsAfterTitle();return this.sumButtonWidths(buttons);},set:function(value){debug('set title-end',value);value=parseInt(value,10);if(value===this._titleEnd||isNaN(value)){return;}
|
||
this.setAttr('title-end',value);this._titleEnd=value;}},noFontFit:{get:function(){return this._noFontFit||false;},set:function(value){debug('set no-font-fit',value);value=!!(value||value==='');if(value===this.noFontFit){return;}
|
||
this._noFontFit=value;if(value){this.setAttr('no-font-fit','');}
|
||
else{this.removeAttr('no-font-fit');}}},ignoreDir:{get:function(){return this._ignoreDir||false;},set:function(value){debug('set ignore-dir',value);value=!!(value||value==='');if(value===this.ignoreDir){return;}
|
||
this._ignoreDir=value;this.dirObserver=!value;if(value){this.setAttr('ignore-dir','');}
|
||
else{this.removeAttr('ignore-dir');}}}},template:`<div class="inner">
|
||
<button class="action-button">
|
||
<content select="[l10n-action]"></content>
|
||
</button>
|
||
<content></content>
|
||
</div>
|
||
|
||
<style>
|
||
|
||
:host {
|
||
display: block;
|
||
-moz-user-select: none;
|
||
|
||
--gaia-header-button-color:
|
||
var(--header-button-color,
|
||
var(--header-color,
|
||
var(--link-color,
|
||
inherit)));
|
||
}
|
||
|
||
/**
|
||
* [hidden]
|
||
*/
|
||
|
||
:host[hidden] {
|
||
display: none;
|
||
}
|
||
|
||
/** Reset
|
||
---------------------------------------------------------*/
|
||
|
||
::-moz-focus-inner { border: 0; }
|
||
|
||
/** Inner
|
||
---------------------------------------------------------*/
|
||
|
||
.inner {
|
||
display: flex;
|
||
min-height: 50px;
|
||
-moz-user-select: none;
|
||
|
||
background:
|
||
var(--header-background,
|
||
var(--background,
|
||
#fff));
|
||
}
|
||
|
||
/** Action Button
|
||
---------------------------------------------------------*/
|
||
|
||
/**
|
||
* 1. Hidden by default
|
||
*/
|
||
|
||
.action-button {
|
||
position: relative;
|
||
|
||
display: none; /* 1 */
|
||
width: 50px;
|
||
font-size: 30px;
|
||
margin: 0;
|
||
padding: 0;
|
||
border: 0;
|
||
outline: 0;
|
||
|
||
align-items: center;
|
||
background: none;
|
||
cursor: pointer;
|
||
transition: opacity 200ms 280ms;
|
||
color:
|
||
var(--header-action-button-color,
|
||
var(--header-icon-color,
|
||
var(--gaia-header-button-color)));
|
||
}
|
||
|
||
/**
|
||
* [action=back]
|
||
* [action=menu]
|
||
* [action=close]
|
||
*
|
||
* 1. For icon vertical-alignment
|
||
*/
|
||
|
||
[action=back] .action-button,
|
||
[action=menu] .action-button,
|
||
[action=close] .action-button {
|
||
display: flex; /* 1 */
|
||
}
|
||
|
||
/**
|
||
* :active
|
||
*/
|
||
|
||
.action-button:active {
|
||
transition: none;
|
||
opacity: 0.2;
|
||
}
|
||
|
||
/** Action Button Icon
|
||
---------------------------------------------------------*/
|
||
|
||
.action-button:before {
|
||
font-family: 'gaia-icons';
|
||
font-style: normal;
|
||
text-rendering: optimizeLegibility;
|
||
font-weight: 500;
|
||
}
|
||
|
||
[action=close] .action-button:before { content: 'close' }
|
||
[action=menu] .action-button:before { content: 'menu' }
|
||
|
||
[action=back]:-moz-dir(ltr) .action-button:before { content: 'left' }
|
||
[action=back]:-moz-dir(rtl) .action-button:before { content: 'right' }
|
||
|
||
/** Action Button Icon
|
||
---------------------------------------------------------*/
|
||
|
||
/**
|
||
* 1. To enable vertical alignment.
|
||
*/
|
||
|
||
.action-button:before {
|
||
display: block;
|
||
}
|
||
|
||
/** Action Button Text
|
||
---------------------------------------------------------*/
|
||
|
||
/**
|
||
* To provide custom localized content for
|
||
* the action-button, we allow the user
|
||
* to provide an element with the class
|
||
* .l10n-action. This node is then
|
||
* pulled inside the real action-button.
|
||
*
|
||
* Example:
|
||
*
|
||
* <gaia-header action="back">
|
||
* <span l10n-action aria-label="Back">Localized text</span>
|
||
* <h1>title</h1>
|
||
* </gaia-header>
|
||
*/
|
||
|
||
::content [l10n-action] {
|
||
position: absolute;
|
||
left: 0;
|
||
top: 0;
|
||
width: 100%;
|
||
height: 100%;
|
||
font-size: 0;
|
||
}
|
||
|
||
/** Title
|
||
---------------------------------------------------------*/
|
||
|
||
/**
|
||
* 1. Vertically center text. We can't use flexbox
|
||
* here as it breaks text-overflow ellipsis
|
||
* without an inner div.
|
||
*/
|
||
|
||
::content h1 {
|
||
flex: 1;
|
||
margin: 0;
|
||
padding: 0;
|
||
overflow: hidden;
|
||
|
||
white-space: nowrap;
|
||
text-overflow: ellipsis;
|
||
text-align: center;
|
||
line-height: 50px; /* 1 */
|
||
font-weight: 300;
|
||
font-style: italic;
|
||
font-size: 24px;
|
||
|
||
color:
|
||
var(--header-title-color,
|
||
var(--header-color,
|
||
var(--title-color,
|
||
var(--text-color,
|
||
inherit))));
|
||
}
|
||
|
||
/**
|
||
* [ignore-dir]
|
||
*
|
||
* When the <gaia-header> component has an [ignore-dir] attribute, header
|
||
* direction is forced to LTR but we still want the <h1> text to be reversed
|
||
* so that strings like '1 selected' become 'selected 1'.
|
||
*
|
||
* When we're happy for <gaia-header> to be fully RTL responsive we won't need
|
||
* these rules anymore, but this depends on all Gaia apps being ready.
|
||
*
|
||
* This should be safe to remove when bug 1179459 lands.
|
||
*/
|
||
|
||
:host[ignore-dir] {
|
||
direction: ltr;
|
||
}
|
||
|
||
:host[ignore-dir]:-moz-dir(rtl) h1 {
|
||
direction: rtl;
|
||
}
|
||
|
||
/** Buttons
|
||
---------------------------------------------------------*/
|
||
|
||
::content a,
|
||
::content button {
|
||
position: relative;
|
||
z-index: 1;
|
||
box-sizing: border-box;
|
||
display: flex;
|
||
width: auto;
|
||
height: auto;
|
||
min-width: 50px;
|
||
margin: 0;
|
||
padding: 0 10px;
|
||
outline: 0;
|
||
border: 0;
|
||
|
||
font-size: 14px;
|
||
line-height: 1;
|
||
align-items: center;
|
||
justify-content: center;
|
||
text-decoration: none;
|
||
text-align: center;
|
||
background: none;
|
||
border-radius: 0;
|
||
font-style: italic;
|
||
cursor: pointer;
|
||
transition: opacity 200ms 280ms;
|
||
color: var(--gaia-header-button-color);
|
||
}
|
||
|
||
/**
|
||
* :active
|
||
*/
|
||
|
||
::content a:active,
|
||
::content button:active {
|
||
transition: none;
|
||
opacity: 0.2;
|
||
}
|
||
|
||
/**
|
||
* [hidden]
|
||
*/
|
||
|
||
::content a[hidden],
|
||
::content button[hidden] {
|
||
display: none;
|
||
}
|
||
|
||
/**
|
||
* [disabled]
|
||
*/
|
||
|
||
::content a[disabled],
|
||
::content button[disabled] {
|
||
pointer-events: none;
|
||
color: var(--header-disabled-button-color);
|
||
}
|
||
|
||
/** Icon Buttons
|
||
---------------------------------------------------------*/
|
||
|
||
/**
|
||
* Icons are a different color to text
|
||
*/
|
||
|
||
::content .icon,
|
||
::content [data-icon] {
|
||
color:
|
||
var(--header-icon-color,
|
||
var(--gaia-header-button-color));
|
||
}
|
||
|
||
/**
|
||
* If users want their action button
|
||
* to be in the component's light-dom
|
||
* they can add an .action class
|
||
* to make it look like the
|
||
* shadow action button.
|
||
*/
|
||
|
||
::content .action {
|
||
color:
|
||
var(--header-action-button-color,
|
||
var(--header-icon-color,
|
||
var(--gaia-header-button-color)));
|
||
}
|
||
|
||
/**
|
||
* [data-icon]:empty
|
||
*
|
||
* Icon buttons with no textContent,
|
||
* should always be 50px.
|
||
*
|
||
* This is to prevent buttons being
|
||
* larger than they should be before
|
||
* icon-font has loaded.
|
||
*/
|
||
|
||
::content [data-icon]:empty {
|
||
width: 50px;
|
||
}
|
||
|
||
</style>`,nextTick:nextTick});function contributesToLayout(el){return el.localName!=='style'&&!el.hasAttribute('l10n-action');}
|
||
function setStyleId(el,id){el._styleId=id;}
|
||
function getStyleId(el){return el._styleId;}
|
||
function nextTick(fn){var cleared;Promise.resolve().then(()=>{if(!cleared){fn();}});return{clear:function(){cleared=true;}};}});})(typeof define=='function'&&define.amd?define:(function(n,w){'use strict';return typeof module=='object'?function(c){c(require,exports,module);}:function(c){var m={exports:{}};c(function(n){return w[n];},m.exports,m);w[n]=m.exports;};})('gaia-header',this));},{"font-fit":1,"gaia-component":2,"gaia-icons":3}]},{},[4])(4)});;'use strict';(function IconsHelper(exports){const ICON_CACHE_PERIOD=24*60*60*1000;const FETCH_XHR_TIMEOUT=10000;const DEBUG=false;var dataStore=null;function getDefaultIconSize(){var dpr=window.devicePixelRatio;return(dpr&&dpr>1)?142:84;}
|
||
function sizeIsNearer(size1,size2,targetSize){var delta1=Math.abs(targetSize-size1);var delta2=Math.abs(targetSize-size2);return(delta1<=delta2);}
|
||
function getIcon(uri,iconTargetSize,placeObj={},siteObj={}){var iconUrl=null;iconTargetSize=iconTargetSize*window.devicePixelRatio;if(siteObj.webManifestUrl&&siteObj.webManifest){iconUrl=getBestIconFromWebManifest(siteObj.webManifest,iconTargetSize);if(DEBUG&&iconUrl){console.log('Icon from Web Manifest');}}
|
||
if(!iconUrl&&siteObj.manifest&&siteObj.manifest.icons){iconUrl=getBestIconFromWebManifest({icons:_convertToWebManifestIcons(siteObj.manifest,siteObj.origin||siteObj.manifest.origin)},iconTargetSize);if(DEBUG&&iconUrl){console.log('Icon from Firefox App Manifest');}}
|
||
if(!iconUrl&&placeObj&&placeObj.icons){iconUrl=getBestIconFromMetaTags(placeObj.icons,iconTargetSize);if(DEBUG&&iconUrl){console.log('Icon from Meta tags');}}
|
||
if(!iconUrl){var a=document.createElement('a');a.href=uri;iconUrl=a.origin+'/favicon.ico';if(iconTargetSize){iconUrl+='#-moz-resolution='+iconTargetSize+','+iconTargetSize;}
|
||
DEBUG&&console.log('Icon from favicon.ico');}
|
||
return new Promise(resolve=>{resolve(iconUrl);});}
|
||
function getIconBlob(uri,iconTargetSize,placeObj={},siteObj={}){return new Promise((resolve,reject)=>{getIcon(uri,iconTargetSize,placeObj,siteObj).then(iconUrl=>{getStore().then(iconStore=>{iconStore.get(iconUrl).then(iconObj=>{if(!iconObj||!iconObj.timestamp||Date.now()-iconObj.timestamp>=ICON_CACHE_PERIOD){return fetchIconBlob(iconUrl).then(iconBlob=>{var img=document.createElement('img');var icon=new Icon(img,uri);icon.renderBlob(iconBlob,{size:iconTargetSize,onLoad:function(blob){var iconObj={blob:blob,originalUrl:iconUrl.toString(),timestamp:Date.now()};resolve(iconObj);iconStore.add(iconObj,iconUrl);},onerror:function(e){reject(`Failed to fetch icon ${iconUrl}`);}});}).catch(err=>{reject(`Failed to fetch icon ${iconUrl}: ${err}`);});}
|
||
return resolve(iconObj);}).catch(err=>{reject(`Failed to get icon from dataStore: ${err}`);});}).catch(err=>{reject(`Error opening the dataStore: ${err}`);});});});}
|
||
function setElementIcon(icon,targetSize){return getIconBlob(icon.bookmark.url,targetSize,icon.bookmark,icon.bookmark).then(iconObj=>{if(iconObj.blob){icon.icon=iconObj.blob;return Promise.resolve();}else if(icon.bookmark.icon){return fetchIconBlob(icon.bookmark.icon).then(iconBlob=>{icon.icon=iconBlob;return Promise.resolve();},Promise.reject.bind(Promise));}
|
||
return Promise.reject('No icon data found');},Promise.reject.bind(Promise));}
|
||
function getBestIconFromWebManifest(webManifest,iconSize){var icons=webManifest.icons;if(!icons){return null;}
|
||
var maxSize=10000;var bestSize=maxSize;var iconURL=null;iconSize=iconSize||getDefaultIconSize();icons.forEach((potentialIcon)=>{if(!iconURL){iconURL=potentialIcon.src;}
|
||
var sizes=Array.from(potentialIcon.sizes);var nearestSize=getNearestSize(sizes,iconSize,bestSize);if(nearestSize!==bestSize&&sizeIsNearer(nearestSize,bestSize,iconSize)){iconURL=potentialIcon.src;bestSize=nearestSize;}});return iconURL?iconURL:null;}
|
||
function _convertToWebManifestIcons(manifest,origin){return Object.keys(manifest.icons).map(function(size){var url=manifest.icons[size];var sizes=[size+'x'+size];url=url.indexOf('http')>-1?url:origin+url;return{src:new URL(url),sizes:sizes};});}
|
||
function getBestIconFromMetaTags(icons,iconSize){if(!icons){return null;}
|
||
iconSize=iconSize||getDefaultIconSize();var iconURL=null;var bestSize=10000;Object.keys(icons).forEach((uri)=>{var potentialIcon=icons[uri];if(!iconURL){iconURL=uri;}
|
||
var sizes=Array.from(potentialIcon.sizes);var nearestSize=getNearestSize(sizes,iconSize,bestSize);if(nearestSize!==bestSize&&sizeIsNearer(nearestSize,bestSize,iconSize)){iconURL=uri;bestSize=nearestSize;}
|
||
if(potentialIcon.rel==='apple-touch-icon'||potentialIcon.rel==='apple-touch-icon-precomposed'){var moreInfoUrl='https://developer.mozilla.org/en-US/'+'Apps/Build/Icon_implementation_for_apps#General_icons_for_web_apps';console.warn('Warning: The apple-touch icons are being used '+'as a fallback only. They will be deprecated in '+'the future. See '+moreInfoUrl);}});return iconURL||null;}
|
||
function getNearestSize(sizes,iconSize,bestSize){var bogusSize=10000;if(!bestSize){bestSize=bogusSize;}
|
||
var nearestSize=sizes.reduce(function(nearestSize,sizeString,idx){var size=widthFromSizeString(sizeString);if(isNaN(size)){return nearestSize;}
|
||
if(sizeIsNearer(size,nearestSize,iconSize)){return size;}else{return nearestSize;}},bestSize);return nearestSize===bogusSize?-1:nearestSize;}
|
||
function widthFromSizeString(size){size=size||'';var xIndex=size.indexOf('x');if(!xIndex){return NaN;}
|
||
return parseInt(size.substr(0,xIndex));}
|
||
function getStore(){return new Promise(resolve=>{if(dataStore){return resolve(dataStore);}
|
||
navigator.getDataStores('icons').then(stores=>{dataStore=stores[0];return resolve(dataStore);});});}
|
||
function clear(){return getStore().then(iconStore=>{iconStore.clear();});}
|
||
function fetchIcon(iconUrl){return new Promise((resolve,reject)=>{fetchIconBlob(iconUrl).then((iconBlob)=>{var img=document.createElement('img');img.src=URL.createObjectURL(iconBlob);img.onload=()=>{var iconSize=Math.max(img.naturalWidth,img.naturalHeight);resolve({blob:iconBlob,url:iconUrl,size:iconSize,timestamp:Date.now()});};img.onerror=()=>{reject(new Error(`Error while loading image.`));};}).catch((e)=>{reject(new Error(`Error while loading image: ${e}`));});});}
|
||
function fetchIconBlob(iconUrl){return new Promise((resolve,reject)=>{var xhr=new XMLHttpRequest({mozAnon:true,mozSystem:true});xhr.open('GET',iconUrl,true);xhr.responseType='blob';xhr.timeout=FETCH_XHR_TIMEOUT;xhr.send();xhr.onload=()=>{if(xhr.readyState===XMLHttpRequest.DONE&&xhr.status===200){var iconBlob=xhr.response;resolve(iconBlob);return;}
|
||
reject(new Error(`Got HTTP status ${xhr.status} trying to load ${iconUrl}.`));};xhr.onerror=xhr.ontimeout=()=>{reject(new Error(`Error while getting ${iconUrl}.`));};});}
|
||
exports.IconsHelper={getIcon:getIcon,getIconBlob:getIconBlob,setElementIcon:setElementIcon,getBestIconFromWebManifest:getBestIconFromWebManifest,getBestIconFromMetaTags:getBestIconFromMetaTags,fetchIcon:fetchIcon,fetchIconBlob:fetchIconBlob,get defaultIconSize(){return getDefaultIconSize();},clear:clear,getNearestSize:getNearestSize,};})(window);;(function(exports){'use strict';const MANIFEST_SETTING_NAME='latecustomization.url';const OPERATOR_INFO_SETTING_NAME='latecustomization.operatorInfo';const COMMS_CHANNEL='ftucomms';const ICON_SIZE=32;const IMG_PATH='style/images/late_customization';const ICON_INSTALLING_URL=`${IMG_PATH}/app_installing.svg`;const ICON_FAILED_URL=`${IMG_PATH}/app_install_unrecoverable.svg`;const ICON_DEFAULT_URL=`${IMG_PATH}/default_icon.svg`;function LateCustomizationPanel(){this.debug('LateCustomizationPanel ctor');}
|
||
LateCustomizationPanel.prototype={DEBUG:false,name:'LateCustomizationPanel',constructor:LateCustomizationPanel,_initialized:false,_downloadPossible:false,_customizationManifestUrl:'',get enabled(){return Boolean(this._customizationManifestUrl&&(this._operatorInfo||this._predefinedOperatorInfo));},get operatorInfo(){var info={};Object.assign(info,this._operatorInfo||this.getInfoFromMobileConnection(),this._predefinedOperatorInfo);return info;},get carrierName(){var info=this.operatorInfo;return info.carrier||info.operator;},get region(){return this.operatorInfo.region||'';},start:function(){window.addEventListener('hashchange',this);window.addEventListener('ftu-done',this);window.addEventListener('online',this);window.addEventListener('offline',this);this._operatorInfo=this.getInfoFromMobileConnection();this.waitForSettingValues().then((results)=>{var[url,predefinedInfo]=results;if(url){this._customizationManifestUrl=url;}
|
||
if(predefinedInfo){this._predefinedOperatorInfo=predefinedInfo;}
|
||
this.debug('start, resolved manifest url: '+this._customizationManifestUrl,' is enabled? '+this.enabled,' operatorInfo: ',this._operatorInfo);if(this.enabled){this.init();}else{this.debug('Not enabled; not initializing');if(!this._operatorInfo){this.waitForOperatorInfo().then((info)=>{if(!this._initialized&&this.enabled){this.init();}});}}}).catch(e=>{this.debug('start: didnt init, error from waitForSettingValues: ',e);});},init:function(){if(this._initialized||!this.enabled){return;}
|
||
this._initialized=true;this.appManifestUrls=[];this.render();Navigation.registerStep({hash:'#late_customization',afterStep:'firefox_accounts'});this.attemptToPopulateAppList();},postConnectMessage:function(message){navigator.mozApps.getSelf().onsuccess=function(evt){var app=evt.target.result;if(app.connect){app.connect(COMMS_CHANNEL).then(function onConnAccepted(ports){ports.forEach(function(port){port.postMessage(message);});},function onConnRejected(reason){console.error('Cannot connect to comms channel: ',reason);});}else{console.error('mozApps does not have a connect method. '+'Cannot connect to the comms channel.');}};},attemptToPopulateAppList:function(){this.debug('attemptToPopulateAppList, waiting to go online');var connected=this.whenUsableConnection();connected.then(()=>{this.debug('attemptToPopulateAppList, came online');return this.fetchAppsToInstall().then((appsMap)=>{if(!(this._appsToInstall&&this._appsToInstall.size)){this.debug('No apps in response from '+
|
||
this._customizationManifestUrl+', bailing');return;}
|
||
var urls=Array.from(this._appsToInstall.keys());var postMessageDetail={type:'late-customization-apps',urls:urls};this.postConnectMessage(postMessageDetail);this.updateAppList(this._appsToInstall);}).catch(err=>{console.warn('LateCustomizationPanel, error fetching customization '+'manifest from: '+this._customizationManifestUrl,err.message);});}).catch((e)=>{this.debug('No connection available in time to '+'fetch late customization manifest:',e);});return connected;},fetchAppsToInstall:function(){if(this._appsToInstall){return Promise.resolve(this._appsToInstall);}
|
||
return this.fetchManifest().then((manifestResp)=>{var appsMap=this.getAppsFromManifest(manifestResp);if(!appsMap){return Promise.reject('getAppsFromManifest didnt return appsMap');}
|
||
return(this._appsToInstall=appsMap);},(err)=>{console.warn('LateCustomization: ',err.message||err);});},waitForSettingValues:function(){var haveUrl,haveInfo;var lock=navigator.mozSettings.createLock();function getSetting(name){return new Promise((resolve,reject)=>{lock=(lock&&!lock.closed)?lock:navigator.mozSettings.createLock();var get=lock.get(name);get.addEventListener('success',(function(){resolve(get.result[name]);}));get.addEventListener('error',(function(){reject();}));});}
|
||
if(this._customizationManifestUrl){haveUrl=Promise.resolve(this._customizationManifestUrl);}else{haveUrl=getSetting(MANIFEST_SETTING_NAME);}
|
||
haveInfo=getSetting(OPERATOR_INFO_SETTING_NAME);return Promise.all([haveUrl,haveInfo]);},waitForOperatorInfo:function(){var info=this.getInfoFromMobileConnection();if(info){this._operatorInfo=info;return Promise.resolve(info);}
|
||
return new Promise((resolve,reject)=>{this._operatorInfoRequest={resolve:resolve,reject:reject};});},getInfoFromMobileConnection:function(){var connections=navigator.mozMobileConnections;if(connections){for(var i=0,conn;i<connections.length;i++){conn=connections[i];if(conn&&conn.voice&&conn.voice.connected){var operatorInfos=MobileOperator.userFacingInfo(conn);if(operatorInfos.operator){operatorInfos.mcc=conn.voice.network.mcc;operatorInfos.mnc=conn.voice.network.mnc;return operatorInfos;}}}}
|
||
return null;},getAppsFromManifest:function(data){var apps=new Map();var langs=navigator.languages;var list=data&&(data.apps||data.objects);if(!(list&&list.length)){return apps;}
|
||
list.filter((app)=>{return app.is_disabled!==true&&(new Set(app.device_types)).has('firefoxos');}).forEach((appData)=>{appData.manifestURL=appData.manifest_url;var appName='';langs.some(function tryLanguage(lang){if(this[lang]){appName=this[lang];return true;}},appData.name);appData.displayName=appName;this.debug('app data: ',appData.displayName,appData);apps.set(appData.manifestURL,appData);});return apps;},attemptInstalls:function(){this._installQueue=[];if(this._appsToInstall&&this._appsToInstall.size){var attempts=[];this._appsToInstall.forEach((appData,manifestURL)=>{if(appData.installState=='installed'||appData.installState=='pending'){this.debug('attemptInstalls: app install already underway: ',manifestURL,appData.installState);}else{attempts.push(this.enqueAppInstall(appData));}});return Promise.all(attempts);}else{return Promise.resolve();}},installApp:function(appData){this.debug('installApp: ',appData.manifestURL);return this.whenUsableConnection().then(()=>{return new Promise((resolve,reject)=>{var req=window.navigator.mozApps.install(appData.manifestURL);var onOutcome=(arg)=>{var selector=`li[data-manifest-url="${appData.manifestURL}"]`;var itemNode=this.appListNode.querySelector(selector);var manifestURL=req.result&&req.result.manifestURL;this.debug('appinstall DOMRequest outcome:',arg,req.result);if(req.error){delete appData.installState;itemNode&&itemNode.classList.add('failed');console.warn('Install error: ',req.error);}else if(req.result){appData.installState=req.result.installState;this.debug('Install success, app: ',manifestURL,appData.installState);}
|
||
itemNode&&itemNode.classList.remove('pending');resolve(req);};req.onsuccess=req.onerror=onOutcome;});}).catch(()=>{this.debug('Lost connection while attempting install of '+
|
||
appData.manifestURL);});},enqueAppInstall:function(app){var installQueue=this._installQueue;installQueue.push(app);this.debug('enqueAppInstall, queue: ',app.manifestURL);var currentInstallAttempt=this._installAttempt||Promise.resolve();return currentInstallAttempt.then(req=>{if(req&&req.error){console.warn('install error:',req.error);}
|
||
if(this._installQueue.length){this._installAttempt=this.installApp(this._installQueue.shift());}});},debug:function(){if(!this.DEBUG){return;}
|
||
var args=Array.from(arguments);args.unshift('LateCustomizationPanel');console.log.apply(console,args);},buildManifestUrl:function(url,infos={}){var apiURL=new URL(url);var params=new URLSearchParams(apiURL.search.substr(1));for(var key in infos){if(typeof infos[key]!=='undefined'){params.set(key,infos[key]);}}
|
||
apiURL.search=params.toString();return apiURL.href;},fetchManifest:function(){var url=this.buildManifestUrl(this._customizationManifestUrl,this.operatorInfo);if(!url){return Promise.reject(new Error('No manifest URL available'));}
|
||
this.debug('fetchManifest at: '+url);return new Promise((resolve,reject)=>{LazyLoader.getJSON(url,true).then((resp)=>{if(resp.objects){resolve(resp);}else{reject('No apps in reponse to: '+url);}}).catch(ex=>{reject(ex);});});},whenUsableConnection:function(){if(this._pendingNextOnline){return this._pendingNextOnline;}
|
||
var canDownload=navigator.onLine;if(canDownload){return Promise.resolve(true);}
|
||
return new Promise((resolve,reject)=>{this._nextOnlineRequest={resolve:resolve,reject:reject};});},handleEvent:function(evt){switch(evt.type){case'hashchange':if(this.enabled&&evt.target.location.hash==='#late_customization'){if(this._appsToInstall&&this._appsToInstall.size){this.onPanelShown();}else{Navigation.skipStep();}}
|
||
if(this._operatorInfoRequest){var info=this.getInfoFromMobileConnection();if(info){this._operatorInfo=info;this._operatorInfoRequest.resolve(info);this._operatorInfoRequest=null;}}
|
||
break;case'online':case'offline':if(navigator.onLine&&this._installQueue&&this._installQueue.length){return this.attemptInstalls();}
|
||
if(navigator.onLine&&this._nextOnlineRequest){this._nextOnlineRequest.resolve(true);}else if(this._nextOnlineRequest){this._nextOnlineRequest.reject(new Error('offline'));if(!this._appsToInstall){this.attemptToPopulateAppList();}}
|
||
this._nextOnlineRequest=null;break;case'ftu-done':if(this._operatorInfoRequest){this._operatorInfoRequest.reject(new Error('FTU complete with no viable operator'));this._operatorInfoRequest=null;}
|
||
if(this._nextOnlineRequest){this._nextOnlineRequest.reject(new Error('done before connection became available'));this._nextOnlineRequest=null;}
|
||
break;}},onPanelShown:function(){UIManager.mainTitle.setAttribute('data-l10n-id','late-customization');this.finalizeRender();this.attemptInstalls();},_createElement:function(name,options){var elm=document.createElement(name);if(options.id){elm.id=options.id;}
|
||
if(options.className){elm.className=options.className;}
|
||
if(options.dataset){for(var p in options.dataset){elm.dataset[p]=options.dataset[p];}}
|
||
if(options.attributes){for(var a in options.attributes){elm.setAttribute(a,options.attributes[a]);}}
|
||
if('textContent'in options){elm.textContent=options.textContent;}
|
||
return elm;},render:function(){var section=this.element=document.getElementById('late_customization');if(!section){section=this._createElement('section',{attributes:{role:'region'},id:'late_customization'});this.element=section;}
|
||
section.innerHTML=Sanitizer.escapeHTML`
|
||
<section id="late-customization-cando" class="content hidden">
|
||
<p id="late_customization-downloading-message"></p>
|
||
</section>
|
||
<section id="late-customization-nocando" class="content">
|
||
<p id="late_customization-download-later-message"></p>
|
||
<p id="late_customization-download-later-marketplace"></p>
|
||
</section>
|
||
<article data-type="list">
|
||
<ul id="late_customization-applist" class="hidden"></ul>
|
||
</article>`;function setTranslationById(domId,l10Id,attrs){var elem=section.querySelector('#'+domId);document.l10n.setAttributes(elem,l10Id,attrs);}
|
||
var carrierName=this.carrierName;if(carrierName){setTranslationById('late_customization-downloading-message','late-customization-downloading-message',{carrierName:this.carrierName});setTranslationById('late_customization-download-later-message','late-customization-download-later',{carrierName:this.carrierName});}else{setTranslationById('late_customization-downloading-message','late-customization-downloading-message-default');setTranslationById('late_customization-download-later-message','late-customization-download-later-default');}
|
||
setTranslationById('late_customization-download-later-marketplace','late-customization-download-later-marketplace',{carrierName:this.carrierName});if(!section.parentNode){document.querySelector('#activation-screen > article').appendChild(section);}
|
||
this.appListNode=document.querySelector('#late_customization-applist');},renderAppItem:function(appData){var itemNode=this._createElement('li',{dataset:{manifestUrl:appData.manifestURL},className:'pending'});var listNode=this.element.querySelector('#late_customization-applist');if(!listNode){this.debug('No element found to render app details into');return;}
|
||
itemNode.innerHTML=Sanitizer.escapeHTML`
|
||
<span class="icon"
|
||
style="background-image: url(${ICON_INSTALLING_URL})"></span>
|
||
<p dir="auto">${appData.displayName}</p>
|
||
`;listNode.appendChild(itemNode);var iconElem=itemNode.querySelector('.icon');this.getAppIconUrl(appData).then((iconUrl)=>{this.debug('getAppIconUrl returned:',iconUrl);var img=new Image();img.onload=()=>{iconElem.style.backgroundImage='url('+img.src+')';};img.onerror=()=>{iconElem.style.backgroundImage='url('+ICON_DEFAULT_URL+')';};img.src=iconUrl.href;});return itemNode;},getAppIconUrl:function(appData,iconSize=ICON_SIZE){var siteObj={};var manifest=appData;var manifestURL=appData.manifest_url;var origin=manifest.origin=new URL(manifestURL).origin;var hasIcons=(manifest.icons&&Object.keys(manifest.icons).length);if(!hasIcons){return Promise.resolve(new URL(ICON_DEFAULT_URL));}
|
||
siteObj.manifestURL=manifestURL;siteObj.manifest=manifest;var gotIcon=new Promise((resolve,reject)=>{IconsHelper.getIcon(origin,iconSize,null,siteObj).then((iconUrl)=>{this.debug('getIcon returned: ',iconUrl);resolve(iconUrl);}).catch(err=>{this.debug('Failed to load icon from: '+
|
||
JSON.stringify(appData.icons));console.warn('getIcon errback, err: ',err);resolve(new URL(ICON_FAILED_URL));});});return gotIcon;},finalizeRender:function(){var container=this.element;var appsMap=this._appsToInstall;var hasApps=(appsMap&&appsMap.size);var canDoElm=container.querySelector('#late-customization-cando');var noCanDoElm=container.querySelector('#late-customization-nocando');var appListElm=container.querySelector('#late_customization-applist');canDoElm.classList.toggle('hidden',!hasApps);appListElm.classList.toggle('hidden',!hasApps);noCanDoElm.classList.toggle('hidden',!!hasApps);},updateAppList:function(appsMap){var list=this.element.querySelector('#late_customization-applist');this.debug('updateAppList: ',appsMap);while(list.firstChild){list.firstChild.remove();}
|
||
if(appsMap&&appsMap.size){for(var appData of appsMap.values()){this.debug('calling renderAppItem with app: ',appData.manifestURL);this.renderAppItem(appData);}}
|
||
this.finalizeRender();}};exports.LateCustomizationPanel=LateCustomizationPanel;var panel;document.l10n.ready.then(()=>{panel=exports.lateCustomizationPanel=new LateCustomizationPanel();});window.addEventListener('ftu-setup',function onSetup(evt){window.removeEventListener('ftu-setup',onSetup);panel&&(panel.manager=evt.detail);panel&&panel.start();});})(window); |