VulpesOS/assets/webapps/sms.gaiamobile.org/views/shared/js/utils.js
OverSu b38dea0597 Publish Vulpes Preview 15 sources for desktop, Android and Tundra
Share Gaia assets and adapters, keep private profiles and development documents local, and update both public READMEs.
2026-09-30 23:13:03 +02:00

55 lines
No EOL
13 KiB
JavaScript

;;;(function(exports){'use strict';var rdashes=/-(.)/g;var rescape=/[.?*+^$[\]\\(){}|-]/g;var rparams=/([^?=&]+)(?:=([^&]*))?/g;var rnondialablechars=/[^,#+\*\d]/g;var rmail=/[\w-]+@[\w\-]/;var Utils={date:{shared:new Date(),formatters:{'time':{options:{hour:'numeric',minute:'numeric',},formatter:null},'full':{options:{month:'2-digit',day:'2-digit',year:'numeric',},formatter:null},'full-wt':{options:{month:'2-digit',day:'2-digit',year:'numeric',hour:'numeric',minute:'numeric',},formatter:null},'day':{options:{weekday:'long',},formatter:null},'day-wt':{options:{weekday:'long',hour:'numeric',minute:'numeric',},formatter:null},},},escapeRegex:function ut_escapeRegex(str){if(typeof str!=='string'){return'';}
return str.replace(rescape,'\\$&');},getFormattedHour:function ut_getFormattedHour(time){this.date.shared.setTime(+time);return this._getFormatter('time',false).format(this.date.shared);},getDayDate:function re_getDayDate(time){this.date.shared.setTime(+time);this.date.shared.setHours(0,0,0,0);return this.date.shared.getTime();},resetDateFormatters:function ut_resetDateFormatters(){for(var type in this.date.formatters){this.date.formatters[type].formatter=null;}},_getFormatter:function ut_getFormatter(type,withTime){if(withTime){type+='-wt';}
if(!this.date.formatters[type].formatter){var options=Object.assign({},this.date.formatters[type].options);if(options.hour){options.hour12=navigator.mozHour12;}
this.date.formatters[type].formatter=Intl.DateTimeFormat(navigator.languages,options);}
return this.date.formatters[type].formatter;},setHeaderDate:function ut_setHeaderDate({time,element,withTime}){var formatter;var today=Utils.getDayDate(Date.now());var otherDay=Utils.getDayDate(time);var dayDiff=(today-otherDay)/86400000;this.date.shared.setTime(+time);if(isNaN(dayDiff)){element.setAttribute('data-l10n-id','incorrectDate');return;}
if(dayDiff<0){formatter=this._getFormatter('full',withTime);element.removeAttribute('data-l10n-id');element.textContent=formatter.format(this.date.shared);return;}
if(dayDiff===0){if(withTime){document.l10n.setAttributes(element,'todayWithTime',{time:this.getFormattedHour(this.date.shared)});}else{element.setAttribute('data-l10n-id','today');}}else if(dayDiff===1){if(withTime){document.l10n.setAttributes(element,'yesterdayWithTime',{time:this.getFormattedHour(this.date.shared)});}else{element.setAttribute('data-l10n-id','yesterday');}}else if(dayDiff<6){formatter=this._getFormatter('day',withTime);element.removeAttribute('data-l10n-id');element.textContent=formatter.format(this.date.shared);}else{formatter=this._getFormatter('full',withTime);element.removeAttribute('data-l10n-id');element.textContent=formatter.format(this.date.shared);}},getContactDetails:function ut_getContactDetails(number,contacts,include){var details={};include=include||{};function updateDetails(contact){var name,phone,i,length,subscriber,org;name=contact.name[0];org=contact.org&&contact.org[0];length=contact.tel?contact.tel.length:0;subscriber=number.length>7?number.substr(-8):number;for(i=0;i<length;i++){if(contact.tel[i].value.indexOf(subscriber)!==-1){phone=contact.tel[i];break;}}
details.isContact=true;if(include.photoURL){var photo=ContactPhotoHelper.getThumbnail(contact);if(photo){details.photoURL=window.URL.createObjectURL(photo);}}
details.name=name;details.org=details.org||org;}
if(!contacts||(Array.isArray(contacts)&&contacts.length===0)){details.title='';}else if(!Array.isArray(contacts)){updateDetails(contacts);details.title=details.name||details.org;}else{for(var i=0,l=contacts.length;i<l;i++){updateDetails(contacts[i]);if(details.name){break;}}
details.title=details.name||details.org;}
return details;},getPhoneDetails:function ut_getPhoneDetails(input,tels){var length=tels.length;var hasUniqueCarriers=true;var hasUniqueTypes=true;var found,tel,type,carrier;for(var i=0;i<length;i++){tel=tels[i];if(tel.value&&Utils.probablyMatches(tel.value,input)){found=tel;}
if(carrier&&carrier===tel.carrier){hasUniqueCarriers=false;}
if(type&&type===tel.type[0]){hasUniqueTypes=false;}
carrier=tel.carrier;type=(tel.type&&tel.type[0])||'';}
if(!found){return null;}
return{type:(found.type&&found.type[0])||'',carrier:hasUniqueCarriers||hasUniqueTypes?found.carrier:'',number:found.value};},removeNonDialables:function ut_removeNonDialables(input){return input.replace(rnondialablechars,'');},probablyMatches:function ut_probablyMatches(a,b){var service=navigator.mozPhoneNumberService;if(typeof a!=='string'||typeof b!=='string'){return false;}
if(Settings.supportEmailRecipient&&Utils.isEmailAddress(a)&&Utils.isEmailAddress(b)){return a===b;}
if(service&&service.normalize){a=service.normalize(a);b=service.normalize(b);}else{a=Utils.removeNonDialables(a);b=Utils.removeNonDialables(b);}
return a===b||a.slice(-7)===b.slice(-7);},multiRecipientMatch:function ut_multiRecipientMatch(a,b){a=[].concat(a);b=[].concat(b);var blen=b.length;if(a.length!==blen){return false;}
return a.every(function(number){for(var i=0;i<blen;i++){if(Utils.probablyMatches(number,b[i])){return true;}}});},getResizedImgBlob:function ut_getResizedImgBlob(blob,limit,callback){var defaultLimit=295*1024;if(typeof limit==='function'){callback=limit;limit=defaultLimit;}
limit=limit===0?defaultLimit:Math.min(limit,defaultLimit);if(blob.size<limit){setTimeout(function blobCb(){callback(blob);});return;}
var ratio=Math.sqrt(blob.size/limit);Utils._resizeImageBlobWithRatio({blob:blob,limit:limit,ratio:ratio,callback:callback});},getSizeForL10n:function ut_getSizeForL10n(size){var sizeKB=size/1024;var sizeMB=sizeKB/1024;if(size<1000){return{l10nId:'attachmentSizeB',l10nArgs:{n:size}};}else if(sizeKB<1000){return{l10nId:'attachmentSizeKB',l10nArgs:{n:sizeKB.toFixed(1)}};}
return{l10nId:'attachmentSizeMB',l10nArgs:{n:sizeMB.toFixed(1)}};},_resizeImageBlobWithRatio:function ut_resizeImageBlobWithRatio(obj){var blob=obj.blob;var callback=obj.callback;var limit=obj.limit;var ratio=Math.ceil(obj.ratio);var qualities=[0.65,0.5,0.25];var sampleSize=1;var sampleSizeHash='';if(blob.size<limit||ratio<=1){setTimeout(function blobCb(){callback(blob);});return;}
if(blob.type==='image/jpeg'){if(ratio>=8){sampleSize=8;}else{sampleSize=ratio=Utils.getClosestSampleSize(ratio);}
sampleSizeHash='#-moz-samplesize='+sampleSize;}
var img=document.createElement('img');var url=window.URL.createObjectURL(blob);img.src=url+sampleSizeHash;img.onload=function onBlobLoaded(){window.URL.revokeObjectURL(url);var targetWidth=img.width*sampleSize/ratio;var targetHeight=img.height*sampleSize/ratio;var canvas=document.createElement('canvas');canvas.width=targetWidth;canvas.height=targetHeight;var context=canvas.getContext('2d',{willReadFrequently:true});context.drawImage(img,0,0,targetWidth,targetHeight);img.src='';var level=0;function cleanup(){canvas.width=canvas.height=0;canvas=null;}
function ensureSizeLimit(resizedBlob){if(resizedBlob.size<limit){cleanup();setTimeout(callback.bind(null,resizedBlob));}else{resizedBlob=null;if(level<qualities.length){canvas.toBlob(ensureSizeLimit,'image/jpeg',qualities[level++]);}else{cleanup();setTimeout(Utils._resizeImageBlobWithRatio.bind(Utils,{blob:blob,limit:limit,ratio:ratio*2,callback:callback}));}}}
canvas.toBlob(ensureSizeLimit,blob.type);};},getClosestSampleSize:function ut_getClosestSampleSize(ratio){if(ratio>=8){return 8;}
if(ratio>=4){return 4;}
if(ratio>=2){return 2;}
return 1;},camelCase:function ut_camelCase(str){return str.replace(rdashes,function replacer(str,p1){return p1.toUpperCase();});},typeFromMimeType:function ut_typeFromMimeType(mime){var MAX_MIME_TYPE_LENGTH=256;if(typeof mime!=='string'||mime.length>MAX_MIME_TYPE_LENGTH){return null;}
var index=mime.indexOf('/');if(index===-1){return null;}
var mainPart=mime.slice(0,index);var secondPart=mime.substr(index+1).toLowerCase();switch(mainPart){case'image':return'img';case'text':if(secondPart.indexOf('vcard')!==-1){return'vcard';}
if(secondPart!=='plain'){return'ref';}
return mainPart;case'video':case'audio':case'application':return mainPart;default:return null;}},params:function(input){var parsed={};input.replace(rparams,function($0,$1,$2){if($2==='true'){$2=true;}else if($2==='false'){$2=false;}
parsed[$1]=$2;});return parsed;},url(base,params){if(base.indexOf('?')===-1){base+='?';}else{base+='&';}
for(var key in params){if(params[key]==null){continue;}
base+=encodeURIComponent(key)+'='+
encodeURIComponent(params[key])+'&';}
return base.slice(0,-1);},basicContact:function(number,records){var record;if(Array.isArray(records)){if(records.length>0){record=records[0];}}else if(records!==null){record=records;}
if(!record&&!number){return;}
var telLength=(record&&record.tel)?record.tel.length:0;var tel;for(var i=0;i<telLength;i++){if(record.tel[i].value===number){tel=record.tel[i];break;}}
if(!tel){tel={type:[''],value:number,carrier:''};}
var details=Utils.getContactDetails(tel,record);var info=Utils.getDisplayObject(details.title||null,tel);return info;},getDisplayObject:function(theTitle,tel){var number=tel.value;var type=tel.type&&tel.type.length?tel.type[0]:'';var data={name:theTitle||number,number:number,type:type,carrier:tel.carrier||''};if(Settings.supportEmailRecipient){data.email=number;data.emailHTML='';}
return data;},asyncLoadRevokeURL:function(url){setTimeout(function(){var image=new Image();image.src=url;image.onload=image.onerror=function revokePhotoURL(){window.URL.revokeObjectURL(this.src);};});},isEmailAddress:function(email){return rmail.test(email);},closeNotificationsForThread:function(threadId){var targetTag='threadId:'+threadId;return Notification.get({tag:targetTag}).then(function onSuccess(notifications){for(var i=0;i<notifications.length;i++){notifications[i].close();}}).catch(function onError(reason){console.error('Notification.get(tag: '+targetTag+'): ',reason);});},debounce:function(func,waitTime){var timeout,args,context;var executeLater=function(){func.apply(context,args);timeout=context=args=null;};return function(){context=this;args=arguments;if(timeout){clearTimeout(timeout);}
timeout=setTimeout(executeLater,waitTime);};},throttle:function(func,delay=300,options={}){var timeout=null;var previous=0;var preventFirstCall=!!options.preventFirstCall;var preventLastCall=!!options.preventLastCall;if(typeof func!=='function'){throw new Error('func must be a Function');}
if(typeof delay!=='number'||delay<0){throw new Error('delay must be a positive number');}
return function(...args){var now=Date.now();if(!previous&&preventFirstCall){previous=now;}
var remaining=delay-(now-previous);if(remaining<=0){if(timeout){clearTimeout(timeout);timeout=null;}
previous=now;func.apply(this,args);}else if(!timeout&&!preventLastCall){timeout=setTimeout(()=>{previous=preventFirstCall?0:Date.now();timeout=null;func.apply(this,args);},remaining);}};},alert:function(message,title){var deferred=this.Promise.defer();var dialog=new Dialog({title:title||'modal-dialog-default-title',body:message,options:{cancel:{text:'modal-dialog-ok-button',method:deferred.resolve}}});dialog.show();return deferred.promise;},confirm:function(message,title,confirmOptions){var confirmButtonText=confirmOptions&&confirmOptions.text||'modal-dialog-ok-button';var confirmButtonClassName=confirmOptions&&confirmOptions.className||'recommend';var deferred=this.Promise.defer();var dialog=new Dialog({title:title||'modal-dialog-default-title',body:message,options:{cancel:{text:'modal-dialog-cancel-button',method:deferred.reject},confirm:{text:confirmButtonText,className:confirmButtonClassName,method:deferred.resolve}}});dialog.show();return deferred.promise;},Promise:{defer:function(){var deferred={};deferred.promise=new Promise(function(resolve,reject){deferred.resolve=resolve;deferred.reject=reject;});return deferred;},async:function(generatorFunction){return function asyncGenerator(){var generator=generatorFunction.apply(this,arguments);function handle(result){if(result.done){return Promise.resolve(result.value);}
return Promise.resolve(result.value).then((result)=>handle(generator.next(result)),(error)=>handle(generator.throw(error)));}
try{return handle(generator.next());}catch(error){return Promise.reject(error);}};}},getSimNameByIccId(iccId){var index=Settings.getServiceIdByIccId(iccId);if(index===null){return Promise.resolve('');}
return document.l10n.formatValue('sim-id-label',{id:index+1});},initializeShimHost(appInstanceId){var shimHostIframe=document.querySelector('.shim-host');var promise=typeof shimHostIframe.contentWindow.bootstrap==='function'?Promise.resolve():new Promise((resolve)=>{shimHostIframe.addEventListener('load',function onLoad(){shimHostIframe.removeEventListener('load',onLoad);resolve();});});return promise.then(()=>{window.mozSetMessageHandler=function(type,handler){navigator.mozSetMessageHandler(type,(request)=>handler(request));};shimHostIframe.contentWindow.bootstrap(appInstanceId);});},onceDocumentIsVisible(){if(!document.hidden){return Promise.resolve();}
var defer=this.Promise.defer();document.addEventListener('visibilitychange',function waitVisibility(){document.removeEventListener('visibilitychange',waitVisibility);defer.resolve();});return defer.promise;}};exports.Utils=Utils;}(this));