markdown.js 18 KB

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