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