-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtdp.min.js
6 lines (6 loc) · 20.1 KB
/
tdp.min.js
1
2
3
4
5
6
/*
TDP - Tiny Dialogue Plugin
Alexej Sidorenko, 2k16-19
https://github.com/fra-iesus/tdp
*/
!function(t){var e=function(e,a,i){var n=this;if(this._defaults={animationSpeed:"slow",animationFastSpeed:"fast",errorMessageEmptyInput:"Field is mandatory",scrollingElement:"body",scrolledElement:"body",scrollToErrorDuration:2e3,scrollToErrorEnabled:!0,scrollToErrorOffset:0,dialogShowDuration:500,dialogCloseDuration:500,dialogAutoclose:!1,validationOkElement:"span.tdp-vld-ok",validationOkText:"✓",prevalidation:!0,notEmptyAsValidated:!0,validationOkShow:function(t){return t.fadeIn(n.options("animationSpeed"))},validationOkHide:function(t){return t.fadeOut(n.options("animationFastSpeed"))},validationWorkingElement:"span.tdp-vld-working",validationWorkingShow:function(t){return t.fadeIn(n.options("animationSpeed"))},validationWorkingHide:function(t){return t.fadeOut(n.options("animationFastSpeed"))},validationMessageElement:"span.tdp-vld-msg",validationMessageSeparator:"<br />",validationMessageProcessor:function(t){return t.join(n.options("validationMessageSeparator"))},validationMessageFlashDelay:300,validationMessageFlash:function(t){return t.fadeIn(n.options("animationSpeed")).fadeOut(n.options("animationSpeed")).fadeIn(n.options("animationSpeed")).fadeOut(n.options("animationSpeed")).fadeIn(n.options("animationSpeed"))},validationMessageShow:function(t){return t.fadeIn(n.options("animationSpeed"))},validationMessageHide:function(t){return t.fadeOut(n.options("animationFastSpeed"))},validatorRequestProcessor:function(t,e){return{data:t,params:e}},validatorResponseProcessor:function(t,e,a){return!!t&&t.response},submitMethod:null,submitTimeout:5e3,submitUrl:null,submitLoadingElement:null,beforeSubmit:null,submitElement:'input[type="submit"]',submitHandlers:{success:function(t){},error:function(t){},always:function(){n.options("submitLoadingElement")&&t(n.options("submitLoadingElement")).hide()}},skipOnInput:["validator","min","not","match"],verbose:!1,logger:null},!i||"object"!=typeof i){if(!a||"object"!=typeof a)return console.warn("$.TdpPlugin constructor called without mandatory parameters");i=a,a={}}function o(t){return t.split(" ")[0]}function s(t,e){var a=t.split(" ");return a[0]+='[name="'+e+'"]',a.join(" ")}function r(t,e){var a;return a=t.is(":visible")?t.offset().top:t.parent().offset().top,e=null===e?a:Math.min(e,a)}function l(t){var e={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"};return String(t).replace(/[&<>"'\/]/g,function(t){return e[t]})}function d(e,a){var i=e.split(" ");i=i.reverse();var n=a;return t.each(i,function(e,a){var i,o,s,r,l,d,u,p,v,f;n=(i=a,o=n,r=i.indexOf("."),l=i.indexOf("#"),d="",(r>0||l>0)&&(s=r>0&&l>0?Math.min(r,l):r>0?r:l,d=i.substring(s),i=i.substring(0,s)),u=d.split("."),p=t("<"+i+"></"+i+">"),v="",f="",t.each(u,function(t,e){e.indexOf("#")>=0?v+=e.replace(/^#/,""):f+=e+" "}),v.length&&p.attr("id",v),f.length&&p.attr("class",f.trim()),t(p).html(o)).prop("outerHTML")}),t(n)}a&&"object"==typeof a||(a={}),this._options=t.extend(!0,{},this._defaults,a),this._parameters=t.extend(!0,{},i),this._parameters.element=e,this.validators_to_go=0,this.after_validators=null,this._fully_validated=!1,this.options=function(e){return e?"string"==typeof e?this._options[e]:t.extend(!0,this._options,e):(0,this._options)},this.options("logger")&&t(this.options("logger")).length?this._log=t(this.options("logger")):this._log=null,this.show=function(){return t(this._parameters.element).show(this.options("dialogShowDuration")),this},this.hide=function(){return t(this._parameters.element).hide(this.options("dialogCloseDuration")),this},this.getInput=function(e){if(!this._parameters.values[e])return console.warn('Unknown input "'+e+'"'),"";var a="radio"===this._parameters.values[e].type?":checked":"",i=t(this._parameters.element).find('input[name="'+e+'"]'+a+',textarea[name="'+e+'"],select[name="'+e+'"]').first();return i.length?i:""!==a&&(i=t(this._parameters.element).find('input[name="'+e+'"],textarea[name="'+e+'"],select[name="'+e+'"]').first()).length?i:(console.warn('Element for input "'+e+'" does not exist'),"")},this.getValue=function(t){if("hidden"===this._parameters.values[t].type)return this._parameters.values[t].value;var e=this.getInput(t);if(e){if("radio"===e.attr("type")){if(!e.prop("checked"))return""}else if("checkbox"===e.attr("type")&&!e.prop("checked"))return 0;return e.val()}return""},this.setValue=function(e,a){var i=this.getInput(e);if(!i.length)return console.warn('Element for input "'+e+'" does not exist'),!1;if("radio"===i.attr("type")||"checkbox"===i.attr("type")){if(!a)return t(this._parameters.element).find('input[name="'+e+'"]:checked').first().prop("checked",!1);t(this._parameters.element).find('input[name="'+e+'"]').filter('[value="'+a+'"]').first().prop("checked",!0)}else i.is("select")&&!i.children('option[value="'+a+'"]').length&&(a=i.children("option:first").val());return this.getInput(e).val(a)},this.showValidationMsg=function(e,a){this._parameters.values[e].validation_element&&(e=this._parameters.values[e].validation_element);var i=t(this._parameters.element).find(o(this.options("validationMessageElement"))+'[name="'+e+'"]').first();i&&(a&&t(this._parameters.element).find(s(this.options("validationMessageElement"),e)).first().html(a),this.options("validationMessageShow")(i))},this.hideValidationMsg=function(e){this._parameters.values[e].validation_element&&(e=this._parameters.values[e].validation_element);var a=t(this._parameters.element).find(o(this.options("validationMessageElement"))+'[name="'+e+'"]').first();a&&(this.options("validationMessageHide")(a),t(this._parameters.element).find(s(this.options("validationMessageElement"),e)).first().html(""))},this.showValidationOk=function(e){var a=t(this._parameters.element).find(o(this.options("validationOkElement"))+'[name="'+e+'"]').first();a&&this.options("validationOkShow")(a)},this.hideValidationOk=function(e){var a=t(this._parameters.element).find(o(this.options("validationOkElement"))+'[name="'+e+'"]').first();a&&this.options("validationOkHide")(a)},this.showValidationWorking=function(e){var a=t(this._parameters.element).find(s(this.options("validationWorkingElement"),e)).first();a&&this.options("validationWorkingShow")(a)},this.hideValidationWorking=function(e){var a=t(this._parameters.element).find(s(this.options("validationWorkingElement"),e)).first();a&&this.options("validationWorkingHide")(a)},this.reset=function(t=null){var e=this;Object.keys(this._parameters.values).forEach(function(a){var i=e._parameters.values[a];t&&a in t&&(i.value=t[a]),"hidden"!==i.type&&(i.validated=null,i.partial_error=!1,i.old_value=null,i.in_progress=!1,e.setValue(a,i.value),e.hideValidationMsg(a),e.hideValidationOk(a),i.value&&e.options("prevalidation")&&e.validate(a))}),e.after_validators=null,e.validators_to_go=0,e._fully_validated=!1},this.resetAfterValidators=function(){n.after_validators=null,n.validators_to_go=0},this.validationCallback=function(t,e){if(t in n._parameters.values){var a=n._parameters.values[t],i=e?"success":"error",o=n.getValue(t);a.validationCallbacks&&"function"==typeof a.validationCallbacks[i]&&a.validationCallbacks[i](o,e,t,n),a.validationCallbacks&&"function"==typeof a.validationCallbacks.always&&a.validationCallbacks.always(o,e,t,n)}else console.warn('Input "'+t+'" is not defined for validation');return e},this.validate=function(e,a,i){if(this._fully_validated=!1,"string"==typeof e&&"hidden"===this._parameters.values[e].type)return this._parameters.values[e].validated=!0,!0;var n=e instanceof jQuery?e:"string"==typeof e?this.getInput(e):t(e);if(n&&n.is("input,textarea,select")){var o=this,s=n.attr("name");if(s in o._parameters.values){var l=o._parameters.values[s],d=o.getValue(s);if("string"==typeof d&&(d=d.trim(),"tel"===l.type&&(d=d.replace(/[ -]/g,""))),null!==l.old_value&&d===l.old_value&&!l.match&&!l.revalidate)return l.validated;a?l.old_value=null:l.old_value=d,l.matches&&(l.validated=null,l.matches.some(function(t){null!==o._parameters.values[t].validated&&o.validate(t,a,i)}));var u=[],p=!1,v=!1;if(a&&(v=!0),"number"==typeof d&&isNaN(d)||void 0==d||null==d||""==d){if(o.hideValidationOk(s),l.empty&&!l.revalidate)return o.hideValidationMsg(s),l.validated=!0,o.validationCallback(s,!0);if(!l.empty)return o.showValidationMsg(s,l.empty_message?l.empty_message:o.options("errorMessageEmptyInput")),l.validated=!1,o.validationCallback(s,!1)}if(!l.conditions||!l.conditions.length)return l.validated=!0,o.hideValidationMsg(s),o.options("notEmptyAsValidated")&&o.showValidationOk(s),o.validationCallback(s,!0);l.partial_error=!1,l.fulfilled_conditions=[],l.conditions.some(function(e){if(a&&t.inArray(e.type,a)>-1||e.conditioned&&!l.fulfilled_conditions[e.conditioned])return!1;var f=!0;switch(l.type){case"tel":case"email":case"password":case"text":m=d.length,c=e.value;break;case"date":m=new Date(d),c=new Date(e.value);break;case"integer":(m=parseInt(d,10))!=d&&(m=void 0),c=e.value;break;case"float":(m=parseFloat(d,10))!=d&&(m=void 0),c=e.value;break;case"checkbox":case"radio":case"select":m=d,c=e.value;break;case"hidden":break;default:console.warn('Input "'+s+'" has unknown input type "'+l.type+'"')}switch(null!==o._log&&o._log.append("Evaluating condition '"+e.type+"("+m+", "+c+")'\n"),e.type){case"regular":f=RegExp(e.value).test(d);break;case"not":f=m!==c;break;case"notNaN":f=!("number"==typeof m&&isNaN(m))&&void 0!==m;break;case"valid":f=m==d;break;case"min":f=!("number"==typeof m&&isNaN(m))&&void 0!==m&&m>=c;break;case"max":f=!("number"==typeof m&&isNaN(m))&&void 0!==m&&m<=c;break;case"match":f=d==o.getValue(e.value);break;case"date":case"age":var m,c,h,g,y,b=!1;if(t.isArray(e.value)?(h=o.getValue(e.value[0]),g=o.getValue(e.value[1]),y=o.getValue(e.value[2]),h&&g&&y?date=new Date(h,g-1,y):(i?l.empty?(l.validated=!0,f=!0):(v=!0,f=!1):(f=!0,l.empty?l.validated=!0:v=!0),b=!0)):date=new Date(d),!b){if("[object Date]"!==Object.prototype.toString.call(date)||isNaN(date.getTime()))f=!1;else if("age"===e.type){var $=+date;f=~~((Date.now()-$-864e5)/315576e5)>=e.value[3]}else if(date.getFullYear()==h&&date.getMonth()==g-1&&date.getDate()==y){if(f=!0,t.isArray(e.value)){var k=l.validated;l.validated=!0,e.value.some(function(t){s==t||o._parameters.values[t].validated||o.validate(t,a,i)}),l.validated=k}}else f=!1}break;case"validator":d==l.value&&l.prevalidated?f=!0:l.in_progress||(o.hideValidationMsg(s),o.hideValidationOk(s),o.showValidationWorking(s),p=!0,l.validated=!1,o.validators_to_go++,l.in_progress=!0,t.ajax({url:e.value+"?_="+new Date().getTime(),type:"POST",data:JSON.stringify(o.options("validatorRequestProcessor")(d,e.params)),dataType:"json",jsonp:!1,timeout:o.options("submitTimeout"),cache:!1,success:function(a){var i=o.options("validatorResponseProcessor")(a,o,s),d=!1;if((d="string"==typeof i?o.options("validationMessageProcessor")([i]):!!i&&e.message)||l.partial_error){if(l.validated=!1,"string"==typeof d&&o.showValidationMsg(s,d),o.hideValidationOk(s),o.validators_to_go--,o.first_unvalidated=r(n.parent().children("label").length?n.parent().children("label").first():n,o.first_unvalidated),o.after_validators=null,!o.validators_to_go){var u=o.first_unvalidated-t(o.options("scrolledElement")).offset().top+o.options("scrollToErrorOffset");o.options("scrollToErrorEnabled")&&o.first_unvalidated&&t(o.options("scrollingElement")).animate({scrollTop:u},o.options("scrollToErrorDuration"))}o.validationCallback(s,!1)}else l.validated=!0,o.showValidationOk(s),o.validators_to_go--,0===o.validators_to_go&&null!==o.after_validators&&(o.after_validators(),o.after_validators=null),o.validationCallback(s,a)},error:function(a){if(l.validated=!1,o.validators_to_go--,o.first_unvalidated=r(n.parent().children("label").length?n.parent().children("label").first():n,o.first_unvalidated),o.after_validators=null,f=o.options("validationMessageProcessor")([e.message]),o.showValidationMsg(s,f),o.hideValidationOk(s),!o.validators_to_go){var i=o.first_unvalidated-t(o.options("scrolledElement")).offset().top+o.options("scrollToErrorOffset");o.options("scrollToErrorEnabled")&&o.first_unvalidated&&t(o.options("scrollingElement")).animate({scrollTop:i},o.options("scrollToErrorDuration"))}},async:!0}).always(function(){l.in_progress=!1,o.hideValidationWorking(s)}));break;default:console.warn('Unknown condition type "'+e.type+'"')}if(e.is_condition)f&&(l.fulfilled_conditions[e.is_condition]=!0);else if(!f&&(p||(l.partial_error=!0),u.push(e.message),e.last))return!0;return!1}),v||p?v&&(l.validated=!1):l.validated=0===u.length;var f=o.options("validationMessageProcessor")(u);return f?(o.showValidationMsg(s,f),o.hideValidationOk(s)):(o.hideValidationMsg(s),v||p||l.match&&!o._parameters.values[l.match].validated?o.hideValidationOk(s):o.showValidationOk(s)),o.validationCallback(s,!f)}console.warn('Input "'+s+'" is not defined for validation')}else console.warn('Element "'+e+'" is not valid input')},Object.keys(this._parameters.values).forEach(function(a){var i=n._parameters.values[a];i.validated||(i.validated=null),i.old_value=null;var o=!1,r=!1,l=null,u=null;if(i.conditions&&i.conditions.length&&i.conditions.some(function(e){if("match"===e.type){o=e.value,n._parameters.values[o].matches||(n._parameters.values[o].matches=[]),n._parameters.values[o].matches.push(a),r=!0;return}if("date"===e.type||"age"===e.type){r=!0,t.isArray(e.value)&&e.value[0]!=a&&(i.validation_element=e.value[0]);return}"min"===e.type?l=e.value:"max"===e.type&&(u=e.value)}),i.match=o,i.revalidate=r,"hidden"!==i.type){if(input_element=e.find('input[name="'+a+'"],textarea[name="'+a+'"],select[name="'+a+'"]'),"select"===i.type&&(i.interval||i.values)&&(i.values&&i.values.some(function(t){var e=[];e="string"==typeof t||"number"==typeof t?[t,t,!1]:[t[0],t.length>1?t[1]:t[0],t.length>2&&!t[2]];var a=d("option",t[1]).attr("value",t[0]);t[2]&&a.attr("disabled"),i.value==e[1]&&a.attr("selected"),input_element.append(a)}),i.interval)){var p,v=i.interval[0],f=i.interval[1],m=v<f?1:-1;for(i.interval.length>2&&(m*=i.interval[2]),p=v;p*m<=f*m;p+=m){var c=d("option",p).attr("value",p);i.value==p&&c.attr("selected"),input_element.append(c)}}"radio"===i.type?(i.value&&n.setValue(a,i.value),input_element.on("click",function(){return n.validate(a),!0})):((l||u)&&("number"===input_element.attr("type")&&(l&&input_element.attr("min",l),u&&input_element.attr("max",u)),("text"===input_element.attr("type")||"tel"===input_element.attr("type"))&&u&&input_element.attr("maxlength",("text"===i.type?u:u.toString().length)+1)),i.value&&n.setValue(a,i.value),"select"===i.type?(input_element.on("input",function(){n.validate(a)}),input_element.on("change",function(){setTimeout(function(){n.validate(a)},100)})):(input_element.on("input",function(){n.validate(a,n.options("skipOnInput"))}),input_element.on("change, blur",function(){setTimeout(function(){n.validate(a)},100)}))),input_element.is("textarea")||input_element.keypress(function(e){if(e&&13==e.which)return t(e.currentTarget).length&&n.validate(t(e.currentTarget).attr("name")),n.submitForm(),!1}),input_element.on("change.autofill DOMAttrModified.autofill keydown.autofill propertychange.autofill",function(t){setTimeout(function(){""!==input_element.val()&&input_element.trigger("input")},0)});var h=input_element;"radio"===i.type&&(h=e.find('input[name="'+a+'"]').last()).length&&h.next('label[for="'+h.attr("id")+'"]').length&&(h=h.next('label[for="'+h.attr("id")+'"]')),!h.length||e.find(s(n.options("validationMessageElement"),a)).length||e.find(s(n.options("validationOkElement"),a)).length||h.after(d(n.options("validationMessageElement"),"").attr("name",a).hide()).after(d(n.options("validationOkElement"),n.options("validationOkText")).attr("name",a).hide());var g=!1;i.conditions&&i.conditions.length&&i.conditions.some(function(t){if("validator"===t.type){g=!0;return}}),g&&h.length&&!e.find(s(n.options("validationWorkingElement"),a)).length&&h.after(d(n.options("validationWorkingElement"),"").attr("name",a).hide()),i.validationCallbacks&&Object.keys(i.validationCallbacks).forEach(function(t){var e=i.validationCallbacks[t];"string"==typeof e&&(i.validationCallbacks[t]=Function("value","result","name","tdp",e))}),n.hideValidationOk(a),n.hideValidationMsg(a),n.hideValidationWorking(a),i.value&&n.options("prevalidation")&&n.validate(a)}}),this.revalidateAll=function(e,a){var i=!0,n=0,s=this;if(s.first_unvalidated=null,Object.keys(s._parameters.values).forEach(function(l){var d=s._parameters.values[l];if("hidden"!==d.type&&(!d.validated||d.revalidate)){var u=s.getInput(l);if(u.parent().is(":visible")){if(d.in_progress)i=!1;else{var p=s.validators_to_go;e&&null!==d.validated&&!d.revalidate||d.in_progress||s.validate(l,a,!0),!1===d.validated&&(i=!1,s.validators_to_go===p&&(s.after_validators=null,s.first_unvalidated=r(u.parent().children("label").length?u.parent().children("label").first():u,s.first_unvalidated),setTimeout(function(){s.options("validationMessageFlash")(t(o(s.options("validationMessageElement"))+'[name="'+l+'"]').first())},s.options("validationMessageFlashDelay")*n++)))}}}}),!i){if(s.first_unvalidated&&s.options("scrollToErrorEnabled")&&!s.validators_to_go){var l=s.first_unvalidated-t(s.options("scrolledElement")).offset().top+s.options("scrollToErrorOffset");t(s.options("scrollingElement")).animate({scrollTop:l},s.options("scrollToErrorDuration"))}return!1}return s._fully_validated=!0,!0},this.isValidated=function(){return this._fully_validated},this.getSubmitData=function(){var t=this,e={},a=!1;return Object.keys(t._parameters.values).forEach(function(i){var n,o=!1;"hidden"===t._parameters.values[i].type?(n=t._parameters.values[i].value,o=!0,t._parameters.alwaysSubmit&&(a=!0)):!t._parameters.values[i].match&&t.getInput(i).parent().is(":visible")&&("string"==typeof(n=t.getValue(i))&&(n=n.trim(),"tel"===t._parameters.values[i].type&&(n=n.replace(/[ -]/g,""))),(o=!!t._parameters.alwaysSubmit||n!=t._parameters.values[i].value&&(null!=n&&""!=n||null!=t._parameters.values[i].value&&""!=t._parameters.values[i].value))&&(a=!0)),o&&(t._parameters.values[i].prefix?(t._parameters.values[i].prefix in e||(e[t._parameters.values[i].prefix]={}),e[t._parameters.values[i].prefix][i]=n):e[i]=n)}),{submitData:e,updateNeeded:a}},this.ajaxSubmit=function(){var e=this,a=this.getSubmitData(),i=a&&a.submitData?a.submitData:{};if(!(a&&void 0!==a.updateNeeded&&a.updateNeeded)){e._parameters.displayElement&&(t(e._parameters.element).hide(e.options("animationFastSpeed")),e._parameters.editLink&&t(e._parameters.editLink).show());return}e.options("beforeSubmit")&&e.options("beforeSubmit")(e),e.options("submitLoadingElement")&&t(e.options("submitLoadingElement")).show(),t.ajax({url:e.options("submitUrl")+"?_="+new Date().getTime(),type:"POST",data:JSON.stringify(i),dataType:"json",jsonp:!1,timeout:e.options("submitTimeout"),cache:!1,success:function(a){(e._parameters.displayElement||e._parameters.editLink)&&(t(e._parameters.element).hide(e.options("animationFastSpeed")),e._parameters.editLink&&t(e._parameters.editLink).show()),"function"==typeof e.options("submitHandlers").success&&e.options("submitHandlers").success(a,e,i)},error:function(t){"function"==typeof e.options("submitHandlers").error&&e.options("submitHandlers").error(t,e,i)},async:!0}).always(function(){"function"==typeof e.options("submitHandlers").always&&e.options("submitHandlers").always(e,i)})},this.submitForm=function(t){return n.after_validators=function(){return null!==n.options("submitMethod")?n.options("submitMethod")(n):n.ajaxSubmit()},null!==t&&"object"==typeof t&&(t.preventDefault(),t.stopPropagation()),!!n.revalidateAll(!1)&&(null!==n.options("submitMethod")?n.options("submitMethod")(n):n.ajaxSubmit())},(e.is("form")||e.find("form").length)&&(e.is("form")?e:e.find("form").first()).bind("submit",function(t){return n.submitForm(t),!1}),e.find(this.options("submitElement")).on("click",function(t){return n.submitForm(t),!1})};t.fn.tdp=function(a){var i,n="string"==typeof a?a:void 0,o=arguments.length>1?Array.prototype.slice.call(arguments,1)[0]:void 0,s=[],r=[];return n?(this.each(function e(){var a=t(this).data("TdpPlugin");s.push(a)}),this.each(function t(e){var a=s[e];if(!a){console.warn("$.TdpPlugin not instantiated yet"),console.info(this),r.push(void 0);return}if("function"==typeof a[n]){var i=a[n].apply(a,o);r.push(i)}else console.warn("Method '"+n+"' not defined in $.TdpPlugin")}),r.length>1?r:r[0]):(i="object"==typeof a?a:void 0,this.each(function a(){var n=t(this),s=new e(n,i,o);n.data("TdpPlugin",s)}))}}(jQuery);