markdown.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870
  1. $(function () {
  2. editormd.katexURL = {
  3. js: window.katex.js,
  4. css: window.katex.css
  5. };
  6. var drawio = new Object()
  7. drawio.processMarkers = function (from, to) {
  8. var _this = this
  9. var found = null
  10. var foundStart = 0
  11. var cm = window.editor.cm;
  12. cm.doc.getAllMarks().forEach(mk => {
  13. if (mk.__kind) {
  14. mk.clear()
  15. }
  16. })
  17. cm.eachLine(from, to, function (ln) {
  18. const line = ln.lineNo()
  19. if (ln.text.startsWith('```drawio')) {
  20. found = 'drawio'
  21. foundStart = line
  22. } else if (ln.text === '```' && found) {
  23. switch (found) {
  24. // -> DRAWIO
  25. case 'drawio': {
  26. if (line - foundStart !== 2) {
  27. return
  28. }
  29. _this.addMarker({
  30. kind: 'drawio',
  31. from: { line: foundStart, ch: 3 },
  32. to: { line: foundStart, ch: 10 },
  33. text: 'drawio',
  34. action: (function (start, end) {
  35. return function (ev) {
  36. cm.doc.setSelection({ line: start, ch: 0 }, { line: end, ch: 3 })
  37. try {
  38. // save state data
  39. const raw = cm.doc.getLine(end - 1)
  40. window.sessionStorage.setItem("drawio", raw);
  41. _this.show()
  42. } catch (err) {
  43. console.log(err)
  44. }
  45. }
  46. })(foundStart, line)
  47. })
  48. if (ln.height > 0) {
  49. cm.foldCode(foundStart)
  50. }
  51. break;
  52. }
  53. }
  54. found = null
  55. }
  56. })
  57. }
  58. drawio.addMarker = function ({ kind, from, to, text, action }) {
  59. const markerElm = document.createElement('span')
  60. markerElm.appendChild(document.createTextNode(text))
  61. markerElm.className = 'CodeMirror-buttonmarker'
  62. markerElm.addEventListener('click', action)
  63. var cm = window.editor.cm;
  64. cm.markText(from, to, { replacedWith: markerElm, __kind: kind })
  65. }
  66. drawio.show = function () {
  67. const drawUrl = 'https://embed.diagrams.net/?embed=1&libraries=1&proto=json&spin=1&saveAndExit=1&noSaveBtn=1&noExitBtn=0'; // TODO: with Tomcat & https://github.com/jgraph/drawio
  68. this.div = document.createElement('div');
  69. this.div.id = 'diagram';
  70. this.gXml = '';
  71. this.div.innerHTML = '';
  72. this.iframe = document.createElement('iframe');
  73. this.iframe.setAttribute('frameborder', '0');
  74. this.iframe.style.zIndex = 9999;
  75. this.iframe.style.width = "100%";
  76. this.iframe.style.height = "100%";
  77. this.iframe.style.position = "absolute";
  78. this.iframe.style.top = window.scrollY + "px";
  79. binded = this.postMessage.bind(this);
  80. window.addEventListener("message", binded, false);
  81. this.iframe.setAttribute('src', drawUrl);
  82. document.body.appendChild(this.iframe);
  83. }
  84. drawio.postMessage = function (evt) {
  85. if (evt.data.length < 1) return
  86. var msg = JSON.parse(evt.data)
  87. var svg = '';
  88. switch (msg.event) {
  89. case "configure":
  90. this.iframe.contentWindow.postMessage(
  91. JSON.stringify({
  92. action: "configure",
  93. config: {
  94. defaultFonts: ["Humor Sans", "Helvetica", "Times New Roman"],
  95. },
  96. }),
  97. "*"
  98. );
  99. break;
  100. case "init":
  101. code = window.sessionStorage.getItem("drawio")
  102. svg = decodeURIComponent(escape(window.atob(code)))
  103. this.iframe.contentWindow.postMessage(
  104. JSON.stringify({ action: "load", autosave: 1, xml: svg }),
  105. "*"
  106. );
  107. break;
  108. case "autosave":
  109. window.sessionStorage.setItem("drawio", svg);
  110. break;
  111. case "save":
  112. this.iframe.contentWindow.postMessage(
  113. JSON.stringify({
  114. action: "export",
  115. format: "xmlsvg",
  116. xml: msg.xml,
  117. spin: "Updating page",
  118. }),
  119. "*"
  120. );
  121. break;
  122. case "export":
  123. svgData = msg.data.substring(msg.data.indexOf(',') + 1);
  124. // clean event bind
  125. window.removeEventListener("message", this.binded);
  126. document.body.removeChild(this.iframe);
  127. // write back svg data
  128. var cm = window.editor.cm;
  129. cm.doc.replaceSelection('```drawio\n' + svgData + '\n```', 'start')
  130. // clean state data
  131. window.sessionStorage.setItem("drawio", '');
  132. break;
  133. case "exit":
  134. window.removeEventListener("message", this.binded);
  135. document.body.removeChild(this.iframe);
  136. break;
  137. }
  138. }
  139. window.editormdLocales = {
  140. 'zh-CN': {
  141. placeholder: '本编辑器支持 Markdown 编辑,左边编写,右边预览。',
  142. contentUnsaved: '编辑内容未保存,需要保存吗?',
  143. noDocNeedPublish: '没有需要发布的文档',
  144. loadDocFailed: '文档加载失败',
  145. fetchDocFailed: '获取当前文档信息失败',
  146. cannotAddToEmptyNode: '空节点不能添加内容',
  147. overrideModified: '文档已被其他人修改确定覆盖已存在的文档吗?',
  148. confirm: '确定',
  149. cancel: '取消',
  150. contentsNameEmpty: '目录名称不能为空',
  151. addDoc: '添加文档',
  152. edit: '编辑',
  153. delete: '删除',
  154. loadFailed: '加载失败请重试',
  155. tplNameEmpty: '模板名称不能为空',
  156. tplContentEmpty: '模板内容不能为空',
  157. saveSucc: '保存成功',
  158. serverExcept: '服务器异常',
  159. paramName: '参数名称',
  160. paramType: '参数类型',
  161. example: '示例值',
  162. remark: '备注',
  163. },
  164. 'en': {
  165. placeholder: 'This editor supports Markdown editing, writing on the left and previewing on the right.',
  166. contentUnsaved: 'The edited content is not saved, need to save it?',
  167. noDocNeedPublish: 'No Document need to be publish',
  168. loadDocFailed: 'Load Document failed',
  169. fetchDocFailed: 'Fetch Document info failed',
  170. cannotAddToEmptyNode: 'Cannot add content to empty node',
  171. overrideModified: 'The document has been modified by someone else, are you sure to overwrite the document?',
  172. confirm: 'Confirm',
  173. cancel: 'Cancel',
  174. contentsNameEmpty: 'Document Name cannot be empty',
  175. addDoc: 'Add Document',
  176. edit: 'Edit',
  177. delete: 'Delete',
  178. loadFailed: 'Failed to load, please try again',
  179. tplNameEmpty: 'Template name cannot be empty',
  180. tplContentEmpty: 'Template content cannot be empty',
  181. saveSucc: 'Save success',
  182. serverExcept: 'Server Exception',
  183. paramName: 'Parameter',
  184. paramType: 'Type',
  185. example: 'Example',
  186. remark: 'Remark',
  187. }
  188. };
  189. var htmlDecodeList = ["style", "script", "title", "onmouseover", "onmouseout", "style"];
  190. if (!window.IS_ENABLE_IFRAME) {
  191. htmlDecodeList.unshift("iframe");
  192. }
  193. window.editor = editormd("docEditor", {
  194. width: "100%",
  195. height: "100%",
  196. path: window.editormdLib,
  197. toolbar: true,
  198. placeholder: window.editormdLocales[window.lang].placeholder,
  199. imageUpload: true,
  200. imageFormats: ["jpg", "jpeg", "gif", "png", "svg", "JPG", "JPEG", "GIF", "PNG", "SVG"],
  201. imageUploadURL: window.imageUploadURL,
  202. toolbarModes: "full",
  203. fileUpload: true,
  204. fileUploadURL: window.fileUploadURL,
  205. taskList: true,
  206. flowChart: true,
  207. htmlDecode: htmlDecodeList.join(','),
  208. lineNumbers: true,
  209. sequenceDiagram: true,
  210. tocStartLevel: 1,
  211. tocm: true,
  212. previewCodeHighlight: 1,
  213. highlightStyle: window.highlightStyle ? window.highlightStyle : "github",
  214. tex: true,
  215. saveHTMLToTextarea: true,
  216. codeFold: true,
  217. onload: function() {
  218. this.registerHelper()
  219. this.hideToolbar();
  220. var keyMap = {
  221. "Ctrl-S": function (cm) {
  222. saveDocument(false);
  223. },
  224. "Cmd-S": function (cm) {
  225. saveDocument(false);
  226. },
  227. "Ctrl-A": function (cm) {
  228. cm.execCommand("selectAll");
  229. }
  230. };
  231. this.addKeyMap(keyMap);
  232. //如果没有选中节点则选中默认节点
  233. openLastSelectedNode();
  234. uploadImage("docEditor", function ($state, $res) {
  235. if ($state === "before") {
  236. return layer.load(1, {
  237. shade: [0.1, '#fff'] // 0.1 透明度的白色背景
  238. });
  239. } else if ($state === "success") {
  240. if ($res.errcode === 0) {
  241. var value = '![](' + $res.url + ')';
  242. window.editor.insertValue(value);
  243. }
  244. }
  245. });
  246. window.isLoad = true;
  247. this.tableEditor = TableEditor.initTableEditor(this.cm)
  248. },
  249. onchange: function () {
  250. /**
  251. * 实现画图的事件注入
  252. *
  253. * 1. 分析文本,添加点击编辑事件,processMarkers
  254. * 2. 获取内容,存储状态数据
  255. * 3. 打开编辑画面
  256. * 4. 推出触发变更事件,并回写数据
  257. */
  258. var cm = window.editor.cm;
  259. drawio.processMarkers(cm.firstLine(), cm.lastLine() + 1)
  260. resetEditorChanged(true);
  261. }
  262. });
  263. editormd.fn.registerHelper = function () {
  264. const maxDepth = 100
  265. const codeBlockStartMatch = /^`{3}[a-zA-Z0-9]+$/
  266. const codeBlockEndMatch = /^`{3}$/
  267. editormd.$CodeMirror.registerHelper('fold', 'markdown', function (cm, start) {
  268. const firstLine = cm.getLine(start.line)
  269. const lastLineNo = cm.lastLine()
  270. let end
  271. function isHeader(lineNo) {
  272. const tokentype = cm.getTokenTypeAt(CodeMirror.Pos(lineNo, 0))
  273. return tokentype && /\bheader\b/.test(tokentype)
  274. }
  275. function headerLevel(lineNo, line, nextLine) {
  276. let match = line && line.match(/^#+/)
  277. if (match && isHeader(lineNo)) return match[0].length
  278. match = nextLine && nextLine.match(/^[=-]+\s*$/)
  279. if (match && isHeader(lineNo + 1)) return nextLine[0] === '=' ? 1 : 2
  280. return maxDepth
  281. }
  282. // -> CODE BLOCK
  283. if (codeBlockStartMatch.test(cm.getLine(start.line))) {
  284. end = start.line
  285. let nextNextLine = cm.getLine(end + 1)
  286. while (end < lastLineNo) {
  287. if (codeBlockEndMatch.test(nextNextLine)) {
  288. end++
  289. break
  290. }
  291. end++
  292. nextNextLine = cm.getLine(end + 1)
  293. }
  294. } else {
  295. // -> HEADER
  296. let nextLine = cm.getLine(start.line + 1)
  297. const level = headerLevel(start.line, firstLine, nextLine)
  298. if (level === maxDepth) return undefined
  299. end = start.line
  300. let nextNextLine = cm.getLine(end + 2)
  301. while (end < lastLineNo) {
  302. if (headerLevel(end + 1, nextLine, nextNextLine) <= level) break
  303. ++end
  304. nextLine = nextNextLine
  305. nextNextLine = cm.getLine(end + 2)
  306. }
  307. }
  308. return {
  309. from: CodeMirror.Pos(start.line, firstLine.length),
  310. to: CodeMirror.Pos(end, cm.getLine(end).length)
  311. }
  312. })
  313. }
  314. function insertToMarkdown(body) {
  315. window.isLoad = true;
  316. window.editor.insertValue(body);
  317. window.editor.setCursor({ line: 0, ch: 0 });
  318. resetEditorChanged(true);
  319. }
  320. function insertAndClearToMarkdown(body) {
  321. window.isLoad = true;
  322. window.editor.clear();
  323. window.editor.insertValue(body);
  324. window.editor.setCursor({ line: 0, ch: 0 });
  325. resetEditorChanged(true);
  326. }
  327. /**
  328. * 实现标题栏操作
  329. */
  330. $("#editormd-tools").on("click", "a[class!='disabled']", function () {
  331. var name = $(this).find("i").attr("name");
  332. if (name === "attachment") {
  333. $("#uploadAttachModal").modal("show");
  334. } else if (name === "history") {
  335. window.documentHistory();
  336. } else if (name === "save") {
  337. saveDocument(false);
  338. } else if (name === "template") {
  339. $("#documentTemplateModal").modal("show");
  340. } else if (name === "save-template") {
  341. $("#saveTemplateModal").modal("show");
  342. } else if (name === 'json') {
  343. $("#convertJsonToTableModal").modal("show");
  344. } else if (name === "sidebar") {
  345. $("#manualCategory").toggle(0, "swing", function () {
  346. var $then = $("#manualEditorContainer");
  347. var left = parseInt($then.css("left"));
  348. if (left > 0) {
  349. window.editorContainerLeft = left;
  350. $then.css("left", "0");
  351. } else {
  352. $then.css("left", window.editorContainerLeft + "px");
  353. }
  354. window.editor.resize();
  355. });
  356. } else if (name === "release") {
  357. if (Object.prototype.toString.call(window.documentCategory) === '[object Array]' && window.documentCategory.length > 0) {
  358. if ($("#markdown-save").hasClass('change')) {
  359. var confirm_result = confirm(editormdLocales[lang].contentUnsaved);
  360. if (confirm_result) {
  361. saveDocument(false, releaseBook);
  362. return;
  363. }
  364. }
  365. releaseBook();
  366. } else {
  367. layer.msg(editormdLocales[lang].noDocNeedPublish)
  368. }
  369. } else if (name === "tasks") {
  370. // 插入 GFM 任务列表
  371. var cm = window.editor.cm;
  372. var selection = cm.getSelection();
  373. var cursor = cm.getCursor();
  374. if (selection === "") {
  375. cm.setCursor(cursor.line, 0);
  376. cm.replaceSelection("- [x] " + selection);
  377. cm.setCursor(cursor.line, cursor.ch + 6);
  378. } else {
  379. var selectionText = selection.split("\n");
  380. for (var i = 0, len = selectionText.length; i < len; i++) {
  381. selectionText[i] = (selectionText[i] === "") ? "" : "- [x] " + selectionText[i];
  382. }
  383. cm.replaceSelection(selectionText.join("\n"));
  384. }
  385. } else if (name === "drawio") {
  386. /**
  387. * TODO: 画图功能实现
  388. *
  389. * 1. 获取光标处数据,存储数据
  390. * 2. 打开画图页面,初始化数据(获取数据)
  391. */
  392. window.sessionStorage.setItem("drawio", '');
  393. var cm = window.editor.cm;
  394. const selStartLine = cm.getCursor('from').line
  395. const selEndLine = cm.getCursor('to').line + 1
  396. drawio.processMarkers(selStartLine, selEndLine)
  397. drawio.show()
  398. } else {
  399. var action = window.editor.toolbarHandlers[name];
  400. if (!!action && action !== "undefined") {
  401. $.proxy(action, window.editor)();
  402. window.editor.focus();
  403. }
  404. }
  405. });
  406. /***
  407. * 加载指定的文档到编辑器中
  408. * @param $node
  409. */
  410. window.loadDocument = function ($node) {
  411. var index = layer.load(1, {
  412. shade: [0.1, '#fff'] // 0.1 透明度的白色背景
  413. });
  414. $.get(window.editURL + $node.node.id).done(function (res) {
  415. layer.close(index);
  416. if (res.errcode === 0) {
  417. window.isLoad = true;
  418. try {
  419. window.editor.clear();
  420. window.editor.insertValue(res.data.markdown);
  421. window.editor.setCursor({ line: 0, ch: 0 });
  422. } catch (e) {
  423. console.log(e);
  424. }
  425. var node = { "id": res.data.doc_id, 'parent': res.data.parent_id === 0 ? '#' : res.data.parent_id, "text": res.data.doc_name, "identify": res.data.identify, "version": res.data.version };
  426. pushDocumentCategory(node);
  427. window.selectNode = node;
  428. pushVueLists(res.data.attach);
  429. setLastSelectNode($node);
  430. } else {
  431. layer.msg(editormdLocales[lang].loadDocFailed);
  432. }
  433. }).fail(function () {
  434. layer.close(index);
  435. layer.msg(editormdLocales[lang].loadDocFailed);
  436. });
  437. };
  438. /**
  439. * 保存文档到服务器
  440. * @param $is_cover 是否强制覆盖
  441. */
  442. function saveDocument($is_cover, callback) {
  443. var index = null;
  444. var node = window.selectNode;
  445. var content = window.editor.getMarkdown();
  446. var html = window.editor.getPreviewedHTML();
  447. var version = "";
  448. if (!node) {
  449. layer.msg(editormdLocales[lang].fetchDocFailed);
  450. return;
  451. }
  452. if (node.a_attr && node.a_attr.disabled) {
  453. layer.msg(editormdLocales[lang].cannotAddToEmptyNode);
  454. return;
  455. }
  456. var doc_id = parseInt(node.id);
  457. for (var i in window.documentCategory) {
  458. var item = window.documentCategory[i];
  459. if (item.id === doc_id) {
  460. version = item.version;
  461. break;
  462. }
  463. }
  464. $.ajax({
  465. beforeSend: function () {
  466. index = layer.load(1, { shade: [0.1, '#fff'] });
  467. window.saveing = true;
  468. },
  469. url: window.editURL,
  470. data: { "identify": window.book.identify, "doc_id": doc_id, "markdown": content, "html": html, "cover": $is_cover ? "yes" : "no", "version": version },
  471. type: "post",
  472. timeout: 30000,
  473. dataType: "json",
  474. success: function (res) {
  475. if (res.errcode === 0) {
  476. resetEditorChanged(false);
  477. for (var i in window.documentCategory) {
  478. var item = window.documentCategory[i];
  479. if (item.id === doc_id) {
  480. window.documentCategory[i].version = res.data.version;
  481. break;
  482. }
  483. }
  484. $.each(window.documentCategory, function (i, item) {
  485. var $item = window.documentCategory[i];
  486. if (item.id === doc_id) {
  487. window.documentCategory[i].version = res.data.version;
  488. }
  489. });
  490. if (typeof callback === "function") {
  491. callback();
  492. }
  493. } else if (res.errcode === 6005) {
  494. var confirmIndex = layer.confirm(editormdLocales[lang].overrideModified, {
  495. btn: [editormdLocales[lang].confirm, editormdLocales[lang].cancel] // 按钮
  496. }, function () {
  497. layer.close(confirmIndex);
  498. saveDocument(true, callback);
  499. });
  500. } else {
  501. layer.msg(res.message);
  502. }
  503. },
  504. error: function (XMLHttpRequest, textStatus, errorThrown) {
  505. layer.msg(window.editormdLocales[window.lang].serverExcept + errorThrown);
  506. },
  507. complete: function () {
  508. layer.close(index);
  509. window.saveing = false;
  510. }
  511. });
  512. }
  513. /**
  514. * 设置编辑器变更状态
  515. * @param $is_change
  516. */
  517. function resetEditorChanged($is_change) {
  518. if ($is_change && !window.isLoad) {
  519. $("#markdown-save").removeClass('disabled').addClass('change');
  520. } else {
  521. $("#markdown-save").removeClass('change').addClass('disabled');
  522. }
  523. window.isLoad = false;
  524. }
  525. /**
  526. * 添加文档
  527. */
  528. $("#addDocumentForm").ajaxForm({
  529. beforeSubmit: function () {
  530. var doc_name = $.trim($("#documentName").val());
  531. if (doc_name === "") {
  532. return showError(editormdLocales[lang].contentsNameEmpty, "#add-error-message")
  533. }
  534. $("#btnSaveDocument").button("loading");
  535. return true;
  536. },
  537. success: function (res) {
  538. if (res.errcode === 0) {
  539. var data = {
  540. "id": res.data.doc_id,
  541. 'parent': res.data.parent_id === 0 ? '#' : res.data.parent_id,
  542. "text": res.data.doc_name,
  543. "identify": res.data.identify,
  544. "version": res.data.version,
  545. state: { opened: res.data.is_open == 1 },
  546. a_attr: { is_open: res.data.is_open == 1 }
  547. };
  548. var node = window.treeCatalog.get_node(data.id);
  549. if (node) {
  550. window.treeCatalog.rename_node({ "id": data.id }, data.text);
  551. $("#sidebar").jstree(true).get_node(data.id).a_attr.is_open = data.state.opened;
  552. } else {
  553. window.treeCatalog.create_node(data.parent, data);
  554. window.treeCatalog.deselect_all();
  555. window.treeCatalog.select_node(data);
  556. }
  557. pushDocumentCategory(data);
  558. $("#markdown-save").removeClass('change').addClass('disabled');
  559. $("#addDocumentModal").modal('hide');
  560. } else {
  561. showError(res.message, "#add-error-message");
  562. }
  563. $("#btnSaveDocument").button("reset");
  564. }
  565. });
  566. /**
  567. * 文档目录树
  568. */
  569. $("#sidebar").jstree({
  570. 'plugins': ["wholerow", "types", 'dnd', 'contextmenu'],
  571. "types": {
  572. "default": {
  573. "icon": false // 删除默认图标
  574. }
  575. },
  576. 'core': {
  577. 'check_callback': true,
  578. "multiple": false,
  579. 'animation': 0,
  580. "data": window.documentCategory
  581. },
  582. "contextmenu": {
  583. show_at_node: false,
  584. select_node: false,
  585. "items": {
  586. "添加文档": {
  587. "separator_before": false,
  588. "separator_after": true,
  589. "_disabled": false,
  590. "label": window.editormdLocales[window.lang].addDoc,//"添加文档",
  591. "icon": "fa fa-plus",
  592. "action": function (data) {
  593. var inst = $.jstree.reference(data.reference),
  594. node = inst.get_node(data.reference);
  595. openCreateCatalogDialog(node);
  596. }
  597. },
  598. "编辑": {
  599. "separator_before": false,
  600. "separator_after": true,
  601. "_disabled": false,
  602. "label": window.editormdLocales[window.lang].edit,
  603. "icon": "fa fa-edit",
  604. "action": function (data) {
  605. var inst = $.jstree.reference(data.reference);
  606. var node = inst.get_node(data.reference);
  607. openEditCatalogDialog(node);
  608. }
  609. },
  610. "删除": {
  611. "separator_before": false,
  612. "separator_after": true,
  613. "_disabled": false,
  614. "label": window.editormdLocales[window.lang].delete,
  615. "icon": "fa fa-trash-o",
  616. "action": function (data) {
  617. var inst = $.jstree.reference(data.reference);
  618. var node = inst.get_node(data.reference);
  619. openDeleteDocumentDialog(node);
  620. }
  621. }
  622. }
  623. }
  624. }).on("ready.jstree", function () {
  625. window.treeCatalog = $("#sidebar").jstree(true);
  626. //如果没有选中节点则选中默认节点
  627. // openLastSelectedNode();
  628. }).on('select_node.jstree', function (node, selected) {
  629. if ($("#markdown-save").hasClass('change')) {
  630. if (confirm(window.editormdLocales[window.lang].contentUnsaved)) {
  631. saveDocument(false, function () {
  632. loadDocument(selected);
  633. });
  634. return true;
  635. }
  636. }
  637. //如果是空目录则直接出发展开下一级功能
  638. if (selected.node.a_attr && selected.node.a_attr.disabled) {
  639. selected.instance.toggle_node(selected.node);
  640. return false
  641. }
  642. loadDocument(selected);
  643. }).on("move_node.jstree", jstree_save).on("delete_node.jstree", function ($node, $parent) {
  644. openLastSelectedNode();
  645. });
  646. /**
  647. * 打开文档模板
  648. */
  649. $("#documentTemplateModal").on("click", ".section>a[data-type]", function () {
  650. var $this = $(this).attr("data-type");
  651. if ($this === "customs") {
  652. $("#displayCustomsTemplateModal").modal("show");
  653. return;
  654. }
  655. var body = $("#template-" + $this).html();
  656. if (body) {
  657. window.isLoad = true;
  658. window.editor.clear();
  659. window.editor.insertValue(body);
  660. window.editor.setCursor({ line: 0, ch: 0 });
  661. resetEditorChanged(true);
  662. }
  663. $("#documentTemplateModal").modal('hide');
  664. });
  665. /**
  666. * 展示自定义模板列表
  667. */
  668. $("#displayCustomsTemplateModal").on("show.bs.modal", function () {
  669. window.sessionStorage.setItem("displayCustomsTemplateList", $("#displayCustomsTemplateList").html());
  670. var index;
  671. $.ajax({
  672. beforeSend: function () {
  673. index = layer.load(1, { shade: [0.1, '#fff'] });
  674. },
  675. url: window.template.listUrl,
  676. data: { "identify": window.book.identify },
  677. type: "POST",
  678. dataType: "html",
  679. success: function ($res) {
  680. $("#displayCustomsTemplateList").html($res);
  681. },
  682. error: function () {
  683. layer.msg(window.editormdLocales[window.lang].loadFailed);
  684. },
  685. complete: function () {
  686. layer.close(index);
  687. }
  688. });
  689. $("#documentTemplateModal").modal("hide");
  690. }).on("hidden.bs.modal", function () {
  691. var cache = window.sessionStorage.getItem("displayCustomsTemplateList");
  692. $("#displayCustomsTemplateList").html(cache);
  693. });
  694. /**
  695. * 添加模板
  696. */
  697. $("#saveTemplateForm").ajaxForm({
  698. beforeSubmit: function () {
  699. var doc_name = $.trim($("#templateName").val());
  700. if (doc_name === "") {
  701. return showError(window.editormdLocales[window.lang].tplNameEmpty, "#saveTemplateForm .show-error-message");
  702. }
  703. var content = $("#saveTemplateForm").find("input[name='content']").val();
  704. if (content === "") {
  705. return showError(window.editormdLocales[window.lang].tplContentEmpty, "#saveTemplateForm .show-error-message");
  706. }
  707. $("#btnSaveTemplate").button("loading");
  708. return true;
  709. },
  710. success: function ($res) {
  711. if ($res.errcode === 0) {
  712. $("#saveTemplateModal").modal("hide");
  713. layer.msg(window.editormdLocales[window.lang].saveSucc);
  714. } else {
  715. return showError($res.message, "#saveTemplateForm .show-error-message");
  716. }
  717. },
  718. complete: function () {
  719. $("#btnSaveTemplate").button("reset");
  720. }
  721. });
  722. /**
  723. * 当添加模板弹窗事件发生
  724. */
  725. $("#saveTemplateModal").on("show.bs.modal", function () {
  726. window.sessionStorage.setItem("saveTemplateModal", $(this).find(".modal-body").html());
  727. var content = window.editor.getMarkdown();
  728. $("#saveTemplateForm").find("input[name='content']").val(content);
  729. $("#saveTemplateForm .show-error-message").html("");
  730. }).on("hidden.bs.modal", function () {
  731. $(this).find(".modal-body").html(window.sessionStorage.getItem("saveTemplateModal"));
  732. });
  733. /**
  734. * 插入自定义模板内容
  735. */
  736. $("#displayCustomsTemplateList").on("click", ".btn-insert", function () {
  737. var templateId = $(this).attr("data-id");
  738. $.ajax({
  739. url: window.template.getUrl,
  740. data: { "identify": window.book.identify, "template_id": templateId },
  741. dataType: "json",
  742. type: "get",
  743. success: function ($res) {
  744. if ($res.errcode !== 0) {
  745. layer.msg($res.message);
  746. return;
  747. }
  748. window.isLoad = true;
  749. window.editor.clear();
  750. window.editor.insertValue($res.data.template_content);
  751. window.editor.setCursor({ line: 0, ch: 0 });
  752. resetEditorChanged(true);
  753. $("#displayCustomsTemplateModal").modal("hide");
  754. }, error: function () {
  755. layer.msg(window.editormdLocales[window.lang].serverExcept);
  756. }
  757. });
  758. }).on("click", ".btn-delete", function () {
  759. var $then = $(this);
  760. var templateId = $then.attr("data-id");
  761. $then.button("loading");
  762. $.ajax({
  763. url: window.template.deleteUrl,
  764. data: { "identify": window.book.identify, "template_id": templateId },
  765. dataType: "json",
  766. type: "post",
  767. success: function ($res) {
  768. if ($res.errcode !== 0) {
  769. layer.msg($res.message);
  770. } else {
  771. $then.parents("tr").empty().remove();
  772. }
  773. }, error: function () {
  774. layer.msg(window.editormdLocales[window.lang].serverExcept);
  775. },
  776. complete: function () {
  777. $then.button("reset");
  778. }
  779. })
  780. });
  781. $("#btnInsertTable").on("click", function () {
  782. var content = $("#jsonContent").val();
  783. if (content !== "") {
  784. try {
  785. var jsonObj = $.parseJSON(content);
  786. var data = foreachJson(jsonObj, "");
  787. var table = "| " + window.editormdLocales[window.lang].paramName
  788. + " | " + window.editormdLocales[window.lang].paramType
  789. + " | " + window.editormdLocales[window.lang].example
  790. + " | " + window.editormdLocales[window.lang].remark
  791. + " |\n| ------------ | ------------ | ------------ | ------------ |\n";
  792. $.each(data, function (i, item) {
  793. table += "|" + item.key + "|" + item.type + "|" + item.value + "| |\n";
  794. });
  795. insertToMarkdown(table);
  796. } catch (e) {
  797. showError("Json 格式错误:" + e.toString(), "#json-error-message");
  798. return;
  799. }
  800. }
  801. $("#convertJsonToTableModal").modal("hide");
  802. });
  803. $("#convertJsonToTableModal").on("hidden.bs.modal", function () {
  804. $("#jsonContent").val("");
  805. }).on("shown.bs.modal", function () {
  806. $("#jsonContent").focus();
  807. });
  808. });