layedit.js 103 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236
  1. /**
  2. @Name:Kz.layedit 富文本编辑器
  3. @Author:贤心
  4. @Modifier:KnifeZ
  5. @License:MIT
  6. @Version: V18.11.16
  7. */
  8. layui.define(['layer', 'form'], function (exports) {
  9. "use strict";
  10. var $ = layui.$
  11. , layer = layui.layer
  12. , form = layui.form
  13. , hint = layui.hint()
  14. , device = layui.device()
  15. , MOD_NAME = 'layedit', THIS = 'layui-this', SHOW = 'layui-show', ABLED = 'layui-disabled'
  16. , Edit = function () {
  17. var that = this;
  18. that.index = 0;
  19. //全局配置
  20. that.config = {
  21. //默认工具bar
  22. tool: [
  23. 'strong', 'italic', 'underline', 'del'
  24. , '|'
  25. , 'left', 'center', 'right'
  26. , '|'
  27. , 'link', 'unlink', 'face', 'image'
  28. ]
  29. , uploadImage: {
  30. url: '',
  31. accept: 'image',
  32. acceptMime: 'image/*',
  33. exts: 'jpg|png|gif|bmp|jpeg',
  34. size: '10240'
  35. }
  36. , uploadVideo: {
  37. url: '',
  38. accept: 'video',
  39. acceptMime: 'video/*',
  40. exts: 'mp4|flv|avi|rm|rmvb',
  41. size: '20480'
  42. }
  43. , calldel: {
  44. url: ''
  45. }
  46. , quote: {
  47. style: [],
  48. js: []
  49. }
  50. , devmode: false
  51. , hideTool: []
  52. , height: 280 //默认高
  53. };
  54. };
  55. //全局设置
  56. Edit.prototype.set = function (options) {
  57. var that = this;
  58. $.extend(true, that.config, options);
  59. return that;
  60. };
  61. //事件监听
  62. Edit.prototype.on = function (events, callback) {
  63. return layui.onevent(MOD_NAME, events, callback);
  64. };
  65. //建立编辑器
  66. Edit.prototype.build = function (id, settings) {
  67. settings = settings || {};
  68. var that = this
  69. , config = that.config
  70. , ELEM = 'layui-layedit', textArea = $(typeof (id) == 'string' ? '#' + id : id)
  71. , name = 'LAY_layedit_' + (++that.index)
  72. , haveBuild = textArea.next('.' + ELEM)
  73. , set = $.extend({}, config, settings)
  74. , tool = function () {
  75. var node = [], hideTools = {};
  76. layui.each(set.hideTool, function (_, item) {
  77. hideTools[item] = true;
  78. });
  79. layui.each(set.tool, function (_, item) {
  80. if (tools[item] && !hideTools[item]) {
  81. node.push(tools[item]);
  82. }
  83. });
  84. return node.join('');
  85. }()
  86. , editor = $(['<div class="' + ELEM + '">'
  87. , '<div class="layui-unselect layui-layedit-tool">' + tool + '</div>'
  88. , '<div class="layui-layedit-iframe">'
  89. , '<iframe id="' + name + '" name="' + name + '" textarea="' + id + '" frameborder="0"></iframe>'
  90. , '</div>'
  91. , '</div>'].join(''))
  92. //编辑器不兼容ie8以下
  93. if (device.ie && device.ie < 8) {
  94. return textArea.removeClass('layui-hide').addClass(SHOW);
  95. }
  96. haveBuild[0] && (haveBuild.remove());
  97. setIframe.call(that, editor, textArea[0], set)
  98. textArea.addClass('layui-hide').after(editor);
  99. return that.index;
  100. };
  101. //获得编辑器中内容
  102. Edit.prototype.getContent = function (index) {
  103. var iframeWin = getWin(index);
  104. if (!iframeWin[0]) return;
  105. return toLower(iframeWin[0].document.body.innerHTML);
  106. };
  107. //获得编辑器中纯文本内容
  108. Edit.prototype.getText = function (index) {
  109. var iframeWin = getWin(index);
  110. if (!iframeWin[0]) return;
  111. return $(iframeWin[0].document.body).text();
  112. };
  113. /**
  114. * 设置编辑器内容
  115. * @param {[type]} index 编辑器索引
  116. * @param {[type]} content 要设置的内容
  117. * @param {[type]} flag 是否追加模式
  118. */
  119. Edit.prototype.setContent = function (index, content, flag) {
  120. var iframeWin = getWin(index);
  121. if (!iframeWin[0]) return;
  122. if (flag) {
  123. $(iframeWin[0].document.body).append(content)
  124. } else {
  125. $(iframeWin[0].document.body).html(content)
  126. };
  127. this.sync(index)
  128. };
  129. //将编辑器内容同步到textarea(一般用于异步提交时)
  130. Edit.prototype.sync = function (index) {
  131. var iframeWin = getWin(index);
  132. if (!iframeWin[0]) return;
  133. var textarea = $('#' + iframeWin[1].attr('textarea'));
  134. textarea.val(toLower(iframeWin[0].document.body.innerHTML));
  135. };
  136. //获取编辑器选中内容
  137. Edit.prototype.getSelection = function (index) {
  138. var iframeWin = getWin(index);
  139. if (!iframeWin[0]) return;
  140. var range = Range(iframeWin[0].document);
  141. return document.selection ? range.text : range.toString();
  142. };
  143. //iframe初始化
  144. var setIframe = function (editor, textArea, set) {
  145. var that = this, iframe = editor.find('iframe');
  146. iframe.css({
  147. height: set.height
  148. }).on('load', function () {
  149. var conts = iframe.contents()
  150. , iframeWin = iframe.prop('contentWindow')
  151. , head = conts.find('head')
  152. , style = $(['<style>'
  153. , '*{margin: 0; padding: 0;}'
  154. , 'body{padding: 10px; line-height: 20px; overflow-x: hidden; word-wrap: break-word; font: 14px Helvetica Neue,Helvetica,PingFang SC,Microsoft YaHei,Tahoma,Arial,sans-serif; -webkit-box-sizing: border-box !important; -moz-box-sizing: border-box !important; box-sizing: border-box !important;}'
  155. , 'a{color:#01AAED; text-decoration:none;}a:hover{color:#c00}'
  156. , 'p{margin-bottom: 10px;}'
  157. , 'video{max-width:400px;}'
  158. , '.anchor:after{content:"¿";background-color:yellow;color: red;font - weight: bold;}'
  159. , 'img{display: inline-block; border: none; vertical-align: middle;}'
  160. , 'pre{margin: 10px 0; padding: 10px; line-height: 20px; border: 1px solid #ddd; border-left-width: 6px; background-color: #F2F2F2; color: #333; font-family: Courier New; font-size: 12px;}'
  161. , '</style>'].join(''))
  162. , body = conts.find('body');
  163. head.append(style);
  164. body.attr('contenteditable', 'true').css({
  165. 'min-height': set.height
  166. }).html(textArea.value || '');
  167. hotkey.apply(that, [iframeWin, iframe, textArea, set]); //快捷键处理
  168. toolActive.call(that, iframeWin, editor, set); //触发工具
  169. });
  170. }
  171. //获得iframe窗口对象
  172. , getWin = function (index) {
  173. var iframe = $('#LAY_layedit_' + index)
  174. , iframeWin = iframe.prop('contentWindow');
  175. return [iframeWin, iframe];
  176. }
  177. //IE8下将标签处理成小写
  178. , toLower = function (html) {
  179. if (device.ie == 8) {
  180. html = html.replace(/<.+>/g, function (str) {
  181. return str.toLowerCase();
  182. });
  183. }
  184. return html;
  185. }
  186. //快捷键处理
  187. , hotkey = function (iframeWin, iframe, textArea, set) {
  188. var iframeDOM = iframeWin.document, body = $(iframeDOM.body);
  189. body.on('keydown', function (e) {
  190. var keycode = e.keyCode;
  191. //处理回车
  192. if (keycode === 13) {
  193. var range = Range(iframeDOM);
  194. var container = getContainer(range)
  195. , parentNode = container.parentNode;
  196. if (parentNode.tagName.toLowerCase() === 'pre') {
  197. if (e.shiftKey) return
  198. layer.msg('请暂时用shift+enter');
  199. return false;
  200. }
  201. if (parentNode.tagName.toLowerCase() === 'body') {
  202. iframeDOM.execCommand('formatBlock', false, '<p>');
  203. }
  204. }
  205. });
  206. //给textarea同步内容
  207. $(textArea).parents('form').on('submit', function () {
  208. var html = body.html();
  209. //IE8下将标签处理成小写
  210. if (device.ie == 8) {
  211. html = html.replace(/<.+>/g, function (str) {
  212. return str.toLowerCase();
  213. });
  214. }
  215. textArea.value = html;
  216. });
  217. //处理粘贴
  218. body.on('paste', function (e) {
  219. iframeDOM.execCommand('formatBlock', false, '<p>');
  220. setTimeout(function () {
  221. filter.call(iframeWin, body);
  222. textArea.value = body.html();
  223. }, 100);
  224. });
  225. }
  226. //标签过滤
  227. , filter = function (body) {
  228. var iframeWin = this
  229. , iframeDOM = iframeWin.document;
  230. //清除影响版面的css属性
  231. body.find('*[style]').each(function () {
  232. var textAlign = this.style.textAlign;
  233. this.removeAttribute('style');
  234. $(this).css({
  235. 'text-align': textAlign || ''
  236. })
  237. });
  238. ////修饰表格
  239. //body.find('table').addClass('layui-table');
  240. //移除不安全的标签
  241. body.find('script,link').remove();
  242. }
  243. //Range对象兼容性处理
  244. , Range = function (iframeDOM) {
  245. return iframeDOM.selection
  246. ? iframeDOM.selection.createRange()
  247. : iframeDOM.getSelection().getRangeAt(0);
  248. }
  249. //当前Range对象的endContainer兼容性处理
  250. , getContainer = function (range) {
  251. return range.endContainer || range.parentElement().childNodes[0]
  252. }
  253. //在选区插入内联元素
  254. , insertInline = function (tagName, attr, range) {
  255. var iframeDOM = this.document
  256. , elem = document.createElement(tagName)
  257. for (var key in attr) {
  258. elem.setAttribute(key, attr[key]);
  259. }
  260. elem.removeAttribute('text');
  261. if (iframeDOM.selection) { //IE
  262. var text = range.text || attr.text;
  263. if (tagName === 'a' && !text) return;
  264. if (text) {
  265. elem.innerHTML = text;
  266. }
  267. range.pasteHTML($(elem).prop('outerHTML'));
  268. range.select();
  269. } else { //非IE
  270. var text = range.toString() || attr.text;
  271. if (tagName === 'a' && !text) return;
  272. if (text) {
  273. elem.innerHTML = text;
  274. }
  275. range.deleteContents();
  276. range.insertNode(elem);
  277. }
  278. }
  279. //工具选中
  280. , toolCheck = function (tools, othis) {
  281. var iframeDOM = this.document
  282. , CHECK = 'layedit-tool-active'
  283. , container = getContainer(Range(iframeDOM))
  284. , item = function (type) {
  285. return tools.find('.layedit-tool-' + type)
  286. }
  287. if (othis) {
  288. othis[othis.hasClass(CHECK) ? 'removeClass' : 'addClass'](CHECK);
  289. }
  290. tools.find('>i').removeClass(CHECK);
  291. item('unlink').addClass(ABLED);
  292. $(container).parents().each(function () {
  293. var tagName = this.tagName.toLowerCase()
  294. , textAlign = this.style.textAlign;
  295. //文字
  296. //if (tagName === 'b' || tagName === 'strong') {
  297. // item('b').addClass(CHECK)
  298. //}
  299. //if (tagName === 'i' || tagName === 'em') {
  300. // item('i').addClass(CHECK)
  301. //}
  302. //if (tagName === 'u') {
  303. // item('u').addClass(CHECK)
  304. //}
  305. //if (tagName === 'strike') {
  306. // item('d').addClass(CHECK)
  307. //}
  308. //对齐
  309. if (tagName === 'p') {
  310. if (textAlign === 'center') {
  311. item('center').addClass(CHECK);
  312. } else if (textAlign === 'right') {
  313. item('right').addClass(CHECK);
  314. } else {
  315. item('left').addClass(CHECK);
  316. }
  317. }
  318. //超链接
  319. if (tagName === 'a') {
  320. item('link').addClass(CHECK);
  321. item('unlink').removeClass(ABLED);
  322. }
  323. });
  324. }
  325. //触发工具
  326. , toolActive = function (iframeWin, editor, set) {
  327. var iframeDOM = iframeWin.document
  328. , body = $(iframeDOM.body)
  329. , toolEvent = {
  330. //超链接
  331. link: function (range) {
  332. var container = getContainer(range)
  333. , parentNode = $(container).parent();
  334. link.call(body, {
  335. href: parentNode.attr('href')
  336. , target: parentNode.attr('target')
  337. , rel: parentNode.attr('rel')
  338. , text: parentNode.attr('text')
  339. , dmode: set.devmode
  340. }, function (field) {
  341. var parent = parentNode[0];
  342. if (parent.tagName === 'A') {
  343. parent.href = field.url;
  344. parent.rel = field.rel;
  345. parent.text = field.text;
  346. } else {
  347. insertInline.call(iframeWin, 'a', {
  348. target: field.target
  349. , href: field.url
  350. , rel: field.rel
  351. , text: field.text
  352. }, range);
  353. }
  354. });
  355. }
  356. //清除超链接
  357. , unlink: function (range) {
  358. iframeDOM.execCommand('unlink');
  359. }
  360. //表情
  361. , face: function (range) {
  362. face.call(this, function (img) {
  363. insertInline.call(iframeWin, 'img', {
  364. src: img.src
  365. , alt: img.alt
  366. }, range);
  367. });
  368. }
  369. //图片
  370. , image: function (range) {
  371. var that = this;
  372. layui.use('upload', function (upload) {
  373. var uploadImage = set.uploadImage || {};
  374. upload.render({
  375. url: uploadImage.url
  376. , method: uploadImage.type
  377. , accept: uploadImage.accept
  378. , acceptMime: uploadImage.acceptMime
  379. , exts: uploadImage.exts
  380. , size: uploadImage.size
  381. , elem: $(that).find('input')[0]
  382. , done: function (res) {
  383. if (res.code == 0) {
  384. res.data = res.data[0] || {};
  385. insertInline.call(iframeWin, 'img', {
  386. src: window.hywa.config.href+window.hywa.config.port['show_img']+encodeURIComponent(e.data.src)
  387. , alt: res.data.title
  388. }, range);
  389. } else {
  390. layer.msg(res.msg || '上传失败');
  391. }
  392. }
  393. });
  394. });
  395. }
  396. //插入代码
  397. , code: function (range) {
  398. var codeConfig = set.codeConfig || { hide: false };
  399. code.call(body, { hide: codeConfig.hide, default: codeConfig.default }, function (pre) {
  400. insertInline.call(iframeWin, 'pre', {
  401. text: pre.code
  402. , 'lay-lang': pre.lang
  403. }, range);
  404. });
  405. }
  406. /*#Extens#*/
  407. //图片2
  408. , image_alt: function (range) {
  409. var that = this;
  410. layer.open({
  411. type: 1
  412. , id: 'fly-jie-image-upload'
  413. , title: '图片管理'
  414. , shade: false
  415. , area: '485px'
  416. , offset: '100px'
  417. , skin: 'layui-layer-border'
  418. , content: ['<ul class="layui-form layui-form-pane" style="margin: 20px;">'
  419. , '<li class="layui-form-item">'
  420. , '<label class="layui-form-label">图片</label>'
  421. , '<button type="button" class="layui-btn" id="LayEdit_InsertImage"> <i class="layui-icon"></i>上传图片</button>'
  422. , '<input type="text" name="Imgsrc" placeholder="请选择文件" style="width: 49%;position: relative;float: right;" class="layui-input">'
  423. , '</li>'
  424. , '<li class="layui-form-item">'
  425. , '<label class="layui-form-label">描述</label>'
  426. , '<input type="text" required name="altStr" placeholder="alt属性" style="width: 75%;" value="" class="layui-input">'
  427. , '</li>'
  428. , '<li class="layui-form-item">'
  429. , '<label class="layui-form-label">宽度</label>'
  430. , '<input type="text" required name="imgWidth" placeholder="width" style="width: 25%;position: relative;float: left;" value="" class="layui-input">'
  431. , '<label class="layui-form-label">高度</label>'
  432. , '<input type="text" required name="imgHeight" placeholder="height" style="width: 25%;" value="" class="layui-input">'
  433. , '</li>'
  434. , '<li class="layui-form-item" style="text-align: center;">'
  435. , '<button type="button" lay-submit class="layui-btn layedit-btn-yes"> 确定 </button>'
  436. , '<button style="margin-left: 20px;" type="button" class="layui-btn layui-btn-primary"> 取消 </button>'
  437. , '</li>'
  438. , '</ul>'].join('')
  439. , success: function (layero, index) {
  440. layui.use('upload', function (upload) {
  441. var upload = layui.upload;
  442. var loding, altStr = layero.find('input[name="altStr"]'), Imgsrc = layero.find('input[name="Imgsrc"]');
  443. var uploadImage = set.uploadImage || {};
  444. //执行实例
  445. upload.render({
  446. elem: '#LayEdit_InsertImage'
  447. , url: uploadImage.url
  448. , method: uploadImage.type
  449. , accept: uploadImage.accept
  450. , acceptMime: uploadImage.acceptMime
  451. , exts: uploadImage.exts
  452. , size: uploadImage.size
  453. , before: function (obj) { loding = layer.msg('文件上传中,请稍等哦', { icon: 16, shade: 0.3, time: 0 }); }
  454. , done: function (res, input, upload) {
  455. layer.close(loding);
  456. if (res.code == 0) {
  457. res.data = res.data[0] || {};
  458. Imgsrc.val(window.hywa.config.href+window.hywa.config.port['show_img']+encodeURIComponent(res.data.src));
  459. altStr.val(res.data.title);
  460. } else {
  461. var curIndex = layer.open({
  462. type: 1
  463. , anim: 2
  464. , icon: 5
  465. , title: '提示'
  466. , area: ['390px', '260px']
  467. , offset: 't'
  468. , content: res.msg + "<div style='text-align:center;'><img src='" + window.hywa.config.href+window.hywa.config.port['show_img']+encodeURIComponent(e.data.src) + "' style='max-height:80px'/></div><p style='text-align:center'>确定使用该文件吗?</p>"
  469. , btn: ['确定', '取消']
  470. , yes: function () {
  471. res.data = res.data[0] || {};
  472. Imgsrc.val(window.hywa.config.href+window.hywa.config.port['show_img']+encodeURIComponent(res.data.src));
  473. altStr.val(res.data.title);
  474. layer.close(curIndex);
  475. }
  476. , btn2: function () {
  477. layer.close(curIndex);
  478. }
  479. });
  480. }
  481. }
  482. });
  483. layero.find('.layui-btn-primary').on('click', function () {
  484. layer.close(index);
  485. });
  486. layero.find('.layedit-btn-yes').on('click', function () {
  487. var styleStr = "";
  488. if (layero.find('input[name="imgWidth"]').val() != "") {
  489. styleStr += "width:" + layero.find('input[name="imgWidth"]').val() + ";";
  490. }
  491. if (layero.find('input[name="imgHeight"]').val() != "") {
  492. styleStr += "height:" + layero.find('input[name="imgHeight"]').val() + ";";
  493. }
  494. insertInline.call(iframeWin, 'img', {
  495. src: Imgsrc.val()
  496. , alt: altStr.val()
  497. , style: styleStr
  498. }, range);
  499. layer.close(index);
  500. });
  501. })
  502. }
  503. });
  504. }
  505. //插入视频
  506. , video: function (range) {
  507. var body = this;
  508. layer.open({
  509. type: 1
  510. , id: 'fly-jie-video-upload'
  511. , title: '视频'
  512. , shade: false
  513. , area: '600px'
  514. , offset: '100px'
  515. , skin: 'layui-layer-border'
  516. , content: ['<ul class="layui-form layui-form-pane" style="margin: 20px;">'
  517. , '<li class="layui-form-item">'
  518. , '<button type="button" class="layui-btn" id="LayEdit_InsertVideo"> <i class="layui-icon"></i>上传视频</button>'
  519. , '<input type="text" name="video" placeholder="请选择文件" style="width: 79%;position: relative;float: right;" class="layui-input">'
  520. , '</li>'
  521. , '<li class="layui-form-item">'
  522. , '<button type="button" class="layui-btn" id="LayEdit_InsertImage"> <i class="layui-icon"></i>上传封面</button>'
  523. , '<input type="text" name="cover" placeholder="请选择文件" style="width: 79%;position: relative;float: right;" class="layui-input">'
  524. , '</li>'
  525. , '<li class="layui-form-item" style="text-align: center;">'
  526. , '<button type="button" lay-submit class="layui-btn layedit-btn-yes"> 确定 </button>'
  527. , '<button style="margin-left: 20px;" type="button" class="layui-btn layui-btn-primary"> 取消 </button>'
  528. , '</li>'
  529. , '</ul>'].join('')
  530. , success: function (layero, index) {
  531. layui.use('upload', function (upload) {
  532. var loding, video = layero.find('input[name="video"]'), cover = layero.find('input[name="cover"]');
  533. var upload = layui.upload;
  534. var uploadImage = set.uploadImage || {};
  535. var uploadfile = set.uploadVideo || {};
  536. //执行实例
  537. upload.render({
  538. elem: '#LayEdit_InsertImage'
  539. , url: uploadImage.url
  540. , method: uploadImage.type
  541. , accept: uploadImage.accept
  542. , acceptMime: uploadImage.acceptMime
  543. , exts: uploadImage.exts
  544. , size: uploadImage.size
  545. , before: function (obj) { loding = layer.msg('文件上传中,请稍等哦', { icon: 16, shade: 0.3, time: 0 }); }
  546. , done: function (res, input, upload) {
  547. layer.close(loding);
  548. if (res.code == 0) {
  549. res.data = res.data[0] || {};
  550. cover.val(window.hywa.config.href+window.hywa.config.port['show_img']+encodeURIComponent(e.data.src));
  551. } else {
  552. var curIndex = layer.open({
  553. type: 1
  554. , anim: 2
  555. , icon: 5
  556. , title: '提示'
  557. , area: ['390px', '260px']
  558. , offset: 't'
  559. , content: res.msg + "<div><img src='" + window.hywa.config.href+window.hywa.config.port['show_img']+encodeURIComponent(e.data.src) + "' style='max-height:100px'/></div><label class='layui-form-label'>确定使用该文件吗?</label>"
  560. , btn: ['确定', '取消']
  561. , yes: function () {
  562. res.data = res.data[0] || {};
  563. cover.val(window.hywa.config.href+window.hywa.config.port['show_img']+encodeURIComponent(e.data.src));
  564. layer.close(curIndex);
  565. }
  566. , btn2: function () {
  567. layer.close(curIndex);
  568. }
  569. });
  570. }
  571. }
  572. });
  573. upload.render({
  574. elem: '#LayEdit_InsertVideo'
  575. , url: uploadfile.url
  576. , accept: uploadfile.accept
  577. , acceptMime: uploadfile.acceptMime
  578. , exts: uploadfile.exts
  579. , size: uploadfile.size
  580. , before: function (obj) { loding = layer.msg('文件上传中,请稍等哦', { icon: 16, shade: 0.3, time: 0 }); }
  581. , done: function (res, input, upload) {
  582. layer.close(loding);
  583. if (res.code == 0) {
  584. res.data = res.data || {};
  585. video.val(window.hywa.config.href+window.hywa.config.port['show_img']+encodeURIComponent(e.data.src));
  586. } else {
  587. var curIndex = layer.open({
  588. type: 1
  589. , anim: 2
  590. , icon: 5
  591. , title: '提示'
  592. , area: ['390px', '260px']
  593. , offset: 't'
  594. , content: res.msg + "<div><video src='" + window.hywa.config.href+window.hywa.config.port['show_img']+encodeURIComponent(e.data.src) + "' style='max-height:100px' controls='controls'/></div>确定使用该文件吗?"
  595. , btn: ['确定', '取消']
  596. , yes: function () {
  597. res.data = res.data || {};
  598. video.val(window.hywa.config.href+window.hywa.config.port['show_img']+encodeURIComponent(e.data.src));
  599. layer.close(curIndex);
  600. }
  601. , btn2: function () {
  602. layer.close(curIndex);
  603. }
  604. });
  605. }
  606. }
  607. });
  608. layero.find('.layui-btn-primary').on('click', function () {
  609. layer.close(index);
  610. });
  611. layero.find('.layedit-btn-yes').on('click', function () {
  612. var container = getContainer(range)
  613. , parentNode = $(container).parent();
  614. insertInline.call(iframeWin, 'p', {
  615. text: '&nbsp;<video src="' + video.val() + '" poster="' + cover.val() + '" controls="controls" >您的浏览器不支持video播放</video>&nbsp;'
  616. }, range);
  617. layer.close(index);
  618. });
  619. })
  620. }
  621. });
  622. }
  623. //源码模式
  624. , html: function (range) {
  625. var that = this;
  626. var docs = that.parentElement.nextElementSibling.firstElementChild.contentDocument.body.innerHTML;
  627. docs = style_html(docs, 4, ' ', 80);
  628. layer.open({
  629. type: 1
  630. , id: 'knife-z-html'
  631. , title: '源码模式'
  632. , shade: 0.3
  633. //, maxmin: true
  634. , area: ['1366px', '700px']
  635. , offset: '0px'
  636. , content: ['<div id ="aceHtmleditor" style="width:100%;height:80%"></div>'
  637. , '<div style="text-align:center">'
  638. , '<button type="button" class="layui-btn layedit-btn-yes"> 确定 </button>'
  639. , '<button style="margin-left: 20px;" type="button" class="layui-btn layui-btn-primary"> 取消 </button>'
  640. , '</div>'
  641. ].join('')
  642. , success: function (layero, index) {
  643. var editor = ace.edit('aceHtmleditor');
  644. editor.setFontSize(14);
  645. editor.session.setMode("ace/mode/html");
  646. editor.setTheme("ace/theme/tomorrow");
  647. editor.setValue(docs);
  648. editor.setOption("wrap", "free")
  649. editor.gotoLine(0);
  650. layero.find('.layui-btn-primary').on('click', function () {
  651. layer.close(index);
  652. });
  653. layero.find('.layedit-btn-yes').on('click', function () {
  654. iframeWin.document.body.innerHTML = editor.getValue();
  655. layer.close(index);
  656. });
  657. window.onresize = function () {
  658. editor.resize();
  659. }
  660. }
  661. });
  662. }
  663. //全屏
  664. , fullScreen: function (range) {
  665. if (this.parentElement.parentElement.getAttribute("style") == null) {
  666. this.parentElement.parentElement.setAttribute("style", "position: fixed;top: 0;left: 0;height: 100%;width: 100%;background-color: antiquewhite;z-index: 9999;");
  667. this.parentElement.nextElementSibling.style = "height:100%";
  668. this.parentElement.nextElementSibling.firstElementChild.style = "height:100%";
  669. } else {
  670. this.parentElement.parentElement.removeAttribute("style");
  671. this.parentElement.nextElementSibling.removeAttribute("style");
  672. this.parentElement.nextElementSibling.firstElementChild.style = "height:" + set.height;
  673. }
  674. }
  675. //字体颜色选择
  676. , colorpicker: function (range) {
  677. colorpicker.call(this, function (color) {
  678. iframeDOM.execCommand('forecolor', false, color);
  679. setTimeout(function () {
  680. body.focus();
  681. }, 10);
  682. });
  683. }
  684. , fontFomatt: function (range) {
  685. var alt = set.fontFomatt || {
  686. code: ["p", "h1", "h2", "h3", "h4", "div"],
  687. text: ["正文(p)", "一级标题(h1)", "二级标题(h2)", "三级标题(h3)", "四级标题(h4)", "块级元素(div)"]
  688. }, arr = {}, arr2 = {};
  689. var codes = alt.code;
  690. var texts = alt.text;
  691. var fonts = function () {
  692. layui.each(codes, function (index, item) {
  693. arr[index] = item;
  694. });
  695. return arr;
  696. }();
  697. var fonttexts = function () {
  698. layui.each(texts, function (index, item) {
  699. arr2[index] = item;
  700. });
  701. return arr2;
  702. }();
  703. fontFomatt.call(this, { fonts: fonts, texts: fonttexts }, function (value) {
  704. iframeDOM.execCommand('formatBlock', false, "<" + value + ">");
  705. setTimeout(function () {
  706. body.focus();
  707. }, 10);
  708. });
  709. }
  710. , anchors: function (range) {
  711. anchors.call(body, {}, function (field) {
  712. insertInline.call(iframeWin, 'a', {
  713. name: "#" + field.text
  714. , text: " ", class: 'anchor'
  715. }, range);
  716. });
  717. }
  718. , addhr: function (range) {
  719. insertInline.call(iframeWin, 'hr', {}, range);
  720. }
  721. /*End*/
  722. //帮助
  723. , help: function () {
  724. layer.open({
  725. type: 2
  726. , title: '帮助'
  727. , area: ['600px', '380px']
  728. , shadeClose: true
  729. , shade: 0.1
  730. , offset: '100px'
  731. , skin: 'layui-layer-msg'
  732. , content: ['http://www.layui.com/about/layedit/help.html', 'no']
  733. });
  734. }
  735. }
  736. , tools = editor.find('.layui-layedit-tool')
  737. , click = function () {
  738. var othis = $(this)
  739. , events = othis.attr('layedit-event')
  740. , command = othis.attr('lay-command');
  741. if (othis.hasClass(ABLED)) return;
  742. body.focus();
  743. var range = Range(iframeDOM)
  744. , container = range.commonAncestorContainer
  745. if (command) {
  746. if (/justifyLeft|justifyCenter|justifyRight/.test(command)) {
  747. if (container.parentNode.tagName === 'BODY') {
  748. iframeDOM.execCommand('formatBlock', false, '<p>');
  749. }
  750. }
  751. iframeDOM.execCommand(command);
  752. setTimeout(function () {
  753. body.focus();
  754. }, 10);
  755. } else {
  756. toolEvent[events] && toolEvent[events].call(this, range, iframeDOM);
  757. }
  758. toolCheck.call(iframeWin, tools, othis);
  759. }
  760. , isClick = /image/
  761. tools.find('>i').on('mousedown', function () {
  762. var othis = $(this)
  763. , events = othis.attr('layedit-event');
  764. if (isClick.test(events)) return;
  765. click.call(this)
  766. }).on('click', function () {
  767. var othis = $(this)
  768. , events = othis.attr('layedit-event');
  769. if (!isClick.test(events)) return;
  770. click.call(this)
  771. });
  772. //触发内容区域
  773. body.on('click', function () {
  774. toolCheck.call(iframeWin, tools);
  775. layer.close(face.index);
  776. layer.close(colorpicker.index);
  777. layer.close(fontFomatt.index);
  778. });
  779. //右键菜单自定义
  780. body.on('contextmenu', function (event) {
  781. if (event != null) {
  782. switch (event.target.tagName) {
  783. case "IMG":
  784. layer.open({
  785. type: 1,
  786. title: false,
  787. area: "485px",
  788. offset: [event.clientY + "px", event.clientX + "px"],
  789. shadeClose: true,
  790. content: ['<ul class="layui-form layui-form-pane" style="margin: 20px;">'
  791. , '<li class="layui-form-item">'
  792. , '<label class="layui-form-label">图片</label>'
  793. , '<button type="button" class="layui-btn" id="LayEdit_UpdateImage"> <i class="layui-icon"></i>上传图片</button>'
  794. , '<input type="text" name="Imgsrc" placeholder="请选择文件" style="width: 49%;position: relative;float: right;" value="' + event.target.src + '" class="layui-input">'
  795. , '</li>'
  796. , '<li class="layui-form-item">'
  797. , '<label class="layui-form-label">描述</label>'
  798. , '<input type="text" required name="altStr" placeholder="alt属性" style="width: 75%;" value="' + event.target.alt + '" class="layui-input">'
  799. , '</li>'
  800. , '</li>'
  801. , '<li class="layui-form-item">'
  802. , '<label class="layui-form-label">宽度</label>'
  803. , '<input type="text" required name="imgWidth" placeholder="width" style="width: 25%;position: relative;float: left;" value="' + event.target.width + '" class="layui-input">'
  804. , '<label class="layui-form-label">高度</label>'
  805. , '<input type="text" required name="imgHeight" placeholder="height" style="width: 25%;" value="' + event.target.height + '" class="layui-input">'
  806. , '</li>'
  807. , '<li class="layui-form-item" style="text-align: center;">'
  808. , '<button type="button" lay-submit class="layui-btn layedit-btn-yes"> 确定 </button>'
  809. , '<button style="margin-left: 20px;" type="button" class="layui-btn layui-btn-primary"> 取消 </button>'
  810. , '<button type="button" class="layui-btn layui-btn-danger" > 删除 </button>'
  811. , '</li>'
  812. , '</ul>'].join(''),
  813. success: function (layero, index) {
  814. var uploadImage = set.uploadImage || {};
  815. layui.use('upload', function (upload) {
  816. var loding, altStr = layero.find('input[name="altStr"]'), Imgsrc = layero.find('input[name="Imgsrc"]');
  817. upload = layui.upload;
  818. upload.render({
  819. elem: '#LayEdit_UpdateImage'
  820. , url: uploadImage.url
  821. , method: uploadImage.type
  822. , accept: uploadImage.accept
  823. , acceptMime: uploadImage.acceptMime
  824. , exts: uploadImage.exts
  825. , size: uploadImage.size
  826. , before: function (obj) { loding = layer.msg('文件上传中,请稍等哦', { icon: 16, shade: 0.3, time: 0 }); }
  827. , done: function (res, input, upload) {
  828. layer.close(loding);
  829. if (res.code == 0) {
  830. res.data = res.data[0] || {};
  831. Imgsrc.val(window.hywa.config.href+window.hywa.config.port['show_img']+encodeURIComponent(e.data.src));
  832. altStr.val(res.data.title);
  833. } else {
  834. var curIndex = layer.open({
  835. type: 1
  836. , anim: 2
  837. , icon: 5
  838. , title: '提示'
  839. , area: ['390px', '260px']
  840. , offset: 't'
  841. , content: res.msg + "<div style='text-align:center;'><img src='" + window.hywa.config.href+window.hywa.config.port['show_img']+encodeURIComponent(e.data.src) + "' style='max-height:80px'/></div><p style='text-align:center'>确定使用该文件吗?</p>"
  842. , btn: ['确定', '取消']
  843. , yes: function () {
  844. res.data = res.data[0] || {};
  845. Imgsrc.val(window.hywa.config.href+window.hywa.config.port['show_img']+encodeURIComponent(e.data.src));
  846. altStr.val(res.data.title);
  847. layer.close(curIndex);
  848. }
  849. , btn2: function () {
  850. layer.close(curIndex);
  851. }
  852. });
  853. }
  854. }
  855. });
  856. })
  857. layero.find('.layui-btn-primary').on('click', function () {
  858. layer.close(index);
  859. });
  860. layero.find('.layedit-btn-yes').on('click', function () {
  861. event.target.src = layero.find('input[name="Imgsrc"]').val();
  862. event.target.alt = layero.find('input[name="altStr"]').val();
  863. event.target.width = layero.find('input[name="imgWidth"]').val();
  864. event.target.height = layero.find('input[name="imgHeight"]').val();
  865. layer.close(index);
  866. });
  867. layero.find('.layui-btn-danger').on('click', function () {
  868. var callDel = set.calldel;
  869. if (callDel.url != "") {
  870. $.post(callDel.url, { "imgpath": event.target.src }, function (r) {
  871. event.toElement.remove();
  872. })
  873. } else {
  874. event.toElement.remove();
  875. }
  876. layer.close(index);
  877. });
  878. return false;
  879. }
  880. })
  881. break;
  882. default:
  883. var currenNode = event.toElement, parentNode = event.toElement.parentNode;
  884. layer.open({
  885. type: 1,
  886. title: false,
  887. offset: [event.clientY + "px", event.clientX + "px"],
  888. shadeClose: true,
  889. content: ['<ul style="width:100px">'
  890. , '<li><a type="button" class="layui-btn layui-btn-primary layui-btn-sm" style="width:80%" lay-command="left"> 居左 </a></li>'
  891. , '<li><a type="button" class="layui-btn layui-btn-primary layui-btn-sm" style="width:80%" lay-command="center"> 居中 </a></li>'
  892. , '<li><a type="button" class="layui-btn layui-btn-primary layui-btn-sm" style="width:80%" lay-command="right"> 居右 </a></li>'
  893. , '<li><a type="button" class="layui-btn layui-btn-danger layui-btn-sm" style="width:80%"> 删除 </a></li>'
  894. , '</ul>'].join(''),
  895. success: function (layero, index) {
  896. var callDel = set.calldel;
  897. layero.find('.layui-btn-primary').on('click', function () {
  898. var othis = $(this), command = othis.attr('lay-command');
  899. if (command) {
  900. if (currenNode.tagName == "VIDEO") {
  901. parentNode.style = "text-align:" + command;
  902. } else {
  903. currenNode.style = "text-align:" + command;
  904. }
  905. }
  906. layer.close(index);
  907. });
  908. layero.find('.layui-btn-danger').on('click', function () {
  909. if (currenNode.tagName == "BODY") {
  910. layer.msg("不能再删除了")
  911. }
  912. else if (currenNode.tagName == "VIDEO") {
  913. if (callDel.url != "") {
  914. $.post(callDel.url, { "filepath": event.target.src, "imgpath": event.target.poster }, function (r) {
  915. parentNode.remove();
  916. })
  917. } else {
  918. parentNode.remove();
  919. }
  920. }
  921. else if (currenNode.tagName == "IMG") {
  922. if (callDel.url != "") {
  923. $.post(callDel.url, { para: event.target.src }, function (r) {
  924. currenNode.remove();
  925. })
  926. } else {
  927. currenNode.remove();
  928. }
  929. } else {
  930. currenNode.remove();
  931. }
  932. layer.close(index);
  933. });
  934. }
  935. })
  936. break;
  937. }
  938. }
  939. return false;
  940. })
  941. }
  942. //超链接面板
  943. , link = function (options, callback) {
  944. var dMode = options.dmode;
  945. var body = this, index = layer.open({
  946. type: 1
  947. , id: 'LAY_layedit_link'
  948. , area: '460px'
  949. , offset: '100px'
  950. , shade: 0.05
  951. , shadeClose: true
  952. , moveType: 1
  953. , title: '超链接'
  954. , skin: 'layui-layer-msg'
  955. , content: ['<ul class="layui-form" style="margin: 15px;">'
  956. , '<li class="layui-form-item">'
  957. , '<label class="layui-form-label" style="width: 70px;">链接地址</label>'
  958. , '<div class="layui-input-block">'
  959. , '<input name="url" value="' + (options.href || '') + '" autofocus="true" autocomplete="off" class="layui-input">'
  960. , '</div>'
  961. , '</li>'
  962. , '<li class="layui-form-item">'
  963. , '<label class="layui-form-label" style="width: 70px;">链接文本</label>'
  964. , '<div class="layui-input-block">'
  965. , '<input name="text" value="' + (options.text || '') + '" autofocus="true" autocomplete="off" class="layui-input">'
  966. , '</div>'
  967. , '</li>'
  968. , '<li class="layui-form-item layui-hide">'
  969. , '<label class="layui-form-label" style="width: 70px;">打开方式</label>'
  970. , '<div class="layui-input-block">'
  971. , '<input type="radio" name="target" value="_blank" class="layui-input" title="新窗口" '
  972. + ((options.target === '_blank' || !options.target) ? 'checked' : '') + '>'
  973. , '<input type="radio" name="target" value="_self" class="layui-input" title="当前窗口"'
  974. + (options.target === '_self' ? 'checked' : '') + '>'
  975. , '</div>'
  976. , '</li>'
  977. , '<li class="layui-form-item layui-hide">'
  978. , '<label class="layui-form-label" style="width: 70px;">rel属性</label>'
  979. , '<div class="layui-input-block">'
  980. , '<input type="radio" name="rel" value="nofollow" class="layui-input" title="nofollow"'
  981. + ((options.rel === 'nofollow' || !options.target) ? 'checked' : '') + '>'
  982. , '<input type="radio" name="rel" value="" class="layui-input" title="无" '
  983. + (options.rel === '' ? 'checked' : '') + '>'
  984. , '</div>'
  985. , '</li>'
  986. , '<li class="layui-form-item" style="text-align: center;">'
  987. , '<button type="button" lay-submit lay-filter="layedit-link-yes" class="layui-btn"> 确定 </button>'
  988. , '<button style="margin-left: 20px;" type="button" class="layui-btn layui-btn-primary"> 取消 </button>'
  989. , '</li>'
  990. , '</ul>'].join('')
  991. , success: function (layero, index) {
  992. if (dMode) {
  993. layero.find('.layui-hide').removeClass("layui-hide");
  994. }
  995. var eventFilter = 'submit(layedit-link-yes)';
  996. form.render('radio');
  997. layero.find('.layui-btn-primary').on('click', function () {
  998. layer.close(index);
  999. setTimeout(function () {
  1000. body.focus();
  1001. }, 10);
  1002. });
  1003. form.on(eventFilter, function (data) {
  1004. layer.close(link.index);
  1005. callback && callback(data.field);
  1006. });
  1007. }
  1008. });
  1009. link.index = index;
  1010. }
  1011. , anchors = function (options, callback) {
  1012. var body = this, index = layer.open({
  1013. type: 1
  1014. , id: 'LAY_layedit_addmd'
  1015. , area: '300px'
  1016. , offset: '100px'
  1017. , shade: 0.05
  1018. , shadeClose: true
  1019. , moveType: 1
  1020. , title: '添加锚点'
  1021. , skin: 'layui-layer-msg'
  1022. , content: ['<ul class="layui-form" style="margin: 15px;">'
  1023. , '<li class="layui-form-item">'
  1024. , '<label class="layui-form-label" style="width: 60px;">名称</label>'
  1025. , '<div class="layui-input-block" style="margin-left: 90px">'
  1026. , '<input name="text" value="' + (options.name || '') + '" autofocus="true" autocomplete="off" class="layui-input">'
  1027. , '</div>'
  1028. , '</li>'
  1029. , '<li class="layui-form-item" style="text-align: center;">'
  1030. , '<button type="button" lay-submit lay-filter="layedit-link-yes" class="layui-btn"> 确定 </button>'
  1031. , '<button style="margin-left: 20px;" type="button" class="layui-btn layui-btn-primary"> 取消 </button>'
  1032. , '</li>'
  1033. , '</ul>'].join('')
  1034. , success: function (layero, index) {
  1035. var eventFilter = 'submit(layedit-link-yes)';
  1036. form.render('radio');
  1037. layero.find('.layui-btn-primary').on('click', function () {
  1038. layer.close(index);
  1039. setTimeout(function () {
  1040. body.focus();
  1041. }, 10);
  1042. });
  1043. form.on(eventFilter, function (data) {
  1044. layer.close(anchors.index);
  1045. callback && callback(data.field);
  1046. });
  1047. }
  1048. });
  1049. anchors.index = index;
  1050. }
  1051. //表情面板
  1052. , face = function (callback) {
  1053. //表情库
  1054. var faces = function () {
  1055. var alt = ["[微笑]", "[嘻嘻]", "[哈哈]", "[可爱]", "[可怜]", "[挖鼻]", "[吃惊]", "[害羞]", "[挤眼]", "[闭嘴]", "[鄙视]", "[爱你]", "[泪]", "[偷笑]", "[亲亲]", "[生病]", "[太开心]", "[白眼]", "[右哼哼]", "[左哼哼]", "[嘘]", "[衰]", "[委屈]", "[吐]", "[哈欠]", "[抱抱]", "[怒]", "[疑问]", "[馋嘴]", "[拜拜]", "[思考]", "[汗]", "[困]", "[睡]", "[钱]", "[失望]", "[酷]", "[色]", "[哼]", "[鼓掌]", "[晕]", "[悲伤]", "[抓狂]", "[黑线]", "[阴险]", "[怒骂]", "[互粉]", "[心]", "[伤心]", "[猪头]", "[熊猫]", "[兔子]", "[ok]", "[耶]", "[good]", "[NO]", "[赞]", "[来]", "[弱]", "[草泥马]", "[神马]", "[囧]", "[浮云]", "[给力]", "[围观]", "[威武]", "[奥特曼]", "[礼物]", "[钟]", "[话筒]", "[蜡烛]", "[蛋糕]"], arr = {};
  1056. layui.each(alt, function (index, item) {
  1057. arr[item] = layui.cache.dir + 'images/face/' + index + '.gif';
  1058. });
  1059. return arr;
  1060. }();
  1061. face.hide = face.hide || function (e) {
  1062. if ($(e.target).attr('layedit-event') !== 'face') {
  1063. layer.close(face.index);
  1064. }
  1065. }
  1066. return face.index = layer.tips(function () {
  1067. var content = [];
  1068. layui.each(faces, function (key, item) {
  1069. content.push('<li title="' + key + '"><img src="' + item + '" alt="' + key + '"/></li>');
  1070. });
  1071. return '<ul class="layui-clear">' + content.join('') + '</ul>';
  1072. }(), this, {
  1073. tips: 1
  1074. , time: 0
  1075. , skin: 'layui-box layui-util-face'
  1076. , maxWidth: 500
  1077. , success: function (layero, index) {
  1078. layero.css({
  1079. marginTop: -4
  1080. , marginLeft: -10
  1081. }).find('.layui-clear>li').on('click', function () {
  1082. callback && callback({
  1083. src: faces[this.title]
  1084. , alt: this.title
  1085. });
  1086. layer.close(index);
  1087. });
  1088. $(document).off('click', face.hide).on('click', face.hide);
  1089. }
  1090. });
  1091. }
  1092. //字体颜色
  1093. , colorpicker = function (callback) {
  1094. var colors = function () {
  1095. var alt = ["#fff", "#000", "#800000", "#ffb800", "#1e9fff", "#5fb878", "#ff5722", "#999999", "#01aaed", "#cc0000", "#ff8c00", "#ffd700", "#90ee90", "#00ced1", "#1e90ff",
  1096. "#c71585", "#00babd", "#ff7800"], arr = {};
  1097. layui.each(alt, function (index, item) {
  1098. arr[item] = item;
  1099. });
  1100. return arr;
  1101. }();
  1102. colorpicker.hide = colorpicker.hide || function (e) {
  1103. if ($(e.target).attr('layedit-event') !== 'colorpicker') {
  1104. layer.close(colorpicker.index);
  1105. }
  1106. }
  1107. return colorpicker.index = layer.tips(function () {
  1108. var content = [];
  1109. layui.each(colors, function (key, item) {
  1110. content.push('<li title="' + item + '" style="background-color:' + item + '"><span style="background-' + item + '" alt="' + key + '"/></li>');
  1111. });
  1112. return '<ul class="layui-clear">' + content.join('') + '</ul>';
  1113. }(), this, {
  1114. tips: 1
  1115. , time: 0
  1116. , skin: 'layui-box layui-util-face'
  1117. //, maxWidth: 300
  1118. , success: function (layero, index) {
  1119. layero.css({
  1120. marginTop: -4
  1121. , marginLeft: -10
  1122. }).find('.layui-clear>li').on('click', function () {
  1123. callback && callback(this.title);
  1124. layer.close(index);
  1125. });
  1126. $(document).off('click', colorpicker.hide).on('click', colorpicker.hide);
  1127. }
  1128. });
  1129. }
  1130. , fontFomatt = function (options, callback) {
  1131. fontFomatt.hide = fontFomatt.hide || function (e) {
  1132. if ($(e.target).attr('layedit-event') !== 'fontFomatt') {
  1133. layer.close(fontFomatt.index);
  1134. }
  1135. }
  1136. fontFomatt.index = layer.tips(function () {
  1137. var content = [];
  1138. layui.each(options.fonts, function (index, item) {
  1139. content.push('<li title="' + options.fonts[index] + '"><' + options.fonts[index] + '>' + options.texts[index] + '</' + options.fonts[index] + '></li>');
  1140. });
  1141. return '<ul class="layui-clear" style="width: max-content;">' + content.join('') + '</ul>';
  1142. }(), this, {
  1143. tips: 1
  1144. , time: 0
  1145. , skin: 'layui-box layui-util-font'
  1146. , success: function (layero, index) {
  1147. layero.css({ marginTop: -4, marginLeft: -10 }).find('.layui-clear>li').on('click', function () {
  1148. callback && callback(this.title, options.fonts);
  1149. layer.close(index);
  1150. });
  1151. $(document).off('click', fontFomatt.hide).on('click', fontFomatt.hide);
  1152. }
  1153. });
  1154. }
  1155. //插入代码面板
  1156. , code = function (options, callback) {
  1157. var objSel = ['<li class="layui-form-item objSel">'
  1158. , '<label class="layui-form-label">请选择语言</label>'
  1159. , '<div class="layui-input-block">'
  1160. , '<select name="lang">'
  1161. , '<option value="JavaScript">JavaScript</option>'
  1162. , '<option value="HTML">HTML</option>'
  1163. , '<option value="CSS">CSS</option>'
  1164. , '<option value="Java">Java</option>'
  1165. , '<option value="PHP">PHP</option>'
  1166. , '<option value="C#">C#</option>'
  1167. , '<option value="Python">Python</option>'
  1168. , '<option value="Ruby">Ruby</option>'
  1169. , '<option value="Go">Go</option>'
  1170. , '</select>'
  1171. , '</div>'
  1172. , '</li>'].join('');
  1173. if (options.hide) {
  1174. objSel = ['<li class="layui-form-item" style="display:none">'
  1175. , '<label class="layui-form-label">请选择语言</label>'
  1176. , '<div class="layui-input-block">'
  1177. , '<select name="lang">'
  1178. , '<option value="' + options.default + '" selected="selected">'
  1179. , options.default
  1180. , '</option>'
  1181. , '</select>'
  1182. , '</div>'
  1183. , '</li>'].join('');
  1184. }
  1185. var body = this, index = layer.open({
  1186. type: 1
  1187. , id: 'LAY_layedit_code'
  1188. , area: '550px'
  1189. , shade: 0.05
  1190. , shadeClose: true
  1191. , offset: '100px'
  1192. , moveType: 1
  1193. , title: '插入代码'
  1194. , skin: 'layui-layer-msg'
  1195. , content: ['<ul class="layui-form layui-form-pane" style="margin: 15px;">'
  1196. , objSel
  1197. , '<li class="layui-form-item layui-form-text">'
  1198. , '<label class="layui-form-label">代码</label>'
  1199. , '<div class="layui-input-block">'
  1200. , '<textarea name="code" lay-verify="required" autofocus="true" class="layui-textarea" style="height: 200px;"></textarea>'
  1201. , '</div>'
  1202. , '</li>'
  1203. , '<li class="layui-form-item" style="text-align: center;">'
  1204. , '<button type="button" lay-submit lay-filter="layedit-code-yes" class="layui-btn"> 确定 </button>'
  1205. , '<button style="margin-left: 20px;" type="button" class="layui-btn layui-btn-primary"> 取消 </button>'
  1206. , '</li>'
  1207. , '</ul>'].join('')
  1208. , success: function (layero, index) {
  1209. var eventFilter = 'submit(layedit-code-yes)';
  1210. form.render('select');
  1211. layero.find('.layui-btn-primary').on('click', function () {
  1212. layer.close(index);
  1213. body.focus();
  1214. });
  1215. form.on(eventFilter, function (data) {
  1216. layer.close(code.index);
  1217. callback && callback(data.field, options.hide, options.default);
  1218. });
  1219. }
  1220. });
  1221. code.index = index;
  1222. }
  1223. //全部工具
  1224. , tools = {
  1225. html: '<i class="layui-icon layedit-tool-html" title="HTML源代码" layedit-event="html"">&#xe64b;</i><span class="layedit-tool-mid"></span>'
  1226. , strong: '<i class="layui-icon layedit-tool-b" title="加粗" lay-command="Bold" layedit-event="b"">&#xe62b;</i>'
  1227. , italic: '<i class="layui-icon layedit-tool-i" title="斜体" lay-command="italic" layedit-event="i"">&#xe644;</i>'
  1228. , underline: '<i class="layui-icon layedit-tool-u" title="下划线" lay-command="underline" layedit-event="u"">&#xe646;</i>'
  1229. , del: '<i class="layui-icon layedit-tool-d" title="删除线" lay-command="strikeThrough" layedit-event="d"">&#xe64f;</i>'
  1230. , '|': '<span class="layedit-tool-mid"></span>'
  1231. , left: '<i class="layui-icon layedit-tool-left" title="左对齐" lay-command="justifyLeft" layedit-event="left"">&#xe649;</i>'
  1232. , center: '<i class="layui-icon layedit-tool-center" title="居中对齐" lay-command="justifyCenter" layedit-event="center"">&#xe647;</i>'
  1233. , right: '<i class="layui-icon layedit-tool-right" title="右对齐" lay-command="justifyRight" layedit-event="right"">&#xe648;</i>'
  1234. , link: '<i class="layui-icon layedit-tool-link" title="插入链接" layedit-event="link"">&#xe64c;</i>'
  1235. , unlink: '<i class="layui-icon layedit-tool-unlink layui-disabled" title="清除链接" lay-command="unlink" layedit-event="unlink"" style="font-size:18px">&#xe64d;</i>'
  1236. , face: '<i class="layui-icon layedit-tool-face" title="表情" layedit-event="face"" style="font-size:18px">&#xe650;</i>'
  1237. , image: '<i class="layui-icon layedit-tool-image" title="图片" layedit-event="image" style="font-size:18px">&#xe64a;<input type="file" name="file"></i>'
  1238. , code: '<i class="layui-icon layedit-tool-code" title="插入代码" layedit-event="code" style="font-size:18px">&#xe64e;</i>'
  1239. , image_alt: '<i class="layui-icon layedit-tool-image_alt" title="图片" layedit-event="image_alt" style="font-size:18px">&#xe64a;</i>'
  1240. , video: '<i class="layui-icon layedit-tool-video" title="插入视频" layedit-event="video" style="font-size:18px">&#xe6ed;</i>'
  1241. , fullScreen: '<i class="layui-icon layedit-tool-fullScreen" title="全屏" layedit-event="fullScreen"style="font-size:18px">&#xe638;</i>'
  1242. , colorpicker: '<i class="layui-icon layedit-tool-colorpicker" title="字体颜色选择" layedit-event="colorpicker" style="font-size:18px">&#xe66a;</i>'
  1243. , fontFomatt: '<i class="layui-icon layedit-tool-fontFomatt" title="段落格式" layedit-event="fontFomatt" style="font-size:18px">&#xe639;</i>'
  1244. , fontFamily: '<i class="layui-icon layedit-tool-fontFamily" title="字体" layedit-event="fontFamily" style="font-size:18px">&#xe702;</i>'
  1245. , addhr: '<i class="layui-icon layui-icon-chart layedit-tool-addhr" title="添加水平线" layedit-event="addhr" style="font-size:18px"></i>'
  1246. , anchors: '<i class="layui-icon layedit-tool-anchors" title="添加锚点" layedit-event="anchors" style="font-size:18px">&#xe60b;</i>'
  1247. , help: '<i class="layui-icon layedit-tool-help" title="帮助" layedit-event="help">&#xe607;</i>'
  1248. }
  1249. , edit = new Edit();
  1250. form.render();
  1251. exports(MOD_NAME, edit);
  1252. });
  1253. //HTML 格式化
  1254. function style_html(html_source, indent_size, indent_character, max_char) {
  1255. var Parser, multi_parser;
  1256. function Parser() {
  1257. this.pos = 0;
  1258. this.token = '';
  1259. this.current_mode = 'CONTENT';
  1260. this.tags = {
  1261. parent: 'parent1',
  1262. parentcount: 1,
  1263. parent1: ''
  1264. };
  1265. this.tag_type = '';
  1266. this.token_text = this.last_token = this.last_text = this.token_type = '';
  1267. this.Utils = {
  1268. whitespace: "\n\r\t ".split(''),
  1269. single_token: 'br,input,link,meta,!doctype,basefont,base,area,hr,wbr,param,img,isindex,?xml,embed'.split(','),
  1270. extra_liners: 'head,body,/html'.split(','),
  1271. in_array: function (what, arr) {
  1272. for (var i = 0; i < arr.length; i++) {
  1273. if (what === arr[i]) {
  1274. return true;
  1275. }
  1276. }
  1277. return false;
  1278. }
  1279. }
  1280. this.get_content = function () {
  1281. var char = '';
  1282. var content = [];
  1283. var space = false;
  1284. while (this.input.charAt(this.pos) !== '<') {
  1285. if (this.pos >= this.input.length) {
  1286. return content.length ? content.join('') : ['', 'TK_EOF'];
  1287. }
  1288. char = this.input.charAt(this.pos);
  1289. this.pos++;
  1290. this.line_char_count++;
  1291. if (this.Utils.in_array(char, this.Utils.whitespace)) {
  1292. if (content.length) {
  1293. space = true;
  1294. }
  1295. this.line_char_count--;
  1296. continue;
  1297. }
  1298. else if (space) {
  1299. if (this.line_char_count >= this.max_char) {
  1300. content.push('\n');
  1301. for (var i = 0; i < this.indent_level; i++) {
  1302. content.push(this.indent_string);
  1303. }
  1304. this.line_char_count = 0;
  1305. }
  1306. else {
  1307. content.push(' ');
  1308. this.line_char_count++;
  1309. }
  1310. space = false;
  1311. }
  1312. content.push(char);
  1313. }
  1314. return content.length ? content.join('') : '';
  1315. }
  1316. this.get_script = function () {
  1317. var char = '';
  1318. var content = [];
  1319. var reg_match = new RegExp('\<\/script' + '\>', 'igm');
  1320. reg_match.lastIndex = this.pos;
  1321. var reg_array = reg_match.exec(this.input);
  1322. var end_script = reg_array ? reg_array.index : this.input.length;
  1323. while (this.pos < end_script) {
  1324. if (this.pos >= this.input.length) {
  1325. return content.length ? content.join('') : ['', 'TK_EOF'];
  1326. }
  1327. char = this.input.charAt(this.pos);
  1328. this.pos++;
  1329. content.push(char);
  1330. }
  1331. return content.length ? content.join('') : '';
  1332. }
  1333. this.record_tag = function (tag) {
  1334. if (this.tags[tag + 'count']) {
  1335. this.tags[tag + 'count']++;
  1336. this.tags[tag + this.tags[tag + 'count']] = this.indent_level;
  1337. }
  1338. else {
  1339. this.tags[tag + 'count'] = 1;
  1340. this.tags[tag + this.tags[tag + 'count']] = this.indent_level;
  1341. }
  1342. this.tags[tag + this.tags[tag + 'count'] + 'parent'] = this.tags.parent;
  1343. this.tags.parent = tag + this.tags[tag + 'count'];
  1344. }
  1345. this.retrieve_tag = function (tag) {
  1346. if (this.tags[tag + 'count']) {
  1347. var temp_parent = this.tags.parent;
  1348. while (temp_parent) {
  1349. if (tag + this.tags[tag + 'count'] === temp_parent) {
  1350. break;
  1351. }
  1352. temp_parent = this.tags[temp_parent + 'parent'];
  1353. }
  1354. if (temp_parent) {
  1355. this.indent_level = this.tags[tag + this.tags[tag + 'count']];
  1356. this.tags.parent = this.tags[temp_parent + 'parent'];
  1357. }
  1358. delete this.tags[tag + this.tags[tag + 'count'] + 'parent'];
  1359. delete this.tags[tag + this.tags[tag + 'count']];
  1360. if (this.tags[tag + 'count'] == 1) {
  1361. delete this.tags[tag + 'count'];
  1362. }
  1363. else {
  1364. this.tags[tag + 'count']--;
  1365. }
  1366. }
  1367. }
  1368. this.get_tag = function () {
  1369. var char = '';
  1370. var content = [];
  1371. var space = false;
  1372. do {
  1373. if (this.pos >= this.input.length) {
  1374. return content.length ? content.join('') : ['', 'TK_EOF'];
  1375. }
  1376. char = this.input.charAt(this.pos);
  1377. this.pos++;
  1378. this.line_char_count++;
  1379. if (this.Utils.in_array(char, this.Utils.whitespace)) {
  1380. space = true;
  1381. this.line_char_count--;
  1382. continue;
  1383. }
  1384. if (char === "'" || char === '"') {
  1385. if (!content[1] || content[1] !== '!') {
  1386. char += this.get_unformatted(char);
  1387. space = true;
  1388. }
  1389. }
  1390. if (char === '=') {
  1391. space = false;
  1392. }
  1393. if (content.length && content[content.length - 1] !== '=' && char !== '>'
  1394. && space) {
  1395. if (this.line_char_count >= this.max_char) {
  1396. this.print_newline(false, content);
  1397. this.line_char_count = 0;
  1398. }
  1399. else {
  1400. content.push(' ');
  1401. this.line_char_count++;
  1402. }
  1403. space = false;
  1404. }
  1405. content.push(char);
  1406. } while (char !== '>');
  1407. var tag_complete = content.join('');
  1408. var tag_index;
  1409. if (tag_complete.indexOf(' ') != -1) {
  1410. tag_index = tag_complete.indexOf(' ');
  1411. }
  1412. else {
  1413. tag_index = tag_complete.indexOf('>');
  1414. }
  1415. var tag_check = tag_complete.substring(1, tag_index).toLowerCase();
  1416. if (tag_complete.charAt(tag_complete.length - 2) === '/' ||
  1417. this.Utils.in_array(tag_check, this.Utils.single_token)) {
  1418. this.tag_type = 'SINGLE';
  1419. }
  1420. else if (tag_check === 'script') {
  1421. this.record_tag(tag_check);
  1422. this.tag_type = 'SCRIPT';
  1423. }
  1424. else if (tag_check === 'style') {
  1425. this.record_tag(tag_check);
  1426. this.tag_type = 'STYLE';
  1427. }
  1428. else if (tag_check.charAt(0) === '!') {
  1429. if (tag_check.indexOf('[if') != -1) {
  1430. if (tag_complete.indexOf('!IE') != -1) {
  1431. var comment = this.get_unformatted('-->', tag_complete);
  1432. content.push(comment);
  1433. }
  1434. this.tag_type = 'START';
  1435. }
  1436. else if (tag_check.indexOf('[endif') != -1) {
  1437. this.tag_type = 'END';
  1438. this.unindent();
  1439. }
  1440. else if (tag_check.indexOf('[cdata[') != -1) {
  1441. var comment = this.get_unformatted(']]>', tag_complete);
  1442. content.push(comment);
  1443. this.tag_type = 'SINGLE';
  1444. }
  1445. else {
  1446. var comment = this.get_unformatted('-->', tag_complete);
  1447. content.push(comment);
  1448. this.tag_type = 'SINGLE';
  1449. }
  1450. }
  1451. else {
  1452. if (tag_check.charAt(0) === '/') {
  1453. this.retrieve_tag(tag_check.substring(1));
  1454. this.tag_type = 'END';
  1455. }
  1456. else {
  1457. this.record_tag(tag_check);
  1458. this.tag_type = 'START';
  1459. }
  1460. if (this.Utils.in_array(tag_check, this.Utils.extra_liners)) {
  1461. this.print_newline(true, this.output);
  1462. }
  1463. }
  1464. return content.join('');
  1465. }
  1466. this.get_unformatted = function (delimiter, orig_tag) {
  1467. if (orig_tag && orig_tag.indexOf(delimiter) != -1) {
  1468. return '';
  1469. }
  1470. var char = '';
  1471. var content = '';
  1472. var space = true;
  1473. do {
  1474. char = this.input.charAt(this.pos);
  1475. this.pos++
  1476. if (this.Utils.in_array(char, this.Utils.whitespace)) {
  1477. if (!space) {
  1478. this.line_char_count--;
  1479. continue;
  1480. }
  1481. if (char === '\n' || char === '\r') {
  1482. content += '\n';
  1483. for (var i = 0; i < this.indent_level; i++) {
  1484. content += this.indent_string;
  1485. }
  1486. space = false;
  1487. this.line_char_count = 0;
  1488. continue;
  1489. }
  1490. }
  1491. content += char;
  1492. this.line_char_count++;
  1493. space = true;
  1494. } while (content.indexOf(delimiter) == -1);
  1495. return content;
  1496. }
  1497. this.get_token = function () {
  1498. var token;
  1499. if (this.last_token === 'TK_TAG_SCRIPT') {
  1500. var temp_token = this.get_script();
  1501. if (typeof temp_token !== 'string') {
  1502. return temp_token;
  1503. }
  1504. token = js_beautify(temp_token, this.indent_size, this.indent_character, this.indent_level);
  1505. return [token, 'TK_CONTENT'];
  1506. }
  1507. if (this.current_mode === 'CONTENT') {
  1508. token = this.get_content();
  1509. if (typeof token !== 'string') {
  1510. return token;
  1511. }
  1512. else {
  1513. return [token, 'TK_CONTENT'];
  1514. }
  1515. }
  1516. if (this.current_mode === 'TAG') {
  1517. token = this.get_tag();
  1518. if (typeof token !== 'string') {
  1519. return token;
  1520. }
  1521. else {
  1522. var tag_name_type = 'TK_TAG_' + this.tag_type;
  1523. return [token, tag_name_type];
  1524. }
  1525. }
  1526. }
  1527. this.printer = function (js_source, indent_character, indent_size, max_char) {
  1528. this.input = js_source || '';
  1529. this.output = [];
  1530. this.indent_character = indent_character || ' ';
  1531. this.indent_string = '';
  1532. this.indent_size = indent_size || 2;
  1533. this.indent_level = 0;
  1534. this.max_char = max_char || 7000;
  1535. this.line_char_count = 0;
  1536. for (var i = 0; i < this.indent_size; i++) {
  1537. this.indent_string += this.indent_character;
  1538. }
  1539. this.print_newline = function (ignore, arr) {
  1540. this.line_char_count = 0;
  1541. if (!arr || !arr.length) {
  1542. return;
  1543. }
  1544. if (!ignore) {
  1545. while (this.Utils.in_array(arr[arr.length - 1], this.Utils.whitespace)) {
  1546. arr.pop();
  1547. }
  1548. }
  1549. arr.push('\n');
  1550. for (var i = 0; i < this.indent_level; i++) {
  1551. arr.push(this.indent_string);
  1552. }
  1553. }
  1554. this.print_token = function (text) {
  1555. this.output.push(text);
  1556. }
  1557. this.indent = function () {
  1558. this.indent_level++;
  1559. }
  1560. this.unindent = function () {
  1561. if (this.indent_level > 0) {
  1562. this.indent_level--;
  1563. }
  1564. }
  1565. }
  1566. return this;
  1567. }
  1568. multi_parser = new Parser();
  1569. multi_parser.printer(html_source, indent_character, indent_size);
  1570. var f = true;
  1571. while (true) {
  1572. var t = multi_parser.get_token();
  1573. multi_parser.token_text = t[0];
  1574. multi_parser.token_type = t[1];
  1575. if (multi_parser.token_type === 'TK_EOF') {
  1576. break;
  1577. }
  1578. switch (multi_parser.token_type) {
  1579. case 'TK_TAG_START': case 'TK_TAG_SCRIPT': case 'TK_TAG_STYLE':
  1580. multi_parser.print_newline(false, multi_parser.output);
  1581. multi_parser.print_token(multi_parser.token_text);
  1582. multi_parser.indent();
  1583. multi_parser.current_mode = 'CONTENT';
  1584. break;
  1585. case 'TK_TAG_END':
  1586. if (f)
  1587. multi_parser.print_newline(true, multi_parser.output);
  1588. multi_parser.print_token(multi_parser.token_text);
  1589. multi_parser.current_mode = 'CONTENT';
  1590. f = true;
  1591. break;
  1592. case 'TK_TAG_SINGLE':
  1593. multi_parser.print_newline(false, multi_parser.output);
  1594. multi_parser.print_token(multi_parser.token_text);
  1595. multi_parser.current_mode = 'CONTENT';
  1596. break;
  1597. case 'TK_CONTENT':
  1598. if (multi_parser.token_text !== '') {
  1599. f = false;
  1600. multi_parser.print_token(multi_parser.token_text);
  1601. }
  1602. multi_parser.current_mode = 'TAG';
  1603. break;
  1604. }
  1605. multi_parser.last_token = multi_parser.token_type;
  1606. multi_parser.last_text = multi_parser.token_text;
  1607. }
  1608. return multi_parser.output.join('');
  1609. }
  1610. function js_beautify(js_source_text, indent_size, indent_character, indent_level) {
  1611. var input, output, token_text, last_type, last_text, last_word, current_mode, modes, indent_string;
  1612. var whitespace, wordchar, punct, parser_pos, line_starters, in_case;
  1613. var prefix, token_type, do_block_just_closed, var_line, var_line_tainted;
  1614. function trim_output() {
  1615. while (output.length && (output[output.length - 1] === ' ' || output[output.length - 1] === indent_string)) {
  1616. output.pop();
  1617. }
  1618. }
  1619. function print_newline(ignore_repeated) {
  1620. ignore_repeated = typeof ignore_repeated === 'undefined' ? true : ignore_repeated;
  1621. trim_output();
  1622. if (!output.length) {
  1623. return; // no newline on start of file
  1624. }
  1625. if (output[output.length - 1] !== "\n" || !ignore_repeated) {
  1626. output.push("\n");
  1627. }
  1628. for (var i = 0; i < indent_level; i++) {
  1629. output.push(indent_string);
  1630. }
  1631. }
  1632. function print_space() {
  1633. var last_output = output.length ? output[output.length - 1] : ' ';
  1634. if (last_output !== ' ' && last_output !== '\n' && last_output !== indent_string) { // prevent occassional duplicate space
  1635. output.push(' ');
  1636. }
  1637. }
  1638. function print_token() {
  1639. output.push(token_text);
  1640. }
  1641. function indent() {
  1642. indent_level++;
  1643. }
  1644. function unindent() {
  1645. if (indent_level) {
  1646. indent_level--;
  1647. }
  1648. }
  1649. function remove_indent() {
  1650. if (output.length && output[output.length - 1] === indent_string) {
  1651. output.pop();
  1652. }
  1653. }
  1654. function set_mode(mode) {
  1655. modes.push(current_mode);
  1656. current_mode = mode;
  1657. }
  1658. function restore_mode() {
  1659. do_block_just_closed = current_mode === 'DO_BLOCK';
  1660. current_mode = modes.pop();
  1661. }
  1662. function in_array(what, arr) {
  1663. for (var i = 0; i < arr.length; i++) {
  1664. if (arr[i] === what) {
  1665. return true;
  1666. }
  1667. }
  1668. return false;
  1669. }
  1670. function get_next_token() {
  1671. var n_newlines = 0;
  1672. var c = '';
  1673. do {
  1674. if (parser_pos >= input.length) {
  1675. return ['', 'TK_EOF'];
  1676. }
  1677. c = input.charAt(parser_pos);
  1678. parser_pos += 1;
  1679. if (c === "\n") {
  1680. n_newlines += 1;
  1681. }
  1682. }
  1683. while (in_array(c, whitespace));
  1684. if (n_newlines > 1) {
  1685. for (var i = 0; i < 2; i++) {
  1686. print_newline(i === 0);
  1687. }
  1688. }
  1689. var wanted_newline = (n_newlines === 1);
  1690. if (in_array(c, wordchar)) {
  1691. if (parser_pos < input.length) {
  1692. while (in_array(input.charAt(parser_pos), wordchar)) {
  1693. c += input.charAt(parser_pos);
  1694. parser_pos += 1;
  1695. if (parser_pos === input.length) {
  1696. break;
  1697. }
  1698. }
  1699. }
  1700. // small and surprisingly unugly hack for 1E-10 representation
  1701. if (parser_pos !== input.length && c.match(/^[0-9]+[Ee]$/) && input.charAt(parser_pos) === '-') {
  1702. parser_pos += 1;
  1703. var t = get_next_token(parser_pos);
  1704. c += '-' + t[0];
  1705. return [c, 'TK_WORD'];
  1706. }
  1707. if (c === 'in') { // hack for 'in' operator
  1708. return [c, 'TK_OPERATOR'];
  1709. }
  1710. return [c, 'TK_WORD'];
  1711. }
  1712. if (c === '(' || c === '[') {
  1713. return [c, 'TK_START_EXPR'];
  1714. }
  1715. if (c === ')' || c === ']') {
  1716. return [c, 'TK_END_EXPR'];
  1717. }
  1718. if (c === '{') {
  1719. return [c, 'TK_START_BLOCK'];
  1720. }
  1721. if (c === '}') {
  1722. return [c, 'TK_END_BLOCK'];
  1723. }
  1724. if (c === ';') {
  1725. return [c, 'TK_END_COMMAND'];
  1726. }
  1727. if (c === '/') {
  1728. var comment = '';
  1729. // peek for comment /* ... */
  1730. if (input.charAt(parser_pos) === '*') {
  1731. parser_pos += 1;
  1732. if (parser_pos < input.length) {
  1733. while (!(input.charAt(parser_pos) === '*' && input.charAt(parser_pos + 1) && input.charAt(parser_pos + 1) === '/') && parser_pos < input.length) {
  1734. comment += input.charAt(parser_pos);
  1735. parser_pos += 1;
  1736. if (parser_pos >= input.length) {
  1737. break;
  1738. }
  1739. }
  1740. }
  1741. parser_pos += 2;
  1742. return ['/*' + comment + '*/', 'TK_BLOCK_COMMENT'];
  1743. }
  1744. // peek for comment // ...
  1745. if (input.charAt(parser_pos) === '/') {
  1746. comment = c;
  1747. while (input.charAt(parser_pos) !== "\x0d" && input.charAt(parser_pos) !== "\x0a") {
  1748. comment += input.charAt(parser_pos);
  1749. parser_pos += 1;
  1750. if (parser_pos >= input.length) {
  1751. break;
  1752. }
  1753. }
  1754. parser_pos += 1;
  1755. if (wanted_newline) {
  1756. print_newline();
  1757. }
  1758. return [comment, 'TK_COMMENT'];
  1759. }
  1760. }
  1761. if (c === "'" || // string
  1762. c === '"' || // string
  1763. (c === '/' &&
  1764. ((last_type === 'TK_WORD' && last_text === 'return') || (last_type === 'TK_START_EXPR' || last_type === 'TK_END_BLOCK' || last_type === 'TK_OPERATOR' || last_type === 'TK_EOF' || last_type === 'TK_END_COMMAND')))) { // regexp
  1765. var sep = c;
  1766. var esc = false;
  1767. c = '';
  1768. if (parser_pos < input.length) {
  1769. while (esc || input.charAt(parser_pos) !== sep) {
  1770. c += input.charAt(parser_pos);
  1771. if (!esc) {
  1772. esc = input.charAt(parser_pos) === '\\';
  1773. } else {
  1774. esc = false;
  1775. }
  1776. parser_pos += 1;
  1777. if (parser_pos >= input.length) {
  1778. break;
  1779. }
  1780. }
  1781. }
  1782. parser_pos += 1;
  1783. if (last_type === 'TK_END_COMMAND') {
  1784. print_newline();
  1785. }
  1786. return [sep + c + sep, 'TK_STRING'];
  1787. }
  1788. if (in_array(c, punct)) {
  1789. while (parser_pos < input.length && in_array(c + input.charAt(parser_pos), punct)) {
  1790. c += input.charAt(parser_pos);
  1791. parser_pos += 1;
  1792. if (parser_pos >= input.length) {
  1793. break;
  1794. }
  1795. }
  1796. return [c, 'TK_OPERATOR'];
  1797. }
  1798. return [c, 'TK_UNKNOWN'];
  1799. }
  1800. //----------------------------------
  1801. indent_character = indent_character || ' ';
  1802. indent_size = indent_size || 4;
  1803. indent_string = '';
  1804. while (indent_size--) {
  1805. indent_string += indent_character;
  1806. }
  1807. input = js_source_text;
  1808. last_word = ''; // last 'TK_WORD' passed
  1809. last_type = 'TK_START_EXPR'; // last token type
  1810. last_text = ''; // last token text
  1811. output = [];
  1812. do_block_just_closed = false;
  1813. var_line = false;
  1814. var_line_tainted = false;
  1815. whitespace = "\n\r\t ".split('');
  1816. wordchar = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_$'.split('');
  1817. punct = '+ - * / % & ++ -- = += -= *= /= %= == === != !== > < >= <= >> << >>> >>>= >>= <<= && &= | || ! !! , : ? ^ ^= |='.split(' ');
  1818. // words which should always start on new line.
  1819. line_starters = 'continue,try,throw,return,var,if,switch,case,default,for,while,break,function'.split(',');
  1820. // states showing if we are currently in expression (i.e. "if" case) - 'EXPRESSION', or in usual block (like, procedure), 'BLOCK'.
  1821. // some formatting depends on that.
  1822. current_mode = 'BLOCK';
  1823. modes = [current_mode];
  1824. indent_level = indent_level || 0;
  1825. parser_pos = 0; // parser position
  1826. in_case = false; // flag for parser that case/default has been processed, and next colon needs special attention
  1827. while (true) {
  1828. var t = get_next_token(parser_pos);
  1829. token_text = t[0];
  1830. token_type = t[1];
  1831. if (token_type === 'TK_EOF') {
  1832. break;
  1833. }
  1834. switch (token_type) {
  1835. case 'TK_START_EXPR':
  1836. var_line = false;
  1837. set_mode('EXPRESSION');
  1838. if (last_type === 'TK_END_EXPR' || last_type === 'TK_START_EXPR') {
  1839. // do nothing on (( and )( and ][ and ]( ..
  1840. } else if (last_type !== 'TK_WORD' && last_type !== 'TK_OPERATOR') {
  1841. print_space();
  1842. } else if (in_array(last_word, line_starters) && last_word !== 'function') {
  1843. print_space();
  1844. }
  1845. print_token();
  1846. break;
  1847. case 'TK_END_EXPR':
  1848. print_token();
  1849. restore_mode();
  1850. break;
  1851. case 'TK_START_BLOCK':
  1852. if (last_word === 'do') {
  1853. set_mode('DO_BLOCK');
  1854. } else {
  1855. set_mode('BLOCK');
  1856. }
  1857. if (last_type !== 'TK_OPERATOR' && last_type !== 'TK_START_EXPR') {
  1858. if (last_type === 'TK_START_BLOCK') {
  1859. print_newline();
  1860. } else {
  1861. print_space();
  1862. }
  1863. }
  1864. print_token();
  1865. indent();
  1866. break;
  1867. case 'TK_END_BLOCK':
  1868. if (last_type === 'TK_START_BLOCK') {
  1869. // nothing
  1870. trim_output();
  1871. unindent();
  1872. } else {
  1873. unindent();
  1874. print_newline();
  1875. }
  1876. print_token();
  1877. restore_mode();
  1878. break;
  1879. case 'TK_WORD':
  1880. if (do_block_just_closed) {
  1881. print_space();
  1882. print_token();
  1883. print_space();
  1884. break;
  1885. }
  1886. if (token_text === 'case' || token_text === 'default') {
  1887. if (last_text === ':') {
  1888. // switch cases following one another
  1889. remove_indent();
  1890. } else {
  1891. // case statement starts in the same line where switch
  1892. unindent();
  1893. print_newline();
  1894. indent();
  1895. }
  1896. print_token();
  1897. in_case = true;
  1898. break;
  1899. }
  1900. prefix = 'NONE';
  1901. if (last_type === 'TK_END_BLOCK') {
  1902. if (!in_array(token_text.toLowerCase(), ['else', 'catch', 'finally'])) {
  1903. prefix = 'NEWLINE';
  1904. } else {
  1905. prefix = 'SPACE';
  1906. print_space();
  1907. }
  1908. } else if (last_type === 'TK_END_COMMAND' && (current_mode === 'BLOCK' || current_mode === 'DO_BLOCK')) {
  1909. prefix = 'NEWLINE';
  1910. } else if (last_type === 'TK_END_COMMAND' && current_mode === 'EXPRESSION') {
  1911. prefix = 'SPACE';
  1912. } else if (last_type === 'TK_WORD') {
  1913. prefix = 'SPACE';
  1914. } else if (last_type === 'TK_START_BLOCK') {
  1915. prefix = 'NEWLINE';
  1916. } else if (last_type === 'TK_END_EXPR') {
  1917. print_space();
  1918. prefix = 'NEWLINE';
  1919. }
  1920. if (last_type !== 'TK_END_BLOCK' && in_array(token_text.toLowerCase(), ['else', 'catch', 'finally'])) {
  1921. print_newline();
  1922. } else if (in_array(token_text, line_starters) || prefix === 'NEWLINE') {
  1923. if (last_text === 'else') {
  1924. // no need to force newline on else break
  1925. print_space();
  1926. } else if ((last_type === 'TK_START_EXPR' || last_text === '=') && token_text === 'function') {
  1927. // no need to force newline on 'function': (function
  1928. // DONOTHING
  1929. } else if (last_type === 'TK_WORD' && (last_text === 'return' || last_text === 'throw')) {
  1930. // no newline between 'return nnn'
  1931. print_space();
  1932. } else if (last_type !== 'TK_END_EXPR') {
  1933. if ((last_type !== 'TK_START_EXPR' || token_text !== 'var') && last_text !== ':') {
  1934. // no need to force newline on 'var': for (var x = 0...)
  1935. if (token_text === 'if' && last_type === 'TK_WORD' && last_word === 'else') {
  1936. // no newline for } else if {
  1937. print_space();
  1938. } else {
  1939. print_newline();
  1940. }
  1941. }
  1942. } else {
  1943. if (in_array(token_text, line_starters) && last_text !== ')') {
  1944. print_newline();
  1945. }
  1946. }
  1947. } else if (prefix === 'SPACE') {
  1948. print_space();
  1949. }
  1950. print_token();
  1951. last_word = token_text;
  1952. if (token_text === 'var') {
  1953. var_line = true;
  1954. var_line_tainted = false;
  1955. }
  1956. break;
  1957. case 'TK_END_COMMAND':
  1958. print_token();
  1959. var_line = false;
  1960. break;
  1961. case 'TK_STRING':
  1962. if (last_type === 'TK_START_BLOCK' || last_type === 'TK_END_BLOCK') {
  1963. print_newline();
  1964. } else if (last_type === 'TK_WORD') {
  1965. print_space();
  1966. }
  1967. print_token();
  1968. break;
  1969. case 'TK_OPERATOR':
  1970. var start_delim = true;
  1971. var end_delim = true;
  1972. if (var_line && token_text !== ',') {
  1973. var_line_tainted = true;
  1974. if (token_text === ':') {
  1975. var_line = false;
  1976. }
  1977. }
  1978. if (token_text === ':' && in_case) {
  1979. print_token(); // colon really asks for separate treatment
  1980. print_newline();
  1981. break;
  1982. }
  1983. in_case = false;
  1984. if (token_text === ',') {
  1985. if (var_line) {
  1986. if (var_line_tainted) {
  1987. print_token();
  1988. print_newline();
  1989. var_line_tainted = false;
  1990. } else {
  1991. print_token();
  1992. print_space();
  1993. }
  1994. } else if (last_type === 'TK_END_BLOCK') {
  1995. print_token();
  1996. print_newline();
  1997. } else {
  1998. if (current_mode === 'BLOCK') {
  1999. print_token();
  2000. print_newline();
  2001. } else {
  2002. // EXPR od DO_BLOCK
  2003. print_token();
  2004. print_space();
  2005. }
  2006. }
  2007. break;
  2008. } else if (token_text === '--' || token_text === '++') { // unary operators special case
  2009. if (last_text === ';') {
  2010. // space for (;; ++i)
  2011. start_delim = true;
  2012. end_delim = false;
  2013. } else {
  2014. start_delim = false;
  2015. end_delim = false;
  2016. }
  2017. } else if (token_text === '!' && last_type === 'TK_START_EXPR') {
  2018. // special case handling: if (!a)
  2019. start_delim = false;
  2020. end_delim = false;
  2021. } else if (last_type === 'TK_OPERATOR') {
  2022. start_delim = false;
  2023. end_delim = false;
  2024. } else if (last_type === 'TK_END_EXPR') {
  2025. start_delim = true;
  2026. end_delim = true;
  2027. } else if (token_text === '.') {
  2028. // decimal digits or object.property
  2029. start_delim = false;
  2030. end_delim = false;
  2031. } else if (token_text === ':') {
  2032. // zz: xx
  2033. // can't differentiate ternary op, so for now it's a ? b: c; without space before colon
  2034. if (last_text.match(/^\d+$/)) {
  2035. // a little help for ternary a ? 1 : 0;
  2036. start_delim = true;
  2037. } else {
  2038. start_delim = false;
  2039. }
  2040. }
  2041. if (start_delim) {
  2042. print_space();
  2043. }
  2044. print_token();
  2045. if (end_delim) {
  2046. print_space();
  2047. }
  2048. break;
  2049. case 'TK_BLOCK_COMMENT':
  2050. print_newline();
  2051. print_token();
  2052. print_newline();
  2053. break;
  2054. case 'TK_COMMENT':
  2055. // print_newline();
  2056. print_space();
  2057. print_token();
  2058. print_newline();
  2059. break;
  2060. case 'TK_UNKNOWN':
  2061. print_token();
  2062. break;
  2063. }
  2064. last_type = token_type;
  2065. last_text = token_text;
  2066. }
  2067. return output.join('');
  2068. }