mindoc/static/js/markdown.js

634 lines
24 KiB
Go
Raw Normal View History

2017-04-26 18:17:38 +08:00
$(function () {
editormd.katexURL = {
2018-08-07 18:29:15 +08:00
js : window.katex.js,
css : window.katex.css
};
window.editormdLocales = {
'zh-CN': {
placeholder: ' Markdown ',
contentUnsaved: '',
noDocNeedPublish: '',
loadDocFailed: '',
fetchDocFailed: '',
cannotAddToEmptyNode: '',
overrideModified: '',
confirm: '',
cancel: '',
contentsNameEmpty: '',
addDoc: '',
edit: '',
delete: '',
loadFailed: '',
tplNameEmpty: '',
tplContentEmpty: '',
saveSucc: '',
serverExcept: '',
paramName: '',
paramType: '',
example: '',
remark: '',
},
'en': {
placeholder: 'This editor supports Markdown editing, writing on the left and previewing on the right.',
contentUnsaved: 'The edited content is not saved, need to save it?',
noDocNeedPublish: 'No Document need to be publish',
loadDocFailed: 'Load Document failed',
fetchDocFailed: 'Fetch Document info failed',
cannotAddToEmptyNode: 'Cannot add content to empty node',
overrideModified: 'The document has been modified by someone else, are you sure to overwrite the document?',
confirm: 'Confirm',
cancel: 'Cancel',
contentsNameEmpty: 'Document Name cannot be empty',
addDoc: 'Add Document',
edit: 'Edit',
delete: 'Delete',
loadFailed: 'Failed to load, please try again',
tplNameEmpty: 'Template name cannot be empty',
tplContentEmpty: 'Template content cannot be empty',
saveSucc: 'Save success',
serverExcept: 'Server Exception',
paramName: 'Parameter',
paramType: 'Type',
example: 'Example',
remark: 'Remark',
}
};
var htmlDecodeList = ["style","script","title","onmouseover","onmouseout","style"];
if (!window.IS_ENABLE_IFRAME) {
htmlDecodeList.unshift("iframe");
}
2017-04-26 18:17:38 +08:00
window.editor = editormd("docEditor", {
width: "100%",
height: "100%",
2018-08-07 18:29:15 +08:00
path: window.editormdLib,
toolbar: true,
placeholder: window.editormdLocales[window.lang].placeholder,
imageUpload: true,
2019-03-11 17:36:45 +08:00
imageFormats: ["jpg", "jpeg", "gif", "png","svg", "JPG", "JPEG", "GIF", "PNG","SVG"],
imageUploadURL: window.imageUploadURL,
toolbarModes: "full",
fileUpload: true,
fileUploadURL: window.fileUploadURL,
taskList: true,
flowChart: true,
htmlDecode: htmlDecodeList.join(','),
lineNumbers: true,
2018-01-27 11:27:11 +08:00
sequenceDiagram: true,
tocStartLevel: 1,
tocm: true,
previewCodeHighlight: 1,
highlightStyle: window.highlightStyle ? window.highlightStyle : "github",
tex:true,
saveHTMLToTextarea: true,
onload: function() {
2017-04-26 18:17:38 +08:00
this.hideToolbar();
var keyMap = {
"Ctrl-S": function(cm) {
saveDocument(false);
},
"Cmd-S": function(cm){
saveDocument(false);
},
"Ctrl-A": function(cm) {
cm.execCommand("selectAll");
}
};
this.addKeyMap(keyMap);
//如果没有选中节点则选中默认节点
openLastSelectedNode();
uploadImage("docEditor", function ($state, $res) {
if ($state === "before") {
2017-06-09 18:14:55 +08:00
return layer.load(1, {
shade: [0.1, '#fff'] // 0.1 透明度的白色背景
2017-06-09 18:14:55 +08:00
});
} else if ($state === "success") {
if ($res.errcode === 0) {
2017-06-09 18:14:55 +08:00
var value = '![](' + $res.url + ')';
window.editor.insertValue(value);
}
}
});
2018-09-03 15:39:01 +08:00
window.isLoad = true;
2017-04-28 18:08:01 +08:00
},
onchange: function () {
2017-04-28 18:08:01 +08:00
resetEditorChanged(true);
2017-04-26 18:17:38 +08:00
}
});
2017-04-28 18:08:01 +08:00
2018-11-21 18:07:24 +08:00
function insertToMarkdown(body) {
window.isLoad = true;
window.editor.insertValue(body);
window.editor.setCursor({ line: 0, ch: 0 });
resetEditorChanged(true);
}
function insertAndClearToMarkdown(body) {
window.isLoad = true;
window.editor.clear();
window.editor.insertValue(body);
window.editor.setCursor({ line: 0, ch: 0 });
resetEditorChanged(true);
}
2017-04-27 18:19:37 +08:00
/**
*
*/
$("#editormd-tools").on("click", "a[class!='disabled']", function () {
2017-04-26 18:17:38 +08:00
var name = $(this).find("i").attr("name");
if (name === "attachment") {
2017-05-13 12:12:37 +08:00
$("#uploadAttachModal").modal("show");
} else if (name === "history") {
2017-05-25 15:19:17 +08:00
window.documentHistory();
} else if (name === "save") {
2017-04-28 18:08:01 +08:00
saveDocument(false);
} else if (name === "template") {
2017-05-26 14:19:27 +08:00
$("#documentTemplateModal").modal("show");
} else if(name === "save-template"){
$("#saveTemplateModal").modal("show");
2018-11-21 18:07:24 +08:00
} else if(name === 'json'){
$("#convertJsonToTableModal").modal("show");
} else if (name === "sidebar") {
$("#manualCategory").toggle(0, "swing", function () {
2017-04-26 18:17:38 +08:00
var $then = $("#manualEditorContainer");
var left = parseInt($then.css("left"));
if (left > 0) {
2017-04-26 18:17:38 +08:00
window.editorContainerLeft = left;
$then.css("left", "0");
} else {
$then.css("left", window.editorContainerLeft + "px");
2017-04-26 18:17:38 +08:00
}
window.editor.resize();
});
} else if (name === "release") {
if (Object.prototype.toString.call(window.documentCategory) === '[object Array]' && window.documentCategory.length > 0) {
if ($("#markdown-save").hasClass('change')) {
var confirm_result = confirm(editormdLocales[lang].contentUnsaved);
2018-08-13 19:05:49 +08:00
if (confirm_result) {
saveDocument(false, releaseBook);
return;
}
}
releaseBook();
} else {
layer.msg(editormdLocales[lang].noDocNeedPublish)
}
} else if (name === "tasks") {
// 插入 GFM 任务列表
2017-04-26 18:17:38 +08:00
var cm = window.editor.cm;
var selection = cm.getSelection();
var cursor = cm.getCursor();
2017-04-26 18:17:38 +08:00
if (selection === "") {
cm.setCursor(cursor.line, 0);
2017-04-26 18:17:38 +08:00
cm.replaceSelection("- [x] " + selection);
cm.setCursor(cursor.line, cursor.ch + 6);
} else {
2017-04-26 18:17:38 +08:00
var selectionText = selection.split("\n");
for (var i = 0, len = selectionText.length; i < len; i++) {
selectionText[i] = (selectionText[i] === "") ? "" : "- [x] " + selectionText[i];
}
cm.replaceSelection(selectionText.join("\n"));
}
} else {
2017-04-26 18:17:38 +08:00
var action = window.editor.toolbarHandlers[name];
if (!!action && action !== "undefined") {
2017-04-26 18:17:38 +08:00
$.proxy(action, window.editor)();
window.editor.focus();
}
}
}) ;
2017-04-27 18:19:37 +08:00
2017-04-28 18:08:01 +08:00
/***
*
* @param $node
*/
2017-05-25 15:19:17 +08:00
window.loadDocument = function($node) {
2017-04-27 18:19:37 +08:00
var index = layer.load(1, {
shade: [0.1, '#fff'] // 0.1 透明度的白色背景
2017-04-27 18:19:37 +08:00
});
2017-04-28 18:08:01 +08:00
$.get(window.editURL + $node.node.id ).done(function (res) {
2017-04-27 18:19:37 +08:00
layer.close(index);
2017-04-28 18:08:01 +08:00
if (res.errcode === 0) {
window.isLoad = true;
try {
window.editor.clear();
window.editor.insertValue(res.data.markdown);
window.editor.setCursor({line: 0, ch: 0});
}catch(e){
console.log(e);
}
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 };
2017-04-28 18:08:01 +08:00
pushDocumentCategory(node);
2017-04-28 18:28:08 +08:00
window.selectNode = node;
2017-05-13 12:12:37 +08:00
pushVueLists(res.data.attach);
setLastSelectNode($node);
} else {
layer.msg(editormdLocales[lang].loadDocFailed);
2017-04-27 18:19:37 +08:00
}
}).fail(function () {
layer.close(index);
layer.msg(editormdLocales[lang].loadDocFailed);
2017-04-27 18:19:37 +08:00
});
2017-05-26 14:19:27 +08:00
};
2017-04-28 18:08:01 +08:00
/**
*
* @param $is_cover
2017-04-28 18:08:01 +08:00
*/
function saveDocument($is_cover, callback) {
2017-04-28 18:08:01 +08:00
var index = null;
2017-04-28 18:28:08 +08:00
var node = window.selectNode;
2017-04-28 18:08:01 +08:00
var content = window.editor.getMarkdown();
var html = window.editor.getPreviewedHTML();
var version = "";
if (!node) {
layer.msg(editormdLocales[lang].fetchDocFailed);
2017-04-28 18:08:01 +08:00
return;
}
if (node.a_attr && node.a_attr.disabled) {
layer.msg(editormdLocales[lang].cannotAddToEmptyNode);
return;
}
2017-04-28 18:28:08 +08:00
var doc_id = parseInt(node.id);
2017-04-28 18:08:01 +08:00
for (var i in window.documentCategory) {
2017-04-28 18:08:01 +08:00
var item = window.documentCategory[i];
if (item.id === doc_id) {
2017-04-28 18:08:01 +08:00
version = item.version;
break;
}
}
$.ajax({
beforeSend: function () {
index = layer.load(1, { shade: [0.1, '#fff'] });
window.saveing = true;
2017-04-28 18:08:01 +08:00
},
url: window.editURL,
data: { "identify": window.book.identify, "doc_id": doc_id, "markdown": content, "html": html, "cover": $is_cover ? "yes" : "no", "version": version },
type: "post",
timeout : 30000,
dataType: "json",
success: function (res) {
if (res.errcode === 0) {
2017-04-28 18:08:01 +08:00
resetEditorChanged(false);
for (var i in window.documentCategory) {
2017-04-28 18:08:01 +08:00
var item = window.documentCategory[i];
if (item.id === doc_id) {
2017-04-28 18:08:01 +08:00
window.documentCategory[i].version = res.data.version;
break;
}
}
2018-08-17 18:42:20 +08:00
$.each(window.documentCategory,function (i, item) {
var $item = window.documentCategory[i];
if (item.id === doc_id) {
window.documentCategory[i].version = res.data.version;
}
});
if (typeof callback === "function") {
callback();
}
} else if(res.errcode === 6005) {
var confirmIndex = layer.confirm(editormdLocales[lang].overrideModified, {
btn: [editormdLocales[lang].confirm, editormdLocales[lang].cancel] // 按钮
}, function() {
2017-04-28 18:08:01 +08:00
layer.close(confirmIndex);
saveDocument(true, callback);
2017-04-28 18:08:01 +08:00
});
} else {
2017-04-28 18:08:01 +08:00
layer.msg(res.message);
}
},
error : function (XMLHttpRequest, textStatus, errorThrown) {
layer.msg(window.editormdLocales[window.lang].serverExcept + errorThrown);
},
complete :function () {
layer.close(index);
window.saveing = false;
2017-04-28 18:08:01 +08:00
}
});
}
2017-04-28 18:08:01 +08:00
/**
*
* @param $is_change
*/
2017-04-28 18:08:01 +08:00
function resetEditorChanged($is_change) {
if ($is_change && !window.isLoad) {
2017-04-28 18:08:01 +08:00
$("#markdown-save").removeClass('disabled').addClass('change');
} else {
2017-04-28 18:08:01 +08:00
$("#markdown-save").removeClass('change').addClass('disabled');
}
window.isLoad = false;
2017-04-28 18:08:01 +08:00
}
2017-04-28 18:08:01 +08:00
/**
*
2017-04-27 18:19:37 +08:00
*/
$("#addDocumentForm").ajaxForm({
beforeSubmit: function () {
2017-04-27 18:19:37 +08:00
var doc_name = $.trim($("#documentName").val());
if (doc_name === "") {
return showError(editormdLocales[lang].contentsNameEmpty, "#add-error-message")
2017-04-27 18:19:37 +08:00
}
2017-05-02 18:09:46 +08:00
$("#btnSaveDocument").button("loading");
2017-04-27 18:19:37 +08:00
return true;
},
success: function (res) {
if (res.errcode === 0) {
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 ,
state: { opened: res.data.is_open == 1},
a_attr: { is_open: res.data.is_open == 1}
};
2017-04-27 18:19:37 +08:00
var node = window.treeCatalog.get_node(data.id);
if (node) {
window.treeCatalog.rename_node({ "id": data.id }, data.text);
$("#sidebar").jstree(true).get_node(data.id).a_attr.is_open = data.state.opened;
} else {
2017-04-28 18:08:01 +08:00
window.treeCatalog.create_node(data.parent, data);
2017-04-27 18:19:37 +08:00
window.treeCatalog.deselect_all();
window.treeCatalog.select_node(data);
}
2017-04-28 18:08:01 +08:00
pushDocumentCategory(data);
2017-04-27 18:19:37 +08:00
$("#markdown-save").removeClass('change').addClass('disabled');
$("#addDocumentModal").modal('hide');
} else {
showError(res.message, "#add-error-message");
2017-04-27 18:19:37 +08:00
}
2017-05-02 18:09:46 +08:00
$("#btnSaveDocument").button("reset");
2017-04-27 18:19:37 +08:00
}
});
/**
*
*/
$("#sidebar").jstree({
'plugins': ["wholerow", "types", 'dnd', 'contextmenu'],
"types": {
"default": {
"icon": false // 删除默认图标
2017-04-27 18:19:37 +08:00
}
},
'core': {
'check_callback': true,
"multiple": false,
'animation': 0,
"data": window.documentCategory
2017-04-27 18:19:37 +08:00
},
"contextmenu": {
show_at_node: false,
select_node: false,
"items": {
"添加文档": {
"separator_before": false,
"separator_after": true,
"_disabled": false,
"label": window.editormdLocales[window.lang].addDoc,//"添加文档",
"icon": "fa fa-plus",
"action": function (data) {
2017-04-27 18:19:37 +08:00
var inst = $.jstree.reference(data.reference),
node = inst.get_node(data.reference);
openCreateCatalogDialog(node);
}
},
"编辑": {
"separator_before": false,
"separator_after": true,
"_disabled": false,
"label": window.editormdLocales[window.lang].edit,
"icon": "fa fa-edit",
"action": function (data) {
2017-04-27 18:19:37 +08:00
var inst = $.jstree.reference(data.reference);
var node = inst.get_node(data.reference);
2017-04-28 18:08:01 +08:00
openEditCatalogDialog(node);
2017-04-27 18:19:37 +08:00
}
},
"删除": {
"separator_before": false,
"separator_after": true,
"_disabled": false,
"label": window.editormdLocales[window.lang].delete,
"icon": "fa fa-trash-o",
"action": function (data) {
2017-04-27 18:19:37 +08:00
var inst = $.jstree.reference(data.reference);
var node = inst.get_node(data.reference);
2017-04-28 18:08:01 +08:00
openDeleteDocumentDialog(node);
2017-04-27 18:19:37 +08:00
}
}
}
}
}).on("ready.jstree",function () {
window.treeCatalog = $("#sidebar").jstree(true);
//如果没有选中节点则选中默认节点
// openLastSelectedNode();
}).on('select_node.jstree', function (node, selected) {
if ($("#markdown-save").hasClass('change')) {
if (confirm(window.editormdLocales[window.lang].contentUnsaved)) {
saveDocument(false, function () {
loadDocument(selected);
});
return true;
2017-04-28 18:28:08 +08:00
}
}
//如果是空目录则直接出发展开下一级功能
if (selected.node.a_attr && selected.node.a_attr.disabled) {
selected.instance.toggle_node(selected.node);
return false
}
2017-04-28 18:28:08 +08:00
loadDocument(selected);
}).on("move_node.jstree", jstree_save).on("delete_node.jstree",function($node,$parent) {
openLastSelectedNode();
});
/**
*
*/
$("#documentTemplateModal").on("click", ".section>a[data-type]", function () {
2017-05-26 14:19:27 +08:00
var $this = $(this).attr("data-type");
2018-08-13 19:05:49 +08:00
if($this === "customs"){
$("#displayCustomsTemplateModal").modal("show");
return;
}
2017-05-26 14:19:27 +08:00
var body = $("#template-" + $this).html();
if (body) {
window.isLoad = true;
window.editor.clear();
window.editor.insertValue(body);
window.editor.setCursor({ line: 0, ch: 0 });
2017-05-26 14:19:27 +08:00
resetEditorChanged(true);
}
$("#documentTemplateModal").modal('hide');
});
/**
*
*/
2018-08-13 19:05:49 +08:00
$("#displayCustomsTemplateModal").on("show.bs.modal",function () {
window.sessionStorage.setItem("displayCustomsTemplateList",$("#displayCustomsTemplateList").html());
var index ;
$.ajax({
beforeSend: function () {
index = layer.load(1, { shade: [0.1, '#fff'] });
},
url : window.template.listUrl,
data: {"identify":window.book.identify},
type: "POST",
dataType: "html",
2018-08-13 19:05:49 +08:00
success: function ($res) {
$("#displayCustomsTemplateList").html($res);
2018-08-13 19:05:49 +08:00
},
error : function () {
layer.msg(window.editormdLocales[window.lang].loadFailed);
2018-08-13 19:05:49 +08:00
},
complete : function () {
layer.close(index);
}
});
$("#documentTemplateModal").modal("hide");
}).on("hidden.bs.modal",function () {
var cache = window.sessionStorage.getItem("displayCustomsTemplateList");
$("#displayCustomsTemplateList").html(cache);
});
/**
*
*/
$("#saveTemplateForm").ajaxForm({
beforeSubmit: function () {
var doc_name = $.trim($("#templateName").val());
if (doc_name === "") {
return showError(window.editormdLocales[window.lang].tplNameEmpty, "#saveTemplateForm .show-error-message");
}
var content = $("#saveTemplateForm").find("input[name='content']").val();
if (content === ""){
return showError(window.editormdLocales[window.lang].tplContentEmpty, "#saveTemplateForm .show-error-message");
}
$("#btnSaveTemplate").button("loading");
return true;
},
success: function ($res) {
if($res.errcode === 0){
$("#saveTemplateModal").modal("hide");
layer.msg(window.editormdLocales[window.lang].saveSucc);
}else{
return showError($res.message, "#saveTemplateForm .show-error-message");
}
},
complete : function () {
$("#btnSaveTemplate").button("reset");
}
});
/**
*
*/
$("#saveTemplateModal").on("show.bs.modal",function () {
window.sessionStorage.setItem("saveTemplateModal",$(this).find(".modal-body").html());
var content = window.editor.getMarkdown();
$("#saveTemplateForm").find("input[name='content']").val(content);
$("#saveTemplateForm .show-error-message").html("");
}).on("hidden.bs.modal",function () {
$(this).find(".modal-body").html(window.sessionStorage.getItem("saveTemplateModal"));
});
/**
*
*/
$("#displayCustomsTemplateList").on("click",".btn-insert",function () {
var templateId = $(this).attr("data-id");
$.ajax({
url: window.template.getUrl,
data :{"identify": window.book.identify, "template_id": templateId},
dataType: "json",
type: "get",
success : function ($res) {
if ($res.errcode !== 0){
layer.msg($res.message);
return;
}
window.isLoad = true;
window.editor.clear();
window.editor.insertValue($res.data.template_content);
window.editor.setCursor({ line: 0, ch: 0 });
resetEditorChanged(true);
$("#displayCustomsTemplateModal").modal("hide");
},error : function () {
layer.msg(window.editormdLocales[window.lang].serverExcept);
}
});
}).on("click",".btn-delete",function () {
var $then = $(this);
var templateId = $then.attr("data-id");
$then.button("loading");
$.ajax({
url : window.template.deleteUrl,
data: {"identify": window.book.identify, "template_id": templateId},
dataType: "json",
type: "post",
success: function ($res) {
if($res.errcode !== 0){
layer.msg($res.message);
}else{
$then.parents("tr").empty().remove();
}
},error : function () {
layer.msg(window.editormdLocales[window.lang].serverExcept);
},
complete: function () {
$then.button("reset");
}
})
});
2018-11-21 18:07:24 +08:00
$("#btnInsertTable").on("click",function () {
var content = $("#jsonContent").val();
if(content !== "") {
try {
var jsonObj = $.parseJSON(content);
var data = foreachJson(jsonObj,"");
var table = "| " + window.editormdLocales[window.lang].paramName
+ " | " + window.editormdLocales[window.lang].paramType
+ " | " + window.editormdLocales[window.lang].example
+ " | " + window.editormdLocales[window.lang].remark
+ " |\n| ------------ | ------------ | ------------ | ------------ |\n";
2018-11-21 18:07:24 +08:00
$.each(data,function (i,item) {
table += "|" + item.key + "|" + item.type + "|" + item.value +"| |\n";
});
insertToMarkdown(table);
}catch (e) {
showError("Json 格式错误:" + e.toString(),"#json-error-message");
return;
}
}
$("#convertJsonToTableModal").modal("hide");
});
2018-11-21 18:10:25 +08:00
$("#convertJsonToTableModal").on("hidden.bs.modal",function () {
$("#jsonContent").val("");
}).on("shown.bs.modal",function () {
$("#jsonContent").focus();
});
2017-04-26 18:17:38 +08:00
});