Last active
April 27, 2021 12:32
-
-
Save FerraBraiZ/71f3305d662e20b54846408cf8b440cd to your computer and use it in GitHub Desktop.
JS utils
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* BOOLEAN UTILS */ | |
const isFunction = value => value && (Object.prototype.toString.call(value) === "[object Function]" || "function" === typeof value || value instanceof Function); | |
const isReady = (condition, fn) => { | |
if (document.readyState == "complete" && eval('typeof ' + condition) !== 'undefined' && condition) { | |
fn(); | |
} else { | |
setTimeout(function () { | |
isReady(condition, fn); | |
}, 100); | |
} | |
} | |
const isEmpty = (what) => { | |
/** | |
* Has own property. | |
* | |
* @type {Function} | |
*/ | |
let has = Object.prototype.hasOwnProperty; | |
/** | |
* To string. | |
* | |
* @type {Function} | |
*/ | |
let toString = Object.prototype.toString; | |
/** | |
* Test whether a whatue is "empty". | |
* | |
* @param {Mixed} what | |
* @return {Boolean} | |
*/ | |
// Null and Undefined... | |
if (what == null) return true; | |
// Booleans... | |
if ('boolean' == typeof what) return false; | |
// Numbers... | |
if ('number' == typeof what) return what === 0; | |
// Strings... | |
if ('string' == typeof what) return what.length === 0; | |
// Functions... | |
if ('function' == typeof what) return what.length === 0; | |
// Arrays... | |
if (Array.isArray(what)) return what.length === 0; | |
// Errors... | |
if (what instanceof Error) return what.message === ''; | |
// Objects... | |
if (what.toString == toString) { | |
switch (what.toString()) { | |
// Maps, Sets, Files and Errors... | |
case '[object File]': | |
case '[object Map]': | |
case '[object Set]': { | |
return what.size === 0 | |
} | |
// Plain objects... | |
case '[object Object]': { | |
for (let key in what) { | |
if (has.call(what, key)) return false | |
} | |
return true | |
} | |
} | |
} | |
// Anything else... | |
return false; | |
}; | |
const isJSON = (text) => { | |
let re = /^\{[\s\S]*\}$|^\[[\s\S]*\]$/; | |
if (typeof text !== 'string') { | |
return false; | |
} | |
if (!re.test(text)) { | |
return false; | |
} | |
try { | |
JSON.parse(text); | |
} catch (err) { | |
return false; | |
} | |
return true; | |
}; | |
const isMobile = function () { | |
let isMobile = false; | |
// device detection | |
if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(navigator.userAgent) || | |
/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(navigator.userAgent.substr(0, 4))) isMobile = true; | |
return isMobile; | |
}; | |
const isIPhone = function () { | |
return /iphone|ipad/ig.test(navigator.userAgent); | |
}; | |
const isLocalStorageSupported = function () { | |
let testKey = 'test', storage = window.sessionStorage; | |
try { | |
storage.setItem(testKey, '1'); | |
storage.removeItem(testKey); | |
return true; | |
} catch (error) { | |
return false; | |
} | |
}; | |
const isElementInViewport = function (el) { | |
if (isEmpty(el)) return; | |
try { | |
//special bonus for those using jQuery | |
if (typeof $ === "function" && el instanceof $) { | |
el = el[0]; | |
} | |
if (typeof el.getBoundingClientRect === 'function') { | |
let rect = el.getBoundingClientRect(); | |
return ( | |
(rect.top >= 0 || (rect.top < 0 && rect.height - rect.top >= 0)) && | |
rect.left >= 0 && | |
// !(rect.top == 0 && rect.right == 0 && rect.bottom == 0 && rect.left == 0 && rect.width == 0) && // Avoid itens on no pointview | |
rect.top <= (window.innerHeight || document.documentElement.clientHeight) | |
); | |
} | |
return; | |
} catch (e) { | |
return; | |
} | |
}; | |
const isValidCPF = function (CPF) { | |
let sum = 0; | |
let _module; | |
if (CPF == "00000000000") return false; | |
for (let i = 1; i <= 9; i++) sum = sum + parseInt(CPF.substring(i - 1, i)) * (11 - i); | |
_module = (sum * 10) % 11; | |
if ((_module == 10) || (_module == 11)) _module = 0; | |
if (_module != parseInt(CPF.substring(9, 10))) return false; | |
sum = 0; | |
for (let i = 1; i <= 10; i++) sum = sum + parseInt(CPF.substring(i - 1, i)) * (12 - i); | |
_module = (sum * 10) % 11; | |
if ((_module == 10) || (_module == 11)) _module = 0; | |
if (_module != parseInt(CPF.substring(10, 11))) return false; | |
return true; | |
}; | |
const isValidEmail = function (email) { | |
let re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; | |
return re.test(String(email).toLowerCase()); | |
}; | |
const isUrl = function (string) { | |
if (typeof string !== 'string') return false; | |
let match = string.match(/^(?:\w+:)?\/\/(\S+)$/); | |
if (!match) return false; | |
let everythingAfterProtocol = match[1]; | |
if (!everythingAfterProtocol) return false; | |
if (/^localhost[\:?\d]*(?:[^\:?\d]\S*)?$/.test(everythingAfterProtocol) || | |
/^[^\s\.]+\.\S{2,}$/.test(everythingAfterProtocol)) { | |
return true; | |
} | |
return false; | |
}; | |
const isUndefined = function (value) { | |
return typeof value === 'undefined' | |
}; | |
const isInArray = function (array, value) { | |
array = array || []; | |
let len = array.length; | |
let i; | |
for (i = 0; i < len; i++) { | |
if (array[i] === value) { | |
return true; | |
} | |
} | |
return false; | |
}; | |
/* BOOLEAN UTILS */ | |
/* FORM UTILS */ | |
const getThatFormData = ( formIdStringWithHash ) => { | |
const formData = {}; | |
for (const [key, value] of ( new FormData( document.querySelector(formIdStringWithHash) ) ).entries()) { | |
formData[key] = value; | |
} | |
return formData; | |
}; | |
const sendDataViaAjax = ( formData,formElement ) => { | |
return $.ajax({ | |
"url":formElement.attr('action'), | |
"type":formElement.attr('method'), | |
"data":formData | |
}); | |
}; | |
const validateForm = ( formData, mandatoryFields ) => { | |
if( isEmpty( formData )) return false; | |
if( isEmpty( mandatoryFields )) return false; | |
let errorsCount=0; | |
//console.log('errorsCount: ',errorsCount); | |
for (const [key, value] of Object.entries(formData)) { | |
if( mandatoryFields.includes(key) && isEmpty(value) ){ | |
console.log('key: ',key); | |
let htmlElement = $(`#${key}`); | |
htmlElement.css('border',"1px solid red"); | |
htmlElement.on('input focus select change blur',(evt)=>{ | |
//console.log( $(this) ); | |
htmlElement.css('border',"1px solid #ced4da"); | |
if(errorsCount > 0 ) errorsCount --; | |
//console.log('errorsCount: ',errorsCount); | |
}); | |
errorsCount ++; | |
//console.log('errorsCount: ',errorsCount); | |
} | |
} | |
return !errorsCount; | |
}; | |
const onFormSubmitEventSendData = ( formElementId, mandatoryFields ) => { | |
const formElement = $(`#${formElementId}`); | |
const formSelector = `#${formElement.attr('id')}`; | |
formElement.on('keypress', function (evt) { | |
if(evt.keyCode === 13) { | |
evt.preventDefault(); | |
return false; | |
} | |
}); | |
formElement.on('submit', function(evt){ | |
evt.preventDefault(); | |
const loading = $('.form-loading-svg'); | |
const submitBtn = $('.btn-submit-form'); | |
const errorMessage = $('#error-message'); | |
const loadingMessage = $('#loading-message'); | |
const formData = getThatFormData(formSelector); | |
const action = ((formData||{}).acao||''); | |
if( !isEmpty(action) && action=='add-project'){ | |
delete mandatoryFields[ mandatoryFields.indexOf("emails") ]; | |
delete mandatoryFields[ mandatoryFields.indexOf("acao") ]; | |
} | |
if( !isEmpty(action) && action=='add-user'){ | |
delete mandatoryFields[ mandatoryFields.indexOf("acao") ]; | |
} | |
if( !isEmpty(action) && action=='rm-user'){ | |
delete mandatoryFields[ mandatoryFields.indexOf("projetos") ]; | |
delete mandatoryFields[ mandatoryFields.indexOf("acao") ]; | |
} | |
if( !validateForm(formData,mandatoryFields)) { | |
errorMessage.removeClass('hide'); | |
swal('Erro!','Campos obrigatórios não preenchidos!', 'error'); | |
return; | |
} | |
loading.removeClass('hide'); | |
loadingMessage.removeClass('hide'); | |
submitBtn.addClass('hide'); | |
sendDataViaAjax( formData,formElement ).then( | |
function resolve(response){ | |
swal('Sucesso!', response, 'success') | |
.then( (result,formElement) => { | |
if (result.value) { | |
resetForm(formElement); | |
} | |
}) | |
}, | |
function reject(error){ | |
console.error(error.responseText); | |
swal('Erro!','Vishhh deu ruim truta!, confere o console do navegador ai', 'error'); | |
}) | |
.always( function(){ | |
loading.addClass('hide'); | |
loadingMessage.addClass('hide'); | |
submitBtn.removeClass('hide'); | |
}); | |
}); | |
}; | |
const resetForm = ( formElement ) => { | |
formElement[0].reset(); | |
}; | |
const transformObjectIntoFormData = (ObjectToFormData) => { | |
if (!ObjectToFormData instanceof Object) { | |
throw Error('ObjectToFormData is not an object, an Object is expected!'); | |
} | |
const formData = new FormData(); | |
for (const [key, value] of Object.entries(ObjectToFormData)) { | |
formData[key] = value; | |
} | |
return formData; | |
}; | |
/* FORM UTILS */ | |
/* DATE & TIME UTILS */ | |
const convertToRFC2822ISODate = (date) => { | |
const arr = date.split("/"); | |
return arr[2] + '-' + ("0" + arr[1]).slice(-2) + '-' + ("0" + arr[0]).slice(-2); | |
}; | |
const prepareDatePickerSingle = (selector, maxDate, minDate) => { | |
let dataDatePicker = { | |
"singleDatePicker": true, | |
"showDropdowns": true, | |
"minYear": 1901, | |
"maxYear": 2099, | |
"showWeekNumbers": true, | |
"showISOWeekNumbers": true, | |
locale: { | |
format: 'DD/MM/YYYY', | |
daysOfWeek: [ | |
"Dom", | |
"Seg", | |
"Ter", | |
"Qua", | |
"Qui", | |
"Sex", | |
"Sab" | |
], | |
monthNames: [ | |
"Janeiro", | |
"Fevereiro", | |
"Março", | |
"Abril", | |
"Maio", | |
"Junho", | |
"Julho", | |
"Agosto", | |
"Setembro", | |
"Outubro", | |
"Novembro", | |
"Dezembro" | |
] | |
} | |
}; | |
if (minDate !== false) { | |
dataDatePicker.minDate = minDate; | |
} | |
if (maxDate !== false) { | |
dataDatePicker.maxDate = maxDate; | |
} | |
return dataDatePicker; | |
}; | |
const dateToLocaleTimeString = (date, locale)=>{ | |
if (isEmpty(date)) date = ''; | |
if (isEmpty(locale)) locale = 'en'; | |
return new Date(date).toLocaleTimeString(locale,{ | |
hour: '2-digit', | |
minute: '2-digit', | |
hour12: true, | |
timezone: 'long' | |
}); | |
}; | |
/* DATE & TIME UTILS */ | |
/* STRING UTILS */ | |
const makeUFunabbreviated = (uf) => { | |
let estado = ''; | |
switch (uf) { | |
case 'AC': | |
estado = 'Acre - AC'; | |
break; | |
case 'AL': | |
estado = 'Alagoas - AL'; | |
break; | |
case 'AM': | |
estado = 'Amazonas - AM'; | |
break; | |
case 'AP': | |
estado = 'Amap\u00E1 - AP'; | |
break; | |
case 'BA': | |
estado = 'Bahia - BA'; | |
break; | |
case 'CE': | |
estado = 'Cear\u00E1 - CE'; | |
break; | |
case 'DF': | |
estado = 'Distrito Federal - DF'; | |
break; | |
case 'ES': | |
estado = 'Esp\u00EDrito Santo - ES'; | |
break; | |
case 'GO': | |
estado = 'Goi\u00E1s - GO'; | |
break; | |
case 'MA': | |
estado = 'Maranh\u00E3o - MA'; | |
break; | |
case 'MG': | |
estado = 'Minas Gerais - MG'; | |
break; | |
case 'MS': | |
estado = 'Mato Grosso do Sul - MS'; | |
break; | |
case 'MT': | |
estado = 'Mato Grosso - MT'; | |
break; | |
case 'PA': | |
estado = 'Par\u00E1 - PA'; | |
break; | |
case 'PB': | |
estado = 'Para\u00EDba - PB'; | |
break; | |
case 'PE': | |
estado = 'Pernambuco - PE'; | |
break; | |
case 'PI': | |
estado = 'Piau\u00ED - PI'; | |
break; | |
case 'PR': | |
estado = 'Paran\u00E1 - PR'; | |
break; | |
case 'RJ': | |
estado = 'Rio de Janeiro - RJ'; | |
break; | |
case 'RN': | |
estado = 'Rio Grande do Norte - RN'; | |
break; | |
case 'RS': | |
estado = 'Rio Grande do Sul - RS'; | |
break; | |
case 'RR': | |
estado = 'Roraima - RR'; | |
break; | |
case 'RO': | |
estado = 'Rond\u00F4nia - RO'; | |
break; | |
case 'SC': | |
estado = 'Santa Catarina - SC'; | |
break; | |
case 'SP': | |
estado = 'S\u00E3o Paulo - SP'; | |
break; | |
case 'TO': | |
estado = 'Tocantins - TO'; | |
break; | |
} | |
return estado; | |
}; | |
const capitalizeFirstLetter = function (string) { | |
return string.charAt(0).toUpperCase() + string.slice(1); | |
}; | |
const getLeroLero = async function () { | |
return await (await fetch("http://whatthecommit.com/index.txt", { | |
method: 'GET', | |
headers: ((new Headers()).append("Content-Type", "text/plain")), | |
mode: 'cors', | |
cache: 'default' | |
})).text(); | |
}; | |
const sortAlphabeticalyByTerm = function (arrayOrObjectToSort, term) { | |
return arrayOrObjectToSort.sort(function (a, b) { | |
if (a.term < b.term) return -1; | |
if (a.term > b.term) return 1; | |
return 0; | |
}); | |
}; | |
const findAndReplaceUrls = function (text) { | |
return (text || '').replace( | |
/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)(:[0-9]*)?((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%@\.\w_]*)#?(?:[\.\!\/\\\w]*))?)/gi, | |
function (ocur) { | |
let link = ocur; | |
if (!/^(http:\/\/|https:\/\/)/.test(link.toLowerCase())) link = '//' + link; | |
return '<a href="javascript:false;" onclick="window.open(\'' + link + '\')">' + ocur + '</a>'; | |
} | |
); | |
}; | |
/* STRING UTILS */ | |
/* COOKIE UTILS PROVIDED BY GOOGLE */ | |
const setCookie = function (cname, cvalue, exdays, cdomain) { | |
if (typeof exdays === 'undefined') { | |
exdays = new Date("Thu, 30 Sep 2027 00:00:01 GMT"); | |
} else if (typeof exdays === 'number') { | |
let days = exdays, t = exdays = new Date(); | |
t.setMilliseconds(t.getMilliseconds() + (days * 864e+5)); | |
} | |
return (document.cookie = [ | |
encodeURIComponent(cname), '=', String(cvalue), | |
exdays ? '; expires=' + exdays.toUTCString() : '', | |
'; path=/', | |
'; domain=' + cdomain || '.madeiramadeira.com.br', | |
].join('')); | |
}; | |
const getCookie = function (cname) { | |
let name = cname ? cname + "=" : ''; | |
let decodedCookie = decodeURIComponent(window.parent.document.cookie); | |
let ca = decodedCookie.split(';'); | |
let all = {}; | |
let hasAll = false; | |
for (let i = 0; i < ca.length; i++) { | |
let c = ca[i]; | |
while (c.charAt(0) == ' ') { | |
c = c.substring(1); | |
} | |
if (name === '') { | |
let indice = c.indexOf('='); | |
all[c.substr(0, indice)] = c.substr((indice + 1)); | |
hasAll = true; | |
continue; | |
} | |
if (c.indexOf(name) == 0) { | |
return c.substring(name.length, c.length); | |
} | |
} | |
return hasAll ? all : ""; | |
}; | |
/* COOKIE UTILS */ | |
/* LOCALSTORAGE UTILS */ | |
const setItemInLocalStorage = function (key, value) { | |
return window.localStorage.setItem(key, value); | |
}; | |
const getItemFromLocalStorage = function (key) { | |
return window.localStorage.getItem(key); | |
}; | |
const removeItemFromLocalStorage = function (key) { | |
return window.localStorage.removeItem(key); | |
}; | |
const clearAllLocalStorage = function () { | |
return window.localStorage.clear(); | |
}; | |
/* LOCALSTORAGE UTILS */ | |
/* HTML UTILS */ | |
const queryBySelector = function (selector) { | |
let element = document.querySelector(selector); | |
if (!element) { | |
throw Error('Function getBySelector: HTML ELEMENT WITH SELECTOR:' + selector + ' WAS NOT FOUND!'); | |
} | |
return element; | |
}; | |
const queryAllBySelector = function (selector) { | |
let elements = document.querySelectorAll(selector); | |
//console.log('elements: ',typeof elements,elements.__proto__,elements ); | |
if (!elements) { | |
throw Error('Function queryAllBySelector: HTML ELEMENTS WITH SELECTOR:' + selector + ' WERE NOT FOUND!'); | |
} | |
return Array.prototype.slice.call(elements); | |
}; | |
const toggleElementClass = (element,cssClass) => { | |
$(element).toggleClass(cssClass); | |
}; | |
const hideElement = (element) => { | |
$(element).addClass('hide'); | |
}; | |
const showElement = (element) => { | |
$(element).removeClass('hide'); | |
}; | |
const toggleElementProperty = (element,prop) => { | |
$(element).prop(prop,( $(element).prop(prop) === true ? false: true)); | |
}; | |
const wipeAllTableRowsExceptTitle = (tableName)=>{ | |
if( !(tableName instanceof jQuery ) ){ | |
throw Error("the parameter tableName MUST me an instance of jQuery, that is $(tableName)"); | |
} | |
$( tableName ).find("tr:gt(0)").remove(); | |
}; | |
const parseHTMLFromString = ( HTMLMessageTemplate ) => { | |
let parser; | |
try{ | |
//https://caniuse.com/#search=DOMParser | |
parser = new DOMParser(); | |
return parser.parseFromString( HTMLMessageTemplate , "text/html" ).querySelector("body").childNodes[0]; | |
} catch(error){ | |
console.error("DOMParser: ",error); | |
} | |
}; | |
/* HTML UTILS */ | |
const customSpeechSynthesis =()=>{ | |
const synth = window.speechSynthesis; | |
const utterThis = new SpeechSynthesisUtterance('hey there bitches'); | |
const voices = synth.getVoices(); | |
const voice = voices.find(voice => voice.name ==='Fiona'); | |
utterThis.voice = voice; | |
utterThis.pitch = 1.5; | |
utterThis.rate = 0.8; | |
synth.speak(utterThis); | |
/* | |
extracted from https://www.youtube.com/watch?v=qaxG4-b_VyI&t=536s | |
*/ | |
}; | |
const dataTableLanguage = { | |
"sEmptyTable": "Nenhum registro encontrado", | |
"sInfo": "Mostrando de _START_ até _END_ de _TOTAL_ Registros", | |
"sInfoEmpty": "Mostrando 0 até 0 de 0 Registros", | |
"sInfoFiltered": "", | |
"sInfoPostFix": "", | |
"sInfoThousands": ".", | |
"sLoadingRecords": "Carregando...", | |
"sProcessing": "Carregando...", | |
"sSearch": 'Busca:', | |
"sLengthMenu": 'Exibir: _MENU_', | |
"sZeroRecords": "Nenhum registro encontrado", | |
"oPaginate": { | |
"sNext": "Próximo", | |
"sPrevious": "Anterior", | |
"sFirst": "Primeiro", | |
"sLast": "Último" | |
}, | |
"oAria": { | |
"sSortAscending": ": Ordenação ascendente", | |
"sSortDescending": ": Ordenação descendente" | |
} | |
}; | |
const dd = ($data) => { | |
console.log($data); | |
debugger; | |
}; | |
const debounce = (func, wait, immediate) => { | |
let timeout; | |
return function () { | |
let context = this, args = arguments; | |
let later = function () { | |
timeout = null; | |
if (!immediate) func.apply(context, args); | |
}; | |
let callNow = immediate && !timeout; | |
clearTimeout(timeout); | |
timeout = setTimeout(later, wait); | |
if (callNow) func.apply(context, args); | |
}; | |
}; | |
const memorySizeOf = function (obj) { | |
let bytes = 0; | |
function sizeOf(obj) { | |
if (obj !== null && obj !== undefined) { | |
switch (typeof obj) { | |
case 'number': | |
bytes += 8; | |
break; | |
case 'string': | |
bytes += obj.length * 2; | |
break; | |
case 'boolean': | |
bytes += 4; | |
break; | |
case 'object': | |
let objClass = Object.prototype.toString.call(obj).slice(8, -1); | |
if (objClass === 'Object' || objClass === 'Array') { | |
for (let key in obj) { | |
if (!obj.hasOwnProperty(key)) continue; | |
sizeOf(obj[key]); | |
} | |
} else bytes += obj.toString().length * 2; | |
break; | |
} | |
} | |
return bytes; | |
}; | |
function formatByteSize(bytes) { | |
if (bytes < 1024) return bytes + " bytes"; | |
else if (bytes < 1048576) return (bytes / 1024).toFixed(3) + " KB"; | |
else if (bytes < 1073741824) return (bytes / 1048576).toFixed(3) + " MB"; | |
else return (bytes / 1073741824).toFixed(3) + " GB"; | |
}; | |
return formatByteSize(sizeOf(obj)); | |
}; | |
const getOsAndBrowserData = function () { | |
let module = { | |
options: [], | |
header: [navigator.platform, navigator.userAgent, navigator.appVersion, navigator.vendor, window.opera], | |
dataos: [ | |
{name: 'Windows Phone', value: 'Windows Phone', version: 'OS'}, | |
{name: 'Windows', value: 'Win', version: 'NT'}, | |
{name: 'iPhone', value: 'iPhone', version: 'OS'}, | |
{name: 'iPad', value: 'iPad', version: 'OS'}, | |
{name: 'Kindle', value: 'Silk', version: 'Silk'}, | |
{name: 'Android', value: 'Android', version: 'Android'}, | |
{name: 'PlayBook', value: 'PlayBook', version: 'OS'}, | |
{name: 'BlackBerry', value: 'BlackBerry', version: '/'}, | |
{name: 'Macintosh', value: 'Mac', version: 'OS X'}, | |
{name: 'Linux', value: 'Linux', version: 'rv'}, | |
{name: 'Palm', value: 'Palm', version: 'PalmOS'} | |
], | |
databrowser: [ | |
{name: 'Chrome', value: 'Chrome', version: 'Chrome'}, | |
{name: 'Firefox', value: 'Firefox', version: 'Firefox'}, | |
{name: 'Safari', value: 'Safari', version: 'Version'}, | |
{name: 'Internet Explorer', value: 'MSIE', version: 'MSIE'}, | |
{name: 'Opera', value: 'Opera', version: 'Opera'}, | |
{name: 'BlackBerry', value: 'CLDC', version: 'CLDC'}, | |
{name: 'Mozilla', value: 'Mozilla', version: 'Mozilla'} | |
], | |
init: function () { | |
let agent = this.header.join(' '), | |
os = this.matchItem(agent, this.dataos), | |
browser = this.matchItem(agent, this.databrowser); | |
return {os: os, browser: browser}; | |
}, | |
matchItem: function (string, data) { | |
let i = 0, | |
j = 0, | |
html = '', | |
regex, | |
regexv, | |
match, | |
matches, | |
version; | |
for (i = 0; i < data.length; i += 1) { | |
regex = new RegExp(data[i].value, 'i'); | |
match = regex.test(string); | |
if (match) { | |
regexv = new RegExp(data[i].version + '[- /:;]([\\d._]+)', 'i'); | |
matches = string.match(regexv); | |
version = ''; | |
if (matches) { | |
if (matches[1]) { | |
matches = matches[1]; | |
} | |
} | |
if (matches) { | |
matches = matches.split(/[._]+/); | |
for (j = 0; j < matches.length; j += 1) { | |
if (j === 0) { | |
version += matches[j] + '.'; | |
} else { | |
version += matches[j]; | |
} | |
} | |
} else { | |
version = '0'; | |
} | |
return { | |
name: data[i].name, | |
version: parseFloat(version) | |
}; | |
} | |
} | |
return {name: 'unknown', version: 0}; | |
} | |
}; | |
let e = module.init(); | |
let obj = { | |
"user_os_name": e.os.name | |
, "user_os_version": e.os.version | |
, "user_navigator_name": e.browser.name | |
, "user_navigator_version": e.browser.version | |
, "user_navigator_user_agent": navigator.userAgent | |
, "user_navigator_app_version": navigator.appVersion | |
, "user_navigator_platform": navigator.platform | |
, "user_navigator_vendor": navigator.vendor | |
}; | |
return obj; | |
}; | |
const createModal = (response) => { | |
}; | |
const laravel_jquery_csrf_token = ()=>{ | |
if(! isFunction( window.$ )|| !isFunction( window.jQuery ) ) return; | |
$.ajaxSetup({ | |
headers: { | |
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') | |
} | |
}); | |
}; | |
const $loading = { | |
loader: $('.loading'), | |
hide(milliseconds) { | |
this.loader.fadeOut(milliseconds); | |
}, | |
show(milliseconds) { | |
this.loader.fadeIn(milliseconds); | |
} | |
}; | |
const httpRequest = ( cfg )=>{ | |
//USAGE | |
// httpRequest({ | |
// method: "POST/GET", | |
// payload: "YOUR PAYLOAD STRING BASED", | |
// url: "https://www.google.com", | |
// headers: [ | |
// {"contentType": "text/plain"}, | |
// {"Cache-Control": "no-cache"}, | |
// {"Accept": "*"} | |
// {"Authorization":"Basic XXXXXXXXXXXXXXX"}, | |
// {"Access-Control-Allow-Origin": "*"}, | |
// {"Access-Control-Allow-Methods": "*"}, | |
// {"Access-Control-Allow-Credentials": "true"}, | |
// {"Access-Control-Allow-Headers": "Content-Length Origin Accept Access-Control-Allow-Headers Authorization X-Requested-With Client-Security-Token Accept-Encoding"}, | |
// ], | |
// beforeSend: function() | |
// { | |
// console.time("http request elapsed: "); | |
// //DO SOMETHING BEFORE THE AJAX CALL | |
// }, | |
// done: function( completed ) success or error, u have to handle the response | |
// { | |
// console.timeEnd("http request elapsed: "); | |
// //DO SOMETHING WHEN THE AJAX CALL FINISHES | |
// }, | |
// error: function( error ) // 400 or 500 | |
// { | |
// //DO SOMETHING IF THE AJAX CALL FAIL | |
// } | |
// success: function( error ) // 200 | |
// { | |
// //DO SOMETHING IF THE AJAX CALL FAIL | |
// } | |
// }); | |
try{ | |
if( navigator && !navigator.onLine ) | |
{ | |
throw Error("No network detected, please verify your internet conection and try again."); | |
} | |
if( typeof(cfg) !== "object" || Object.keys(cfg).length === 0 ) | |
{ | |
throw Error("The configuration object provided is either MALFORMED or EMPY, please use the example below: \n" + | |
"httpRequest({\n" + | |
" method: POST OR GET,\n" + | |
" payload: THE DATA TO BE SENT, EITHER JSON OR PLAIN TEXT,\n" + | |
" url: URL OR URI,\n" + | |
" headers: [],\n" + | |
" beforeSend: function(){ \n" + | |
" YOUR CODE GOES HERE \n" + | |
" }, \n" + | |
" error: function( $error ){ \n" + | |
" YOUR CODE GOES HERE \n" + | |
" }, \n" + | |
" success: function( $error ){ \n" + | |
" YOUR CODE GOES HERE \n" + | |
" }, \n" + | |
" done: function( $data ){ \n" + | |
" YOUR CODE GOES HERE \n" + | |
" })"); | |
} | |
if( cfg.beforeSend && typeof(cfg.beforeSend) === "function" ) | |
{ | |
cfg.beforeSend(); | |
} | |
if( !cfg.hasOwnProperty('method') ) | |
{ | |
throw Error('The configuration object expects the property "method" to be of type string'); | |
} | |
if( cfg.method !== "POST" && cfg.method !== "GET" ) | |
{ | |
throw Error('Only a "POST" or "GET" requests are supported!'); | |
} | |
if( !cfg.hasOwnProperty('url') || cfg.url ==="" ) | |
{ | |
throw Error('The configuration object expects the property "url" to be an NON-EMPTY STRING'); | |
} | |
if( (!cfg.payload || cfg.payload === "") && cfg.method == "POST" ) | |
{ | |
throw Error('The configuration object expects the "payload" property to be an NON-EMPTY STRING for POST requests!'); | |
} | |
if( cfg.success && typeof(cfg.success) !== "function") | |
{ | |
throw Error('Configuration Object property "success" MUST be of type FUNCTION()'); | |
} | |
if( cfg.error && typeof(cfg.error) !== "function") | |
{ | |
throw Error('Configuration Object property "error" MUST be of type FUNCTION()'); | |
} | |
if( cfg.fail && typeof(cfg.fail) !== "function") | |
{ | |
throw Error('Configuration Object property "error" MUST be of type FUNCTION()'); | |
} | |
if( cfg.done && typeof(cfg.done) !== "function") | |
{ | |
throw Error('Configuration Object property "done" MUST be of type FUNCTION()'); | |
} | |
const ajax = typeof( window.ActiveXObject ) !== "undefined" ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest(); | |
ajax.onreadystatechange = function(){ | |
if( ajax.readyState === 4 ) | |
{ | |
if( ajax.status === 200 || ajax.status >= 300 ) | |
{ | |
if (cfg.success) | |
{ | |
cfg.success({ status: ajax.status, response: ajax.responseText }); | |
} | |
} | |
if( ajax.status >= 400 ) | |
{ | |
if( cfg.fail ) | |
{ | |
cfg.fail({ status: ajax.status, response: ajax.responseText }); | |
} | |
} | |
if( cfg.done ) | |
{ | |
cfg.done({ status: ajax.status, response: ajax.responseText }); | |
} | |
} | |
}; | |
ajax.onerror = function( onerror ){ | |
if( ajax.readyState == 4 ) | |
{ | |
console.error('httpRequest.onerror,readyState 4: ', ajax.responseText); | |
} | |
else if (ajax.readyState == 0) | |
{ | |
// Network error (i.e. connection refused, access denied due to CORS, etc.) | |
console.error('httpRequest.onerror, Network error (i.e. connection refused, access denied due to CORS, etc. ReadyState 0: ', ajax.responseText); | |
} | |
else { | |
console.error('httpRequest.onerror, Erro desconhecido.',ajax.responseText); | |
} | |
if( cfg.error ) | |
{ | |
cfg.error({ status: ajax.status, response: ajax.responseText }); | |
} | |
}; | |
if( Array.isArray(cfg.headers) && cfg.headers.length > 0 ) | |
{ | |
cfg.headers.map( function(index,value){ | |
if( (typeof(index) !='undefined' && index != "") && ( typeof(value) !=='undefined' && value != "" ) ) | |
{ | |
ajax.setRequestHeader(index, value); | |
} | |
}); | |
} | |
if( cfg.timeout && cfg.timeout !== "" ) | |
{ | |
ajax.timeout = cfg.timeout; | |
} | |
if( cfg.method.toUpperCase() === "POST" ) | |
{ | |
ajax.open("POST", cfg.url, true); | |
ajax.send(data); | |
return ajax; | |
} | |
if( cfg.method.toUpperCase() === "GET" ) | |
{ | |
if( cfg.payload ) | |
{ | |
let query = urlEncodeObject( cfg.payload ); | |
if( query && query.length > 0 ) cfg.url +'?'+query; | |
} | |
ajax.open("GET", cfg.url, true); | |
ajax.send(); | |
return ajax; | |
} | |
} | |
catch(error){ | |
console.error("Error: Unable to make the http request"); | |
console.trace(error); | |
return false; | |
}finally{} | |
}; | |
const jQuery_ajax_promise_when_then_stub = ()=>{ | |
let promisedData = function() { | |
let deferredQuery = $.Deferred(); | |
$.ajax({ | |
type: "GET", | |
crossDomain: true, | |
dataType: "json", | |
cache: false, | |
data: "data=data", | |
url: Url, | |
success: function( result ) | |
{ | |
deferredQuery.resolve( result ); | |
}, | |
error:function( result ) | |
{ | |
deferredQuery.reject( result ); | |
} | |
}); | |
return deferredQuery.promise(); | |
}; | |
$.when( promisedData() ).then( | |
function resolved( resolved ) { | |
console.log( 'Resolved: ', resolved ); | |
}, | |
function rejected( rejected ) { | |
console.log( 'Rejected: ', rejected ); | |
} | |
).catch( | |
function error( error ) { | |
console.log( 'Error: ', error ); | |
} | |
); | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment