markdown.js 19 KB

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