markdown.js 18 KB

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