markdown.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897
  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. uploadResource("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. if ($res.resource_type === 'video') {
  242. let value = `<video controls><source src="${$res.url}" type="video/mp4"></video>`;
  243. window.editor.insertValue(value);
  244. } else {
  245. let value = '![](' + $res.url + ')';
  246. window.editor.insertValue(value);
  247. }
  248. } else {
  249. layer.msg("上传失败:" + $res.message);
  250. }
  251. }
  252. });
  253. window.isLoad = true;
  254. this.tableEditor = TableEditor.initTableEditor(this.cm)
  255. },
  256. onchange: function () {
  257. /**
  258. * 实现画图的事件注入
  259. *
  260. * 1. 分析文本,添加点击编辑事件,processMarkers
  261. * 2. 获取内容,存储状态数据
  262. * 3. 打开编辑画面
  263. * 4. 推出触发变更事件,并回写数据
  264. */
  265. var cm = window.editor.cm;
  266. drawio.processMarkers(cm.firstLine(), cm.lastLine() + 1)
  267. resetEditorChanged(true);
  268. }
  269. });
  270. editormd.fn.registerHelper = function () {
  271. const maxDepth = 100
  272. const codeBlockStartMatch = /^`{3}[a-zA-Z0-9]+$/
  273. const codeBlockEndMatch = /^`{3}$/
  274. editormd.$CodeMirror.registerHelper('fold', 'markdown', function (cm, start) {
  275. const firstLine = cm.getLine(start.line)
  276. const lastLineNo = cm.lastLine()
  277. let end
  278. function isHeader(lineNo) {
  279. const tokentype = cm.getTokenTypeAt(CodeMirror.Pos(lineNo, 0))
  280. return tokentype && /\bheader\b/.test(tokentype)
  281. }
  282. function headerLevel(lineNo, line, nextLine) {
  283. let match = line && line.match(/^#+/)
  284. if (match && isHeader(lineNo)) return match[0].length
  285. match = nextLine && nextLine.match(/^[=-]+\s*$/)
  286. if (match && isHeader(lineNo + 1)) return nextLine[0] === '=' ? 1 : 2
  287. return maxDepth
  288. }
  289. // -> CODE BLOCK
  290. if (codeBlockStartMatch.test(cm.getLine(start.line))) {
  291. end = start.line
  292. let nextNextLine = cm.getLine(end + 1)
  293. while (end < lastLineNo) {
  294. if (codeBlockEndMatch.test(nextNextLine)) {
  295. end++
  296. break
  297. }
  298. end++
  299. nextNextLine = cm.getLine(end + 1)
  300. }
  301. } else {
  302. // -> HEADER
  303. let nextLine = cm.getLine(start.line + 1)
  304. const level = headerLevel(start.line, firstLine, nextLine)
  305. if (level === maxDepth) return undefined
  306. end = start.line
  307. let nextNextLine = cm.getLine(end + 2)
  308. while (end < lastLineNo) {
  309. if (headerLevel(end + 1, nextLine, nextNextLine) <= level) break
  310. ++end
  311. nextLine = nextNextLine
  312. nextNextLine = cm.getLine(end + 2)
  313. }
  314. }
  315. return {
  316. from: CodeMirror.Pos(start.line, firstLine.length),
  317. to: CodeMirror.Pos(end, cm.getLine(end).length)
  318. }
  319. })
  320. }
  321. function insertToMarkdown(body) {
  322. window.isLoad = true;
  323. window.editor.insertValue(body);
  324. window.editor.setCursor({ line: 0, ch: 0 });
  325. resetEditorChanged(true);
  326. }
  327. function insertAndClearToMarkdown(body) {
  328. window.isLoad = true;
  329. window.editor.clear();
  330. window.editor.insertValue(body);
  331. window.editor.setCursor({ line: 0, ch: 0 });
  332. resetEditorChanged(true);
  333. }
  334. /**
  335. * 实现标题栏操作
  336. */
  337. $("#editormd-tools").on("click", "a[class!='disabled']", function () {
  338. var name = $(this).find("i").attr("name");
  339. if (name === "attachment") {
  340. $("#uploadAttachModal").modal("show");
  341. } else if (name === "history") {
  342. window.documentHistory();
  343. } else if (name === "save") {
  344. saveDocument(false);
  345. } else if (name === "template") {
  346. $("#documentTemplateModal").modal("show");
  347. } else if (name === "save-template") {
  348. $("#saveTemplateModal").modal("show");
  349. } else if (name === 'json') {
  350. $("#convertJsonToTableModal").modal("show");
  351. } else if (name === "sidebar") {
  352. $("#manualCategory").toggle(0, "swing", function () {
  353. var $then = $("#manualEditorContainer");
  354. var left = parseInt($then.css("left"));
  355. if (left > 0) {
  356. window.editorContainerLeft = left;
  357. $then.css("left", "0");
  358. } else {
  359. $then.css("left", window.editorContainerLeft + "px");
  360. }
  361. window.editor.resize();
  362. });
  363. } else if (name === "release") {
  364. if (Object.prototype.toString.call(window.documentCategory) === '[object Array]' && window.documentCategory.length > 0) {
  365. if ($("#markdown-save").hasClass('change')) {
  366. var confirm_result = confirm(editormdLocales[lang].contentUnsaved);
  367. if (confirm_result) {
  368. saveDocument(false, releaseBook);
  369. return;
  370. }
  371. }
  372. releaseBook();
  373. } else {
  374. layer.msg(editormdLocales[lang].noDocNeedPublish)
  375. }
  376. } else if (name === "tasks") {
  377. // 插入 GFM 任务列表
  378. var cm = window.editor.cm;
  379. var selection = cm.getSelection();
  380. var cursor = cm.getCursor();
  381. if (selection === "") {
  382. cm.setCursor(cursor.line, 0);
  383. cm.replaceSelection("- [x] " + selection);
  384. cm.setCursor(cursor.line, cursor.ch + 6);
  385. } else {
  386. var selectionText = selection.split("\n");
  387. for (var i = 0, len = selectionText.length; i < len; i++) {
  388. selectionText[i] = (selectionText[i] === "") ? "" : "- [x] " + selectionText[i];
  389. }
  390. cm.replaceSelection(selectionText.join("\n"));
  391. }
  392. } else if (name === "drawio") {
  393. /**
  394. * TODO: 画图功能实现
  395. *
  396. * 1. 获取光标处数据,存储数据
  397. * 2. 打开画图页面,初始化数据(获取数据)
  398. */
  399. window.sessionStorage.setItem("drawio", '');
  400. var cm = window.editor.cm;
  401. const selStartLine = cm.getCursor('from').line
  402. const selEndLine = cm.getCursor('to').line + 1
  403. drawio.processMarkers(selStartLine, selEndLine)
  404. drawio.show()
  405. } else if (name === 'wordToContent') {
  406. let converter = new WordToHtmlConverter();
  407. converter.handleFileSelect(function (response) {
  408. if (response.messages.length) {
  409. let messages = response.messages.map((item)=>{
  410. return item.message + "<br/>";
  411. }).join('\n');
  412. layer.msg(messages);
  413. }
  414. converter.replaceHtmlBase64(response.value).then((html)=>{
  415. let cm = window.editor.cm;
  416. cm.replaceSelection(html);
  417. });
  418. })
  419. } else if (name === 'htmlToMarkdown') {
  420. let converter = new HtmlToMarkdownConverter();
  421. converter.handleFileSelect(function (response) {
  422. let cm = window.editor.cm;
  423. cm.replaceSelection(response);
  424. })
  425. } else {
  426. var action = window.editor.toolbarHandlers[name];
  427. if (!!action && action !== "undefined") {
  428. $.proxy(action, window.editor)();
  429. window.editor.focus();
  430. }
  431. }
  432. });
  433. /***
  434. * 加载指定的文档到编辑器中
  435. * @param $node
  436. */
  437. window.loadDocument = function ($node) {
  438. var index = layer.load(1, {
  439. shade: [0.1, '#fff'] // 0.1 透明度的白色背景
  440. });
  441. $.get(window.editURL + $node.node.id).done(function (res) {
  442. layer.close(index);
  443. if (res.errcode === 0) {
  444. window.isLoad = true;
  445. try {
  446. window.editor.clear();
  447. window.editor.insertValue(res.data.markdown);
  448. window.editor.setCursor({ line: 0, ch: 0 });
  449. } catch (e) {
  450. console.log(e);
  451. }
  452. 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 };
  453. pushDocumentCategory(node);
  454. window.selectNode = node;
  455. pushVueLists(res.data.attach);
  456. setLastSelectNode($node);
  457. } else {
  458. layer.msg(editormdLocales[lang].loadDocFailed);
  459. }
  460. }).fail(function () {
  461. layer.close(index);
  462. layer.msg(editormdLocales[lang].loadDocFailed);
  463. });
  464. };
  465. /**
  466. * 保存文档到服务器
  467. * @param $is_cover 是否强制覆盖
  468. */
  469. function saveDocument($is_cover, callback) {
  470. var index = null;
  471. var node = window.selectNode;
  472. var content = window.editor.getMarkdown();
  473. var html = window.editor.getPreviewedHTML();
  474. var version = "";
  475. if (!node) {
  476. layer.msg(editormdLocales[lang].fetchDocFailed);
  477. return;
  478. }
  479. if (node.a_attr && node.a_attr.disabled) {
  480. layer.msg(editormdLocales[lang].cannotAddToEmptyNode);
  481. return;
  482. }
  483. var doc_id = parseInt(node.id);
  484. for (var i in window.documentCategory) {
  485. var item = window.documentCategory[i];
  486. if (item.id === doc_id) {
  487. version = item.version;
  488. break;
  489. }
  490. }
  491. $.ajax({
  492. beforeSend: function () {
  493. index = layer.load(1, { shade: [0.1, '#fff'] });
  494. window.saveing = true;
  495. },
  496. url: window.editURL,
  497. data: { "identify": window.book.identify, "doc_id": doc_id, "markdown": content, "html": html, "cover": $is_cover ? "yes" : "no", "version": version },
  498. type: "post",
  499. timeout: 30000,
  500. dataType: "json",
  501. success: function (res) {
  502. if (res.errcode === 0) {
  503. resetEditorChanged(false);
  504. for (var i in window.documentCategory) {
  505. var item = window.documentCategory[i];
  506. if (item.id === doc_id) {
  507. window.documentCategory[i].version = res.data.version;
  508. break;
  509. }
  510. }
  511. $.each(window.documentCategory, function (i, item) {
  512. var $item = window.documentCategory[i];
  513. if (item.id === doc_id) {
  514. window.documentCategory[i].version = res.data.version;
  515. }
  516. });
  517. if (typeof callback === "function") {
  518. callback();
  519. }
  520. } else if (res.errcode === 6005) {
  521. var confirmIndex = layer.confirm(editormdLocales[lang].overrideModified, {
  522. btn: [editormdLocales[lang].confirm, editormdLocales[lang].cancel] // 按钮
  523. }, function () {
  524. layer.close(confirmIndex);
  525. saveDocument(true, callback);
  526. });
  527. } else {
  528. layer.msg(res.message);
  529. }
  530. },
  531. error: function (XMLHttpRequest, textStatus, errorThrown) {
  532. layer.msg(window.editormdLocales[window.lang].serverExcept + errorThrown);
  533. },
  534. complete: function () {
  535. layer.close(index);
  536. window.saveing = false;
  537. }
  538. });
  539. }
  540. /**
  541. * 设置编辑器变更状态
  542. * @param $is_change
  543. */
  544. function resetEditorChanged($is_change) {
  545. if ($is_change && !window.isLoad) {
  546. $("#markdown-save").removeClass('disabled').addClass('change');
  547. } else {
  548. $("#markdown-save").removeClass('change').addClass('disabled');
  549. }
  550. window.isLoad = false;
  551. }
  552. /**
  553. * 添加文档
  554. */
  555. $("#addDocumentForm").ajaxForm({
  556. beforeSubmit: function () {
  557. var doc_name = $.trim($("#documentName").val());
  558. if (doc_name === "") {
  559. return showError(editormdLocales[lang].contentsNameEmpty, "#add-error-message")
  560. }
  561. $("#btnSaveDocument").button("loading");
  562. return true;
  563. },
  564. success: function (res) {
  565. if (res.errcode === 0) {
  566. var data = {
  567. "id": res.data.doc_id,
  568. 'parent': res.data.parent_id === 0 ? '#' : res.data.parent_id,
  569. "text": res.data.doc_name,
  570. "identify": res.data.identify,
  571. "version": res.data.version,
  572. state: { opened: res.data.is_open == 1 },
  573. a_attr: { is_open: res.data.is_open == 1 }
  574. };
  575. var node = window.treeCatalog.get_node(data.id);
  576. if (node) {
  577. window.treeCatalog.rename_node({ "id": data.id }, data.text);
  578. $("#sidebar").jstree(true).get_node(data.id).a_attr.is_open = data.state.opened;
  579. } else {
  580. window.treeCatalog.create_node(data.parent, data);
  581. window.treeCatalog.deselect_all();
  582. window.treeCatalog.select_node(data);
  583. }
  584. pushDocumentCategory(data);
  585. $("#markdown-save").removeClass('change').addClass('disabled');
  586. $("#addDocumentModal").modal('hide');
  587. } else {
  588. showError(res.message, "#add-error-message");
  589. }
  590. $("#btnSaveDocument").button("reset");
  591. }
  592. });
  593. /**
  594. * 文档目录树
  595. */
  596. $("#sidebar").jstree({
  597. 'plugins': ["wholerow", "types", 'dnd', 'contextmenu'],
  598. "types": {
  599. "default": {
  600. "icon": false // 删除默认图标
  601. }
  602. },
  603. 'core': {
  604. 'check_callback': true,
  605. "multiple": false,
  606. 'animation': 0,
  607. "data": window.documentCategory
  608. },
  609. "contextmenu": {
  610. show_at_node: false,
  611. select_node: false,
  612. "items": {
  613. "添加文档": {
  614. "separator_before": false,
  615. "separator_after": true,
  616. "_disabled": false,
  617. "label": window.editormdLocales[window.lang].addDoc,//"添加文档",
  618. "icon": "fa fa-plus",
  619. "action": function (data) {
  620. var inst = $.jstree.reference(data.reference),
  621. node = inst.get_node(data.reference);
  622. openCreateCatalogDialog(node);
  623. }
  624. },
  625. "编辑": {
  626. "separator_before": false,
  627. "separator_after": true,
  628. "_disabled": false,
  629. "label": window.editormdLocales[window.lang].edit,
  630. "icon": "fa fa-edit",
  631. "action": function (data) {
  632. var inst = $.jstree.reference(data.reference);
  633. var node = inst.get_node(data.reference);
  634. openEditCatalogDialog(node);
  635. }
  636. },
  637. "删除": {
  638. "separator_before": false,
  639. "separator_after": true,
  640. "_disabled": false,
  641. "label": window.editormdLocales[window.lang].delete,
  642. "icon": "fa fa-trash-o",
  643. "action": function (data) {
  644. var inst = $.jstree.reference(data.reference);
  645. var node = inst.get_node(data.reference);
  646. openDeleteDocumentDialog(node);
  647. }
  648. }
  649. }
  650. }
  651. }).on("ready.jstree", function () {
  652. window.treeCatalog = $("#sidebar").jstree(true);
  653. //如果没有选中节点则选中默认节点
  654. // openLastSelectedNode();
  655. }).on('select_node.jstree', function (node, selected) {
  656. if ($("#markdown-save").hasClass('change')) {
  657. if (confirm(window.editormdLocales[window.lang].contentUnsaved)) {
  658. saveDocument(false, function () {
  659. loadDocument(selected);
  660. });
  661. return true;
  662. }
  663. }
  664. //如果是空目录则直接出发展开下一级功能
  665. if (selected.node.a_attr && selected.node.a_attr.disabled) {
  666. selected.instance.toggle_node(selected.node);
  667. return false
  668. }
  669. loadDocument(selected);
  670. }).on("move_node.jstree", jstree_save).on("delete_node.jstree", function ($node, $parent) {
  671. openLastSelectedNode();
  672. });
  673. /**
  674. * 打开文档模板
  675. */
  676. $("#documentTemplateModal").on("click", ".section>a[data-type]", function () {
  677. var $this = $(this).attr("data-type");
  678. if ($this === "customs") {
  679. $("#displayCustomsTemplateModal").modal("show");
  680. return;
  681. }
  682. var body = $("#template-" + $this).html();
  683. if (body) {
  684. window.isLoad = true;
  685. window.editor.clear();
  686. window.editor.insertValue(body);
  687. window.editor.setCursor({ line: 0, ch: 0 });
  688. resetEditorChanged(true);
  689. }
  690. $("#documentTemplateModal").modal('hide');
  691. });
  692. /**
  693. * 展示自定义模板列表
  694. */
  695. $("#displayCustomsTemplateModal").on("show.bs.modal", function () {
  696. window.sessionStorage.setItem("displayCustomsTemplateList", $("#displayCustomsTemplateList").html());
  697. var index;
  698. $.ajax({
  699. beforeSend: function () {
  700. index = layer.load(1, { shade: [0.1, '#fff'] });
  701. },
  702. url: window.template.listUrl,
  703. data: { "identify": window.book.identify },
  704. type: "POST",
  705. dataType: "html",
  706. success: function ($res) {
  707. $("#displayCustomsTemplateList").html($res);
  708. },
  709. error: function () {
  710. layer.msg(window.editormdLocales[window.lang].loadFailed);
  711. },
  712. complete: function () {
  713. layer.close(index);
  714. }
  715. });
  716. $("#documentTemplateModal").modal("hide");
  717. }).on("hidden.bs.modal", function () {
  718. var cache = window.sessionStorage.getItem("displayCustomsTemplateList");
  719. $("#displayCustomsTemplateList").html(cache);
  720. });
  721. /**
  722. * 添加模板
  723. */
  724. $("#saveTemplateForm").ajaxForm({
  725. beforeSubmit: function () {
  726. var doc_name = $.trim($("#templateName").val());
  727. if (doc_name === "") {
  728. return showError(window.editormdLocales[window.lang].tplNameEmpty, "#saveTemplateForm .show-error-message");
  729. }
  730. var content = $("#saveTemplateForm").find("input[name='content']").val();
  731. if (content === "") {
  732. return showError(window.editormdLocales[window.lang].tplContentEmpty, "#saveTemplateForm .show-error-message");
  733. }
  734. $("#btnSaveTemplate").button("loading");
  735. return true;
  736. },
  737. success: function ($res) {
  738. if ($res.errcode === 0) {
  739. $("#saveTemplateModal").modal("hide");
  740. layer.msg(window.editormdLocales[window.lang].saveSucc);
  741. } else {
  742. return showError($res.message, "#saveTemplateForm .show-error-message");
  743. }
  744. },
  745. complete: function () {
  746. $("#btnSaveTemplate").button("reset");
  747. }
  748. });
  749. /**
  750. * 当添加模板弹窗事件发生
  751. */
  752. $("#saveTemplateModal").on("show.bs.modal", function () {
  753. window.sessionStorage.setItem("saveTemplateModal", $(this).find(".modal-body").html());
  754. var content = window.editor.getMarkdown();
  755. $("#saveTemplateForm").find("input[name='content']").val(content);
  756. $("#saveTemplateForm .show-error-message").html("");
  757. }).on("hidden.bs.modal", function () {
  758. $(this).find(".modal-body").html(window.sessionStorage.getItem("saveTemplateModal"));
  759. });
  760. /**
  761. * 插入自定义模板内容
  762. */
  763. $("#displayCustomsTemplateList").on("click", ".btn-insert", function () {
  764. var templateId = $(this).attr("data-id");
  765. $.ajax({
  766. url: window.template.getUrl,
  767. data: { "identify": window.book.identify, "template_id": templateId },
  768. dataType: "json",
  769. type: "get",
  770. success: function ($res) {
  771. if ($res.errcode !== 0) {
  772. layer.msg($res.message);
  773. return;
  774. }
  775. window.isLoad = true;
  776. window.editor.clear();
  777. window.editor.insertValue($res.data.template_content);
  778. window.editor.setCursor({ line: 0, ch: 0 });
  779. resetEditorChanged(true);
  780. $("#displayCustomsTemplateModal").modal("hide");
  781. }, error: function () {
  782. layer.msg(window.editormdLocales[window.lang].serverExcept);
  783. }
  784. });
  785. }).on("click", ".btn-delete", function () {
  786. var $then = $(this);
  787. var templateId = $then.attr("data-id");
  788. $then.button("loading");
  789. $.ajax({
  790. url: window.template.deleteUrl,
  791. data: { "identify": window.book.identify, "template_id": templateId },
  792. dataType: "json",
  793. type: "post",
  794. success: function ($res) {
  795. if ($res.errcode !== 0) {
  796. layer.msg($res.message);
  797. } else {
  798. $then.parents("tr").empty().remove();
  799. }
  800. }, error: function () {
  801. layer.msg(window.editormdLocales[window.lang].serverExcept);
  802. },
  803. complete: function () {
  804. $then.button("reset");
  805. }
  806. })
  807. });
  808. $("#btnInsertTable").on("click", function () {
  809. var content = $("#jsonContent").val();
  810. if (content !== "") {
  811. try {
  812. var jsonObj = $.parseJSON(content);
  813. var data = foreachJson(jsonObj, "");
  814. var table = "| " + window.editormdLocales[window.lang].paramName
  815. + " | " + window.editormdLocales[window.lang].paramType
  816. + " | " + window.editormdLocales[window.lang].example
  817. + " | " + window.editormdLocales[window.lang].remark
  818. + " |\n| ------------ | ------------ | ------------ | ------------ |\n";
  819. $.each(data, function (i, item) {
  820. table += "|" + item.key + "|" + item.type + "|" + item.value + "| |\n";
  821. });
  822. insertToMarkdown(table);
  823. } catch (e) {
  824. showError("Json 格式错误:" + e.toString(), "#json-error-message");
  825. return;
  826. }
  827. }
  828. $("#convertJsonToTableModal").modal("hide");
  829. });
  830. $("#convertJsonToTableModal").on("hidden.bs.modal", function () {
  831. $("#jsonContent").val("");
  832. }).on("shown.bs.modal", function () {
  833. $("#jsonContent").focus();
  834. });
  835. });