meraproject/lib/js/bws/form.js

944 lines
21 KiB
JavaScript
Raw Normal View History

(function($) {
var F;
$.fn.FORM = function(method) {
var f;
if (F[method]) {
return F[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === "object" || !method) {
return F.init.apply(this, arguments);
} else {
f = $(this).data('form');
if (f === void 0) {
f = new Form(this);
}
if (f[method] !== void 0) {
return f[method].apply(f, Array.prototype.slice.call(arguments, 1));
} else {
return $.error('Метод с именем ' + method + ' не существует для jQuery.FORM');
}
}
};
return F = {
init: function(data = {}) {
var $t, f;
$t = $(this);
if ($t.length === 1) {
return new Form(this, data);
} else {
f = [];
$(this).each(function() {
return f.push(new Form(this, data));
});
return f;
}
},
setPrepareValidate: function(cb) {
return Form.globalPrepareValidate = cb;
},
setGlobalGood: function(cb) {
return Form.globalGood = cb;
},
setGlobalBad: function(cb) {
return Form.globalBad = cb;
},
setGlobalJSON: function(cb) {
return Form.globalJSON = cb;
},
setGlobalOptions: function(o) {
return Form.globalOptions = o;
}
};
})(jQuery);
var Form;
Form = (function() {
class Form {
constructor(container, init_data1) {
this.container = container;
this.init_data = init_data1;
this.container = $(this.container);
if (this.isInited()) {
return;
}
this.container.on('destroyed', this.destroy.bind(this));
this.init(this.init_data);
}
init(data = {}) {
var c, ref, ref1;
this.container.data('form_inited', true);
this.container.data('form', this);
if (this.inputActionWithParent == null) {
this.inputActionWithParent = (ref = data.inputActionWithParent) != null ? ref : (c = (ref1 = Form.globalOptions.inputActionWithParent) != null ? ref1 : false);
}
this.initInputs(data != null ? data.inputs : void 0);
this.checkRules();
return this.initActions();
}
isInited() {
return this.container.data('form_inited') === true;
}
destroy() {
var i, j, len, ref, results;
ref = this.getInputs();
//console.log 'FORM destroy'
results = [];
for (j = 0, len = ref.length; j < len; j++) {
i = ref[j];
results.push(i.form = null);
}
return results;
}
initActions() {
var $i, a, i, j, len, results;
a = this.getInputs();
results = [];
for (j = 0, len = a.length; j < len; j++) {
$i = a[j];
if ($i.rules === null) {
continue;
}
results.push((function() {
var k, len1, ref, results1;
ref = $i.rules;
results1 = [];
for (k = 0, len1 = ref.length; k < len1; k++) {
i = ref[k];
switch (i[1]) {
case FormRuleCommand.ON:
switch (i[2]) {
case FormRuleOperator.CHANGE:
switch (i[3]) {
case FormRuleAction.FUNCTION:
results1.push(this.initActionOnChange($i, i));
break;
default:
results1.push(void 0);
}
break;
default:
results1.push(void 0);
}
break;
default:
results1.push(void 0);
}
}
return results1;
}).call(this));
}
return results;
}
initActionOnChange($i, i) {
var n, name;
n = this.getInputByName(i[0]);
name = 'function' + (new Date()).getTime();
eval("Form['" + name + "']=" + i[4]);
console.log('$I', $i);
n.$wrap.on('input:change', function() {
return Form[name]($i, n.value());
});
return n.$wrap.on('destroyed', function() {
if (Form[name] != null) {
return delete Form[name];
}
});
}
validate(options = {}) {
var i, j, len, o, r, ref, res;
res = {
bad: {},
good: {},
success: true
};
ref = this.getInputs();
for (j = 0, len = ref.length; j < len; j++) {
i = ref[j];
r = i.validate();
o = {
input: i,
result: r
};
if (options.prepare !== void 0) {
if (typeof options.prepare === "function") {
options.prepare(i, r);
}
} else {
Form.globalPrepareValidate(i, r);
}
if (r.errors.length > 0) {
res.bad[i.getName()] = o;
res.success = false;
if (options.bad !== void 0) {
if (typeof options.bad === "function") {
options.bad(i, r);
}
} else {
Form.globalBad(i, r);
}
} else {
res.good[i.getName()] = o;
if (options.good !== void 0) {
if (typeof options.good === "function") {
options.good(i, r);
}
} else {
Form.globalGood(i, r);
}
}
}
if (res.success) {
if (typeof options.success === "function") {
options.success(res);
}
} else {
if (typeof options.fail === "function") {
options.fail(res);
}
}
return res;
}
getInputs(init_data = {}) {
var res;
res = [];
$("[data-input]", this.container).each(function() {
var i;
i = Input.init($(this));
if ((init_data != null ? init_data[i.getName()] : void 0) != null) {
i.initData(init_data[i.getName()]);
}
return res.push(i);
});
return res;
}
json() {
var i, j, len, name, ref, res;
if (Form.globalJSON != null) {
res = Form.globalJSON(this.container);
} else {
res = {};
ref = this.getInputs();
for (j = 0, len = ref.length; j < len; j++) {
i = ref[j];
name = i.getName();
if (i.isCheckbox) {
if (res[name] === void 0) {
res[name] = i.value();
} else {
if (Array.isArray(res[name])) {
res[name].push(i.value());
} else {
res[name] = [res[name], i.value()];
}
}
} else if (i.isRadio) {
if (i.checked()) {
res[name] = i.value();
}
} else {
res[name] = i.value();
}
}
}
return res;
}
// Иницилизация полей ввода
initInputs(data = {}) {
var i, j, len, ref, results;
ref = this.getInputs(data);
results = [];
for (j = 0, len = ref.length; j < len; j++) {
i = ref[j];
i.$wrap.on('input:change', this.checkRules.bind(this));
i.$wrap.on('input:show', this.recheckRules.bind(this));
i.$wrap.on('input:hide', this.recheckRules.bind(this));
results.push(i.form = this);
}
return results;
}
getInputByName(name) {
var i, j, len, ref;
ref = this.getInputs();
for (j = 0, len = ref.length; j < len; j++) {
i = ref[j];
if (i.getName() === name) {
return i;
}
}
return null;
}
// Проверка правил формы
checkRules() {
var data, i, j, len, ref;
data = this.json();
this.needRecheckRules = false;
ref = this.getInputs();
for (j = 0, len = ref.length; j < len; j++) {
i = ref[j];
i.checkRules(data);
}
if (this.needRecheckRules) {
return this.checkRules();
}
}
recheckRules() {
return this.needRecheckRules = true;
}
// Функции для переопределения
static globalBad(i, r) {}
static globalGood(i, r) {}
};
Form.globalOptions = {};
Form.globalJSON = null;
return Form;
}).call(this);
var Input;
Input = (function() {
class Input {
static init($wrap, data = null) {
var e, i, inp, type;
$wrap = $($wrap);
if ($wrap.data(Input._data_input) !== void 0) {
if (data === null) {
return $wrap.data(Input._data_input);
} else {
inp = $wrap.data(Input._data_input);
inp.initData(data);
return inp;
}
} else {
if (data === null) {
try {
//console.log('TRY PARSE')
data = JSON.parse($wrap.attr('data-init'));
} catch (error) {
//console.log('PARSED',data)
// $wrap.removeAttr('data-init')
e = error;
data = {};
}
}
type = $wrap.attr('data-input');
if (type !== void 0) {
type = type.toLowerCase();
type = type.substr(0, 1).toUpperCase() + type.substr(1);
if (Input[type] !== void 0) {
i = new Input[type]($wrap, data);
} else {
i = new Input($wrap, data);
}
} else {
i = new Input($wrap, data);
}
return i;
}
}
constructor($wrap1 = null, init_data = {}) {
this.$wrap = $wrap1;
this.init_data = init_data;
if (this.$wrap !== null && this.$wrap.data(Input._data_input) !== void 0) {
return;
}
this.initData(this.init_data);
}
initData(data = {}) {
var ref, ref1, v;
if ((v = data.validation) !== void 0) {
this.isErrorWhenEmpty = (ref = v.notEmpty) != null ? ref : false;
this.required = (ref1 = v.required) != null ? ref1 : false;
}
if (data.rules != null) {
this.rules = data.rules;
}
if (this.$wrap === null) {
this.$wrap = this.render();
}
this.initInput();
return this.$wrap.data(Input._data_input, this);
}
initInput() {
if (this.$wrap[0].tagName === 'INPUT') {
this.$input = this.$wrap;
} else {
this.$input = $("input:eq(0)", this.$wrap);
}
return this.$input.on('change', this.triggerChange.bind(this));
}
triggerChange() {
this.format();
return this.$wrap.trigger('input:change');
}
format() {}
value(x) {
if (x !== void 0) {
return this.$input.val(x);
} else {
return this.$input.val();
}
}
getName() {
var name;
name = this.$wrap.attr('data-name');
return name;
}
// РАБОТЫ С ПРАВИЛАМИ
testRule(rule, data) {
var name, need, ref, ref1, res, value;
name = rule[0];
// если такого поля ввода нет, то true ?
if (data[name] === void 0) {
return true;
}
value = data[rule[0]].toString();
need = rule[2].toString();
switch (rule[1]) {
case '=':
return value === need;
case 'is':
case 'not':
switch (need) {
case 'visible':
res = (ref = this.form) != null ? ref.getInputByName(name).isVisible() : void 0;
break;
case 'checked':
res = (ref1 = this.form) != null ? ref1.getInputByName(name).checked() : void 0;
}
if (rule[1] === 'is') {
return res;
} else {
return !res;
}
default:
return false;
}
}
checkRule(rule, data) {
var action, i, j, k, len, len1, ref, ref1, res;
action = null;
if (rule[FormRuleCommand.OR] !== void 0) {
res = false;
ref = rule[FormRuleCommand.OR];
for (j = 0, len = ref.length; j < len; j++) {
i = ref[j];
res = res || this.testRule(i, data);
}
action = rule.action;
} else if (rule[FormRuleCommand.AND] !== void 0) {
res = true;
ref1 = rule[FormRuleCommand.AND];
for (k = 0, len1 = ref1.length; k < len1; k++) {
i = ref1[k];
res = res && this.testRule(i, data);
}
action = rule.action;
} else {
res = this.testRule(rule, data);
action = rule[3];
}
if (action !== null) {
switch (action) {
case FormRuleAction.HIDE:
if (res) {
return this.hide();
} else {
return this.show();
}
case FormRuleAction.SHOW:
if (res) {
return this.show();
} else {
return this.hide();
}
}
}
}
checkRules(data) {
var i, j, len, ref, results;
if (this.rules === null) {
return;
}
ref = this.rules;
results = [];
for (j = 0, len = ref.length; j < len; j++) {
i = ref[j];
results.push(this.checkRule(i, data));
}
return results;
}
// ACTIONS - действия с полями ввода
isInputActionWithParent() {
return this.form.inputActionWithParent;
}
hide() {
if (this.isVisible()) {
if (this.isInputActionWithParent()) {
this.$wrap.parent().hide();
} else {
this.$wrap.hide();
}
return this.$wrap.trigger('input:hide');
}
}
//console.log('i hide')
show() {
if (!this.isVisible()) {
if (this.isInputActionWithParent()) {
this.$wrap.parent().show();
} else {
this.$wrap.show();
}
return this.$wrap.trigger('input:show');
}
}
//console.log('i show')
// Отрисовка поля ввода
attributesToString() {
var a, i;
a = [];
for (i in this.attributes) {
a.push(i + '="' + this.attributes[i] + '"');
}
return a.join(" ");
}
toString() {
return '<input data-input="text" ' + this.attributesToString() + '/>';
}
render() {
return this.$input = $(this.toString());
}
// STATUSES
isVisible() {
return this.$wrap.is(':visible');
}
checkErrors(res) {
return res;
}
// VALIDATION
validate() {
var res;
res = {
errors: []
};
if (this.isEmpty()) {
res.isEmpty = true;
if (this.isErrorWhenEmpty || this.required) {
res.errorEmptyText = InputError.errorEmptyText;
res.errors.push(InputError.errorEmptyText);
}
} else {
// Если поле ввода не пустое, то проверяем на ошибки
res = this.checkErrors(res);
}
return res;
}
isEmpty() {
return false;
}
};
Input.prototype.errorEmptyText = 'Не должно быть пустым';
Input.prototype.name = '';
Input.prototype.isErrorWhenEmpty = false;
Input.prototype.rules = null;
Input.prototype.required = false;
Input.prototype.isRadio = false;
Input.prototype.isCheckbox = false;
Input._data_input = '_data_input';
return Input;
}).call(this);
var InputError;
InputError = (function() {
class InputError {};
InputError.errorEmptyText = 'Не должно быть пустым';
InputError.errorEmailInvalid = 'Некорректный email';
return InputError;
}).call(this);
var FormRuleAction, FormRuleCommand, FormRuleOperator;
FormRuleCommand = (function() {
class FormRuleCommand {};
FormRuleCommand.OR = 'or';
FormRuleCommand.AND = 'and';
FormRuleCommand.IN = 'in';
FormRuleCommand.IS = 'is';
FormRuleCommand.ON = 'on';
return FormRuleCommand;
}).call(this);
FormRuleOperator = (function() {
class FormRuleOperator {};
FormRuleOperator.EQUAL = '=';
return FormRuleOperator;
}).call(this);
FormRuleAction = (function() {
class FormRuleAction {};
FormRuleAction.HIDE = 'hide';
FormRuleAction.SHOW = 'show';
FormRuleAction.FUNCTION = 'function';
return FormRuleAction;
}).call(this);
FormRuleOperator = (function() {
class FormRuleOperator {};
FormRuleOperator.CHANGE = 'change';
return FormRuleOperator;
}).call(this);
Input.Text = class Text extends Input {
constructor($inp = null, data = {}) {
super($inp, data);
}
// VALIDATION
isEmpty() {
return $.trim(this.value()).length === 0;
}
};
Input.Email = (function() {
class Email extends Input.Text {
testMail(x) {
return this.mail.test(x);
}
checkErrors(res) {
var value;
//res = super()
value = this.value();
value = value.replace(/ /g, '');
if (!this.testMail(value)) {
res.isEmailInvalid = true;
res.errorEmailInvalid = InputError.errorEmailInvalid;
res.errors.push(InputError.errorEmailInvalid);
}
return res;
}
};
// VALIDATION
Email.prototype.mail = /^([A-Za-z0-9_-]+\.)*[A-Za-z0-9_-]+@[A-Za-z0-9_-]+(\.[A-Za-z0-9_-]+)*\.[A-Za-z]{2,6}$/;
return Email;
}).call(this);
Input.Int = class Int extends Input.Text {
format() {
var val;
val = this.value();
val = parseInt(val);
if (isNaN(val)) {
val = 0;
}
return this.$input.val(val);
}
};
Input.Hidden = class Hidden extends Input {};
Input.Select = class Select extends Input {
// VALIDATION
initInput() {
if (this.$wrap[0].tagName === 'SELECT') {
this.$input = this.$wrap;
} else {
this.$input = $("select:eq(0)", this.$wrap);
}
return this.$input.on('change', this.triggerChange.bind(this));
}
isEmpty() {
return this.value() === "";
}
};
Input.Select_ajax = class Select_ajax extends Input.Select {
// VALIDATION
isEmpty() {
var res;
res = this.value() === null || this.value === void 0;
return res;
}
};
Input.Checkbox = (function() {
class Checkbox extends Input {
// VALIDATION
initInput() {
if (this.$wrap[0].tagName === 'INPUT') {
this.$input = this.$wrap;
} else {
this.$input = $("input[type=checkbox]:eq(0)", this.$wrap);
}
return this.$input.on('change', this.triggerChange.bind(this));
}
value(x) {
if (x != null) {
this.$input.val(x);
}
if (this.checked()) {
return this.$input.val();
} else {
return 0;
}
}
checked() {
return this.$input.is(":checked");
}
isEmpty() {
return this.value() === null;
}
};
Checkbox.prototype.isCheckbox = true;
return Checkbox;
}).call(this);
Input.Textarea = class Textarea extends Input {
// VALIDATION
initInput() {
if (this.$wrap[0].tagName === 'TEXTAREA') {
this.$input = this.$wrap;
} else {
this.$input = $("textarea:eq(0)", this.$wrap);
}
return this.$input.on('change', this.triggerChange.bind(this));
}
isEmpty() {
return this.value() === '';
}
};
Input.Image = class Image extends Input {
// VALIDATION
initInput() {
this.$input = $("input[type=hidden]:eq(0)", this.$wrap);
return this.$input.on('change', this.triggerChange.bind(this));
}
static value(x) {
if (x !== void 0) {
return this.$input.val(x);
} else {
return this.$input.val();
}
}
isEmpty() {
return this.value() === '';
}
};
Input.Radio = (function() {
class Radio extends Input {
initInput() {
if (this.$wrap[0].tagName === 'INPUT') {
this.$input = this.$wrap;
} else {
this.$input = $("input[type=radio]:eq(0)", this.$wrap);
}
return this.$input.on('change', this.triggerChange.bind(this));
}
value(x) {
if (x != null) {
this.$input.val(x);
}
if (this.checked()) {
return this.$input.val();
} else {
return null;
}
}
checked() {
return this.$input.is(":checked");
}
isEmpty() {
return this.value() === null;
}
};
// VALIDATION
Radio.prototype.isRadio = true;
return Radio;
}).call(this);
Input.Date = class Date extends Input.Text {};
Input.Video = class Video extends Input {
// VALIDATION
initInput() {
this.$input = $("input[type=hidden]:eq(0)", this.$wrap);
return this.$input.on('change', this.triggerChange.bind(this));
}
static value(x) {
if (x !== void 0) {
return this.$input.val(x);
} else {
return this.$input.val();
}
}
isEmpty() {
return this.value() === '';
}
};
Input.Datetime = class Datetime extends Input.Text {
value(x) {
var val;
if (x !== void 0) {
return this.$input.val(x);
} else {
val = Date.parse(this.$input.val()) / 1000;
if (isNaN(val)) {
val = 0;
}
return val;
}
}
};
Input.Float = class Float extends Input.Text {
format() {
var val;
val = this.value();
val = parseFloat(val);
if (isNaN(val)) {
val = 0;
}
return this.$input.val(val);
}
value(x) {
var val;
if (x !== void 0) {
val = x;
} else {
val = this.$input.val();
}
val = parseFloat(val);
if (isNaN(val)) {
val = 0;
}
this.$input.val(val);
return val;
}
};
Input.Tinymce = class Tinymce extends Input {
getNodeId() {
return this.$wrap.attr('data-input-tinymce');
}
value(x) {
if (x !== void 0) {
return tinymce.get(this.getNodeId()).setContent(x);
} else {
return tinymce.get(this.getNodeId()).getContent();
}
}
};