markdown.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. $(function () {
  2. editormd.katexURL = {
  3. js : window.katex.js,
  4. css : window.katex.css
  5. };
  6. window.editor = editormd("docEditor", {
  7. width: "100%",
  8. height: "100%",
  9. path: window.editormdLib,
  10. toolbar: true,
  11. placeholder: "本编辑器支持 Markdown 编辑,左边编写,右边预览。",
  12. imageUpload: true,
  13. imageFormats: ["jpg", "jpeg", "gif", "png","svg", "JPG", "JPEG", "GIF", "PNG","SVG"],
  14. imageUploadURL: window.imageUploadURL,
  15. toolbarModes: "full",
  16. fileUpload: true,
  17. fileUploadURL: window.fileUploadURL,
  18. taskList: true,
  19. flowChart: true,
  20. htmlDecode: "style,script,iframe,title,onmouseover,onmouseout,style",
  21. lineNumbers: false,
  22. sequenceDiagram: true,
  23. tocStartLevel: 1,
  24. tocm: true,
  25. previewCodeHighlight: 1,
  26. highlightStyle: window.highlightStyle ? window.highlightStyle : "github",
  27. tex:true,
  28. saveHTMLToTextarea: true,
  29. onload: function() {
  30. this.hideToolbar();
  31. var keyMap = {
  32. "Ctrl-S": function(cm) {
  33. saveDocument(false);
  34. },
  35. "Cmd-S": function(cm){
  36. saveDocument(false);
  37. },
  38. "Ctrl-A": function(cm) {
  39. cm.execCommand("selectAll");
  40. }
  41. };
  42. this.addKeyMap(keyMap);
  43. //如果没有选中节点则选中默认节点
  44. openLastSelectedNode();
  45. uploadImage("docEditor", function ($state, $res) {
  46. if ($state === "before") {
  47. return layer.load(1, {
  48. shade: [0.1, '#fff'] // 0.1 透明度的白色背景
  49. });
  50. } else if ($state === "success") {
  51. if ($res.errcode === 0) {
  52. var value = '![](' + $res.url + ')';
  53. window.editor.insertValue(value);
  54. }
  55. }
  56. });
  57. window.isLoad = true;
  58. },
  59. onchange: function () {
  60. resetEditorChanged(true);
  61. }
  62. });
  63. function insertToMarkdown(body) {
  64. window.isLoad = true;
  65. window.editor.insertValue(body);
  66. window.editor.setCursor({ line: 0, ch: 0 });
  67. resetEditorChanged(true);
  68. }
  69. function insertAndClearToMarkdown(body) {
  70. window.isLoad = true;
  71. window.editor.clear();
  72. window.editor.insertValue(body);
  73. window.editor.setCursor({ line: 0, ch: 0 });
  74. resetEditorChanged(true);
  75. }
  76. /**
  77. * 实现标题栏操作
  78. */
  79. $("#editormd-tools").on("click", "a[class!='disabled']", function () {
  80. var name = $(this).find("i").attr("name");
  81. if (name === "attachment") {
  82. $("#uploadAttachModal").modal("show");
  83. } else if (name === "history") {
  84. window.documentHistory();
  85. } else if (name === "save") {
  86. saveDocument(false);
  87. } else if (name === "template") {
  88. $("#documentTemplateModal").modal("show");
  89. } else if(name === "save-template"){
  90. $("#saveTemplateModal").modal("show");
  91. } else if(name === 'json'){
  92. $("#convertJsonToTableModal").modal("show");
  93. } else if (name === "sidebar") {
  94. $("#manualCategory").toggle(0, "swing", function () {
  95. var $then = $("#manualEditorContainer");
  96. var left = parseInt($then.css("left"));
  97. if (left > 0) {
  98. window.editorContainerLeft = left;
  99. $then.css("left", "0");
  100. } else {
  101. $then.css("left", window.editorContainerLeft + "px");
  102. }
  103. window.editor.resize();
  104. });
  105. } else if (name === "release") {
  106. if (Object.prototype.toString.call(window.documentCategory) === '[object Array]' && window.documentCategory.length > 0) {
  107. if ($("#markdown-save").hasClass('change')) {
  108. var confirm_result = confirm("编辑内容未保存,需要保存吗?");
  109. if (confirm_result) {
  110. saveDocument(false, releaseBook);
  111. return;
  112. }
  113. }
  114. releaseBook();
  115. } else {
  116. layer.msg("没有需要发布的文档")
  117. }
  118. } else if (name === "tasks") {
  119. // 插入 GFM 任务列表
  120. var cm = window.editor.cm;
  121. var selection = cm.getSelection();
  122. var cursor = cm.getCursor();
  123. if (selection === "") {
  124. cm.setCursor(cursor.line, 0);
  125. cm.replaceSelection("- [x] " + selection);
  126. cm.setCursor(cursor.line, cursor.ch + 6);
  127. } else {
  128. var selectionText = selection.split("\n");
  129. for (var i = 0, len = selectionText.length; i < len; i++) {
  130. selectionText[i] = (selectionText[i] === "") ? "" : "- [x] " + selectionText[i];
  131. }
  132. cm.replaceSelection(selectionText.join("\n"));
  133. }
  134. } else {
  135. var action = window.editor.toolbarHandlers[name];
  136. if (action !== "undefined") {
  137. $.proxy(action, window.editor)();
  138. window.editor.focus();
  139. }
  140. }
  141. }) ;
  142. /***
  143. * 加载指定的文档到编辑器中
  144. * @param $node
  145. */
  146. window.loadDocument = function($node) {
  147. var index = layer.load(1, {
  148. shade: [0.1, '#fff'] // 0.1 透明度的白色背景
  149. });
  150. $.get(window.editURL + $node.node.id ).done(function (res) {
  151. layer.close(index);
  152. if (res.errcode === 0) {
  153. window.isLoad = true;
  154. try {
  155. window.editor.clear();
  156. window.editor.insertValue(res.data.markdown);
  157. window.editor.setCursor({line: 0, ch: 0});
  158. }catch(e){
  159. console.log(e);
  160. }
  161. 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 };
  162. pushDocumentCategory(node);
  163. window.selectNode = node;
  164. pushVueLists(res.data.attach);
  165. setLastSelectNode($node);
  166. } else {
  167. layer.msg("文档加载失败");
  168. }
  169. }).fail(function () {
  170. layer.close(index);
  171. layer.msg("文档加载失败");
  172. });
  173. };
  174. /**
  175. * 保存文档到服务器
  176. * @param $is_cover 是否强制覆盖
  177. */
  178. function saveDocument($is_cover, callback) {
  179. var index = null;
  180. var node = window.selectNode;
  181. var content = window.editor.getMarkdown();
  182. var html = window.editor.getPreviewedHTML();
  183. var version = "";
  184. if (!node) {
  185. layer.msg("获取当前文档信息失败");
  186. return;
  187. }
  188. if (node.a_attr && node.a_attr.disabled) {
  189. layer.msg("空节点不能添加内容");
  190. return;
  191. }
  192. var doc_id = parseInt(node.id);
  193. for (var i in window.documentCategory) {
  194. var item = window.documentCategory[i];
  195. if (item.id === doc_id) {
  196. version = item.version;
  197. break;
  198. }
  199. }
  200. $.ajax({
  201. beforeSend: function () {
  202. index = layer.load(1, { shade: [0.1, '#fff'] });
  203. window.saveing = true;
  204. },
  205. url: window.editURL,
  206. data: { "identify": window.book.identify, "doc_id": doc_id, "markdown": content, "html": html, "cover": $is_cover ? "yes" : "no", "version": version },
  207. type: "post",
  208. timeout : 30000,
  209. dataType: "json",
  210. success: function (res) {
  211. if (res.errcode === 0) {
  212. resetEditorChanged(false);
  213. for (var i in window.documentCategory) {
  214. var item = window.documentCategory[i];
  215. if (item.id === doc_id) {
  216. window.documentCategory[i].version = res.data.version;
  217. break;
  218. }
  219. }
  220. $.each(window.documentCategory,function (i, item) {
  221. var $item = window.documentCategory[i];
  222. if (item.id === doc_id) {
  223. window.documentCategory[i].version = res.data.version;
  224. }
  225. });
  226. if (typeof callback === "function") {
  227. callback();
  228. }
  229. } else if(res.errcode === 6005) {
  230. var confirmIndex = layer.confirm('文档已被其他人修改确定覆盖已存在的文档吗?', {
  231. btn: ['确定', '取消'] // 按钮
  232. }, function() {
  233. layer.close(confirmIndex);
  234. saveDocument(true, callback);
  235. });
  236. } else {
  237. layer.msg(res.message);
  238. }
  239. },
  240. error : function (XMLHttpRequest, textStatus, errorThrown) {
  241. layer.msg("服务器错误:" + errorThrown);
  242. },
  243. complete :function () {
  244. layer.close(index);
  245. window.saveing = false;
  246. }
  247. });
  248. }
  249. /**
  250. * 设置编辑器变更状态
  251. * @param $is_change
  252. */
  253. function resetEditorChanged($is_change) {
  254. if ($is_change && !window.isLoad) {
  255. $("#markdown-save").removeClass('disabled').addClass('change');
  256. } else {
  257. $("#markdown-save").removeClass('change').addClass('disabled');
  258. }
  259. window.isLoad = false;
  260. }
  261. /**
  262. * 添加文档
  263. */
  264. $("#addDocumentForm").ajaxForm({
  265. beforeSubmit: function () {
  266. var doc_name = $.trim($("#documentName").val());
  267. if (doc_name === "") {
  268. return showError("目录名称不能为空", "#add-error-message")
  269. }
  270. $("#btnSaveDocument").button("loading");
  271. return true;
  272. },
  273. success: function (res) {
  274. if (res.errcode === 0) {
  275. var data = {
  276. "id": res.data.doc_id,
  277. 'parent': res.data.parent_id === 0 ? '#' : res.data.parent_id ,
  278. "text": res.data.doc_name,
  279. "identify": res.data.identify,
  280. "version": res.data.version ,
  281. state: { opened: res.data.is_open == 1},
  282. a_attr: { is_open: res.data.is_open == 1}
  283. };
  284. var node = window.treeCatalog.get_node(data.id);
  285. if (node) {
  286. window.treeCatalog.rename_node({ "id": data.id }, data.text);
  287. $("#sidebar").jstree(true).get_node(data.id).a_attr.is_open = data.state.opened;
  288. } else {
  289. window.treeCatalog.create_node(data.parent, data);
  290. window.treeCatalog.deselect_all();
  291. window.treeCatalog.select_node(data);
  292. }
  293. pushDocumentCategory(data);
  294. $("#markdown-save").removeClass('change').addClass('disabled');
  295. $("#addDocumentModal").modal('hide');
  296. } else {
  297. showError(res.message, "#add-error-message");
  298. }
  299. $("#btnSaveDocument").button("reset");
  300. }
  301. });
  302. /**
  303. * 文档目录树
  304. */
  305. $("#sidebar").jstree({
  306. 'plugins': ["wholerow", "types", 'dnd', 'contextmenu'],
  307. "types": {
  308. "default": {
  309. "icon": false // 删除默认图标
  310. }
  311. },
  312. 'core': {
  313. 'check_callback': true,
  314. "multiple": false,
  315. 'animation': 0,
  316. "data": window.documentCategory
  317. },
  318. "contextmenu": {
  319. show_at_node: false,
  320. select_node: false,
  321. "items": {
  322. "添加文档": {
  323. "separator_before": false,
  324. "separator_after": true,
  325. "_disabled": false,
  326. "label": "添加文档",
  327. "icon": "fa fa-plus",
  328. "action": function (data) {
  329. var inst = $.jstree.reference(data.reference),
  330. node = inst.get_node(data.reference);
  331. openCreateCatalogDialog(node);
  332. }
  333. },
  334. "编辑": {
  335. "separator_before": false,
  336. "separator_after": true,
  337. "_disabled": false,
  338. "label": "编辑",
  339. "icon": "fa fa-edit",
  340. "action": function (data) {
  341. var inst = $.jstree.reference(data.reference);
  342. var node = inst.get_node(data.reference);
  343. openEditCatalogDialog(node);
  344. }
  345. },
  346. "删除": {
  347. "separator_before": false,
  348. "separator_after": true,
  349. "_disabled": false,
  350. "label": "删除",
  351. "icon": "fa fa-trash-o",
  352. "action": function (data) {
  353. var inst = $.jstree.reference(data.reference);
  354. var node = inst.get_node(data.reference);
  355. openDeleteDocumentDialog(node);
  356. }
  357. }
  358. }
  359. }
  360. }).on("ready.jstree",function () {
  361. window.treeCatalog = $("#sidebar").jstree(true);
  362. //如果没有选中节点则选中默认节点
  363. // openLastSelectedNode();
  364. }).on('select_node.jstree', function (node, selected) {
  365. if ($("#markdown-save").hasClass('change')) {
  366. if (confirm("编辑内容未保存,需要保存吗?")) {
  367. saveDocument(false, function () {
  368. loadDocument(selected);
  369. });
  370. return true;
  371. }
  372. }
  373. //如果是空目录则直接出发展开下一级功能
  374. if (selected.node.a_attr && selected.node.a_attr.disabled) {
  375. selected.instance.toggle_node(selected.node);
  376. return false
  377. }
  378. loadDocument(selected);
  379. }).on("move_node.jstree", jstree_save).on("delete_node.jstree",function($node,$parent) {
  380. openLastSelectedNode();
  381. });
  382. /**
  383. * 打开文档模板
  384. */
  385. $("#documentTemplateModal").on("click", ".section>a[data-type]", function () {
  386. var $this = $(this).attr("data-type");
  387. if($this === "customs"){
  388. $("#displayCustomsTemplateModal").modal("show");
  389. return;
  390. }
  391. var body = $("#template-" + $this).html();
  392. if (body) {
  393. window.isLoad = true;
  394. window.editor.clear();
  395. window.editor.insertValue(body);
  396. window.editor.setCursor({ line: 0, ch: 0 });
  397. resetEditorChanged(true);
  398. }
  399. $("#documentTemplateModal").modal('hide');
  400. });
  401. /**
  402. * 展示自定义模板列表
  403. */
  404. $("#displayCustomsTemplateModal").on("show.bs.modal",function () {
  405. window.sessionStorage.setItem("displayCustomsTemplateList",$("#displayCustomsTemplateList").html());
  406. var index ;
  407. $.ajax({
  408. beforeSend: function () {
  409. index = layer.load(1, { shade: [0.1, '#fff'] });
  410. },
  411. url : window.template.listUrl,
  412. data: {"identify":window.book.identify},
  413. type: "POST",
  414. dataType: "html",
  415. success: function ($res) {
  416. $("#displayCustomsTemplateList").html($res);
  417. },
  418. error : function () {
  419. layer.msg("加载失败请重试");
  420. },
  421. complete : function () {
  422. layer.close(index);
  423. }
  424. });
  425. $("#documentTemplateModal").modal("hide");
  426. }).on("hidden.bs.modal",function () {
  427. var cache = window.sessionStorage.getItem("displayCustomsTemplateList");
  428. $("#displayCustomsTemplateList").html(cache);
  429. });
  430. /**
  431. * 添加模板
  432. */
  433. $("#saveTemplateForm").ajaxForm({
  434. beforeSubmit: function () {
  435. var doc_name = $.trim($("#templateName").val());
  436. if (doc_name === "") {
  437. return showError("模板名称不能为空", "#saveTemplateForm .show-error-message");
  438. }
  439. var content = $("#saveTemplateForm").find("input[name='content']").val();
  440. if (content === ""){
  441. return showError("模板内容不能为空", "#saveTemplateForm .show-error-message");
  442. }
  443. $("#btnSaveTemplate").button("loading");
  444. return true;
  445. },
  446. success: function ($res) {
  447. if($res.errcode === 0){
  448. $("#saveTemplateModal").modal("hide");
  449. layer.msg("保存成功");
  450. }else{
  451. return showError($res.message, "#saveTemplateForm .show-error-message");
  452. }
  453. },
  454. complete : function () {
  455. $("#btnSaveTemplate").button("reset");
  456. }
  457. });
  458. /**
  459. * 当添加模板弹窗事件发生
  460. */
  461. $("#saveTemplateModal").on("show.bs.modal",function () {
  462. window.sessionStorage.setItem("saveTemplateModal",$(this).find(".modal-body").html());
  463. var content = window.editor.getMarkdown();
  464. $("#saveTemplateForm").find("input[name='content']").val(content);
  465. $("#saveTemplateForm .show-error-message").html("");
  466. }).on("hidden.bs.modal",function () {
  467. $(this).find(".modal-body").html(window.sessionStorage.getItem("saveTemplateModal"));
  468. });
  469. /**
  470. * 插入自定义模板内容
  471. */
  472. $("#displayCustomsTemplateList").on("click",".btn-insert",function () {
  473. var templateId = $(this).attr("data-id");
  474. $.ajax({
  475. url: window.template.getUrl,
  476. data :{"identify": window.book.identify, "template_id": templateId},
  477. dataType: "json",
  478. type: "get",
  479. success : function ($res) {
  480. if ($res.errcode !== 0){
  481. layer.msg($res.message);
  482. return;
  483. }
  484. window.isLoad = true;
  485. window.editor.clear();
  486. window.editor.insertValue($res.data.template_content);
  487. window.editor.setCursor({ line: 0, ch: 0 });
  488. resetEditorChanged(true);
  489. $("#displayCustomsTemplateModal").modal("hide");
  490. },error : function () {
  491. layer.msg("服务器异常");
  492. }
  493. });
  494. }).on("click",".btn-delete",function () {
  495. var $then = $(this);
  496. var templateId = $then.attr("data-id");
  497. $then.button("loading");
  498. $.ajax({
  499. url : window.template.deleteUrl,
  500. data: {"identify": window.book.identify, "template_id": templateId},
  501. dataType: "json",
  502. type: "post",
  503. success: function ($res) {
  504. if($res.errcode !== 0){
  505. layer.msg($res.message);
  506. }else{
  507. $then.parents("tr").empty().remove();
  508. }
  509. },error : function () {
  510. layer.msg("服务器异常");
  511. },
  512. complete: function () {
  513. $then.button("reset");
  514. }
  515. })
  516. });
  517. $("#btnInsertTable").on("click",function () {
  518. var content = $("#jsonContent").val();
  519. if(content !== "") {
  520. try {
  521. var jsonObj = $.parseJSON(content);
  522. var data = foreachJson(jsonObj,"");
  523. var table = "| 参数名称 | 参数类型 | 示例值 | 备注 |\n| ------------ | ------------ | ------------ | ------------ |\n";
  524. $.each(data,function (i,item) {
  525. table += "|" + item.key + "|" + item.type + "|" + item.value +"| |\n";
  526. });
  527. insertToMarkdown(table);
  528. }catch (e) {
  529. showError("Json 格式错误:" + e.toString(),"#json-error-message");
  530. return;
  531. }
  532. }
  533. $("#convertJsonToTableModal").modal("hide");
  534. });
  535. $("#convertJsonToTableModal").on("hidden.bs.modal",function () {
  536. $("#jsonContent").val("");
  537. }).on("shown.bs.modal",function () {
  538. $("#jsonContent").focus();
  539. });
  540. });