markdown.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  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", "JPG", "JPEG", "GIF", "PNG"],
  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. if (selection === "") {
  123. cm.replaceSelection("- [x] " + selection);
  124. } else {
  125. var selectionText = selection.split("\n");
  126. for (var i = 0, len = selectionText.length; i < len; i++) {
  127. selectionText[i] = (selectionText[i] === "") ? "" : "- [x] " + selectionText[i];
  128. }
  129. cm.replaceSelection(selectionText.join("\n"));
  130. }
  131. } else {
  132. var action = window.editor.toolbarHandlers[name];
  133. if (action !== "undefined") {
  134. $.proxy(action, window.editor)();
  135. window.editor.focus();
  136. }
  137. }
  138. }) ;
  139. /***
  140. * 加载指定的文档到编辑器中
  141. * @param $node
  142. */
  143. window.loadDocument = function($node) {
  144. var index = layer.load(1, {
  145. shade: [0.1, '#fff'] // 0.1 透明度的白色背景
  146. });
  147. $.get(window.editURL + $node.node.id ).done(function (res) {
  148. layer.close(index);
  149. if (res.errcode === 0) {
  150. window.isLoad = true;
  151. try {
  152. window.editor.clear();
  153. window.editor.insertValue(res.data.markdown);
  154. window.editor.setCursor({line: 0, ch: 0});
  155. }catch(e){
  156. console.log(e);
  157. }
  158. 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 };
  159. pushDocumentCategory(node);
  160. window.selectNode = node;
  161. pushVueLists(res.data.attach);
  162. setLastSelectNode($node);
  163. } else {
  164. layer.msg("文档加载失败");
  165. }
  166. }).fail(function () {
  167. layer.close(index);
  168. layer.msg("文档加载失败");
  169. });
  170. };
  171. /**
  172. * 保存文档到服务器
  173. * @param $is_cover 是否强制覆盖
  174. */
  175. function saveDocument($is_cover, callback) {
  176. var index = null;
  177. var node = window.selectNode;
  178. var content = window.editor.getMarkdown();
  179. var html = window.editor.getPreviewedHTML();
  180. var version = "";
  181. if (!node) {
  182. layer.msg("获取当前文档信息失败");
  183. return;
  184. }
  185. var doc_id = parseInt(node.id);
  186. for (var i in window.documentCategory) {
  187. var item = window.documentCategory[i];
  188. if (item.id === doc_id) {
  189. version = item.version;
  190. break;
  191. }
  192. }
  193. $.ajax({
  194. beforeSend: function () {
  195. index = layer.load(1, { shade: [0.1, '#fff'] });
  196. window.saveing = true;
  197. },
  198. url: window.editURL,
  199. data: { "identify": window.book.identify, "doc_id": doc_id, "markdown": content, "html": html, "cover": $is_cover ? "yes" : "no", "version": version },
  200. type: "post",
  201. timeout : 30000,
  202. dataType: "json",
  203. success: function (res) {
  204. if (res.errcode === 0) {
  205. resetEditorChanged(false);
  206. for (var i in window.documentCategory) {
  207. var item = window.documentCategory[i];
  208. if (item.id === doc_id) {
  209. window.documentCategory[i].version = res.data.version;
  210. break;
  211. }
  212. }
  213. $.each(window.documentCategory,function (i, item) {
  214. var $item = window.documentCategory[i];
  215. if (item.id === doc_id) {
  216. window.documentCategory[i].version = res.data.version;
  217. }
  218. });
  219. if (typeof callback === "function") {
  220. callback();
  221. }
  222. } else if(res.errcode === 6005) {
  223. var confirmIndex = layer.confirm('文档已被其他人修改确定覆盖已存在的文档吗?', {
  224. btn: ['确定', '取消'] // 按钮
  225. }, function() {
  226. layer.close(confirmIndex);
  227. saveDocument(true, callback);
  228. });
  229. } else {
  230. layer.msg(res.message);
  231. }
  232. },
  233. error : function (XMLHttpRequest, textStatus, errorThrown) {
  234. layer.msg("服务器错误:" + errorThrown);
  235. },
  236. complete :function () {
  237. layer.close(index);
  238. window.saveing = false;
  239. }
  240. });
  241. }
  242. /**
  243. * 设置编辑器变更状态
  244. * @param $is_change
  245. */
  246. function resetEditorChanged($is_change) {
  247. if ($is_change && !window.isLoad) {
  248. $("#markdown-save").removeClass('disabled').addClass('change');
  249. } else {
  250. $("#markdown-save").removeClass('change').addClass('disabled');
  251. }
  252. window.isLoad = false;
  253. }
  254. /**
  255. * 添加文档
  256. */
  257. $("#addDocumentForm").ajaxForm({
  258. beforeSubmit: function () {
  259. var doc_name = $.trim($("#documentName").val());
  260. if (doc_name === "") {
  261. return showError("目录名称不能为空", "#add-error-message")
  262. }
  263. $("#btnSaveDocument").button("loading");
  264. return true;
  265. },
  266. success: function (res) {
  267. if (res.errcode === 0) {
  268. var data = {
  269. "id": res.data.doc_id,
  270. 'parent': res.data.parent_id === 0 ? '#' : res.data.parent_id ,
  271. "text": res.data.doc_name,
  272. "identify": res.data.identify,
  273. "version": res.data.version ,
  274. state: { opened: res.data.is_open == 1},
  275. a_attr: { is_open: res.data.is_open == 1}
  276. };
  277. var node = window.treeCatalog.get_node(data.id);
  278. if (node) {
  279. window.treeCatalog.rename_node({ "id": data.id }, data.text);
  280. $("#sidebar").jstree(true).get_node(data.id).a_attr.is_open = data.state.opened;
  281. } else {
  282. window.treeCatalog.create_node(data.parent, data);
  283. window.treeCatalog.deselect_all();
  284. window.treeCatalog.select_node(data);
  285. }
  286. pushDocumentCategory(data);
  287. $("#markdown-save").removeClass('change').addClass('disabled');
  288. $("#addDocumentModal").modal('hide');
  289. } else {
  290. showError(res.message, "#add-error-message");
  291. }
  292. $("#btnSaveDocument").button("reset");
  293. }
  294. });
  295. /**
  296. * 文档目录树
  297. */
  298. $("#sidebar").jstree({
  299. 'plugins': ["wholerow", "types", 'dnd', 'contextmenu'],
  300. "types": {
  301. "default": {
  302. "icon": false // 删除默认图标
  303. }
  304. },
  305. 'core': {
  306. 'check_callback': true,
  307. "multiple": false,
  308. 'animation': 0,
  309. "data": window.documentCategory
  310. },
  311. "contextmenu": {
  312. show_at_node: false,
  313. select_node: false,
  314. "items": {
  315. "添加文档": {
  316. "separator_before": false,
  317. "separator_after": true,
  318. "_disabled": false,
  319. "label": "添加文档",
  320. "icon": "fa fa-plus",
  321. "action": function (data) {
  322. var inst = $.jstree.reference(data.reference),
  323. node = inst.get_node(data.reference);
  324. openCreateCatalogDialog(node);
  325. }
  326. },
  327. "编辑": {
  328. "separator_before": false,
  329. "separator_after": true,
  330. "_disabled": false,
  331. "label": "编辑",
  332. "icon": "fa fa-edit",
  333. "action": function (data) {
  334. var inst = $.jstree.reference(data.reference);
  335. var node = inst.get_node(data.reference);
  336. openEditCatalogDialog(node);
  337. }
  338. },
  339. "删除": {
  340. "separator_before": false,
  341. "separator_after": true,
  342. "_disabled": false,
  343. "label": "删除",
  344. "icon": "fa fa-trash-o",
  345. "action": function (data) {
  346. var inst = $.jstree.reference(data.reference);
  347. var node = inst.get_node(data.reference);
  348. openDeleteDocumentDialog(node);
  349. }
  350. }
  351. }
  352. }
  353. }).on("ready.jstree",function () {
  354. window.treeCatalog = $("#sidebar").jstree(true);
  355. //如果没有选中节点则选中默认节点
  356. // openLastSelectedNode();
  357. }).on('select_node.jstree', function (node, selected, event) {
  358. if ($("#markdown-save").hasClass('change')) {
  359. if (confirm("编辑内容未保存,需要保存吗?")) {
  360. saveDocument(false, function () {
  361. loadDocument(selected);
  362. });
  363. return true;
  364. }
  365. }
  366. loadDocument(selected);
  367. }).on("move_node.jstree", jstree_save).on("delete_node.jstree",function($node,$parent) {
  368. openLastSelectedNode();
  369. });
  370. /**
  371. * 打开文档模板
  372. */
  373. $("#documentTemplateModal").on("click", ".section>a[data-type]", function () {
  374. var $this = $(this).attr("data-type");
  375. if($this === "customs"){
  376. $("#displayCustomsTemplateModal").modal("show");
  377. return;
  378. }
  379. var body = $("#template-" + $this).html();
  380. if (body) {
  381. window.isLoad = true;
  382. window.editor.clear();
  383. window.editor.insertValue(body);
  384. window.editor.setCursor({ line: 0, ch: 0 });
  385. resetEditorChanged(true);
  386. }
  387. $("#documentTemplateModal").modal('hide');
  388. });
  389. /**
  390. * 展示自定义模板列表
  391. */
  392. $("#displayCustomsTemplateModal").on("show.bs.modal",function () {
  393. window.sessionStorage.setItem("displayCustomsTemplateList",$("#displayCustomsTemplateList").html());
  394. var index ;
  395. $.ajax({
  396. beforeSend: function () {
  397. index = layer.load(1, { shade: [0.1, '#fff'] });
  398. },
  399. url : window.template.listUrl,
  400. data: {"identify":window.book.identify},
  401. type: "POST",
  402. dataType: "html",
  403. success: function ($res) {
  404. $("#displayCustomsTemplateList").html($res);
  405. },
  406. error : function () {
  407. layer.msg("加载失败请重试");
  408. },
  409. complete : function () {
  410. layer.close(index);
  411. }
  412. });
  413. $("#documentTemplateModal").modal("hide");
  414. }).on("hidden.bs.modal",function () {
  415. var cache = window.sessionStorage.getItem("displayCustomsTemplateList");
  416. $("#displayCustomsTemplateList").html(cache);
  417. });
  418. /**
  419. * 添加模板
  420. */
  421. $("#saveTemplateForm").ajaxForm({
  422. beforeSubmit: function () {
  423. var doc_name = $.trim($("#templateName").val());
  424. if (doc_name === "") {
  425. return showError("模板名称不能为空", "#saveTemplateForm .show-error-message");
  426. }
  427. var content = $("#saveTemplateForm").find("input[name='content']").val();
  428. if (content === ""){
  429. return showError("模板内容不能为空", "#saveTemplateForm .show-error-message");
  430. }
  431. $("#btnSaveTemplate").button("loading");
  432. return true;
  433. },
  434. success: function ($res) {
  435. if($res.errcode === 0){
  436. $("#saveTemplateModal").modal("hide");
  437. layer.msg("保存成功");
  438. }else{
  439. return showError($res.message, "#saveTemplateForm .show-error-message");
  440. }
  441. },
  442. complete : function () {
  443. $("#btnSaveTemplate").button("reset");
  444. }
  445. });
  446. /**
  447. * 当添加模板弹窗事件发生
  448. */
  449. $("#saveTemplateModal").on("show.bs.modal",function () {
  450. window.sessionStorage.setItem("saveTemplateModal",$(this).find(".modal-body").html());
  451. var content = window.editor.getMarkdown();
  452. $("#saveTemplateForm").find("input[name='content']").val(content);
  453. $("#saveTemplateForm .show-error-message").html("");
  454. }).on("hidden.bs.modal",function () {
  455. $(this).find(".modal-body").html(window.sessionStorage.getItem("saveTemplateModal"));
  456. });
  457. /**
  458. * 插入自定义模板内容
  459. */
  460. $("#displayCustomsTemplateList").on("click",".btn-insert",function () {
  461. var templateId = $(this).attr("data-id");
  462. $.ajax({
  463. url: window.template.getUrl,
  464. data :{"identify": window.book.identify, "template_id": templateId},
  465. dataType: "json",
  466. type: "get",
  467. success : function ($res) {
  468. if ($res.errcode !== 0){
  469. layer.msg($res.message);
  470. return;
  471. }
  472. window.isLoad = true;
  473. window.editor.clear();
  474. window.editor.insertValue($res.data.template_content);
  475. window.editor.setCursor({ line: 0, ch: 0 });
  476. resetEditorChanged(true);
  477. $("#displayCustomsTemplateModal").modal("hide");
  478. },error : function () {
  479. layer.msg("服务器异常");
  480. }
  481. });
  482. }).on("click",".btn-delete",function () {
  483. var $then = $(this);
  484. var templateId = $then.attr("data-id");
  485. $then.button("loading");
  486. $.ajax({
  487. url : window.template.deleteUrl,
  488. data: {"identify": window.book.identify, "template_id": templateId},
  489. dataType: "json",
  490. type: "post",
  491. success: function ($res) {
  492. if($res.errcode !== 0){
  493. layer.msg($res.message);
  494. }else{
  495. $then.parents("tr").empty().remove();
  496. }
  497. },error : function () {
  498. layer.msg("服务器异常");
  499. },
  500. complete: function () {
  501. $then.button("reset");
  502. }
  503. })
  504. });
  505. $("#btnInsertTable").on("click",function () {
  506. var content = $("#jsonContent").val();
  507. if(content !== "") {
  508. try {
  509. var jsonObj = $.parseJSON(content);
  510. var data = foreachJson(jsonObj,"");
  511. var table = "| 参数名称 | 参数类型 | 示例值 | 备注 |\n| ------------ | ------------ | ------------ | ------------ |\n";
  512. $.each(data,function (i,item) {
  513. table += "|" + item.key + "|" + item.type + "|" + item.value +"| |\n";
  514. });
  515. insertToMarkdown(table);
  516. }catch (e) {
  517. showError("Json 格式错误:" + e.toString(),"#json-error-message");
  518. return;
  519. }
  520. }
  521. $("#convertJsonToTableModal").modal("hide");
  522. });
  523. $("#convertJsonToTableModal").on("hidden.bs.modal",function () {
  524. $("#jsonContent").val("");
  525. }).on("shown.bs.modal",function () {
  526. $("#jsonContent").focus();
  527. });
  528. });