更换后台UI,使用adminlteUI
This commit is contained in:
@@ -0,0 +1,519 @@
|
||||
define(['jquery', 'bootstrap', 'validator'], function ($, undefined, Validator) {
|
||||
var Form = {
|
||||
config: {
|
||||
fieldlisttpl: '<dd class="form-inline"><input type="text" name="<%=name%>[<%=index%>][key]" class="form-control" value="<%=row.key%>" size="10" /> <input type="text" name="<%=name%>[<%=index%>][value]" class="form-control" value="<%=row.value%>" /> <span class="btn btn-sm btn-danger btn-remove"><i class="fa fa-times"></i></span> <span class="btn btn-sm btn-primary btn-dragsort"><i class="fa fa-arrows"></i></span></dd>'
|
||||
},
|
||||
events: {
|
||||
validator: function (form, success, error, submit) {
|
||||
if (!form.is("form"))
|
||||
return;
|
||||
//绑定表单事件
|
||||
form.validator($.extend({
|
||||
validClass: 'has-success',
|
||||
invalidClass: 'has-error',
|
||||
bindClassTo: '.form-group',
|
||||
formClass: 'n-default n-bootstrap',
|
||||
msgClass: 'n-right',
|
||||
stopOnError: true,
|
||||
display: function (elem) {
|
||||
return $(elem).closest('.form-group').find(".control-label").text().replace(/\:/, '');
|
||||
},
|
||||
dataFilter: function (data) {
|
||||
if (data.code === 1) {
|
||||
return data.msg ? {"ok": data.msg} : '';
|
||||
} else {
|
||||
return data.msg;
|
||||
}
|
||||
},
|
||||
target: function (input) {
|
||||
var target = $(input).data("target");
|
||||
if (target && $(target).size() > 0) {
|
||||
return $(target);
|
||||
}
|
||||
var $formitem = $(input).closest('.form-group'),
|
||||
$msgbox = $formitem.find('div.help-block');
|
||||
if (!$msgbox.length) {
|
||||
return [];
|
||||
}
|
||||
return $msgbox;
|
||||
},
|
||||
valid: function (ret) {
|
||||
var that = this, submitBtn = $(".layer-footer [type=submit]", form);
|
||||
that.holdSubmit(true);
|
||||
submitBtn.addClass("disabled");
|
||||
//验证通过提交表单
|
||||
var submitResult = Form.api.submit($(ret), function (data, ret) {
|
||||
that.holdSubmit(false);
|
||||
submitBtn.removeClass("disabled");
|
||||
if (false === $(this).triggerHandler("success.form", [data, ret])) {
|
||||
return false;
|
||||
}
|
||||
if (typeof success === 'function') {
|
||||
if (false === success.call($(this), data, ret)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
//提示及关闭当前窗口
|
||||
var msg = ret.hasOwnProperty("msg") && ret.msg !== "" ? ret.msg : __('Operation completed');
|
||||
sent.msg(msg, 'success');
|
||||
parent.$(".btn-refresh").trigger("click");
|
||||
return false;
|
||||
}, function (data, ret) {
|
||||
that.holdSubmit(false);
|
||||
if (false === $(this).triggerHandler("error.form", [data, ret])) {
|
||||
return false;
|
||||
}
|
||||
submitBtn.removeClass("disabled");
|
||||
if (typeof error === 'function') {
|
||||
if (false === error.call($(this), data, ret)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}, submit);
|
||||
//如果提交失败则释放锁定
|
||||
if (!submitResult) {
|
||||
that.holdSubmit(false);
|
||||
submitBtn.removeClass("disabled");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}, form.data("validator-options") || {}));
|
||||
|
||||
//移除提交按钮的disabled类
|
||||
$(".layer-footer [type=submit],.fixed-footer [type=submit],.normal-footer [type=submit]", form).removeClass("disabled");
|
||||
},
|
||||
editor: function (form) {
|
||||
//绑定编辑器元素事件
|
||||
if ($(".form-editor", form).size() > 0) {
|
||||
require(['NKeditor'], function(){
|
||||
KindEditor.create('.form-editor', {
|
||||
uploadJson: "/admin/upload/editor'",
|
||||
fileManagerJson: "/admin/upload/filemanage"
|
||||
})
|
||||
})
|
||||
}
|
||||
},
|
||||
selectpicker: function (form) {
|
||||
//绑定select元素事件
|
||||
if ($(".selectpicker", form).size() > 0) {
|
||||
require(['bootstrap-select', 'bootstrap-select-lang'], function () {
|
||||
$('.selectpicker', form).selectpicker();
|
||||
$(form).on("reset", function () {
|
||||
setTimeout(function () {
|
||||
$('.selectpicker').selectpicker('refresh').trigger("change");
|
||||
}, 1);
|
||||
});
|
||||
});
|
||||
}
|
||||
},
|
||||
selectpage: function (form) {
|
||||
//绑定selectpage元素事件
|
||||
if ($(".selectpage", form).size() > 0) {
|
||||
require(['selectpage'], function () {
|
||||
$('.selectpage', form).selectPage({
|
||||
eAjaxSuccess: function (data) {
|
||||
data.list = typeof data.rows !== 'undefined' ? data.rows : (typeof data.list !== 'undefined' ? data.list : []);
|
||||
data.totalRow = typeof data.total !== 'undefined' ? data.total : (typeof data.totalRow !== 'undefined' ? data.totalRow : data.list.length);
|
||||
return data;
|
||||
}
|
||||
});
|
||||
});
|
||||
//给隐藏的元素添加上validate验证触发事件
|
||||
$(document).on("change", ".sp_hidden", function () {
|
||||
$(this).trigger("validate");
|
||||
});
|
||||
$(document).on("change", ".sp_input", function () {
|
||||
$(this).closest(".sp_container").find(".sp_hidden").trigger("change");
|
||||
});
|
||||
$(form).on("reset", function () {
|
||||
setTimeout(function () {
|
||||
$('.selectpage', form).selectPageClear();
|
||||
}, 1);
|
||||
});
|
||||
}
|
||||
},
|
||||
cxselect: function (form) {
|
||||
//绑定cxselect元素事件
|
||||
if ($("[data-toggle='cxselect']", form).size() > 0) {
|
||||
require(['cxselect'], function () {
|
||||
$.cxSelect.defaults.jsonName = 'name';
|
||||
$.cxSelect.defaults.jsonValue = 'value';
|
||||
$.cxSelect.defaults.jsonSpace = 'data';
|
||||
$("[data-toggle='cxselect']", form).cxSelect();
|
||||
});
|
||||
}
|
||||
},
|
||||
citypicker: function (form) {
|
||||
//绑定城市远程插件
|
||||
if ($("[data-toggle='city-picker']", form).size() > 0) {
|
||||
require(['citypicker'], function () {
|
||||
$(form).on("reset", function () {
|
||||
setTimeout(function () {
|
||||
$("[data-toggle='city-picker']").citypicker('refresh');
|
||||
}, 1);
|
||||
});
|
||||
});
|
||||
}
|
||||
},
|
||||
datetimepicker: function (form) {
|
||||
//绑定日期时间元素事件
|
||||
if ($(".datetimepicker", form).size() > 0) {
|
||||
require(['bootstrap-datetimepicker'], function () {
|
||||
var options = {
|
||||
format: 'YYYY-MM-DD HH:mm:ss',
|
||||
icons: {
|
||||
time: 'fa fa-clock-o',
|
||||
date: 'fa fa-calendar',
|
||||
up: 'fa fa-chevron-up',
|
||||
down: 'fa fa-chevron-down',
|
||||
previous: 'fa fa-chevron-left',
|
||||
next: 'fa fa-chevron-right',
|
||||
today: 'fa fa-history',
|
||||
clear: 'fa fa-trash',
|
||||
close: 'fa fa-remove'
|
||||
},
|
||||
showTodayButton: true,
|
||||
showClose: true
|
||||
};
|
||||
$('.datetimepicker', form).parent().css('position', 'relative');
|
||||
$('.datetimepicker', form).datetimepicker(options).on('dp.change', function (e) {
|
||||
$(this, document).trigger("changed");
|
||||
});
|
||||
});
|
||||
}
|
||||
},
|
||||
daterangepicker: function (form) {
|
||||
//绑定日期时间元素事件
|
||||
if ($(".datetimerange", form).size() > 0) {
|
||||
require(['bootstrap-daterangepicker'], function () {
|
||||
var ranges = {};
|
||||
ranges[__('Today')] = [Moment().startOf('day'), Moment().endOf('day')];
|
||||
ranges[__('Yesterday')] = [Moment().subtract(1, 'days').startOf('day'), Moment().subtract(1, 'days').endOf('day')];
|
||||
ranges[__('Last 7 Days')] = [Moment().subtract(6, 'days').startOf('day'), Moment().endOf('day')];
|
||||
ranges[__('Last 30 Days')] = [Moment().subtract(29, 'days').startOf('day'), Moment().endOf('day')];
|
||||
ranges[__('This Month')] = [Moment().startOf('month'), Moment().endOf('month')];
|
||||
ranges[__('Last Month')] = [Moment().subtract(1, 'month').startOf('month'), Moment().subtract(1, 'month').endOf('month')];
|
||||
var options = {
|
||||
timePicker: false,
|
||||
autoUpdateInput: false,
|
||||
timePickerSeconds: true,
|
||||
timePicker24Hour: true,
|
||||
autoApply: true,
|
||||
locale: {
|
||||
format: 'YYYY-MM-DD HH:mm:ss',
|
||||
customRangeLabel: __("Custom Range"),
|
||||
applyLabel: __("Apply"),
|
||||
cancelLabel: __("Clear"),
|
||||
},
|
||||
ranges: ranges,
|
||||
};
|
||||
var origincallback = function (start, end) {
|
||||
$(this.element).val(start.format(this.locale.format) + " - " + end.format(this.locale.format));
|
||||
$(this.element).trigger('blur');
|
||||
};
|
||||
$(".datetimerange", form).each(function () {
|
||||
var callback = typeof $(this).data('callback') == 'function' ? $(this).data('callback') : origincallback;
|
||||
$(this).on('apply.daterangepicker', function (ev, picker) {
|
||||
callback.call(picker, picker.startDate, picker.endDate);
|
||||
});
|
||||
$(this).on('cancel.daterangepicker', function (ev, picker) {
|
||||
$(this).val('').trigger('blur');
|
||||
});
|
||||
$(this).daterangepicker($.extend(true, options, $(this).data()), callback);
|
||||
});
|
||||
});
|
||||
}
|
||||
},
|
||||
plupload: function (form) {
|
||||
//绑定plupload上传元素事件
|
||||
if ($(".picker-box", form).size() > 0) {
|
||||
$(".picker-box .picker_button", form).on('click', function(){
|
||||
var type = $(this).data('type');
|
||||
var limit = $(this).data('limit');
|
||||
var name = $(this).siblings('input[type=hidden]').attr('name');
|
||||
layer.open({
|
||||
type: 2,
|
||||
shade: false,
|
||||
area: ['60%', '440px'],
|
||||
title: $(this).text(), //不显示标题
|
||||
content: ['/'+Config.module+'/upload/index?name='+name+'&type='+type+'&limit='+limit, 'no'],
|
||||
});
|
||||
})
|
||||
}
|
||||
},
|
||||
faselect: function (form) {
|
||||
//绑定fachoose选择附件事件
|
||||
if ($(".fachoose", form).size() > 0) {
|
||||
$(".fachoose", form).on('click', function () {
|
||||
var that = this;
|
||||
var multiple = $(this).data("multiple") ? $(this).data("multiple") : false;
|
||||
var mimetype = $(this).data("mimetype") ? $(this).data("mimetype") : '';
|
||||
var admin_id = $(this).data("admin-id") ? $(this).data("admin-id") : '';
|
||||
var user_id = $(this).data("user-id") ? $(this).data("user-id") : '';
|
||||
sent.api.open("general/attachment/select?element_id=" + $(this).attr("id") + "&multiple=" + multiple + "&mimetype=" + mimetype + "&admin_id=" + admin_id + "&user_id=" + user_id, __('Choose'), {
|
||||
callback: function (data) {
|
||||
var button = $("#" + $(that).attr("id"));
|
||||
var maxcount = $(button).data("maxcount");
|
||||
var input_id = $(button).data("input-id") ? $(button).data("input-id") : "";
|
||||
maxcount = typeof maxcount !== "undefined" ? maxcount : 0;
|
||||
if (input_id && data.multiple) {
|
||||
var urlArr = [];
|
||||
var inputObj = $("#" + input_id);
|
||||
var value = $.trim(inputObj.val());
|
||||
if (value !== "") {
|
||||
urlArr.push(inputObj.val());
|
||||
}
|
||||
urlArr.push(data.url)
|
||||
var result = urlArr.join(",");
|
||||
if (maxcount > 0) {
|
||||
var nums = value === '' ? 0 : value.split(/\,/).length;
|
||||
var files = data.url !== "" ? data.url.split(/\,/) : [];
|
||||
var remains = maxcount - nums;
|
||||
if (files.length > remains) {
|
||||
Toastr.error(__('You can choose up to %d file%s', remains));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
inputObj.val(result).trigger("change").trigger("validate");
|
||||
} else {
|
||||
$("#" + input_id).val(data.url).trigger("change").trigger("validate");
|
||||
}
|
||||
}
|
||||
});
|
||||
return false;
|
||||
});
|
||||
}
|
||||
},
|
||||
fieldlist: function (form) {
|
||||
//绑定fieldlist
|
||||
if ($(".fieldlist", form).size() > 0) {
|
||||
require(['dragsort', 'template'], function (undefined, Template) {
|
||||
//刷新隐藏textarea的值
|
||||
var refresh = function (name) {
|
||||
var data = {};
|
||||
var textarea = $("textarea[name='" + name + "']", form);
|
||||
var container = $(".fieldlist[data-name='" + name + "']");
|
||||
var template = container.data("template");
|
||||
$.each($("input,select,textarea", container).serializeArray(), function (i, j) {
|
||||
var reg = /\[(\w+)\]\[(\w+)\]$/g;
|
||||
var match = reg.exec(j.name);
|
||||
if (!match)
|
||||
return true;
|
||||
match[1] = "x" + parseInt(match[1]);
|
||||
if (typeof data[match[1]] == 'undefined') {
|
||||
data[match[1]] = {};
|
||||
}
|
||||
data[match[1]][match[2]] = j.value;
|
||||
});
|
||||
var result = template ? [] : {};
|
||||
$.each(data, function (i, j) {
|
||||
if (j) {
|
||||
if (!template) {
|
||||
if (j.key != '') {
|
||||
result[j.key] = j.value;
|
||||
}
|
||||
} else {
|
||||
result.push(j);
|
||||
}
|
||||
}
|
||||
});
|
||||
textarea.val(JSON.stringify(result));
|
||||
};
|
||||
//监听文本框改变事件
|
||||
$(document).on('change keyup changed', ".fieldlist input,.fieldlist textarea,.fieldlist select", function () {
|
||||
refresh($(this).closest(".fieldlist").data("name"));
|
||||
});
|
||||
//追加控制
|
||||
$(".fieldlist", form).on("click", ".btn-append,.append", function (e, row) {
|
||||
var container = $(this).closest(".fieldlist");
|
||||
var tagName = container.data("tag") || "dd";
|
||||
var index = container.data("index");
|
||||
var name = container.data("name");
|
||||
var template = container.data("template");
|
||||
var data = container.data();
|
||||
index = index ? parseInt(index) : 0;
|
||||
container.data("index", index + 1);
|
||||
row = row ? row : {};
|
||||
var vars = {index: index, name: name, data: data, row: row};
|
||||
var html = template ? Template(template, vars) : Template.render(Form.config.fieldlisttpl, vars);
|
||||
$(html).insertBefore($(tagName + ":last", container));
|
||||
$(this).trigger("fa.event.appendfieldlist", $(this).closest(tagName).prev());
|
||||
});
|
||||
//移除控制
|
||||
$(".fieldlist", form).on("click", ".btn-remove", function () {
|
||||
var container = $(this).closest(".fieldlist");
|
||||
var tagName = container.data("tag") || "dd";
|
||||
$(this).closest(tagName).remove();
|
||||
refresh(container.data("name"));
|
||||
});
|
||||
//渲染数据&拖拽排序
|
||||
$(".fieldlist", form).each(function () {
|
||||
var container = this;
|
||||
var tagName = $(this).data("tag") || "dd";
|
||||
$(this).dragsort({
|
||||
itemSelector: tagName,
|
||||
dragSelector: ".btn-dragsort",
|
||||
dragEnd: function () {
|
||||
refresh($(this).closest(".fieldlist").data("name"));
|
||||
},
|
||||
placeHolderTemplate: $("<" + tagName + "/>")
|
||||
});
|
||||
var textarea = $("textarea[name='" + $(this).data("name") + "']", form);
|
||||
if (textarea.val() == '') {
|
||||
return true;
|
||||
}
|
||||
var template = $(this).data("template");
|
||||
var json = {};
|
||||
try {
|
||||
json = JSON.parse(textarea.val());
|
||||
} catch (e) {
|
||||
}
|
||||
$.each(json, function (i, j) {
|
||||
$(".btn-append,.append", container).trigger('click', template ? j : {
|
||||
key: i,
|
||||
value: j
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
},
|
||||
switcher: function (form) {
|
||||
form.on("click", "[data-toggle='switcher']", function () {
|
||||
if ($(this).hasClass("disabled")) {
|
||||
return false;
|
||||
}
|
||||
var input = $(this).prev("input");
|
||||
input = $(this).data("input-id") ? $("#" + $(this).data("input-id")) : input;
|
||||
if (input.size() > 0) {
|
||||
var yes = $(this).data("yes");
|
||||
var no = $(this).data("no");
|
||||
if (input.val() == yes) {
|
||||
input.val(no);
|
||||
$("i", this).addClass("fa-flip-horizontal text-gray");
|
||||
} else {
|
||||
input.val(yes);
|
||||
$("i", this).removeClass("fa-flip-horizontal text-gray");
|
||||
}
|
||||
input.trigger('change');
|
||||
}
|
||||
return false;
|
||||
});
|
||||
},
|
||||
bindevent: function (form) {
|
||||
|
||||
},
|
||||
slider: function (form) {
|
||||
if ($(".slider", form).size() > 0) {
|
||||
require(['bootstrap-slider'], function () {
|
||||
$('.slider').removeClass('hidden').css('width', function (index, value) {
|
||||
return $(this).parents('.form-control').width();
|
||||
}).slider().on('slide', function (ev) {
|
||||
var data = $(this).data();
|
||||
if (typeof data.unit !== 'undefined') {
|
||||
$(this).parents('.form-control').siblings('.value').text(ev.value + data.unit);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
},
|
||||
api: {
|
||||
submit: function (form, success, error, submit) {
|
||||
if (form.size() === 0) {
|
||||
Toastr.error("表单未初始化完成,无法提交");
|
||||
return false;
|
||||
}
|
||||
if (typeof submit === 'function') {
|
||||
if (false === submit.call(form, success, error)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
var type = form.attr("method") ? form.attr("method").toUpperCase() : 'GET';
|
||||
type = type && (type === 'GET' || type === 'POST') ? type : 'GET';
|
||||
url = form.attr("action");
|
||||
url = url ? url : location.href;
|
||||
//修复当存在多选项元素时提交的BUG
|
||||
var params = {};
|
||||
var multipleList = $("[name$='[]']", form);
|
||||
if (multipleList.size() > 0) {
|
||||
var postFields = form.serializeArray().map(function (obj) {
|
||||
return $(obj).prop("name");
|
||||
});
|
||||
$.each(multipleList, function (i, j) {
|
||||
if (postFields.indexOf($(this).prop("name")) < 0) {
|
||||
params[$(this).prop("name")] = '';
|
||||
}
|
||||
});
|
||||
}
|
||||
//调用Ajax请求方法
|
||||
sent.api.ajax({
|
||||
type: type,
|
||||
url: url,
|
||||
data: form.serialize() + (Object.keys(params).length > 0 ? '&' + $.param(params) : ''),
|
||||
dataType: 'json',
|
||||
complete: function (xhr) {
|
||||
var token = xhr.getResponseHeader('__token__');
|
||||
if (token) {
|
||||
$("input[name='__token__']").val(token);
|
||||
}
|
||||
}
|
||||
}, function (data, ret) {
|
||||
$('.form-group', form).removeClass('has-feedback has-success has-error');
|
||||
if (data && typeof data === 'object') {
|
||||
//刷新客户端token
|
||||
if (typeof data.token !== 'undefined') {
|
||||
$("input[name='__token__']").val(data.token);
|
||||
}
|
||||
//调用客户端事件
|
||||
if (typeof data.callback !== 'undefined' && typeof data.callback === 'function') {
|
||||
data.callback.call(form, data);
|
||||
}
|
||||
}
|
||||
if (typeof success === 'function') {
|
||||
if (false === success.call(form, data, ret)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}, function (data, ret) {
|
||||
if (data && typeof data === 'object' && typeof data.token !== 'undefined') {
|
||||
$("input[name='__token__']").val(data.token);
|
||||
}
|
||||
if (typeof error === 'function') {
|
||||
if (false === error.call(form, data, ret)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
});
|
||||
return true;
|
||||
},
|
||||
bindevent: function (form, success, error, submit) {
|
||||
form = typeof form === 'object' ? form : $(form);
|
||||
var events = Form.events;
|
||||
events.bindevent(form);
|
||||
events.validator(form, success, error, submit);
|
||||
events.editor(form);
|
||||
events.selectpicker(form);
|
||||
events.daterangepicker(form);
|
||||
events.selectpage(form);
|
||||
events.cxselect(form);
|
||||
events.citypicker(form);
|
||||
events.datetimepicker(form);
|
||||
events.plupload(form);
|
||||
events.faselect(form);
|
||||
events.fieldlist(form);
|
||||
events.slider(form);
|
||||
events.switcher(form);
|
||||
},
|
||||
custom: {},
|
||||
setFile: function(fileList, param){
|
||||
// console.log(fileList, param);
|
||||
layer.close(layer.index);
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
window.Form = Form;
|
||||
|
||||
return Form;
|
||||
});
|
||||
@@ -0,0 +1,442 @@
|
||||
define(['jquery', 'bootstrap', 'webupload'], function ($, undefined, WebUploader) {
|
||||
var Upload = {
|
||||
config: {
|
||||
image: {
|
||||
title: 'Images',
|
||||
extensions: 'gif,jpg,jpeg,bmp,png',
|
||||
mimeTypes: 'image/*'
|
||||
},
|
||||
file: {
|
||||
title: 'Files',
|
||||
extensions: '*',
|
||||
mimeTypes: '*'
|
||||
},
|
||||
upList: [],
|
||||
},
|
||||
index: function(){
|
||||
var query = sent.parseUrl(window.location.href);
|
||||
$wrap = $('#uploader'),
|
||||
// 图片容器
|
||||
$queue = $('<ul class="filelist"></ul>')
|
||||
.appendTo( $wrap.find('.queueList') ),
|
||||
// 状态栏,包括进度和控制按钮
|
||||
$statusBar = $wrap.find('.statusBar'),
|
||||
// 文件总体选择信息。
|
||||
$info = $statusBar.find('.info'),
|
||||
// 上传按钮
|
||||
$upload = $wrap.find('.uploadBtn'),
|
||||
// 没选择文件之前的内容。
|
||||
$placeHolder = $wrap.find('.placeholder'),
|
||||
// 总体进度条
|
||||
$progress = $statusBar.find('.progress').hide(),
|
||||
// 添加的文件数量
|
||||
fileCount = 0,
|
||||
// 添加的文件总大小
|
||||
fileSize = 0,
|
||||
// 优化retina, 在retina下这个值是2
|
||||
ratio = window.devicePixelRatio || 1,
|
||||
// 缩略图大小
|
||||
thumbnailWidth = 110 * ratio,
|
||||
thumbnailHeight = 110 * ratio,
|
||||
// 可能有pedding, ready, uploading, confirm, done.
|
||||
state = 'pedding',
|
||||
// 所有文件的进度信息,key为file id
|
||||
percentages = {},
|
||||
supportTransition = (function(){
|
||||
var s = document.createElement('p').style,
|
||||
r = 'transition' in s ||
|
||||
'WebkitTransition' in s ||
|
||||
'MozTransition' in s ||
|
||||
'msTransition' in s ||
|
||||
'OTransition' in s;
|
||||
s = null;
|
||||
return r;
|
||||
})(),
|
||||
// WebUploader实例
|
||||
uploader;
|
||||
|
||||
if ( !WebUploader.Uploader.support() ) {
|
||||
alert( 'Web Uploader 不支持您的浏览器!如果你使用的是IE浏览器,请尝试升级 flash 播放器');
|
||||
throw new Error( 'WebUploader does not support the browser you are using.' );
|
||||
}
|
||||
// 实例化
|
||||
uploader = WebUploader.create({
|
||||
pick: {
|
||||
id: '#filePicker',
|
||||
label: '点击选择'+(query.type == 'image' ? '图片' : '文件')
|
||||
},
|
||||
dnd: '#uploader .queueList',
|
||||
paste: document.body,
|
||||
accept: Upload.config[query.type],
|
||||
// swf文件路径
|
||||
// swf: baseRoot + 'plugins/webuploader/Uploader.swf',
|
||||
disableGlobalDnd: true,
|
||||
chunked: true,
|
||||
// server: 'http://webuploader.duapp.com/server/fileupload.php',
|
||||
server: '/'+Config.module+'/upload/upload',
|
||||
fileNumLimit: 300,
|
||||
fileSizeLimit: 5 * 1024 * 1024, // 200 M
|
||||
fileSingleSizeLimit: 1 * 1024 * 1024 // 50 M
|
||||
});
|
||||
|
||||
// 添加“添加文件”的按钮,
|
||||
uploader.addButton({
|
||||
id: '#filePicker2',
|
||||
label: '继续添加'
|
||||
});
|
||||
|
||||
uploader.onUploadProgress = function( file, percentage ) {
|
||||
var $li = $('#'+file.id),
|
||||
$percent = $li.find('.progress span');
|
||||
|
||||
$percent.css( 'width', percentage * 100 + '%' );
|
||||
percentages[ file.id ][ 1 ] = percentage;
|
||||
Upload.updateTotalProgress();
|
||||
};
|
||||
|
||||
uploader.onFileQueued = function( file ) {
|
||||
fileCount++;
|
||||
fileSize += file.size;
|
||||
|
||||
if ( fileCount === 1 ) {
|
||||
$placeHolder.addClass( 'element-invisible' );
|
||||
$statusBar.show();
|
||||
}
|
||||
Upload.addFile( file );
|
||||
Upload.setState( 'ready' );
|
||||
Upload.updateTotalProgress();
|
||||
};
|
||||
|
||||
uploader.onFileDequeued = function( file ) {
|
||||
fileCount--;
|
||||
fileSize -= file.size;
|
||||
|
||||
if ( !fileCount ) {
|
||||
Upload.setState( 'pedding' );
|
||||
}
|
||||
|
||||
Upload.removeFile( file );
|
||||
Upload.updateTotalProgress();
|
||||
|
||||
};
|
||||
|
||||
uploader.on( 'all', function( type, file, response ) {
|
||||
var stats;
|
||||
switch( type ) {
|
||||
case 'uploadFinished':
|
||||
Upload.setState( 'confirm' );
|
||||
break;
|
||||
case 'uploadSuccess':
|
||||
Upload.uploadSuccess(response, file);
|
||||
break;
|
||||
case 'startUpload':
|
||||
Upload.setState( 'uploading' );
|
||||
break;
|
||||
|
||||
case 'stopUpload':
|
||||
Upload.setState( 'paused' );
|
||||
break;
|
||||
|
||||
}
|
||||
});
|
||||
|
||||
uploader.onError = function( code ) {
|
||||
sent.msg( 'Eroor: ' + code, 'error' );
|
||||
};
|
||||
|
||||
$upload.on('click', function() {
|
||||
if ( $(this).hasClass( 'disabled' ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ( state === 'ready' ) {
|
||||
uploader.upload();
|
||||
} else if ( state === 'paused' ) {
|
||||
uploader.upload();
|
||||
} else if ( state === 'uploading' ) {
|
||||
uploader.stop();
|
||||
}
|
||||
});
|
||||
|
||||
$info.on( 'click', '.retry', function() {
|
||||
uploader.retry();
|
||||
} );
|
||||
|
||||
$info.on( 'click', '.ignore', function() {
|
||||
alert( 'todo' );
|
||||
} );
|
||||
|
||||
$upload.addClass( 'state-' + state );
|
||||
Upload.updateTotalProgress();
|
||||
},
|
||||
// 当有文件添加进来时执行,负责view的创建
|
||||
addFile: function ( file ) {
|
||||
var $li = $( '<li id="' + file.id + '">' +
|
||||
'<p class="title">' + file.name + '</p>' +
|
||||
'<p class="imgWrap"></p>'+
|
||||
'<p class="progress"><span></span></p>' +
|
||||
'</li>' ),
|
||||
|
||||
$btns = $('<div class="file-panel">' +
|
||||
'<span class="cancel">删除</span>' +
|
||||
'<span class="rotateRight">向右旋转</span>' +
|
||||
'<span class="rotateLeft">向左旋转</span></div>').appendTo( $li ),
|
||||
$prgress = $li.find('p.progress span'),
|
||||
$wrap = $li.find( 'p.imgWrap' ),
|
||||
$info = $('<p class="error"></p>'),
|
||||
|
||||
showError = function( code ) {
|
||||
switch( code ) {
|
||||
case 'exceed_size':
|
||||
text = '文件大小超出';
|
||||
break;
|
||||
|
||||
case 'interrupt':
|
||||
text = '上传暂停';
|
||||
break;
|
||||
|
||||
default:
|
||||
text = '上传失败,请重试';
|
||||
break;
|
||||
}
|
||||
|
||||
$info.text( text ).appendTo( $li );
|
||||
};
|
||||
|
||||
if ( file.getStatus() === 'invalid' ) {
|
||||
showError( file.statusText );
|
||||
} else {
|
||||
// @todo lazyload
|
||||
$wrap.text( '预览中' );
|
||||
uploader.makeThumb( file, function( error, src ) {
|
||||
if ( error ) {
|
||||
$wrap.text( '不能预览' );
|
||||
return;
|
||||
}
|
||||
|
||||
var img = $('<img src="'+src+'">');
|
||||
$wrap.empty().append( img );
|
||||
}, thumbnailWidth, thumbnailHeight );
|
||||
|
||||
percentages[ file.id ] = [ file.size, 0 ];
|
||||
file.rotation = 0;
|
||||
}
|
||||
|
||||
file.on('statuschange', function( cur, prev ) {
|
||||
if ( prev === 'progress' ) {
|
||||
$prgress.hide().width(0);
|
||||
} else if ( prev === 'queued' ) {
|
||||
$li.off( 'mouseenter mouseleave' );
|
||||
$btns.remove();
|
||||
}
|
||||
|
||||
// 成功
|
||||
if ( cur === 'error' || cur === 'invalid' ) {
|
||||
console.log( file.statusText );
|
||||
showError( file.statusText );
|
||||
percentages[ file.id ][ 1 ] = 1;
|
||||
} else if ( cur === 'interrupt' ) {
|
||||
showError( 'interrupt' );
|
||||
} else if ( cur === 'queued' ) {
|
||||
percentages[ file.id ][ 1 ] = 0;
|
||||
} else if ( cur === 'progress' ) {
|
||||
$info.remove();
|
||||
$prgress.css('display', 'block');
|
||||
} else if ( cur === 'complete' ) {
|
||||
$li.append( '<span class="success"></span>' );
|
||||
}
|
||||
|
||||
$li.removeClass( 'state-' + prev ).addClass( 'state-' + cur );
|
||||
});
|
||||
|
||||
$li.on( 'mouseenter', function() {
|
||||
$btns.stop().animate({height: 30});
|
||||
});
|
||||
|
||||
$li.on( 'mouseleave', function() {
|
||||
$btns.stop().animate({height: 0});
|
||||
});
|
||||
|
||||
$btns.on( 'click', 'span', function() {
|
||||
var index = $(this).index(),
|
||||
deg;
|
||||
|
||||
switch ( index ) {
|
||||
case 0:
|
||||
uploader.removeFile( file );
|
||||
return;
|
||||
|
||||
case 1:
|
||||
file.rotation += 90;
|
||||
break;
|
||||
|
||||
case 2:
|
||||
file.rotation -= 90;
|
||||
break;
|
||||
}
|
||||
|
||||
if ( supportTransition ) {
|
||||
deg = 'rotate(' + file.rotation + 'deg)';
|
||||
$wrap.css({
|
||||
'-webkit-transform': deg,
|
||||
'-mos-transform': deg,
|
||||
'-o-transform': deg,
|
||||
'transform': deg
|
||||
});
|
||||
} else {
|
||||
$wrap.css( 'filter', 'progid:DXImageTransform.Microsoft.BasicImage(rotation='+ (~~((file.rotation/90)%4 + 4)%4) +')');
|
||||
// use jquery animate to rotation
|
||||
// $({
|
||||
// rotation: rotation
|
||||
// }).animate({
|
||||
// rotation: file.rotation
|
||||
// }, {
|
||||
// easing: 'linear',
|
||||
// step: function( now ) {
|
||||
// now = now * Math.PI / 180;
|
||||
|
||||
// var cos = Math.cos( now ),
|
||||
// sin = Math.sin( now );
|
||||
|
||||
// $wrap.css( 'filter', "progid:DXImageTransform.Microsoft.Matrix(M11=" + cos + ",M12=" + (-sin) + ",M21=" + sin + ",M22=" + cos + ",SizingMethod='auto expand')");
|
||||
// }
|
||||
// });
|
||||
}
|
||||
|
||||
|
||||
});
|
||||
|
||||
$li.appendTo( $queue );
|
||||
},
|
||||
// 负责view的销毁
|
||||
removeFile: function ( file ) {
|
||||
var $li = $('#'+file.id);
|
||||
|
||||
delete percentages[ file.id ];
|
||||
Upload.updateTotalProgress();
|
||||
$li.off().find('.file-panel').off().end().remove();
|
||||
},
|
||||
updateTotalProgress: function() {
|
||||
var loaded = 0,
|
||||
total = 0,
|
||||
spans = $progress.children(),
|
||||
percent;
|
||||
|
||||
$.each( percentages, function( k, v ) {
|
||||
total += v[ 0 ];
|
||||
loaded += v[ 0 ] * v[ 1 ];
|
||||
} );
|
||||
|
||||
percent = total ? loaded / total : 0;
|
||||
|
||||
spans.eq( 0 ).text( Math.round( percent * 100 ) + '%' );
|
||||
spans.eq( 1 ).css( 'width', Math.round( percent * 100 ) + '%' );
|
||||
Upload.updateStatus();
|
||||
},
|
||||
updateStatus: function () {
|
||||
var text = '', stats;
|
||||
|
||||
if ( state === 'ready' ) {
|
||||
text = '选中' + fileCount + '张图片,共' +
|
||||
WebUploader.formatSize( fileSize ) + '。';
|
||||
} else if ( state === 'confirm' ) {
|
||||
stats = uploader.getStats();
|
||||
if ( stats.uploadFailNum ) {
|
||||
text = '已成功上传' + stats.successNum+ '张照片至XX相册,'+
|
||||
stats.uploadFailNum + '张照片上传失败,<a class="retry" href="#">重新上传</a>失败图片或<a class="ignore" href="#">忽略</a>'
|
||||
}
|
||||
|
||||
} else {
|
||||
stats = uploader.getStats();
|
||||
text = '共' + fileCount + '张(' +
|
||||
WebUploader.formatSize( fileSize ) +
|
||||
'),已上传' + stats.successNum + '张';
|
||||
|
||||
if ( stats.uploadFailNum ) {
|
||||
text += ',失败' + stats.uploadFailNum + '张';
|
||||
}
|
||||
}
|
||||
|
||||
$info.html( text );
|
||||
},
|
||||
setState: function ( val ) {
|
||||
var file, stats;
|
||||
|
||||
if ( val === state ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$upload.removeClass( 'state-' + state );
|
||||
$upload.addClass( 'state-' + val );
|
||||
state = val;
|
||||
|
||||
switch ( state ) {
|
||||
case 'pedding':
|
||||
$placeHolder.removeClass( 'element-invisible' );
|
||||
$queue.parent().removeClass('filled');
|
||||
$queue.hide();
|
||||
$statusBar.addClass( 'element-invisible' );
|
||||
uploader.refresh();
|
||||
break;
|
||||
|
||||
case 'ready':
|
||||
$placeHolder.addClass( 'element-invisible' );
|
||||
$( '#filePicker2' ).removeClass( 'element-invisible');
|
||||
$queue.parent().addClass('filled');
|
||||
$queue.show();
|
||||
$statusBar.removeClass('element-invisible');
|
||||
uploader.refresh();
|
||||
break;
|
||||
|
||||
case 'uploading':
|
||||
$( '#filePicker2' ).addClass( 'element-invisible' );
|
||||
$progress.show();
|
||||
$upload.text( '暂停上传' );
|
||||
break;
|
||||
|
||||
case 'paused':
|
||||
$progress.show();
|
||||
$upload.text( '继续上传' );
|
||||
break;
|
||||
|
||||
case 'confirm':
|
||||
$progress.hide();
|
||||
$upload.text( '开始上传' ).addClass( 'disabled' );
|
||||
|
||||
stats = uploader.getStats();
|
||||
if ( stats.successNum && !stats.uploadFailNum ) {
|
||||
Upload.setState( 'finish' );
|
||||
return;
|
||||
}
|
||||
break;
|
||||
case 'finish':
|
||||
stats = uploader.getStats();
|
||||
if ( stats.successNum ) {
|
||||
sent.msg( '上传成功', 'success' );
|
||||
} else {
|
||||
// 没有成功的图片,重设
|
||||
state = 'done';
|
||||
location.reload();
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
Upload.updateStatus();
|
||||
},
|
||||
uploadSuccess: function(res, file){
|
||||
if (res.code == 1) {
|
||||
var query = sent.parseUrl(window.location.href);
|
||||
Upload.config.upList.push(res.info);
|
||||
parent.Form.api.setFile(Upload.config.upList, query);
|
||||
}
|
||||
},
|
||||
server: function(){
|
||||
$('button.btn-select').click(function(){
|
||||
var query = sent.parseUrl(window.location.href);
|
||||
parent.Form.api.setFile(Upload.config.upList, query);
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return Upload;
|
||||
})
|
||||
@@ -0,0 +1,3 @@
|
||||
define(['validator-core', 'validator-lang'], function (Validator, undefined) {
|
||||
return Validator;
|
||||
});
|
||||
@@ -0,0 +1,210 @@
|
||||
define(['jquery', 'layer', 'form', 'message'], function($, layer, form) {
|
||||
var sent = {
|
||||
config: {
|
||||
keyName: 'sent_'
|
||||
},
|
||||
init: function(){
|
||||
form.api.bindevent($("form[role=form]"));
|
||||
},
|
||||
msg: function(text, type){
|
||||
if (typeof type != 'undefined') {
|
||||
var message = $.messager.show(text, {
|
||||
placement: 'bottom',
|
||||
type: type
|
||||
});
|
||||
} else {
|
||||
var message = $.messager.show(text, {
|
||||
placement: 'bottom'
|
||||
})
|
||||
}
|
||||
message.show();
|
||||
},
|
||||
parseUrl: function (url) {
|
||||
if (url.indexOf("?") === -1) {
|
||||
return {};
|
||||
}
|
||||
url = decodeURIComponent(url);
|
||||
var query = url.split("?")[1];
|
||||
var queryArr = query.split("&");
|
||||
var obj = {};
|
||||
queryArr.forEach(function (item) {
|
||||
var key = item.split("=")[0];
|
||||
var value = item.split("=")[1];
|
||||
obj[key] = decodeURIComponent(value);
|
||||
});
|
||||
return obj;
|
||||
},
|
||||
store: {
|
||||
set: function(params = {}){
|
||||
var { name, content, type} = params;
|
||||
name = sent.config.keyName + name
|
||||
var obj = {
|
||||
dataType: typeof (content),
|
||||
content: content,
|
||||
type: type,
|
||||
datetime: new Date().getTime()
|
||||
}
|
||||
if (type) window.sessionStorage.setItem(name, JSON.stringify(obj));
|
||||
else window.localStorage.setItem(name, JSON.stringify(obj));
|
||||
},
|
||||
get: function(params = {}){
|
||||
var { name, debug } = params;
|
||||
name = sent.config.keyName + name
|
||||
var obj = {},
|
||||
content;
|
||||
obj = window.sessionStorage.getItem(name);
|
||||
if (sent.validatenull(obj)) obj = window.localStorage.getItem(name);
|
||||
if (sent.validatenull(obj)) return;
|
||||
try {
|
||||
obj = JSON.parse(obj);
|
||||
} catch (error) {
|
||||
return obj;
|
||||
}
|
||||
if (debug) {
|
||||
return obj;
|
||||
}
|
||||
if (obj.dataType == 'string') {
|
||||
content = obj.content;
|
||||
} else if (obj.dataType == 'number') {
|
||||
content = Number(obj.content);
|
||||
} else if (obj.dataType == 'boolean') {
|
||||
content = eval(obj.content);
|
||||
} else if (obj.dataType == 'object') {
|
||||
content = obj.content;
|
||||
}
|
||||
return content;
|
||||
},
|
||||
remove: function(params = {}){
|
||||
let { name, type } = params;
|
||||
name = sent.config.keyName + name
|
||||
if (type) {
|
||||
window.sessionStorage.removeItem(name);
|
||||
} else {
|
||||
window.localStorage.removeItem(name);
|
||||
}
|
||||
},
|
||||
all: function(params = {}){
|
||||
let list = [];
|
||||
let { type } = params;
|
||||
if (type) {
|
||||
for (let i = 0; i <= window.sessionStorage.length; i++) {
|
||||
list.push({
|
||||
name: window.sessionStorage.key(i),
|
||||
content: getStore({
|
||||
name: window.sessionStorage.key(i),
|
||||
type: 'session'
|
||||
})
|
||||
})
|
||||
}
|
||||
} else {
|
||||
for (let i = 0; i <= window.localStorage.length; i++) {
|
||||
list.push({
|
||||
name: window.localStorage.key(i),
|
||||
content: getStore({
|
||||
name: window.localStorage.key(i),
|
||||
})
|
||||
})
|
||||
|
||||
}
|
||||
}
|
||||
return list;
|
||||
},
|
||||
clear: function(params = {}){
|
||||
let { type } = params;
|
||||
if (type) {
|
||||
window.sessionStorage.clear();
|
||||
} else {
|
||||
window.localStorage.clear()
|
||||
}
|
||||
}
|
||||
},
|
||||
events: {
|
||||
//请求成功的回调
|
||||
onAjaxSuccess: function (ret, onAjaxSuccess) {
|
||||
var data = typeof ret.data !== 'undefined' ? ret.data : null;
|
||||
var msg = typeof ret.msg !== 'undefined' && ret.msg ? ret.msg : __('Operation completed');
|
||||
|
||||
if (typeof onAjaxSuccess === 'function') {
|
||||
var result = onAjaxSuccess.call(this, data, ret);
|
||||
if (result === false)
|
||||
return;
|
||||
}
|
||||
sent.msg(msg, 'success');
|
||||
},
|
||||
//请求错误的回调
|
||||
onAjaxError: function (ret, onAjaxError) {
|
||||
var data = typeof ret.data !== 'undefined' ? ret.data : null;
|
||||
if (typeof onAjaxError === 'function') {
|
||||
var result = onAjaxError.call(this, data, ret);
|
||||
if (result === false) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
sent.msg(ret.msg, 'error');
|
||||
},
|
||||
//服务器响应数据后
|
||||
onAjaxResponse: function (response) {
|
||||
try {
|
||||
var ret = typeof response === 'object' ? response : JSON.parse(response);
|
||||
if (!ret.hasOwnProperty('code')) {
|
||||
$.extend(ret, {code: -2, msg: response, data: null});
|
||||
}
|
||||
} catch (e) {
|
||||
var ret = {code: -1, msg: e.message, data: null};
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
},
|
||||
api:{
|
||||
//发送Ajax请求
|
||||
ajax: function (options, success, error) {
|
||||
options = typeof options === 'string' ? {url: options} : options;
|
||||
var index;
|
||||
if (typeof options.loading === 'undefined' || options.loading) {
|
||||
index = layer.load(options.loading || 0);
|
||||
}
|
||||
options = $.extend({
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
success: function (ret) {
|
||||
index && layer.close(index);
|
||||
ret = sent.events.onAjaxResponse(ret);
|
||||
if (ret.code === 1) {
|
||||
sent.events.onAjaxSuccess(ret, success);
|
||||
} else {
|
||||
sent.events.onAjaxError(ret, error);
|
||||
}
|
||||
},
|
||||
error: function (xhr) {
|
||||
index && layer.close(index);
|
||||
var ret = {code: xhr.status, msg: xhr.statusText, data: null};
|
||||
sent.events.onAjaxError(ret, error);
|
||||
}
|
||||
}, options);
|
||||
return $.ajax(options);
|
||||
},
|
||||
},
|
||||
validatenull: function(val){
|
||||
if (typeof val == 'boolean') {
|
||||
return false;
|
||||
}
|
||||
if (typeof val == 'number') {
|
||||
return false;
|
||||
}
|
||||
if (val instanceof Array) {
|
||||
if (val.length == 0) return true;
|
||||
} else if (val instanceof Object) {
|
||||
if (JSON.stringify(val) === '{}') return true;
|
||||
} else {
|
||||
if (val == 'null' || val == null || val == 'undefined' || val == undefined || val == '') return true;
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
};
|
||||
window.sent = sent;
|
||||
window.layer = layer;
|
||||
|
||||
sent.init();
|
||||
return sent;
|
||||
});
|
||||
Reference in New Issue
Block a user