admin.js 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050
  1. // +----------------------------------------------------------------------
  2. // | ThinkAdmin
  3. // +----------------------------------------------------------------------
  4. // | 版权所有 2014~2022 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
  5. // +----------------------------------------------------------------------
  6. // | 官方网站: https://thinkadmin.top
  7. // +----------------------------------------------------------------------
  8. // | 开源协议 ( https://mit-license.org )
  9. // | 免费声明 ( https://thinkadmin.top/disclaimer )
  10. // +----------------------------------------------------------------------
  11. // | gitee 代码仓库:https://gitee.com/zoujingli/ThinkAdmin
  12. // | github 代码仓库:https://github.com/zoujingli/ThinkAdmin
  13. // +----------------------------------------------------------------------
  14. /*! 数组兼容处理 */
  15. if (typeof Array.prototype.some !== 'function') {
  16. Array.prototype.some = function (callable) {
  17. for (var i in this) if (callable(this[i], i, this) === true) {
  18. return true;
  19. }
  20. return false;
  21. };
  22. }
  23. if (typeof Array.prototype.every !== 'function') {
  24. Array.prototype.every = function (callable) {
  25. for (var i in this) if (callable(this[i], i, this) === false) {
  26. return false;
  27. }
  28. return true;
  29. };
  30. }
  31. if (typeof Array.prototype.forEach !== 'function') {
  32. Array.prototype.forEach = function (callable, context) {
  33. typeof context === "undefined" ? context = window : null;
  34. for (var i in this) callable.call(context, this[i], i, this)
  35. };
  36. }
  37. /*! 应用根路径,静态插件库路径,动态插件库路径 */
  38. var srcs = document.scripts[document.scripts.length - 1].src.split('/');
  39. window.appRoot = srcs.slice(0, -2).join('/') + '/';
  40. window.baseRoot = srcs.slice(0, -1).join('/') + '/';
  41. window.tapiRoot = window.tapiRoot || window.appRoot + "admin";
  42. /*! 挂载 layui & jquery 对象 */
  43. layui.config({base: baseRoot + 'plugs/layui_exts/'});
  44. window.form = layui.form, window.layer = layui.layer;
  45. window.laytpl = layui.laytpl, window.laydate = layui.laydate;
  46. window.jQuery = window.$ = window.jQuery || window.$ || layui.$;
  47. /*! 配置 require 参数 */
  48. require.config({
  49. baseUrl: baseRoot,
  50. waitSeconds: 60,
  51. map: {'*': {css: baseRoot + 'plugs/require/css.js'}},
  52. paths: {
  53. 'vue': ['plugs/vue/vue.min'],
  54. 'md5': ['plugs/jquery/md5.min'],
  55. 'json': ['plugs/jquery/json.min'],
  56. 'xlsx': ['plugs/jquery/xlsx.min'],
  57. 'excel': ['plugs/jquery/excel.xlsx'],
  58. 'base64': ['plugs/jquery/base64.min'],
  59. 'upload': [tapiRoot + '/api.upload/index?'],
  60. 'notify': ['plugs/notify/notify.min'],
  61. 'angular': ['plugs/angular/angular.min'],
  62. 'cropper': ['plugs/cropper/cropper.min'],
  63. 'echarts': ['plugs/echarts/echarts.min'],
  64. 'ckeditor4': ['plugs/ckeditor4/ckeditor'],
  65. 'ckeditor5': ['plugs/ckeditor5/ckeditor'],
  66. 'websocket': ['plugs/socket/websocket'],
  67. 'pcasunzips': ['plugs/jquery/pcasunzips'],
  68. 'sortablejs': ['plugs/sortable/sortable.min'],
  69. 'vue.sortable': ['plugs/sortable/vue.draggable.min'],
  70. 'jquery.ztree': ['plugs/ztree/ztree.all.min'],
  71. 'jquery.masonry': ['plugs/jquery/masonry.min'],
  72. 'jquery.cropper': ['plugs/cropper/cropper.min'],
  73. 'jquery.autocompleter': ['plugs/jquery/autocompleter.min'],
  74. }, shim: {
  75. 'excel': {deps: [baseRoot + 'plugs/layui_exts/excel.js']},
  76. 'notify': {deps: ['css!' + baseRoot + 'plugs/notify/light.css']},
  77. 'cropper': {deps: ['css!' + baseRoot + 'plugs/cropper/cropper.min.css']},
  78. 'websocket': {deps: [baseRoot + 'plugs/socket/swfobject.min.js']},
  79. 'ckeditor5': {deps: ['jquery', 'upload', 'css!' + baseRoot + 'plugs/ckeditor5/ckeditor.css']},
  80. 'vue.sortable': {deps: ['vue', 'sortablejs']},
  81. 'jquery.ztree': {deps: ['jquery', 'css!' + baseRoot + 'plugs/ztree/zTreeStyle/zTreeStyle.css']},
  82. 'jquery.autocompleter': {deps: ['jquery', 'css!' + baseRoot + 'plugs/jquery/autocompleter.css']},
  83. }
  84. });
  85. /*! 注册 jquery 组件 */
  86. define('jquery', [], function () {
  87. return layui.$;
  88. });
  89. /*! 注册 ckeditor 组件 */
  90. define('ckeditor', (function (type) {
  91. if (/^ckeditor[45]$/.test(type)) return [type];
  92. return [Object.fromEntries ? 'ckeditor5' : 'ckeditor4'];
  93. })(window.taEditor || 'ckeditor4'), function (ckeditor) {
  94. return ckeditor;
  95. });
  96. $(function () {
  97. window.$body = $('body');
  98. /*! 注册单次事件 */
  99. function onEvent(event, select, callable) {
  100. return $body.off(event, select).on(event, select, callable);
  101. }
  102. /*! 注册确认回调 */
  103. function onConfirm(confirm, callable) {
  104. confirm ? $.msg.confirm(confirm, callable) : callable();
  105. }
  106. /*! 获取加载回调 */
  107. onConfirm.getLoadcallable = function (tabldId, callable) {
  108. typeof callable === 'function' && callable();
  109. return tabldId ? function (ret, time) {
  110. if (ret.code < 1) return true;
  111. time === 'false' ? $.layTable.reload(tabldId) : $.msg.success(ret.info, time, function () {
  112. $.layTable.reload(tabldId);
  113. });
  114. return false;
  115. } : false;
  116. }
  117. /*! 读取 data-rule 绑定 table 值 */
  118. function applyRuleValue(elem, data) {
  119. // 新 tableId 规则兼容处理
  120. if (elem.dataset.tableId && elem.dataset.rule) {
  121. var idx1, idx2, temp, regx, field, rule = {};
  122. var json = layui.table.checkStatus(elem.dataset.tableId).data;
  123. layui.each(elem.dataset.rule.split(';'), function (idx, item, attr) {
  124. (attr = item.split('#', 2)), rule[attr[0]] = attr[1];
  125. });
  126. for (idx1 in rule) {
  127. temp = [], regx = new RegExp(/^{(.*?)}$/);
  128. if (regx.test(rule[idx1]) && (field = rule[idx1].replace(regx, '$1'))) {
  129. for (idx2 in json) if (json[idx2][field]) temp.push(json[idx2][field]);
  130. if (temp.length < 1) return $.msg.tips('请选择需要更改的数据!'), false;
  131. data[idx1] = temp.join(',');
  132. } else {
  133. data[idx1] = rule[idx1];
  134. }
  135. }
  136. return data;
  137. } else {
  138. var value = elem.dataset.value || (function (rule, array) {
  139. $(elem.dataset.target || 'input[type=checkbox].list-check-box').map(function () {
  140. this.checked && array.push(this.value);
  141. });
  142. return array.length > 0 ? rule.replace('{key}', array.join(',')) : '';
  143. })(elem.dataset.rule || '', []) || '';
  144. if (value.length < 1) return $.msg.tips('请选择需要更改的数据!'), false;
  145. return value.split(';').forEach(function (item) {
  146. data[item.split('#')[0]] = item.split('#')[1];
  147. }), data;
  148. }
  149. }
  150. /*! 消息组件实例 */
  151. $.msg = new function () {
  152. var that = this;
  153. this.idx = [], this.mdx = [];
  154. this.shade = [0.02, '#000000'];
  155. /*! 关闭消息框 */
  156. this.close = function (idx) {
  157. if (idx !== null) return layer.close(idx);
  158. for (var i in this.idx) that.close(this.idx[i]);
  159. this.idx = [];
  160. };
  161. /*! 弹出警告框 */
  162. this.alert = function (msg, call) {
  163. var idx = layer.alert(msg, {end: call, scrollbar: false});
  164. return that.idx.push(idx), idx;
  165. };
  166. /*! 显示成功类型的消息 */
  167. this.success = function (msg, time, call) {
  168. var idx = layer.msg(msg, {icon: 1, shade: this.shade, scrollbar: false, end: call, time: (time || 2) * 1000, shadeClose: true});
  169. return that.idx.push(idx), idx;
  170. };
  171. /*! 显示失败类型的消息 */
  172. this.error = function (msg, time, call) {
  173. var idx = layer.msg(msg, {icon: 2, shade: this.shade, scrollbar: false, time: (time || 3) * 1000, end: call, shadeClose: true});
  174. return that.idx.push(idx), idx;
  175. };
  176. /*! 状态消息提示 */
  177. this.tips = function (msg, time, call) {
  178. var idx = layer.msg(msg, {time: (time || 3) * 1000, shade: this.shade, end: call, shadeClose: true});
  179. return that.idx.push(idx), idx;
  180. };
  181. /*! 显示加载提示 */
  182. this.loading = function (msg, call) {
  183. var idx = msg ? layer.msg(msg, {icon: 16, scrollbar: false, shade: this.shade, time: 0, end: call}) : layer.load(2, {time: 0, scrollbar: false, shade: this.shade, end: call});
  184. return that.idx.push(idx), idx;
  185. };
  186. /*! 页面加载层 */
  187. this.page = new function () {
  188. this.$body = $('body>.think-page-loader');
  189. this.$main = $('.think-page-body+.think-page-loader');
  190. this.stat = function () {
  191. return this.$body.is(':visible');
  192. }, this.done = function () {
  193. that.page.$body.fadeOut();
  194. }, this.show = function () {
  195. this.stat() || this.$main.removeClass('layui-hide').show();
  196. }, this.hide = function () {
  197. if (this.time) clearTimeout(this.time);
  198. this.time = setTimeout(function () {
  199. (that.page.time = 0) || that.page.$main.fadeOut();
  200. }, 200);
  201. };
  202. };
  203. /*! 确认对话框 */
  204. this.confirm = function (msg, ok, no) {
  205. return layer.confirm(msg, {title: '操作确认', btn: ['确认', '取消']}, function (idx) {
  206. (typeof ok === 'function' && ok.call(this, idx)), that.close(idx);
  207. }, function (idx) {
  208. (typeof no === 'function' && no.call(this, idx)), that.close(idx);
  209. });
  210. };
  211. /*! 自动处理JSON数据 */
  212. this.auto = function (ret, time) {
  213. var url = ret.url || (typeof ret.data === 'string' ? ret.data : '');
  214. var msg = ret.msg || (typeof ret.info === 'string' ? ret.info : '');
  215. if (parseInt(ret.code) === 1 && time === 'false') {
  216. return url ? location.href = url : $.form.reload();
  217. } else return (parseInt(ret.code) === 1) ? this.success(msg, time, function () {
  218. url ? location.href = url : $.form.reload();
  219. that.close($.msg.mdx.length > 0 ? $.msg.mdx.pop() : null);
  220. }) : this.error(msg, 3, function () {
  221. url ? location.href = url : '';
  222. });
  223. };
  224. };
  225. /*! 表单自动化组件 */
  226. $.form = new function () {
  227. var that = this;
  228. /*! 内容区选择器 */
  229. this.selecter = '.layui-layout-admin>.layui-body>.think-page-body';
  230. /*! 刷新当前页面 */
  231. this.reload = function (force) {
  232. if (force) return top.location.reload();
  233. if (self !== top) return location.reload();
  234. return $.menu.href(location.hash);
  235. };
  236. /*! 内容区域动态加载后初始化 */
  237. this.reInit = function ($dom) {
  238. layui.form.render(), layui.element.render(), $(window).trigger('scroll');
  239. $.vali.listen($dom = $dom || $(this.selecter)), $body.trigger('reInit', $dom);
  240. return $dom.find('[required]').map(function () {
  241. this.$parent = $(this).parent();
  242. if (this.$parent.is('label')) this.$parent.addClass('label-required-prev'); else this.$parent.prevAll('label.layui-form-label').addClass('label-required-next');
  243. }), $dom.find('[data-lazy-src]:not([data-lazy-loaded])').map(function () {
  244. if (this.dataset.lazyLoaded === 'true') return; else this.dataset.lazyLoaded = 'true';
  245. if (this.nodeName === 'IMG') this.src = this.dataset.lazySrc; else this.style.backgroundImage = 'url(' + this.dataset.lazySrc + ')';
  246. }), $dom.find('input[data-date-range]').map(function () {
  247. this.setAttribute('autocomplete', 'off'), laydate.render({
  248. type: this.dataset.dateRange || 'date', range: true, elem: this, done: function (value) {
  249. $(this.elem).val(value).trigger('change');
  250. }
  251. });
  252. }), $dom.find('input[data-date-input]').map(function () {
  253. this.setAttribute('autocomplete', 'off'), laydate.render({
  254. type: this.dataset.dateInput || 'date', range: false, elem: this, done: function (value) {
  255. $(this.elem).val(value).trigger('change');
  256. }
  257. });
  258. }), $dom;
  259. };
  260. /*! 在内容区显示视图 */
  261. this.show = function (html) {
  262. that.reInit($(this.selecter).html(html));
  263. };
  264. /*! 异步加载的数据 */
  265. this.load = function (url, data, method, callable, loading, tips, time, headers) {
  266. // 如果主页面 loader 显示中,绝对不显示 loading 图标
  267. loading = $('.layui-page-loader').is(':visible') ? false : loading;
  268. var loadidx = loading !== false ? $.msg.loading(tips) : 0;
  269. if (typeof data === 'object' && typeof data['_token_'] === 'string') {
  270. headers = headers || {}, headers['User-Form-Token'] = data['_token_'], delete data['_token_'];
  271. }
  272. $.ajax({
  273. data: data || {}, type: method || 'GET', url: $.menu.parseUri(url), beforeSend: function (xhr, i) {
  274. if (typeof Pace === 'object' && loading !== false) Pace.restart();
  275. if (typeof headers === 'object') for (i in headers) xhr.setRequestHeader(i, headers[i]);
  276. }, error: function (XMLHttpRequest, $dialog, layIdx, iframe) {
  277. if (parseInt(XMLHttpRequest.status) !== 200 && XMLHttpRequest.responseText.indexOf('Call Stack') > -1) try {
  278. layIdx = layer.open({title: XMLHttpRequest.status + ' - ' + XMLHttpRequest.statusText, type: 2, move: false, content: 'javascript:;'});
  279. layer.full(layIdx), $dialog = $('#layui-layer' + layIdx), iframe = $dialog.find('iframe').get(0);
  280. (iframe.contentDocument || iframe.contentWindow.document).write(XMLHttpRequest.responseText);
  281. $dialog.find('.layui-layer-setwin').css({right: '35px', top: '28px'}).find('a').css({marginLeft: 0});
  282. $dialog.find('.layui-layer-title').css({color: 'red', height: '70px', lineHeight: '70px', fontSize: '22px', textAlign: 'center', fontWeight: 700});
  283. } catch (e) {
  284. layer.close(layIdx);
  285. }
  286. layer.closeAll('loading');
  287. if (parseInt(XMLHttpRequest.status) !== 200) {
  288. $.msg.tips('E' + XMLHttpRequest.status + ' - 服务器繁忙,请稍候再试!');
  289. } else {
  290. this.success(XMLHttpRequest.responseText);
  291. }
  292. }, success: function (ret) {
  293. time = time || ret.wait || undefined;
  294. if (typeof callable === 'function' && callable.call(that, ret, time) === false) return false;
  295. return typeof ret === 'object' ? $.msg.auto(ret, time) : that.show(ret);
  296. }, complete: function () {
  297. $.msg.page.done();
  298. $.msg.close(loadidx);
  299. }
  300. });
  301. };
  302. /*! 以 HASH 打开新网页 */
  303. this.href = function (url, elem) {
  304. this.isMenu = elem && elem.dataset.menuNode;
  305. if (this.isMenu) layui.sessionData('pages', null);
  306. if (url !== '#') return location.hash = $.menu.parseUri(url, elem);
  307. if (this.isMenu) return $('[data-menu-node^="' + elem.dataset.menuNode + '-"]:first').trigger('click');
  308. };
  309. /*! 加载 HTML 到 BODY 位置 */
  310. this.open = function (url, data, call, load, tips) {
  311. this.load(url, data, 'get', function (ret) {
  312. return (typeof ret === 'object' ? $.msg.auto(ret) : that.show(ret)), false;
  313. }, load, tips);
  314. };
  315. /*! 打开 IFRAME 窗口 */
  316. this.iframe = function (url, name, area, offset, destroy, success, isfull) {
  317. this.idx = layer.open({title: name || '窗口', type: 2, area: area || ['800px', '580px'], end: destroy || null, offset: offset, fixed: true, maxmin: false, content: url, success: success});
  318. return isfull && layer.full(this.idx), this.idx;
  319. };
  320. /*! 加载 HTML 到弹出层 */
  321. this.modal = function (url, data, name, call, load, tips, area, offset, isfull) {
  322. this.load(url, data, 'GET', function (res) {
  323. if (typeof res === 'object') return $.msg.auto(res), false;
  324. return $.msg.mdx.push(this.idx = layer.open({
  325. type: 1, btn: false, area: area || "800px", resize: false, content: res, title: name || '', offset: offset || 'auto', success: function ($dom, idx) {
  326. typeof call === 'function' && call.call(that, $dom);
  327. $.form.reInit($dom.off('click', '[data-close]').on('click', '[data-close]', function () {
  328. onConfirm(this.dataset.confirm, function () {
  329. layer.close(idx);
  330. });
  331. }));
  332. }
  333. })), isfull && layer.full(this.idx), false;
  334. }, load, tips);
  335. };
  336. };
  337. /*! 后台菜单辅助插件 */
  338. $.menu = new function () {
  339. var that = this;
  340. /*! 计算 URL 地址中有效的 URI */
  341. this.getUri = function (uri) {
  342. uri = uri || location.href;
  343. uri = uri.indexOf(location.host) > -1 ? uri.split(location.host)[1] : uri;
  344. return (uri.indexOf('#') > -1 ? uri.split('#')[1] : uri).split('?')[0];
  345. };
  346. /*! 通过 URI 查询最佳菜单 NODE */
  347. this.queryNode = function (uri, node) {
  348. if (!/^m-/.test(node = node || location.href.replace(/.*spm=([\d\-m]+).*/ig, '$1'))) {
  349. var $menu = $('[data-menu-node][data-open*="' + uri.replace(/\.html$/ig, '') + '"]');
  350. return $menu.size() ? $menu.get(0).dataset.menuNode : '';
  351. }
  352. return node;
  353. };
  354. /*! 完整 URL 转 URI 地址 */
  355. this.parseUri = function (uri, elem, vars, temp, attrs) {
  356. vars = {}, attrs = [], elem = elem || document.createElement('a');
  357. if (uri.indexOf('?') > -1) uri.split('?')[1].split('&').forEach(function (item) {
  358. if (item.indexOf('=') > -1 && (temp = item.split('=')) && typeof temp[0] === 'string' && temp[0].length > 0) {
  359. vars[temp[0]] = encodeURIComponent(decodeURIComponent(temp[1].replace(/%2B/ig, '%20')));
  360. }
  361. });
  362. uri = this.getUri(uri);
  363. if (typeof vars.spm !== 'string') vars.spm = elem.dataset.menuNode || this.queryNode(uri) || '';
  364. if (typeof vars.spm !== 'string' || vars.spm.length < 1) delete vars.spm;
  365. for (var i in vars) attrs.push(i + '=' + vars[i]);
  366. return uri + (attrs.length > 0 ? '?' + attrs.join('&') : '');
  367. };
  368. /*! 后台菜单动作初始化 */
  369. this.listen = function () {
  370. var layout = $('.layui-layout-admin'), mclass = 'layui-layout-left-mini';
  371. /*! 菜单切及MiniTips处理 */
  372. onEvent('click', '[data-target-menu-type]', function () {
  373. layui.data('AdminMenuType', {key: 'mini', value: layout.toggleClass(mclass).hasClass(mclass)});
  374. }).on('click', '[data-submenu-layout]>a', function () {
  375. setTimeout("$.menu.sync(1)", 100);
  376. }).on('mouseenter', '[data-target-tips]', function (evt) {
  377. if (!layout.hasClass(mclass) || !this.dataset.targetTips) return;
  378. evt.idx = layer.tips(this.dataset.targetTips, this, {time: 0});
  379. $(this).mouseleave(function () {
  380. layer.close(evt.idx);
  381. });
  382. });
  383. /*! 监听窗口大小及HASH切换 */
  384. $(window).on('resize', function () {
  385. (layui.data('AdminMenuType')['mini'] || $body.width() < 1000) ? layout.addClass(mclass) : layout.removeClass(mclass);
  386. }).trigger('resize').on('hashchange', function () {
  387. if (/^#(https?:)?(\/\/|\\\\)/.test(location.hash)) return $.msg.tips('禁止访问外部链接!');
  388. if (location.hash.length < 1) return $body.find('[data-menu-node]:first').trigger('click'); else return that.href(location.hash);
  389. }).trigger('hashchange');
  390. };
  391. /*! 同步二级菜单展示状态 */
  392. this.sync = function (mode) {
  393. $('[data-submenu-layout]').map(function () {
  394. var node = this.dataset.submenuLayout;
  395. if (mode === 1) layui.data('AdminMenuState', {key: node, value: $(this).hasClass('layui-nav-itemed') ? 2 : 1}); else if (mode === 2) (layui.data('AdminMenuState')[node] || 2) === 2 && $(this).addClass('layui-nav-itemed');
  396. });
  397. };
  398. /*! 页面 LOCATION-HASH 跳转 */
  399. this.href = function (hash, node) {
  400. if ((hash || '').length < 1) return $('[data-menu-node]:first').trigger('click');
  401. // $.msg.page.show(),$.form.load(hash, {}, 'get', $.msg.page.hide, true),that.sync(2);
  402. $.form.load(hash, {}, 'get', false, !$.msg.page.stat()), that.sync(2);
  403. /*! 菜单选择切换 */
  404. if (/^m-/.test(node = node || that.queryNode(that.getUri()))) {
  405. var arr = node.split('-'), tmp = arr.shift(), $all = $('a[data-menu-node]').parent('.layui-this');
  406. while (arr.length > 0) {
  407. tmp = tmp + '-' + arr.shift();
  408. $all = $all.not($('a[data-menu-node="' + tmp + '"]').parent().addClass('layui-this'));
  409. }
  410. $all.removeClass('layui-this');
  411. /*! 菜单模式切换 */
  412. if (node.split('-').length > 2) {
  413. var _tmp = node.split('-'), _node = _tmp.shift() + '-' + _tmp.shift();
  414. $('[data-menu-layout]').not($('[data-menu-layout="' + _node + '"]').removeClass('layui-hide')).addClass('layui-hide');
  415. $('[data-menu-node="' + node + '"]').parent().parent().parent().addClass('layui-nav-itemed');
  416. $('.layui-layout-admin').removeClass('layui-layout-left-hide');
  417. } else {
  418. $('.layui-layout-admin').addClass('layui-layout-left-hide');
  419. }
  420. setTimeout("$.menu.sync(1);", 100);
  421. }
  422. };
  423. };
  424. /*! 表单验证组件 */
  425. $.vali = function (form, callable) {
  426. return $(form).data('validate') || new Validate();
  427. function Validate() {
  428. var that = this;
  429. /* 绑定表单元素 */
  430. this.form = $(form);
  431. /* 绑定元素事件, 筛选表单元素 */
  432. this.evts = 'blur change';
  433. this.tags = 'input,select,textarea';
  434. /* 预设检测规则 */
  435. this.patterns = {
  436. phone: '^1[3-9][0-9]{9}$', email: '^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$'
  437. };
  438. /*! 检测属性是否有定义 */
  439. this.hasProp = function (ele, prop) {
  440. var attrProp = ele.getAttribute(prop);
  441. return typeof attrProp !== 'undefined' && attrProp !== null && attrProp !== false;
  442. }, this.isRegex = function (ele) {
  443. var real = $.trim($(ele).val());
  444. var regexp = ele.getAttribute('pattern');
  445. regexp = this.patterns[regexp] || regexp;
  446. if (real === "" || !regexp) return true;
  447. return new RegExp(regexp, 'i').test(real);
  448. }, this.checkAllInput = function () {
  449. var status = true;
  450. return that.form.find(this.tags).each(function () {
  451. if (that.checkInput(this) === false) return $(this).focus(), status = false;
  452. }), status;
  453. }, this.checkInput = function (input) {
  454. if (this.hasProp(input, 'data-auto-none')) return true;
  455. var type = (input.getAttribute('type') || '').replace(/\W+/, "").toLowerCase();
  456. var ingores = ['file', 'reset', 'image', 'radio', 'checkbox', 'submit', 'hidden'];
  457. if (ingores.length > 0) for (var i in ingores) if (type === ingores[i]) return true;
  458. if (this.hasProp(input, 'required') && $.trim($(input).val()) === '') return this.remind(input);
  459. return this.isRegex(input) ? (this.hideError(input), true) : this.remind(input);
  460. }, this.remind = function (input) {
  461. if (!$(input).is(':visible')) return true;
  462. return this.showError(input, input.getAttribute('title') || input.getAttribute('placeholder') || '输入错误'), false;
  463. }, this.showError = function (ele, tip) {
  464. $(ele).addClass('validate-error');
  465. this.insertError(ele).addClass('layui-anim-fadein').css({width: 'auto'}).html(tip);
  466. }, this.hideError = function (ele) {
  467. $(ele).removeClass('validate-error');
  468. this.insertError(ele).removeClass('layui-anim-fadein').css({width: '30px'}).html('');
  469. }, this.insertError = function (ele) {
  470. if ($(ele).data('input-info')) return $(ele).data('input-info');
  471. var $html = $('<span class="absolute block layui-anim text-center font-s12 notselect" style="color:#A44;z-index:2"></span>');
  472. var $next = $(ele).nextAll('.input-right-icon'), right = ($next ? $next.width() + parseFloat($next.css('right') || '0') : 0) + 10;
  473. var style = {top: $(ele).position().top + 'px', right: right + 'px', lineHeight: ele.nodeName === 'TEXTAREA' ? '32px' : $(ele).css('height')};
  474. return $(ele).data('input-info', $html.css(style).insertAfter(ele)), $html;
  475. };
  476. /*! 表单元素验证 */
  477. this.form.attr({onsubmit: 'return false', novalidate: 'novalidate', autocomplete: 'off'});
  478. this.form.off(this.evts, this.tags).on(this.evts, this.tags, function () {
  479. that.checkInput(this);
  480. }).data('validate', this).bind("submit", function (evt) {
  481. evt.button = that.form.find('button[type=submit],button:not([type=button])');
  482. /* 检查所有表单元素是否通过H5的规则验证 */
  483. if (that.checkAllInput() && typeof callable === 'function') {
  484. if (typeof CKEDITOR === 'object' && typeof CKEDITOR.instances === 'object') {
  485. for (var i in CKEDITOR.instances) CKEDITOR.instances[i].updateElement();
  486. }
  487. /* 触发表单提交后,锁定三秒不能再次提交表单 */
  488. if (that.form.attr('submit-locked')) return false;
  489. that.form.attr('submit-locked', 1), evt.button.addClass('submit-button-loading');
  490. callable.call(this, that.form.formToJson(), []), setTimeout(function () {
  491. that.form.removeAttr('submit-locked'), evt.button.removeClass('submit-button-loading');
  492. }, 3000);
  493. }
  494. return evt.preventDefault(), false;
  495. }).find('[data-form-loaded]').map(function () {
  496. $(this).html(this.dataset.formLoaded || this.innerHTML);
  497. $(this).removeAttr('data-form-loaded').removeClass('layui-disabled');
  498. });
  499. }
  500. };
  501. /*! 自动监听表单 */
  502. $.vali.listen = function ($dom, $els) {
  503. $els = $($dom || $body).find('form[data-auto]');
  504. $dom && $($dom).filter('form[data-auto]') && $els.add($dom);
  505. $els.size() > 0 && $els.map(function (idx, form) {
  506. $(this).vali(function (data) {
  507. var emap = form.dataset, type = form.method || 'POST', href = form.action || location.href;
  508. var tips = emap.tips || undefined, time = emap.time || undefined, taid = emap.tableId || false;
  509. var call = window[emap.callable || '_default_callable'] || (taid ? function (ret) {
  510. if (typeof ret === 'object' && ret.code > 0 && $('#' + taid).size() > 0) {
  511. return $.msg.success(ret.info, 3, function () {
  512. (typeof ret.data === 'string' && ret.data) ? location.href = ret.data : $.layTable.reload(taid);
  513. $.msg.close($.msg.mdx.length > 0 ? $.msg.mdx.pop() : null);
  514. }) && false;
  515. }
  516. } : undefined);
  517. onConfirm(emap.confirm, function () {
  518. $.form.load(href, data, type, call, true, tips, time);
  519. });
  520. });
  521. });
  522. };
  523. /*! 注册对象到JqFn */
  524. $.fn.vali = function (callable) {
  525. return this.each(function () {
  526. $.vali(this, callable);
  527. });
  528. };
  529. /*! 表单转JSON */
  530. $.fn.formToJson = function () {
  531. var self = this, data = {}, push = {};
  532. var rules = {key: /\w+|(?=\[])/g, push: /^$/, fixed: /^\d+$/, named: /^\w+$/};
  533. this.build = function (base, key, value) {
  534. return (base[key] = value), base;
  535. }, this.pushCounter = function (name) {
  536. if (push[name] === undefined) push[name] = 0;
  537. return push[name]++;
  538. }, $.each($(this).serializeArray(), function () {
  539. var key, keys = this.name.match(rules.key), merge = this.value, name = this.name;
  540. while ((key = keys.pop()) !== undefined) {
  541. name = name.replace(new RegExp("\\[" + key + "\\]$"), '');
  542. if (key.match(rules.push)) merge = self.build([], self.pushCounter(name), merge); else if (key.match(rules.fixed)) merge = self.build([], key, merge); else if (key.match(rules.named)) merge = self.build({}, key, merge);
  543. }
  544. data = $.extend(true, data, merge);
  545. });
  546. return data;
  547. };
  548. /*! 全局文件上传插件 */
  549. $.fn.uploadFile = function (callable, initialize) {
  550. return this.each(function () {
  551. if ($(this).data('inited')) return false;
  552. var that = $(this), mult = '|one|btn|'.indexOf(that.data('file') || 'one') > -1 ? 0 : 1;
  553. that.data('inited', true).data('multiple', mult), require(['upload'], function (apply) {
  554. apply(that, callable), (typeof initialize === 'function' && setTimeout(initialize, 100));
  555. });
  556. });
  557. };
  558. /*! 上传单张图片 */
  559. $.fn.uploadOneImage = function () {
  560. return this.each(function () {
  561. if ($(this).data('inited')) return true; else $(this).data('inited', true);
  562. var $in = $(this), $bt = $('<a data-file class="uploadimage transition"><span class="layui-icon">&#x1006;</span><span class="layui-icon">&#xe615;</span></a>').data('input', this);
  563. $bt.attr('data-size', $in.data('size') || 0).attr('data-type', $in.data('type') || 'png,jpg,gif,jpeg').find('span').on('click', function (event) {
  564. event.stopPropagation();
  565. if ($(this).index() === 0) $bt.attr('style', ''), $in.val(''); else $in.val() && $.previewImage(encodeURI($in.val()));
  566. }), $in.on('change', function () {
  567. if (this.value) $bt.css('backgroundImage', 'url(' + encodeURI(this.value) + ')');
  568. }).after($bt).trigger('change');
  569. });
  570. };
  571. /*! 上传多张图片 */
  572. $.fn.uploadMultipleImage = function () {
  573. return this.each(function () {
  574. if ($(this).data('inited')) return true; else $(this).data('inited', true);
  575. var $in = $(this), $bt = $('<a data-file="mul" class="uploadimage"></a>'), imgs = this.value ? this.value.split('|') : []
  576. $in.after($bt.attr('data-size', $in.data('size') || 0).attr('data-type', $in.data('type') || 'gif,png,jpg,jpeg').uploadFile(function (src) {
  577. imgs.push(src), $in.val(imgs.join('|')), showImageContainer([src]);
  578. })), (imgs.length > 0 && showImageContainer(imgs));
  579. function showImageContainer(srcs) {
  580. $(srcs).each(function (idx, src, $image) {
  581. $image = $('<div class="uploadimage uploadimagemtl transition"><div><a class="layui-icon">&#xe603;</a><a class="layui-icon">&#x1006;</a><a class="layui-icon">&#xe602;</a></div></div>');
  582. $image.attr('data-tips-image', encodeURI(src)).css('backgroundImage', 'url(' + encodeURI(src) + ')').on('click', 'a', function (event, index, prevs, $item) {
  583. event.stopPropagation(), $item = $(this).parent().parent(), index = $(this).index();
  584. if (index === 2 && $item.index() !== $bt.prevAll('div.uploadimage').length) $item.next().after($item); else if (index === 0 && $item.index() > 1) $item.prev().before($item); else if (index === 1) $item.remove();
  585. imgs = [], $bt.prevAll('.uploadimage').map(function () {
  586. imgs.push($(this).attr('data-tips-image'));
  587. });
  588. imgs.reverse(), $in.val(imgs.join('|'));
  589. }), $bt.before($image);
  590. });
  591. }
  592. });
  593. };
  594. /*! 上传单个视频 */
  595. $.fn.uploadOneVideo = function () {
  596. return this.each(function () {
  597. if ($(this).data('inited')) return true; else $(this).data('inited', true);
  598. var $in = $(this), $bt = $('<a data-file class="uploadimage uploadvideo transition"><span class="layui-icon">&#x1006;</span><span class="layui-icon">&#xe615;</span></a>').data('input', this);
  599. $bt.attr('data-size', $in.data('size') || 0).attr('data-type', $in.data('type') || 'mp4').find('span').on('click', function (event) {
  600. event.stopPropagation();
  601. if ($(this).index() === 0) $bt.attr('style', ''), $in.val(''); else $in.val() && $.previewImage(encodeURI($in.val()));
  602. }), $in.on('change', function () {
  603. if (this.value) $bt.html('<video width="76" height="76" controls><source src="' + encodeURI(this.value) + '" type="video/mp4"></video>');
  604. }).after($bt).trigger('change');
  605. });
  606. };
  607. /*! 标签输入插件 */
  608. $.fn.initTagInput = function () {
  609. return this.each(function () {
  610. var $this = $(this), tags = this.value ? this.value.split(',') : [];
  611. var $text = $('<textarea class="layui-input layui-input-inline layui-tag-input"></textarea>');
  612. var $tags = $('<div class="layui-tags"></div>').append($text);
  613. $this.parent().append($tags), $text.off('keydown blur'), (tags.length > 0 && showTags(tags));
  614. $text.on('blur keydown', function (event, value) {
  615. if (event.keyCode === 13 || event.type === 'blur') {
  616. event.preventDefault(), (value = $text.val().replace(/^\s*|\s*$/g, ''));
  617. if (tags.indexOf($(this).val()) > -1) return layer.msg('该标签已经存在!');
  618. if (value.length > 0) tags.push(value), $this.val(tags.join(',')), showTags([value]), this.focus(), $text.val('');
  619. }
  620. });
  621. function showTags(tagsArr) {
  622. $(tagsArr).each(function (idx, text, elem) {
  623. elem = $('<div class="layui-tag"></div>').html(text + '<i class="layui-icon">&#x1006;</i>');
  624. elem.on('click', 'i', function (tagText, tagIdx) {
  625. tagText = $(this).parent().text(), tagIdx = tags.indexOf(tagText);
  626. tags.splice(tagIdx, 1), $(this).parent().remove(), $this.val(tags.join(','));
  627. }), $tags.append(elem, $text);
  628. });
  629. }
  630. });
  631. };
  632. /*! 文本框插入内容 */
  633. $.fn.insertAtCursor = function (value) {
  634. return this.each(function () {
  635. this.focus();
  636. if (document.selection) {
  637. var selection = document.selection.createRange();
  638. (selection.text = value), selection.select(), selection.unselect();
  639. } else if (this.selectionStart || this.selectionStart === 0) {
  640. var spos = this.selectionStart, apos = this.selectionEnd || spos;
  641. this.value = this.value.substring(0, spos) + value + this.value.substring(apos);
  642. this.selectionEnd = this.selectionStart = spos + value.length;
  643. } else {
  644. this.value += value;
  645. }
  646. this.focus();
  647. });
  648. };
  649. /*! 组件 layui.table 封装 */
  650. $.fn.layTable = function (params) {
  651. return this.each(function () {
  652. $.layTable.create(this, params);
  653. });
  654. };
  655. $.layTable = new function () {
  656. this.render = function (tabldId) {
  657. return this.reload(tabldId, true);
  658. }, this.reload = function (tabldId, force) {
  659. return typeof tabldId === 'string' ? $('#' + tabldId).trigger(force ? 'render' : 'reload') : $.form.reload();
  660. }, this.create = function (table, params) {
  661. // 动态初始化表格
  662. table.id = table.id || 't' + Math.random().toString().replace('.', '');
  663. var $table = $(table).attr('lay-filter', table.dataset.id = table.getAttribute('lay-filter') || table.id);
  664. // 插件初始化参数
  665. var option = params || {}, data = option.where || {}, sort = option.initSort || option.sort || {};
  666. option.id = table.id, option.elem = table, option.url = params.url || table.dataset.url || location.href;
  667. option.limit = params.limit || 20, option.loading = params.loading !== false, option.autoSort = params.autoSort === true;
  668. option.page = params.page !== false ? (params.page || true) : false, option.cols = params.cols || [[]], option.success = params.done || '';
  669. // 初始化不显示头部
  670. var cls = ['.layui-table-header', '.layui-table-fixed', '.layui-table-body', '.layui-table-page'];
  671. option.css = (option.css || '') + cls.join('{opacity:0}') + '{opacity:0}';
  672. // 默认动态设置页数, 动态设置最大高度
  673. if (option.page === true) option.page = {curr: layui.sessionData('pages')[option.id] || 1};
  674. if (option.height === 'full') if ($table.parents('.iframe-pagination').size()) {
  675. $table.parents('.iframe-pagination').addClass('not-footer');
  676. option.height = $(window).height() - $table.removeClass('layui-hide').offset().top - 20;
  677. } else {
  678. option.height = $(window).height() - $table.removeClass('layui-hide').offset().top - 35;
  679. }
  680. // 动态计算最大页数
  681. option.done = function () {
  682. typeof option.success === 'function' && option.success.call(this);
  683. layui.sessionData('pages', {key: table.id, value: this.page.curr || 1});
  684. $.form.reInit($table.next()).find('[data-load],[data-queue],[data-action],[data-iframe]').not('[data-table-id]').attr('data-table-id', table.id);
  685. (option.loading = this.loading = true) && $table.data('next', this).next().find(cls.join(',')).animate({opacity: 1});
  686. }, option.parseData = function (res) {
  687. if (typeof params.filter === 'function') {
  688. res.data = params.filter(res.data, res);
  689. }
  690. if (!this.page || !this.page.curr) return res;
  691. var curp = this.page.curr, maxp = Math.ceil(res.count / option.limit);
  692. if (curp > maxp && maxp > 1) $table.trigger('reload', {page: {curr: maxp}});
  693. return res;
  694. };
  695. // 关联搜索表单
  696. var sform, search = params.search || table.dataset.targetSearch;
  697. if (search) (sform = $body.find(search)).map(function () {
  698. $(this).attr('data-table-id', table.id);
  699. });
  700. // 关联绑定选择项
  701. var checked = params.checked || table.dataset.targetChecked;
  702. if (checked) $body.find(checked).map(function () {
  703. $(this).attr('data-table-id', table.id);
  704. });
  705. // 实例并绑定事件
  706. $table.data('this', layui.table.render(bindData(option)));
  707. $table.bind('reload render reloadData', function (evt, opts, next) {
  708. data = $.extend({}, data, (opts || {}).where || {});
  709. opts = bindData($.extend({}, opts || {}, {loading: true}));
  710. if (evt.type.indexOf('reload') > -1) {
  711. if (layui.table.reloadData) {
  712. next = $table.data('next'), next.where = data;
  713. next.sort = next.initSort = opts.initSort || {};
  714. layui.table.reloadData(table.id, (opts.page || {}).curr || 1);
  715. } else {
  716. layui.table.reload(table.id, opts);
  717. }
  718. } else {
  719. layui.table.render(table.id, opts);
  720. }
  721. }).bind('row sort tool edit radio toolbar checkbox rowDouble', function (evt, call) {
  722. layui.table.on(evt.type + '(' + table.dataset.id + ')', call)
  723. }).bind('setFullHeight', function () {
  724. $table.trigger('render', {height: $(window).height() - $table.next().offset().top - 35})
  725. }).trigger('sort', function (rets) {
  726. (sort = rets), $table.trigger('reload')
  727. });
  728. return $table;
  729. // 生成初始化参数
  730. function bindData(options) {
  731. data['output'] = 'layui.table';
  732. if (sort.field && sort.type) {
  733. data['_order_'] = sort.type, data['_field_'] = sort.field;
  734. options.initSort = {type: sort.type.split(',')[0].split(' ')[0], field: sort.field.split(',')[0].split(' ')[0]};
  735. if (sform) $(sform).find('[data-form-export]').attr('data-sort-field', sort.field).attr('data-sort-type', sort.type);
  736. }
  737. if (options.page === false) options.limit = '';
  738. return (options['where'] = data), options;
  739. }
  740. };
  741. };
  742. /*! 弹出图片层 */
  743. $.previewImage = function (src, area) {
  744. var img = new Image(), defer = $.Deferred(), loaded = $.msg.loading();
  745. img.style.background = '#FFF', img.referrerPolicy = 'no-referrer';
  746. img.style.height = 'auto', img.style.width = area || '100%', img.style.display = 'none';
  747. return document.body.appendChild(img), img.onerror = function () {
  748. $.msg.close(loaded), defer.reject();
  749. }, img.src = src, img.onload = function () {
  750. layer.open({
  751. type: 1, title: false, shadeClose: true, content: $(img), success: function ($elem, idx) {
  752. $.msg.close(loaded), defer.notify($elem, idx);
  753. }, area: area || '480px', skin: 'layui-layer-nobg', closeBtn: 1, end: function () {
  754. document.body.removeChild(img), defer.resolve()
  755. }
  756. });
  757. }, defer.promise();
  758. };
  759. /*! 以手机模式显示内容 */
  760. $.previewPhonePage = function (href, title) {
  761. var template = '<div class="mobile-preview"><div class="mobile-header">{{d.title}}</div><div class="mobile-body"><iframe src="{{d.url}}"></iframe></div></div>';
  762. layer.style(layer.open({type: true, resize: false, scrollbar: false, area: ['320px', '600px'], title: false, closeBtn: true, shadeClose: false, skin: 'layui-layer-nobg', content: laytpl(template).render({title: title || '公众号', url: href})}), {boxShadow: 'none'});
  763. };
  764. /*! 显示任务进度消息 */
  765. $.loadQueue = function (code, doScript, element) {
  766. var doAjax = true, doReload = false, template = '<div class="padding-30 padding-bottom-0" data-queue-load="{{d.code}}"><div class="layui-elip notselect nowrap" data-message-title><b class="color-desc">...</b></div><div class="margin-top-15 layui-progress layui-progress-big" lay-showPercent="yes"><div class="layui-progress-bar transition" lay-percent="0.00%"></div></div>' + '<div class="margin-top-15"><code class="layui-textarea layui-bg-black border-0" style="resize:none;overflow:hidden;height:190px"></code></div></div>';
  767. layer.open({
  768. type: 1, title: false, area: ['560px', '315px'], anim: 2, shadeClose: false, end: function () {
  769. doAjax = doReload && doScript && $.layTable.reload(((element || {}).dataset || {}).tableId || true), false;
  770. }, content: laytpl(template).render({code: code}), success: function ($elem) {
  771. new function () {
  772. var that = this;
  773. this.$box = $elem.find('[data-queue-load=' + code + ']');
  774. if (doAjax === false || this.$box.length < 1) return false;
  775. this.$coder = this.$box.find('code'), this.$name = this.$box.find('[data-message-title]');
  776. this.$percent = this.$box.find('.layui-progress div'), this.SetCache = function (code, index, value) {
  777. var ckey = code + '_' + index, ctype = 'admin-queue-script';
  778. return value !== undefined ? layui.data(ctype, {key: ckey, value: value}) : layui.data(ctype)[ckey] || 0;
  779. }, this.SetState = function (status, message) {
  780. if (message.indexOf('javascript:') === -1) if (status === 1) {
  781. that.$name.html('<b class="color-text">' + message + '</b>').addClass('text-center');
  782. that.$percent.addClass('layui-bg-blue').removeClass('layui-bg-green layui-bg-red');
  783. } else if (status === 2) {
  784. if (message.indexOf('>>>') > -1) {
  785. that.$name.html('<b class="color-blue">' + message + '</b>').addClass('text-center');
  786. } else {
  787. that.$name.html('<b class="color-blue">正在处理:</b>' + message).removeClass('text-center');
  788. }
  789. that.$percent.addClass('layui-bg-blue').removeClass('layui-bg-green layui-bg-red');
  790. } else if (status === 3) {
  791. doReload = true;
  792. that.$name.html('<b class="color-green">' + message + '</b>').addClass('text-center');
  793. that.$percent.addClass('layui-bg-green').removeClass('layui-bg-blue layui-bg-red');
  794. } else if (status === 4) {
  795. that.$name.html('<b class="color-red">' + message + '</b>').addClass('text-center');
  796. that.$percent.addClass('layui-bg-red').removeClass('layui-bg-blue layui-bg-green');
  797. }
  798. }, (this.LoadProgress = function () {
  799. if (doAjax === false || that.$box.length < 1) return false;
  800. $.form.load(tapiRoot + '/api.queue/progress', {code: code}, 'post', function (ret) {
  801. if (ret.code) {
  802. var lines = [];
  803. for (var idx in ret.data.history) {
  804. var line = ret.data.history[idx], percent = '[ ' + line.progress + '% ] ';
  805. if (line.message.indexOf('javascript:') === -1) lines.push(line.message.indexOf('>>>') > -1 ? line.message : percent + line.message); else if (!that.SetCache(code, idx) && doScript !== false) that.SetCache(code, idx, 1), location.href = line.message;
  806. }
  807. if (ret.data.status > 0) {
  808. that.SetState(parseInt(ret.data.status), ret.data.message);
  809. that.$percent.attr('lay-percent', (parseFloat(ret.data.progress || '0.00').toFixed(2)) + '%'), layui.element.render();
  810. that.$coder.html('<p class="layui-elip">' + lines.join('</p><p class="layui-elip">') + '</p>').animate({scrollTop: that.$coder[0].scrollHeight + 'px'}, 200);
  811. return parseInt(ret.data.status) === 3 || parseInt(ret.data.status) === 4 || setTimeout(that.LoadProgress, Math.floor(Math.random() * 200)), false;
  812. } else return setTimeout(that.LoadProgress, Math.floor(Math.random() * 500) + 200), false;
  813. }
  814. }, false);
  815. })();
  816. };
  817. }
  818. });
  819. };
  820. /*! 注册 data-search 表单搜索行为 */
  821. onEvent('submit', 'form.form-search', function () {
  822. if (this.dataset.tableId) return $('table#' + this.dataset.tableId).trigger('reload', {
  823. page: {curr: 1}, where: $(this).formToJson()
  824. });
  825. var url = $(this).attr('action').replace(/&?page=\d+/g, '');
  826. if ((this.method || 'get').toLowerCase() === 'get') {
  827. var split = url.indexOf('?') > -1 ? '&' : '?', stype = location.href.indexOf('spm=') > -1 ? '#' : '';
  828. return location.href = stype + $.menu.parseUri(url + split + $(this).serialize().replace(/\+/g, ' '));
  829. }
  830. return $.form.load(url, this, 'post');
  831. });
  832. /*! 注册 data-file 事件行为 */
  833. onEvent('click', '[data-file]', function () {
  834. if ($(this).data('inited') !== true) (function (that) {
  835. that.uploadFile(undefined, function () {
  836. that.trigger('upload.start');
  837. });
  838. })($(this));
  839. });
  840. /*! 注册 data-load 事件行为 */
  841. onEvent('click', '[data-load]', function () {
  842. var emap = this.dataset, data = {};
  843. if (emap.rule && (applyRuleValue(this, data)) === false) return false; else onConfirm(emap.confirm, function () {
  844. $.form.load(emap.load, data, 'get', onConfirm.getLoadcallable(emap.tableId), true, emap.tips, emap.time);
  845. });
  846. });
  847. /*! 注册 data-reload 事件行为 */
  848. onEvent('click', '[data-reload]', function () {
  849. $.layTable.reload(this.dataset.tableId || true);
  850. });
  851. /*! 注册 data-dbclick 事件行为 */
  852. onEvent('dblclick', '[data-dbclick]', function () {
  853. $(this).find(this.dataset.dbclick || '[data-dbclick]').trigger('click');
  854. });
  855. /*! 注册 data-check 事件行为 */
  856. onEvent('click', '[data-check-target]', function () {
  857. var target = this;
  858. $(this.dataset.checkTarget).map(function () {
  859. (this.checked = !!target.checked), $(this).trigger('change');
  860. });
  861. });
  862. /*! 表单元素失去焦点时数字 */
  863. onEvent('blur', '[data-blur-number]', function () {
  864. var emap = this.dataset, min = emap.valueMin, max = emap.valueMax;
  865. var value = parseFloat(this.value) || 0, fiexd = parseInt(emap.blurNumber || 0);
  866. if (typeof min !== 'undefined' && value < min) value = min;
  867. if (typeof max !== 'undefined' && value > max) value = max;
  868. this.value = parseFloat(value).toFixed(fiexd);
  869. });
  870. /*! 表单元素失焦时提交 */
  871. onEvent('blur', '[data-action-blur],[data-blur-action]', function () {
  872. var that = $(this), emap = this.dataset, data = {'_token_': emap.token || emap.csrf || '--'};
  873. var attrs = (emap.value || '').replace('{value}', that.val()).split(';');
  874. for (var i in attrs) data[attrs[i].split('#')[0]] = attrs[i].split('#')[1];
  875. onConfirm(emap.confirm, function () {
  876. $.form.load(emap.actionBlur || emap.blurAction, data, emap.method || 'post', function (ret) {
  877. return that.css('border', (ret && ret.code) ? '1px solid #e6e6e6' : '1px solid red') && false;
  878. }, emap.loading !== 'false', emap.loading, emap.time);
  879. });
  880. });
  881. /*! 注册 data-href 事件行为 */
  882. onEvent('click', '[data-href]', function () {
  883. if (this.dataset.href && this.dataset.href.indexOf('#') !== 0) {
  884. location.href = this.dataset.href;
  885. }
  886. });
  887. /*! 注册 data-open 事件行为 */
  888. onEvent('click', '[data-open]', function () {
  889. if (this.dataset.open.match(/^https?:/)) {
  890. location.href = this.dataset.open;
  891. } else {
  892. $.form.href(this.dataset.open, this);
  893. }
  894. });
  895. /*! 注册 data-action 事件行为 */
  896. onEvent('click', '[data-action]', function () {
  897. var emap = this.dataset, data = {'_token_': emap.token || emap.csrf || '--'};
  898. var load = emap.loading !== 'false', tips = typeof load === 'string' ? load : undefined;
  899. if ((applyRuleValue(this, data)) === false) return false; else onConfirm(emap.confirm, function () {
  900. $.form.load(emap.action, data, emap.method || 'post', onConfirm.getLoadcallable(emap.tableId), load, tips, emap.time)
  901. });
  902. });
  903. /*! 注册 data-modal 事件行为 */
  904. onEvent('click', '[data-modal]', function () {
  905. var un = undefined, emap = this.dataset, data = {open_type: 'modal'};
  906. if (emap.rule && (applyRuleValue(this, data)) === false) return false;
  907. return $.form.modal(emap.modal, data, emap.title || this.innerText || '编辑', un, un, un, emap.area || emap.width || '800px', emap.offset || 'auto', emap.full !== un);
  908. });
  909. /*! 注册 data-iframe 事件行为 */
  910. onEvent('click', '[data-iframe]', function () {
  911. var emap = this.dataset, data = {open_type: 'iframe'};
  912. if (emap.rule && (applyRuleValue(this, data)) === false) return false;
  913. var name = emap.title || this.innerText || 'IFRAME 窗口';
  914. var area = emap.area || [emap.width || '800px', emap.height || '580px'];
  915. var frame = emap.iframe + (emap.iframe.indexOf('?') > -1 ? '&' : '?') + $.param(data);
  916. $(this).attr('data-index', $.form.iframe(frame, name, area, emap.offset || 'auto', function () {
  917. typeof emap.refresh !== 'undefined' && $.layTable.reload(emap.tableId || true);
  918. }, undefined, emap.full !== undefined));
  919. });
  920. /*! 注册 data-icon 事件行为 */
  921. onEvent('click', '[data-icon]', function () {
  922. var location = tapiRoot + '/api.plugs/icon', field = this.dataset.icon || this.dataset.field || 'icon';
  923. $.form.iframe(location + (location.indexOf('?') > -1 ? '&' : '?') + 'field=' + field, '图标选择', ['900px', '700px']);
  924. });
  925. /*! 注册 data-copy 事件行为 */
  926. onEvent('click', '[data-copy]', function () {
  927. var copy = this.dataset.copy || this.innerText;
  928. if (window.clipboardData) {
  929. window.clipboardData.setData('text', copy);
  930. $.msg.tips('已复制到剪贴板!');
  931. } else {
  932. var $input = $('<textarea readonly></textarea>');
  933. $input.css({position: 'fixed', top: '-500px'}).appendTo($body).val(copy).select();
  934. $.msg.tips(document.execCommand('Copy') ? '已复制到剪贴板!' : '请使用鼠标操作复制!') && $input.remove();
  935. }
  936. });
  937. /*! 异步任务状态监听与展示 */
  938. onEvent('click', '[data-queue]', function () {
  939. var that = this, emap = this.dataset;
  940. onConfirm(emap.confirm || false, function () {
  941. $.form.load(emap.queue, {}, 'post', function (ret) {
  942. if (typeof ret.data === 'string' && ret.data.indexOf('Q') === 0) {
  943. return $.loadQueue(ret.data, true, that), false;
  944. }
  945. });
  946. });
  947. });
  948. /*! 注册 data-tips-text 事件行为 */
  949. onEvent('mouseenter', '[data-tips-text]', function () {
  950. var opts = {tips: [$(this).attr('data-tips-type') || 3, '#78BA32'], time: 0};
  951. var layidx = layer.tips($(this).attr('data-tips-text') || this.innerText, this, opts);
  952. $(this).off('mouseleave').on('mouseleave', function () {
  953. setTimeout("layer.close('" + layidx + "')", 100);
  954. });
  955. });
  956. /*! 注册 data-tips-hover 事件行为 */
  957. onEvent('mouseenter', '[data-tips-image][data-tips-hover]', function () {
  958. var img = new Image(), ele = $(this);
  959. if ((img.src = this.dataset.tipsImage || this.dataset.lazySrc || this.src)) {
  960. img.layopt = {time: 0, skin: 'layui-layer-image', anim: 5, isOutAnim: false, scrollbar: false};
  961. img.referrerPolicy = 'no-referrer', img.style.maxWidth = '260px', img.style.maxHeight = '260px';
  962. ele.data('layidx', layer.tips(img.outerHTML, this, img.layopt)).off('mouseleave').on('mouseleave', function () {
  963. layer.close(ele.data('layidx'));
  964. });
  965. }
  966. });
  967. /*! 注册 data-tips-image 事件行为 */
  968. onEvent('click', '[data-tips-image]', function (event) {
  969. (event.items = [], event.$imgs = $(this).parent().find('[data-tips-image]')).map(function () {
  970. event.items.push({src: this.dataset.tipsImage || this.dataset.lazySrc || this.src});
  971. }) && layer.photos({
  972. anim: 5, closeBtn: 1, photos: {start: event.$imgs.index(this), data: event.items}, tab: function (pic, $ele) {
  973. $ele.find('img').attr('referrer-policy', 'no-referrer');
  974. $ele.find('.layui-layer-close').css({top: '20px', right: '20px', position: 'fixed'});
  975. }
  976. });
  977. });
  978. /*! 注册 data-phone-view 事件行为 */
  979. onEvent('click', '[data-phone-view]', function () {
  980. $.previewPhonePage(this.dataset.phoneView || this.href);
  981. });
  982. /*! 表单编辑返回操作 */
  983. onEvent('click', '[data-history-back]', function () {
  984. $.msg.confirm(this.dataset.historyBack || '确定要返回吗?', function () {
  985. history.back();
  986. })
  987. });
  988. /*! 图片加载异常处理 */
  989. document.addEventListener('error', function (event) {
  990. if (event.target.nodeName !== 'IMG') return;
  991. event.target.src = baseRoot + 'theme/img/404_icon.png';
  992. }, true);
  993. /*! 系统菜单表单页面初始化 */
  994. $.menu.listen(), $.form.reInit($body);
  995. });