admin.js 57 KB

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