mindoc/static/editor.md/editormd.js

4947 lines
164 KiB
Go
Raw Normal View History

2017-04-26 18:17:38 +08:00
/*
* Editor.md
*
* @file editormd.js
* @version v1.5.0
2017-04-26 18:17:38 +08:00
* @description Open source online markdown editor.
* @license MIT License
* @author Pandao
* {@link https://github.com/pandao/editor.md}
* @updateTime 2015-06-09
*/
;(function(factory) {
"use strict";
2017-04-26 18:17:38 +08:00
// CommonJS/Node.js
if (typeof require === "function" && typeof exports === "object" && typeof module === "object")
{
2017-04-26 18:17:38 +08:00
module.exports = factory;
}
else if (typeof define === "function") // AMD/CMD/Sea.js
{
if (define.amd) // for Require.js
{
/* Require.js define replace */
}
else
2017-04-26 18:17:38 +08:00
{
define(["jquery"], factory); // for Sea.js
}
}
2017-04-26 18:17:38 +08:00
else
{
2017-04-26 18:17:38 +08:00
window.editormd = factory();
}
}(function() {
2017-04-26 18:17:38 +08:00
/* Require.js assignment replace */
2017-04-26 18:17:38 +08:00
"use strict";
2017-04-26 18:17:38 +08:00
var $ = (typeof (jQuery) !== "undefined") ? jQuery : Zepto;
if (typeof ($) === "undefined") {
return ;
}
2017-04-26 18:17:38 +08:00
/**
* editormd
*
2017-04-26 18:17:38 +08:00
* @param {String} id ID
* @param {Object} options Key/Value
* @returns {Object} editormd editormd
*/
2017-04-26 18:17:38 +08:00
var editormd = function (id, options) {
return new editormd.fn.init(id, options);
};
2017-04-26 18:17:38 +08:00
editormd.title = editormd.$name = "Editor.md";
editormd.version = "1.5.0";
editormd.homePage = "https://pandao.github.io/editor.md/";
editormd.classPrefix = "editormd-";
2017-04-26 18:17:38 +08:00
editormd.toolbarModes = {
full : [
"undo", "redo", "|",
"bold", "del", "italic", "quote", "ucwords", "uppercase", "lowercase", "|",
"h1", "h2", "h3", "h4", "h5", "h6", "|",
2017-04-26 18:17:38 +08:00
"list-ul", "list-ol", "hr", "|",
"link", "reference-link", "image", "code", "preformatted-text", "code-block", "table", "datetime", "emoji", "html-entities", "pagebreak", "|",
"goto-line", "watch", "preview", "fullscreen", "clear", "search", "|",
"help", "info"
],
simple : [
"undo", "redo", "|",
"bold", "del", "italic", "quote", "uppercase", "lowercase", "|",
"h1", "h2", "h3", "h4", "h5", "h6", "|",
2017-04-26 18:17:38 +08:00
"list-ul", "list-ol", "hr", "|",
"watch", "preview", "fullscreen", "|",
"help", "info"
],
mini : [
"undo", "redo", "|",
"watch", "preview", "|",
"help", "info"
]
};
2017-04-26 18:17:38 +08:00
editormd.defaults = {
debug : false,
2017-04-26 18:17:38 +08:00
mode : "gfm", //gfm or markdown
name : "", // Form element name
value : "", // value for CodeMirror, if mode not gfm/markdown
theme : "", // Editor.md self themes, before v1.5.0 is CodeMirror theme, default empty
editorTheme : "default", // Editor area, this is CodeMirror theme at v1.5.0
previewTheme : "", // Preview area theme, default empty
markdown : "", // Markdown source code
appendMarkdown : "", // if in init textarea value not empty, append markdown to textarea
width : "100%",
height : "100%",
path : "./lib/", // Dependents module file directory
pluginPath : "", // If this empty, default use settings.path + "../plugins/"
delay : 500, // Delay parse markdown to html, Uint : ms
2017-04-26 18:17:38 +08:00
autoLoadModules : true, // Automatic load dependent module files
watch : true,
placeholder : "Enjoy Markdown! coding now...",
gotoLine : true,
codeFold : false,
autoHeight : false,
autoFocus : true,
autoCloseTags : true,
searchReplace : true,
syncScrolling : true, // true | false | "single", default true
readOnly : false,
tabSize : 4,
indentUnit : 4,
lineNumbers : true,
lineWrapping : true,
autoCloseBrackets : true,
showTrailingSpace : true,
matchBrackets : true,
indentWithTabs : true,
styleSelectedText : true,
matchWordHighlight : true, // options: true, false, "onselected"
styleActiveLine : true, // Highlight the current line
dialogLockScreen : true,
dialogShowMask : true,
dialogDraggable : true,
dialogMaskBgColor : "#fff",
dialogMaskOpacity : 0.1,
fontSize : "13px",
saveHTMLToTextarea : false,
disabledKeyMaps : [],
2017-04-26 18:17:38 +08:00
onload : function() {},
onresize : function() {},
onchange : function() {},
onwatch : null,
onunwatch : null,
onpreviewing : function() {},
onpreviewed : function() {},
onfullscreen : function() {},
onfullscreenExit : function() {},
onscroll : function() {},
onpreviewscroll : function() {},
2017-04-26 18:17:38 +08:00
imageUpload : false,
imageFormats : ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
imageUploadURL : "",
crossDomainUpload : false,
uploadCallbackURL : "",
2017-04-26 18:17:38 +08:00
toc : true, // Table of contents
tocm : false, // Using [TOCM], auto create ToC dropdown menu
tocTitle : "", // for ToC dropdown menu btn
tocDropdown : false,
tocContainer : "",
tocStartLevel : 1, // Said from H1 to create ToC
htmlDecode : false, // Open the HTML tag identification
2017-04-26 18:17:38 +08:00
pageBreak : true, // Enable parse page break [========]
atLink : true, // for @link
emailLink : true, // for email address auto link
taskList : false, // Enable Github Flavored Markdown task lists
emoji : false, // :emoji: , Support Github emoji, Twitter Emoji (Twemoji);
// Support FontAwesome icon emoji :fa-xxx: > Using fontAwesome icon web fonts;
// Support Editor.md logo icon emoji :editormd-logo: :editormd-logo-1x: > 1~8x;
tex : false, // TeX(LaTeX), based on KaTeX
flowChart : false, // flowChart.js only support IE9+
sequenceDiagram : false, // sequenceDiagram.js only support IE9+
mermaid : true,
mindMap : true, // 脑图
2017-04-26 18:17:38 +08:00
previewCodeHighlight : true,
2017-04-26 18:17:38 +08:00
toolbar : true, // show/hide toolbar
toolbarAutoFixed : true, // on window scroll auto fixed position
toolbarIcons : "full",
toolbarTitles : {},
toolbarHandlers : {
ucwords : function() {
return editormd.toolbarHandlers.ucwords;
},
lowercase : function() {
return editormd.toolbarHandlers.lowercase;
}
},
toolbarCustomIcons : { // using html tag create toolbar icon, unused default <a> tag.
lowercase : "<a href=\"javascript:;\" title=\"Lowercase\" unselectable=\"on\"><i class=\"fa\" name=\"lowercase\" style=\"font-size:24px;margin-top: -10px;\">a</i></a>",
"ucwords" : "<a href=\"javascript:;\" title=\"ucwords\" unselectable=\"on\"><i class=\"fa\" name=\"ucwords\" style=\"font-size:20px;margin-top: -3px;\">Aa</i></a>"
},
2017-04-26 18:17:38 +08:00
toolbarIconsClass : {
undo : "fa-undo",
redo : "fa-repeat",
bold : "fa-bold",
del : "fa-strikethrough",
italic : "fa-italic",
quote : "fa-quote-left",
uppercase : "fa-font",
h1 : editormd.classPrefix + "bold",
h2 : editormd.classPrefix + "bold",
h3 : editormd.classPrefix + "bold",
h4 : editormd.classPrefix + "bold",
h5 : editormd.classPrefix + "bold",
h6 : editormd.classPrefix + "bold",
"list-ul" : "fa-list-ul",
"list-ol" : "fa-list-ol",
hr : "fa-minus",
link : "fa-link",
"reference-link" : "fa-anchor",
image : "fa-picture-o",
code : "fa-code",
"preformatted-text" : "fa-file-code-o",
"code-block" : "fa-file-code-o",
table : "fa-table",
datetime : "fa-clock-o",
emoji : "fa-smile-o",
"html-entities" : "fa-copyright",
pagebreak : "fa-newspaper-o",
"goto-line" : "fa-terminal", // fa-crosshairs
watch : "fa-eye-slash",
unwatch : "fa-eye",
preview : "fa-desktop",
search : "fa-search",
fullscreen : "fa-arrows-alt",
clear : "fa-eraser",
help : "fa-question-circle",
info : "fa-info-circle"
},
2017-04-26 18:17:38 +08:00
toolbarIconTexts : {},
2017-04-26 18:17:38 +08:00
lang : {
name : "zh-cn",
description : "开源在线Markdown编辑器<br/>Open source online Markdown editor.",
tocTitle : "目录",
toolbar : {
undo : "撤销Ctrl+Z",
redo : "重做Ctrl+Y",
bold : "粗体",
del : "删除线",
italic : "斜体",
quote : "引用",
ucwords : "将每个单词首字母转成大写",
uppercase : "将所选转换成大写",
lowercase : "将所选转换成小写",
h1 : "标题1",
h2 : "标题2",
h3 : "标题3",
h4 : "标题4",
h5 : "标题5",
h6 : "标题6",
"list-ul" : "无序列表",
"list-ol" : "有序列表",
hr : "横线",
link : "链接",
"reference-link" : "引用链接",
image : "添加图片",
code : "行内代码",
"preformatted-text" : "预格式文本 / 代码块(缩进风格)",
"code-block" : "代码块(多语言风格)",
table : "添加表格",
datetime : "日期时间",
emoji : "Emoji表情",
"html-entities" : "HTML实体字符",
pagebreak : "插入分页符",
"goto-line" : "跳转到行",
watch : "关闭实时预览",
unwatch : "开启实时预览",
preview : "全窗口预览HTML按 Shift + ESC还原",
fullscreen : "全屏按ESC还原",
clear : "清空",
search : "搜索",
help : "使用帮助",
info : "关于" + editormd.title
},
buttons : {
enter : "确定",
cancel : "取消",
close : "关闭"
},
dialog : {
link : {
title : "添加链接",
url : "链接地址",
urlTitle : "链接标题",
urlEmpty : "错误:请填写链接地址。"
},
referenceLink : {
title : "添加引用链接",
name : "引用名称",
url : "链接地址",
urlId : "链接ID",
urlTitle : "链接标题",
nameEmpty: "错误:引用链接的名称不能为空。",
idEmpty : "错误请填写引用链接的ID。",
urlEmpty : "错误请填写引用链接的URL地址。"
},
image : {
title : "添加图片",
url : "图片地址",
link : "图片链接",
alt : "图片描述",
uploadButton : "本地上传",
imageURLEmpty : "错误:图片地址不能为空。",
uploadFileEmpty : "错误:上传的图片不能为空。",
formatNotAllowed : "错误:只允许上传图片文件,允许上传的图片文件格式有:"
},
preformattedText : {
title : "添加预格式文本或代码块",
2017-04-26 18:17:38 +08:00
emptyAlert : "错误:请填写预格式文本或代码的内容。"
},
codeBlock : {
title : "添加代码块",
2017-04-26 18:17:38 +08:00
selectLabel : "代码语言:",
selectDefaultText : "请选择代码语言",
otherLanguage : "其他语言",
unselectedLanguageAlert : "错误:请选择代码所属的语言类型。",
codeEmptyAlert : "错误:请填写代码内容。"
},
htmlEntities : {
title : "HTML 实体字符"
},
help : {
title : "使用帮助"
}
}
}
};
2017-04-26 18:17:38 +08:00
editormd.classNames = {
tex : editormd.classPrefix + "tex"
};
editormd.dialogZindex = 99999;
2017-04-26 18:17:38 +08:00
editormd.$katex = null;
editormd.$marked = null;
editormd.$CodeMirror = null;
editormd.$prettyPrint = null;
2017-04-26 18:17:38 +08:00
var timer, flowchartTimer;
editormd.prototype = editormd.fn = {
state : {
watching : false,
loaded : false,
preview : false,
fullscreen : false
},
2017-04-26 18:17:38 +08:00
/**
* /
* Constructor / instance initialization
*
2017-04-26 18:17:38 +08:00
* @param {String} id ID
* @param {Object} [options={}] Key/Value
* @returns {editormd} editormd
*/
2017-04-26 18:17:38 +08:00
init : function (id, options) {
2017-04-26 18:17:38 +08:00
options = options || {};
2017-04-26 18:17:38 +08:00
if (typeof id === "object")
{
options = id;
}
2017-04-26 18:17:38 +08:00
var _this = this;
var classPrefix = this.classPrefix = editormd.classPrefix;
2017-04-26 18:17:38 +08:00
var settings = this.settings = $.extend(true, editormd.defaults, options);
2017-04-26 18:17:38 +08:00
id = (typeof id === "object") ? settings.id : id;
2017-04-26 18:17:38 +08:00
var editor = this.editor = $("#" + id);
2017-04-26 18:17:38 +08:00
this.id = id;
this.lang = settings.lang;
2017-04-26 18:17:38 +08:00
var classNames = this.classNames = {
textarea : {
html : classPrefix + "html-textarea",
markdown : classPrefix + "markdown-textarea"
}
};
settings.pluginPath = (settings.pluginPath === "") ? settings.path + "../plugins/" : settings.pluginPath;
2017-04-26 18:17:38 +08:00
this.state.watching = (settings.watch) ? true : false;
2017-04-26 18:17:38 +08:00
if ( !editor.hasClass("editormd") ) {
editor.addClass("editormd");
}
2017-04-26 18:17:38 +08:00
editor.css({
width : (typeof settings.width === "number") ? settings.width + "px" : settings.width,
height : (typeof settings.height === "number") ? settings.height + "px" : settings.height
});
2017-04-26 18:17:38 +08:00
if (settings.autoHeight)
{
editor.css("height", "auto");
}
2017-04-26 18:17:38 +08:00
var markdownTextarea = this.markdownTextarea = editor.children("textarea");
2017-04-26 18:17:38 +08:00
if (markdownTextarea.length < 1)
{
editor.append("<textarea></textarea>");
markdownTextarea = this.markdownTextarea = editor.children("textarea");
}
2017-04-26 18:17:38 +08:00
markdownTextarea.addClass(classNames.textarea.markdown).attr("placeholder", settings.placeholder);
2017-04-26 18:17:38 +08:00
if (typeof markdownTextarea.attr("name") === "undefined" || markdownTextarea.attr("name") === "")
{
markdownTextarea.attr("name", (settings.name !== "") ? settings.name : id + "-markdown-doc");
}
2017-04-26 18:17:38 +08:00
var appendElements = [
(!settings.readOnly) ? "<a href=\"javascript:;\" class=\"fa fa-close " + classPrefix + "preview-close-btn\"></a>" : "",
( (settings.saveHTMLToTextarea) ? "<textarea class=\"" + classNames.textarea.html + "\" name=\"" + id + "-html-code\"></textarea>" : "" ),
"<div class=\"" + classPrefix + "preview\"><div class=\"markdown-body " + classPrefix + "preview-container\"></div></div>",
"<div class=\"" + classPrefix + "container-mask\" style=\"display:block;\"></div>",
"<div class=\"" + classPrefix + "mask\"></div>"
].join("\n");
2017-04-26 18:17:38 +08:00
editor.append(appendElements).addClass(classPrefix + "vertical");
if (settings.theme !== "")
2017-04-26 18:17:38 +08:00
{
editor.addClass(classPrefix + "theme-" + settings.theme);
}
this.mask = editor.children("." + classPrefix + "mask");
2017-04-26 18:17:38 +08:00
this.containerMask = editor.children("." + classPrefix + "container-mask");
2017-04-26 18:17:38 +08:00
if (settings.markdown !== "")
{
markdownTextarea.val(settings.markdown);
}
2017-04-26 18:17:38 +08:00
if (settings.appendMarkdown !== "")
{
markdownTextarea.val(markdownTextarea.val() + settings.appendMarkdown);
}
this.htmlTextarea = editor.children("." + classNames.textarea.html);
2017-04-26 18:17:38 +08:00
this.preview = editor.children("." + classPrefix + "preview");
this.previewContainer = this.preview.children("." + classPrefix + "preview-container");
if (settings.previewTheme !== "")
2017-04-26 18:17:38 +08:00
{
this.preview.addClass(classPrefix + "preview-theme-" + settings.previewTheme);
}
2017-04-26 18:17:38 +08:00
if (typeof define === "function" && define.amd)
{
if (typeof katex !== "undefined")
2017-04-26 18:17:38 +08:00
{
editormd.$katex = katex;
}
if (settings.searchReplace && !settings.readOnly)
2017-04-26 18:17:38 +08:00
{
editormd.loadCSS(settings.path + "codemirror/addon/dialog/dialog");
editormd.loadCSS(settings.path + "codemirror/addon/search/matchesonscrollbar");
}
}
2017-04-26 18:17:38 +08:00
if ((typeof define === "function" && define.amd) || !settings.autoLoadModules)
{
if (typeof CodeMirror !== "undefined") {
editormd.$CodeMirror = CodeMirror;
}
2017-04-26 18:17:38 +08:00
if (typeof marked !== "undefined") {
editormd.$marked = marked;
}
2017-04-26 18:17:38 +08:00
this.setCodeMirror().setToolbar().loadedDisplay();
}
else
2017-04-26 18:17:38 +08:00
{
this.loadQueues();
}
return this;
},
2017-04-26 18:17:38 +08:00
/**
*
* Required components loading queue
*
2017-04-26 18:17:38 +08:00
* @returns {editormd} editormd
*/
2017-04-26 18:17:38 +08:00
loadQueues : function() {
var _this = this;
var settings = this.settings;
var loadPath = settings.path;
var isLoadedDisplay = false;
2017-04-26 18:17:38 +08:00
var loadFlowChartOrSequenceDiagram = function() {
if (editormd.isIE8)
2017-04-26 18:17:38 +08:00
{
_this.loadedDisplay();
2017-04-26 18:17:38 +08:00
return ;
}
if (settings.mermaid) {
editormd.loadScript(loadPath + "mermaid/mermaid.min", function () {
window.mermaid.initialize({
theme: 'default',
logLevel: 3,
securityLevel: 'loose',
flowchart: { curve: 'basis' },
gantt: { axisFormat: '%m/%d/%Y' },
sequence: { actorMargin: 50 },
});
mermaid.ganttConfig = {
axisFormatter: [
// Within a day
['%I:%M', function (d) {
return d.getHours();
}],
// Monday a week
['%m/%d', function (d) { // redefine date here as '%m/%d'instead of 'w. %U', search mermaid.js
return d.getDay() == 1;
}],
// Day within a week (not monday)
['%a %d', function (d) {
return d.getDay() && d.getDate() != 1;
}],
// within a month
['%b %d', function (d) {
return d.getDate() != 1;
}],
// Month
['%m-%y', function (d) {
return d.getMonth();
}],[ "%m-%Y", function () {
return d.getFullYear();
}]]
};
if (!isLoadedDisplay){
isLoadedDisplay = true;
_this.loadedDisplay();
}
});
}
2018-09-03 15:39:01 +08:00
if (settings.flowChart)
2017-04-26 18:17:38 +08:00
{
editormd.loadScript(loadPath + "raphael.min", function() {
2018-09-03 15:39:01 +08:00
editormd.loadScript(loadPath + "flowchart.min", function() {
editormd.loadScript(loadPath + "jquery.flowchart.min", function() {
if (!isLoadedDisplay){
isLoadedDisplay = true;
_this.loadedDisplay();
}
2018-09-03 15:39:01 +08:00
});
});
});
}
2017-04-26 18:17:38 +08:00
if (settings.mindMap)
{
editormd.loadScript(loadPath + "mindmap/transform.min", function() {
editormd.loadScript(loadPath + "mindmap/d3@5", function() {
editormd.loadScript(loadPath + "mindmap/view.min", function() {
if (!isLoadedDisplay){
isLoadedDisplay = true;
_this.loadedDisplay();
}
});
});
});
}
2018-09-03 15:39:01 +08:00
if(settings.sequenceDiagram) {
editormd.loadCSS(loadPath + "sequence/sequence-diagram-min", function () {
editormd.loadScript(loadPath + "sequence/webfont", function() {
editormd.loadScript(loadPath + "sequence/snap.svg-min", function() {
editormd.loadScript(loadPath + "sequence/underscore-min", function() {
editormd.loadScript(loadPath + "sequence/sequence-diagram-min", function() {
if (!isLoadedDisplay){
isLoadedDisplay = true;
_this.loadedDisplay();
}
2017-04-26 18:17:38 +08:00
});
});
2018-09-03 15:39:01 +08:00
});
2017-04-26 18:17:38 +08:00
});
});
2018-09-03 15:39:01 +08:00
}
2017-04-26 18:17:38 +08:00
else
{
_this.loadedDisplay();
}
};
2017-04-26 18:17:38 +08:00
editormd.loadCSS(loadPath + "codemirror/codemirror.min");
2017-04-26 18:17:38 +08:00
if (settings.searchReplace && !settings.readOnly)
{
editormd.loadCSS(loadPath + "codemirror/addon/dialog/dialog");
editormd.loadCSS(loadPath + "codemirror/addon/search/matchesonscrollbar");
}
2017-04-26 18:17:38 +08:00
if (settings.codeFold)
{
editormd.loadCSS(loadPath + "codemirror/addon/fold/foldgutter");
2017-04-26 18:17:38 +08:00
}
2017-04-26 18:17:38 +08:00
editormd.loadScript(loadPath + "codemirror/codemirror.min", function() {
editormd.$CodeMirror = CodeMirror;
2017-04-26 18:17:38 +08:00
editormd.loadScript(loadPath + "codemirror/modes.min", function() {
2017-04-26 18:17:38 +08:00
editormd.loadScript(loadPath + "codemirror/addons.min", function() {
2017-04-26 18:17:38 +08:00
_this.setCodeMirror();
if (settings.mode !== "gfm" && settings.mode !== "markdown")
2017-04-26 18:17:38 +08:00
{
_this.loadedDisplay();
2017-04-26 18:17:38 +08:00
return false;
}
2017-04-26 18:17:38 +08:00
_this.setToolbar();
editormd.loadScript(loadPath + "marked", function() {
2017-04-26 18:17:38 +08:00
editormd.$marked = marked;
if(!settings.highlightStyle){
settings.highlightStyle = "github";
}
if (settings.previewCodeHighlight)
2017-04-26 18:17:38 +08:00
{
editormd.loadCSS(loadPath + "highlight/styles/" + settings.highlightStyle);
editormd.loadScript(loadPath + "highlight/highlight", function() {
2017-04-26 18:17:38 +08:00
loadFlowChartOrSequenceDiagram();
});
}
2017-04-26 18:17:38 +08:00
else
{
2017-04-26 18:17:38 +08:00
loadFlowChartOrSequenceDiagram();
}
});
2017-04-26 18:17:38 +08:00
});
2017-04-26 18:17:38 +08:00
});
2017-04-26 18:17:38 +08:00
});
return this;
},
2017-04-26 18:17:38 +08:00
/**
* Editor.md
* Setting Editor.md theme
*
2017-04-26 18:17:38 +08:00
* @returns {editormd} editormd
*/
2017-04-26 18:17:38 +08:00
setTheme : function(theme) {
var editor = this.editor;
var oldTheme = this.settings.theme;
var themePrefix = this.classPrefix + "theme-";
2017-04-26 18:17:38 +08:00
editor.removeClass(themePrefix + oldTheme).addClass(themePrefix + theme);
2017-04-26 18:17:38 +08:00
this.settings.theme = theme;
2017-04-26 18:17:38 +08:00
return this;
},
2017-04-26 18:17:38 +08:00
/**
* CodeMirror
* Setting CodeMirror (Editor area) theme
*
2017-04-26 18:17:38 +08:00
* @returns {editormd} editormd
*/
setEditorTheme : function(theme) {
var settings = this.settings;
settings.editorTheme = theme;
2017-04-26 18:17:38 +08:00
if (theme !== "default")
{
editormd.loadCSS(settings.path + "codemirror/theme/" + settings.editorTheme);
}
2017-04-26 18:17:38 +08:00
this.cm.setOption("theme", theme);
2017-04-26 18:17:38 +08:00
return this;
},
2017-04-26 18:17:38 +08:00
/**
* setEditorTheme()
* setEditorTheme() alias
*
2017-04-26 18:17:38 +08:00
* @returns {editormd} editormd
*/
setCodeMirrorTheme : function (theme) {
2017-04-26 18:17:38 +08:00
this.setEditorTheme(theme);
2017-04-26 18:17:38 +08:00
return this;
},
2017-04-26 18:17:38 +08:00
/**
* Editor.md
* Setting Editor.md theme
*
2017-04-26 18:17:38 +08:00
* @returns {editormd} editormd
*/
setPreviewTheme : function(theme) {
2017-04-26 18:17:38 +08:00
var preview = this.preview;
var oldTheme = this.settings.previewTheme;
var themePrefix = this.classPrefix + "preview-theme-";
2017-04-26 18:17:38 +08:00
preview.removeClass(themePrefix + oldTheme).addClass(themePrefix + theme);
2017-04-26 18:17:38 +08:00
this.settings.previewTheme = theme;
2017-04-26 18:17:38 +08:00
return this;
},
2017-04-26 18:17:38 +08:00
/**
* CodeMirror
* CodeMirror initialization
*
2017-04-26 18:17:38 +08:00
* @returns {editormd} editormd
*/
setCodeMirror : function() {
2017-04-26 18:17:38 +08:00
var settings = this.settings;
var editor = this.editor;
2017-04-26 18:17:38 +08:00
if (settings.editorTheme !== "default")
{
editormd.loadCSS(settings.path + "codemirror/theme/" + settings.editorTheme);
}
2017-04-26 18:17:38 +08:00
var codeMirrorConfig = {
mode : settings.mode,
theme : settings.editorTheme,
tabSize : settings.tabSize,
dragDrop : false,
autofocus : settings.autoFocus,
autoCloseTags : settings.autoCloseTags,
readOnly : (settings.readOnly) ? "nocursor" : false,
indentUnit : settings.indentUnit,
lineNumbers : settings.lineNumbers,
lineWrapping : settings.lineWrapping,
extraKeys : {
"Ctrl-Q": function(cm) {
cm.foldCode(cm.getCursor());
2017-04-26 18:17:38 +08:00
}
},
foldGutter : settings.codeFold,
gutters : ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
matchBrackets : settings.matchBrackets,
indentWithTabs : settings.indentWithTabs,
styleActiveLine : settings.styleActiveLine,
styleSelectedText : settings.styleSelectedText,
autoCloseBrackets : settings.autoCloseBrackets,
showTrailingSpace : settings.showTrailingSpace,
highlightSelectionMatches : ( (!settings.matchWordHighlight) ? false : { showToken: (settings.matchWordHighlight === "onselected") ? false : /\w/ } )
};
2017-04-26 18:17:38 +08:00
this.codeEditor = this.cm = editormd.$CodeMirror.fromTextArea(this.markdownTextarea[0], codeMirrorConfig);
this.codeMirror = this.cmElement = editor.children(".CodeMirror");
2017-04-26 18:17:38 +08:00
if (settings.value !== "")
{
this.cm.setValue(settings.value);
}
this.codeMirror.css({
fontSize : settings.fontSize,
width : (!settings.watch) ? "100%" : "50%"
});
2017-04-26 18:17:38 +08:00
if (settings.autoHeight)
{
this.codeMirror.css("height", "auto");
this.cm.setOption("viewportMargin", Infinity);
}
2017-04-26 18:17:38 +08:00
if (!settings.lineNumbers)
{
this.codeMirror.find(".CodeMirror-gutters").css("border-right", "none");
}
return this;
},
2017-04-26 18:17:38 +08:00
/**
* CodeMirror
* Get CodeMirror setting options
*
2017-04-26 18:17:38 +08:00
* @returns {Mixed} return CodeMirror setting option value
*/
getCodeMirrorOption : function(key) {
2017-04-26 18:17:38 +08:00
return this.cm.getOption(key);
},
2017-04-26 18:17:38 +08:00
/**
* CodeMirror
* CodeMirror setting options / resettings
*
2017-04-26 18:17:38 +08:00
* @returns {editormd} editormd
*/
2017-04-26 18:17:38 +08:00
setCodeMirrorOption : function(key, value) {
2017-04-26 18:17:38 +08:00
this.cm.setOption(key, value);
2017-04-26 18:17:38 +08:00
return this;
},
2017-04-26 18:17:38 +08:00
/**
* CodeMirror
* Add CodeMirror keyboard shortcuts key map
*
2017-04-26 18:17:38 +08:00
* @returns {editormd} editormd
*/
2017-04-26 18:17:38 +08:00
addKeyMap : function(map, bottom) {
this.cm.addKeyMap(map, bottom);
2017-04-26 18:17:38 +08:00
return this;
},
2017-04-26 18:17:38 +08:00
/**
* CodeMirror
* Remove CodeMirror keyboard shortcuts key map
*
2017-04-26 18:17:38 +08:00
* @returns {editormd} editormd
*/
2017-04-26 18:17:38 +08:00
removeKeyMap : function(map) {
this.cm.removeKeyMap(map);
2017-04-26 18:17:38 +08:00
return this;
},
2017-04-26 18:17:38 +08:00
/**
*
* Goto CodeMirror line
*
2017-04-26 18:17:38 +08:00
* @param {String|Intiger} line line number or "first"|"last"
* @returns {editormd} editormd
*/
2017-04-26 18:17:38 +08:00
gotoLine : function (line) {
2017-04-26 18:17:38 +08:00
var settings = this.settings;
2017-04-26 18:17:38 +08:00
if (!settings.gotoLine)
{
return this;
}
2017-04-26 18:17:38 +08:00
var cm = this.cm;
var editor = this.editor;
var count = cm.lineCount();
var preview = this.preview;
2017-04-26 18:17:38 +08:00
if (typeof line === "string")
{
if(line === "last")
{
line = count;
}
2017-04-26 18:17:38 +08:00
if (line === "first")
{
line = 1;
}
}
if (typeof line !== "number")
{
2017-04-26 18:17:38 +08:00
alert("Error: The line number must be an integer.");
return this;
}
2017-04-26 18:17:38 +08:00
line = parseInt(line) - 1;
2017-04-26 18:17:38 +08:00
if (line > count)
{
alert("Error: The line number range 1-" + count);
2017-04-26 18:17:38 +08:00
return this;
}
2017-04-26 18:17:38 +08:00
cm.setCursor( {line : line, ch : 0} );
2017-04-26 18:17:38 +08:00
var scrollInfo = cm.getScrollInfo();
var clientHeight = scrollInfo.clientHeight;
2017-04-26 18:17:38 +08:00
var coords = cm.charCoords({line : line, ch : 0}, "local");
2017-04-26 18:17:38 +08:00
cm.scrollTo(null, (coords.top + coords.bottom - clientHeight) / 2);
2017-04-26 18:17:38 +08:00
if (settings.watch)
{
2017-04-26 18:17:38 +08:00
var cmScroll = this.codeMirror.find(".CodeMirror-scroll")[0];
var height = $(cmScroll).height();
var scrollTop = cmScroll.scrollTop;
2017-04-26 18:17:38 +08:00
var percent = (scrollTop / cmScroll.scrollHeight);
if (scrollTop === 0)
{
preview.scrollTop(0);
}
2017-04-26 18:17:38 +08:00
else if (scrollTop + height >= cmScroll.scrollHeight - 16)
{
preview.scrollTop(preview[0].scrollHeight);
}
2017-04-26 18:17:38 +08:00
else
{
2017-04-26 18:17:38 +08:00
preview.scrollTop(preview[0].scrollHeight * percent);
}
}
cm.focus();
2017-04-26 18:17:38 +08:00
return this;
},
2017-04-26 18:17:38 +08:00
/**
*
* Extend editormd instance object, can mutil setting.
*
2017-04-26 18:17:38 +08:00
* @returns {editormd} this(editormd instance object.)
*/
2017-04-26 18:17:38 +08:00
extend : function() {
if (typeof arguments[1] !== "undefined")
{
if (typeof arguments[1] === "function")
{
arguments[1] = $.proxy(arguments[1], this);
}
this[arguments[0]] = arguments[1];
}
2017-04-26 18:17:38 +08:00
if (typeof arguments[0] === "object" && typeof arguments[0].length === "undefined")
{
$.extend(true, this, arguments[0]);
}
return this;
},
2017-04-26 18:17:38 +08:00
/**
*
* Extend editormd instance object, one by one
*
2017-04-26 18:17:38 +08:00
* @param {String|Object} key option key
* @param {String|Object} value option value
* @returns {editormd} this(editormd instance object.)
*/
2017-04-26 18:17:38 +08:00
set : function (key, value) {
2017-04-26 18:17:38 +08:00
if (typeof value !== "undefined" && typeof value === "function")
{
value = $.proxy(value, this);
}
2017-04-26 18:17:38 +08:00
this[key] = value;
return this;
},
2017-04-26 18:17:38 +08:00
/**
*
* Resetting editor options
*
2017-04-26 18:17:38 +08:00
* @param {String|Object} key option key
* @param {String|Object} value option value
* @returns {editormd} this(editormd instance object.)
*/
2017-04-26 18:17:38 +08:00
config : function(key, value) {
var settings = this.settings;
2017-04-26 18:17:38 +08:00
if (typeof key === "object")
{
settings = $.extend(true, settings, key);
}
2017-04-26 18:17:38 +08:00
if (typeof key === "string")
{
settings[key] = value;
}
2017-04-26 18:17:38 +08:00
this.settings = settings;
this.recreate();
2017-04-26 18:17:38 +08:00
return this;
},
2017-04-26 18:17:38 +08:00
/**
*
* Bind editor event handle
*
2017-04-26 18:17:38 +08:00
* @param {String} eventType event type
* @param {Function} callback
* @returns {editormd} this(editormd instance object.)
*/
2017-04-26 18:17:38 +08:00
on : function(eventType, callback) {
var settings = this.settings;
if (typeof settings["on" + eventType] !== "undefined")
{
settings["on" + eventType] = $.proxy(callback, this);
2017-04-26 18:17:38 +08:00
}
return this;
},
2017-04-26 18:17:38 +08:00
/**
*
* Unbind editor event handle
*
2017-04-26 18:17:38 +08:00
* @param {String} eventType event type
* @returns {editormd} this(editormd instance object.)
*/
2017-04-26 18:17:38 +08:00
off : function(eventType) {
var settings = this.settings;
if (typeof settings["on" + eventType] !== "undefined")
2017-04-26 18:17:38 +08:00
{
settings["on" + eventType] = function(){};
}
2017-04-26 18:17:38 +08:00
return this;
},
2017-04-26 18:17:38 +08:00
/**
*
* Display toolbar
*
2017-04-26 18:17:38 +08:00
* @param {Function} [callback=function(){}]
* @returns {editormd} editormd
*/
2017-04-26 18:17:38 +08:00
showToolbar : function(callback) {
var settings = this.settings;
2017-04-26 18:17:38 +08:00
if(settings.readOnly) {
return this;
}
2017-04-26 18:17:38 +08:00
if (settings.toolbar && (this.toolbar.length < 1 || this.toolbar.find("." + this.classPrefix + "menu").html() === "") )
{
this.setToolbar();
}
settings.toolbar = true;
2017-04-26 18:17:38 +08:00
this.toolbar.show();
this.resize();
2017-04-26 18:17:38 +08:00
$.proxy(callback || function(){}, this)();
return this;
},
2017-04-26 18:17:38 +08:00
/**
*
* Hide toolbar
*
2017-04-26 18:17:38 +08:00
* @param {Function} [callback=function(){}]
* @returns {editormd} this(editormd instance object.)
*/
hideToolbar : function(callback) {
2017-04-26 18:17:38 +08:00
var settings = this.settings;
settings.toolbar = false;
2017-04-26 18:17:38 +08:00
this.toolbar.hide();
this.resize();
2017-04-26 18:17:38 +08:00
$.proxy(callback || function(){}, this)();
return this;
},
2017-04-26 18:17:38 +08:00
/**
*
* Set toolbar in window scroll auto fixed position
*
2017-04-26 18:17:38 +08:00
* @returns {editormd} editormd
*/
2017-04-26 18:17:38 +08:00
setToolbarAutoFixed : function(fixed) {
2017-04-26 18:17:38 +08:00
var state = this.state;
var editor = this.editor;
var toolbar = this.toolbar;
var settings = this.settings;
2017-04-26 18:17:38 +08:00
if (typeof fixed !== "undefined")
{
settings.toolbarAutoFixed = fixed;
}
2017-04-26 18:17:38 +08:00
var autoFixedHandle = function(){
var $window = $(window);
var top = $window.scrollTop();
2017-04-26 18:17:38 +08:00
if (!settings.toolbarAutoFixed)
{
return false;
}
if (top - editor.offset().top > 10 && top < editor.height())
{
toolbar.css({
position : "fixed",
width : editor.width() + "px",
left : ($window.width() - editor.width()) / 2 + "px"
});
}
else
{
toolbar.css({
position : "absolute",
width : "100%",
left : 0
});
}
};
2017-04-26 18:17:38 +08:00
if (!state.fullscreen && !state.preview && settings.toolbar && settings.toolbarAutoFixed)
{
$(window).bind("scroll", autoFixedHandle);
}
return this;
},
2017-04-26 18:17:38 +08:00
/**
*
* Set toolbar and Initialization
*
2017-04-26 18:17:38 +08:00
* @returns {editormd} editormd
*/
2017-04-26 18:17:38 +08:00
setToolbar : function() {
var settings = this.settings;
2017-04-26 18:17:38 +08:00
if(settings.readOnly) {
return this;
}
2017-04-26 18:17:38 +08:00
var editor = this.editor;
var preview = this.preview;
var classPrefix = this.classPrefix;
2017-04-26 18:17:38 +08:00
var toolbar = this.toolbar = editor.children("." + classPrefix + "toolbar");
2017-04-26 18:17:38 +08:00
if (settings.toolbar && toolbar.length < 1)
{
2017-04-26 18:17:38 +08:00
var toolbarHTML = "<div class=\"" + classPrefix + "toolbar\"><div class=\"" + classPrefix + "toolbar-container\"><ul class=\"" + classPrefix + "menu\"></ul></div></div>";
2017-04-26 18:17:38 +08:00
editor.append(toolbarHTML);
toolbar = this.toolbar = editor.children("." + classPrefix + "toolbar");
}
if (!settings.toolbar)
2017-04-26 18:17:38 +08:00
{
toolbar.hide();
2017-04-26 18:17:38 +08:00
return this;
}
2017-04-26 18:17:38 +08:00
toolbar.show();
var icons = (typeof settings.toolbarIcons === "function") ? settings.toolbarIcons()
2017-04-26 18:17:38 +08:00
: ((typeof settings.toolbarIcons === "string") ? editormd.toolbarModes[settings.toolbarIcons] : settings.toolbarIcons);
2017-04-26 18:17:38 +08:00
var toolbarMenu = toolbar.find("." + this.classPrefix + "menu"), menu = "";
var pullRight = false;
2017-04-26 18:17:38 +08:00
for (var i = 0, len = icons.length; i < len; i++)
{
var name = icons[i];
if (name === "||")
{
2017-04-26 18:17:38 +08:00
pullRight = true;
}
2017-04-26 18:17:38 +08:00
else if (name === "|")
{
menu += "<li class=\"divider\" unselectable=\"on\">|</li>";
}
else
{
var isHeader = (/h(\d)/.test(name));
var index = name;
2017-04-26 18:17:38 +08:00
if (name === "watch" && !settings.watch) {
index = "unwatch";
}
2017-04-26 18:17:38 +08:00
var title = settings.lang.toolbar[index];
var iconTexts = settings.toolbarIconTexts[index];
var iconClass = settings.toolbarIconsClass[index];
2017-04-26 18:17:38 +08:00
title = (typeof title === "undefined") ? "" : title;
iconTexts = (typeof iconTexts === "undefined") ? "" : iconTexts;
iconClass = (typeof iconClass === "undefined") ? "" : iconClass;
var menuItem = pullRight ? "<li class=\"pull-right\">" : "<li>";
2017-04-26 18:17:38 +08:00
if (typeof settings.toolbarCustomIcons[name] !== "undefined" && typeof settings.toolbarCustomIcons[name] !== "function")
{
menuItem += settings.toolbarCustomIcons[name];
}
else
2017-04-26 18:17:38 +08:00
{
menuItem += "<a href=\"javascript:;\" title=\"" + title + "\" unselectable=\"on\">";
menuItem += "<i class=\"fa " + iconClass + "\" name=\""+name+"\" unselectable=\"on\">"+((isHeader) ? name.toUpperCase() : ( (iconClass === "") ? iconTexts : "") ) + "</i>";
menuItem += "</a>";
}
menuItem += "</li>";
menu = pullRight ? menuItem + menu : menu + menuItem;
}
}
toolbarMenu.html(menu);
2017-04-26 18:17:38 +08:00
toolbarMenu.find("[title=\"Lowercase\"]").attr("title", settings.lang.toolbar.lowercase);
toolbarMenu.find("[title=\"ucwords\"]").attr("title", settings.lang.toolbar.ucwords);
2017-04-26 18:17:38 +08:00
this.setToolbarHandler();
this.setToolbarAutoFixed();
return this;
},
2017-04-26 18:17:38 +08:00
/**
*
* Get toolbar icons event handlers
*
2017-04-26 18:17:38 +08:00
* @param {Object} cm CodeMirror
* @param {String} name
* @returns {Object}
*/
2017-04-26 18:17:38 +08:00
dialogLockScreen : function() {
$.proxy(editormd.dialogLockScreen, this)();
2017-04-26 18:17:38 +08:00
return this;
},
dialogShowMask : function(dialog) {
$.proxy(editormd.dialogShowMask, this)(dialog);
2017-04-26 18:17:38 +08:00
return this;
},
getToolbarHandles : function(name) {
2017-04-26 18:17:38 +08:00
var toolbarHandlers = this.toolbarHandlers = editormd.toolbarHandlers;
2017-04-26 18:17:38 +08:00
return (name && typeof toolbarIconHandlers[name] !== "undefined") ? toolbarHandlers[name] : toolbarHandlers;
},
2017-04-26 18:17:38 +08:00
/**
*
* Bind toolbar icons event handle
*
2017-04-26 18:17:38 +08:00
* @returns {editormd} editormd
*/
2017-04-26 18:17:38 +08:00
setToolbarHandler : function() {
var _this = this;
var settings = this.settings;
2017-04-26 18:17:38 +08:00
if (!settings.toolbar || settings.readOnly) {
return this;
}
2017-04-26 18:17:38 +08:00
var toolbar = this.toolbar;
var cm = this.cm;
var classPrefix = this.classPrefix;
var toolbarIcons = this.toolbarIcons = toolbar.find("." + classPrefix + "menu > li > a");
var toolbarIconHandlers = this.getToolbarHandles();
2017-04-26 18:17:38 +08:00
toolbarIcons.bind(editormd.mouseOrTouch("click", "touchend"), function(event) {
var icon = $(this).children(".fa");
var name = icon.attr("name");
var cursor = cm.getCursor();
var selection = cm.getSelection();
if (name === "") {
return ;
}
2017-04-26 18:17:38 +08:00
_this.activeIcon = icon;
if (typeof toolbarIconHandlers[name] !== "undefined")
2017-04-26 18:17:38 +08:00
{
$.proxy(toolbarIconHandlers[name], _this)(cm);
}
else
2017-04-26 18:17:38 +08:00
{
if (typeof settings.toolbarHandlers[name] !== "undefined")
2017-04-26 18:17:38 +08:00
{
$.proxy(settings.toolbarHandlers[name], _this)(cm, icon, cursor, selection);
}
}
if (name !== "link" && name !== "reference-link" && name !== "image" && name !== "code-block" &&
name !== "preformatted-text" && name !== "watch" && name !== "preview" && name !== "search" && name !== "fullscreen" && name !== "info")
2017-04-26 18:17:38 +08:00
{
cm.focus();
}
return false;
});
return this;
},
2017-04-26 18:17:38 +08:00
/**
*
* Creating custom dialogs
*
2017-04-26 18:17:38 +08:00
* @param {Object} options Key/Value
* @returns {dialog} dialogjQuery
*/
createDialog : function(options) {
2017-04-26 18:17:38 +08:00
return $.proxy(editormd.createDialog, this)(options);
},
2017-04-26 18:17:38 +08:00
/**
* Editor.md
* Create about Editor.md dialog
*
2017-04-26 18:17:38 +08:00
* @returns {editormd} editormd
*/
2017-04-26 18:17:38 +08:00
createInfoDialog : function() {
var _this = this;
var editor = this.editor;
var classPrefix = this.classPrefix;
2017-04-26 18:17:38 +08:00
var infoDialogHTML = [
"<div class=\"" + classPrefix + "dialog " + classPrefix + "dialog-info\" style=\"\">",
"<div class=\"" + classPrefix + "dialog-container\">",
"<h1><i class=\"editormd-logo editormd-logo-lg editormd-logo-color\"></i> " + editormd.title + "<small>v" + editormd.version + "</small></h1>",
"<p>" + this.lang.description + "</p>",
"<p style=\"margin: 10px 0 20px 0;\"><a href=\"" + editormd.homePage + "\" target=\"_blank\">" + editormd.homePage + " <i class=\"fa fa-external-link\"></i></a></p>",
"<p style=\"font-size: 0.85em;\">Copyright &copy; 2015 <a href=\"https://github.com/pandao\" target=\"_blank\" class=\"hover-link\">Pandao</a>, The <a href=\"https://github.com/pandao/editor.md/blob/master/LICENSE\" target=\"_blank\" class=\"hover-link\">MIT</a> License.</p>",
"</div>",
"<a href=\"javascript:;\" class=\"fa fa-close " + classPrefix + "dialog-close\"></a>",
"</div>"
].join("\n");
editor.append(infoDialogHTML);
2017-04-26 18:17:38 +08:00
var infoDialog = this.infoDialog = editor.children("." + classPrefix + "dialog-info");
infoDialog.find("." + classPrefix + "dialog-close").bind(editormd.mouseOrTouch("click", "touchend"), function() {
_this.hideInfoDialog();
});
2017-04-26 18:17:38 +08:00
infoDialog.css("border", (editormd.isIE8) ? "1px solid #ddd" : "").css("z-index", editormd.dialogZindex).show();
2017-04-26 18:17:38 +08:00
this.infoDialogPosition();
return this;
},
2017-04-26 18:17:38 +08:00
/**
* Editor.md
* Editor.md dialog position handle
*
2017-04-26 18:17:38 +08:00
* @returns {editormd} editormd
*/
2017-04-26 18:17:38 +08:00
infoDialogPosition : function() {
var infoDialog = this.infoDialog;
2017-04-26 18:17:38 +08:00
var _infoDialogPosition = function() {
infoDialog.css({
top : ($(window).height() - infoDialog.height()) / 2 + "px",
left : ($(window).width() - infoDialog.width()) / 2 + "px"
});
};
_infoDialogPosition();
$(window).resize(_infoDialogPosition);
2017-04-26 18:17:38 +08:00
return this;
},
2017-04-26 18:17:38 +08:00
/**
* Editor.md
* Display about Editor.md dialog
*
2017-04-26 18:17:38 +08:00
* @returns {editormd} editormd
*/
2017-04-26 18:17:38 +08:00
showInfoDialog : function() {
$("html,body").css("overflow-x", "hidden");
2017-04-26 18:17:38 +08:00
var _this = this;
var editor = this.editor;
var settings = this.settings;
2017-04-26 18:17:38 +08:00
var infoDialog = this.infoDialog = editor.children("." + this.classPrefix + "dialog-info");
2017-04-26 18:17:38 +08:00
if (infoDialog.length < 1)
{
this.createInfoDialog();
}
2017-04-26 18:17:38 +08:00
this.lockScreen(true);
2017-04-26 18:17:38 +08:00
this.mask.css({
opacity : settings.dialogMaskOpacity,
backgroundColor : settings.dialogMaskBgColor
}).show();
infoDialog.css("z-index", editormd.dialogZindex).show();
this.infoDialogPosition();
return this;
},
2017-04-26 18:17:38 +08:00
/**
* Editor.md
* Hide about Editor.md dialog
*
2017-04-26 18:17:38 +08:00
* @returns {editormd} editormd
*/
hideInfoDialog : function() {
2017-04-26 18:17:38 +08:00
$("html,body").css("overflow-x", "");
this.infoDialog.hide();
this.mask.hide();
this.lockScreen(false);
return this;
},
2017-04-26 18:17:38 +08:00
/**
*
* lock screen
*
2017-04-26 18:17:38 +08:00
* @param {Boolean} lock Boolean
* @returns {editormd} editormd
*/
2017-04-26 18:17:38 +08:00
lockScreen : function(lock) {
editormd.lockScreen(lock);
this.resize();
return this;
},
2017-04-26 18:17:38 +08:00
/**
*
* Recreate editor
*
2017-04-26 18:17:38 +08:00
* @returns {editormd} editormd
*/
2017-04-26 18:17:38 +08:00
recreate : function() {
var _this = this;
var editor = this.editor;
var settings = this.settings;
2017-04-26 18:17:38 +08:00
this.codeMirror.remove();
2017-04-26 18:17:38 +08:00
this.setCodeMirror();
if (!settings.readOnly)
2017-04-26 18:17:38 +08:00
{
if (editor.find(".editormd-dialog").length > 0) {
editor.find(".editormd-dialog").remove();
}
if (settings.toolbar)
{
this.getToolbarHandles();
2017-04-26 18:17:38 +08:00
this.setToolbar();
}
}
2017-04-26 18:17:38 +08:00
this.loadedDisplay(true);
return this;
},
2017-04-26 18:17:38 +08:00
/**
* HTMLpre
* highlight of preview codes
*
2017-04-26 18:17:38 +08:00
* @returns {editormd} editormd
*/
previewCodeHighlight : function() {
2017-04-26 18:17:38 +08:00
var settings = this.settings;
var previewContainer = this.previewContainer;
if (settings.previewCodeHighlight)
2017-04-26 18:17:38 +08:00
{
// previewContainer.find("pre").addClass("prettyprint");
//
// if (typeof prettyPrint !== "undefined")
// {
// prettyPrint();
// }
previewContainer.find("pre").each(function (i, block) {
hljs.highlightBlock(block);
});
2017-04-26 18:17:38 +08:00
}
return this;
},
2017-04-26 18:17:38 +08:00
/**
* TeX(KaTeX)
* TeX(KaTeX) Renderer
*
2017-04-26 18:17:38 +08:00
* @returns {editormd} editormd
*/
2017-04-26 18:17:38 +08:00
katexRender : function() {
2017-04-26 18:17:38 +08:00
if (timer === null)
{
return this;
}
2017-04-26 18:17:38 +08:00
this.previewContainer.find("." + editormd.classNames.tex).each(function(){
var tex = $(this);
editormd.$katex.render(tex.text(), tex[0]);
2017-04-26 18:17:38 +08:00
tex.find(".katex").css("font-size", "1.6em");
});
2017-04-26 18:17:38 +08:00
return this;
},
/**
* - 2020-04-12
*
* @returns {editormd} editormd
*/
mindmapRender:function(){
this.previewContainer.find(".mindmap").each(function(){
var mmap = $(this);
var md_data = window.markmap.transform(mmap.text().trim());
window.markmap.markmap("svg#"+this.id,md_data)
});
return this;
},
2017-04-26 18:17:38 +08:00
/**
*
* FlowChart and SequenceDiagram Renderer
*
2017-04-26 18:17:38 +08:00
* @returns {editormd} editormd
*/
2017-04-26 18:17:38 +08:00
flowChartAndSequenceDiagramRender : function() {
var $this = this;
var settings = this.settings;
var previewContainer = this.previewContainer;
2017-04-26 18:17:38 +08:00
if (editormd.isIE8) {
return this;
}
if (settings.mermaid) {
var mermaid = previewContainer.find(".lang-mermaid");
if (mermaid) {
2018-09-03 15:39:01 +08:00
try {
window.mermaid.init(void 0, mermaid.removeClass("hide"));
}catch (e) {
console.log(e);
}
}
}
2017-04-26 18:17:38 +08:00
if (settings.flowChart) {
if (flowchartTimer === null) {
return this;
}
try {
previewContainer.find(".flowchart").flowChart();
}catch (e) {
console.log(e);
}
2017-04-26 18:17:38 +08:00
}
2018-09-03 15:39:01 +08:00
if (settings.sequenceDiagram) {
try {
previewContainer.find(".sequence-diagram").sequenceDiagram({theme: "simple"});
}catch (e) {
console.log(e);
}
2017-04-26 18:17:38 +08:00
}
2017-04-26 18:17:38 +08:00
var preview = $this.preview;
var codeMirror = $this.codeMirror;
var codeView = codeMirror.find(".CodeMirror-scroll");
var height = codeView.height();
var scrollTop = codeView.scrollTop();
2017-04-26 18:17:38 +08:00
var percent = (scrollTop / codeView[0].scrollHeight);
var tocHeight = 0;
preview.find(".markdown-toc-list").each(function(){
tocHeight += $(this).height();
});
var tocMenuHeight = preview.find(".editormd-toc-menu").height();
2017-04-26 18:17:38 +08:00
tocMenuHeight = (!tocMenuHeight) ? 0 : tocMenuHeight;
if (scrollTop === 0)
2017-04-26 18:17:38 +08:00
{
preview.scrollTop(0);
}
2017-04-26 18:17:38 +08:00
else if (scrollTop + height >= codeView[0].scrollHeight - 16)
{
preview.scrollTop(preview[0].scrollHeight);
}
2017-04-26 18:17:38 +08:00
else
{
2017-04-26 18:17:38 +08:00
preview.scrollTop((preview[0].scrollHeight + tocHeight + tocMenuHeight) * percent);
}
return this;
},
2017-04-26 18:17:38 +08:00
/**
*
* Register CodeMirror keyMaps (keyboard shortcuts).
*
2017-04-26 18:17:38 +08:00
* @param {Object} keyMap KeyMap key/value {"(Ctrl/Shift/Alt)-Key" : function(){}}
* @returns {editormd} return this
*/
2017-04-26 18:17:38 +08:00
registerKeyMaps : function(keyMap) {
2017-04-26 18:17:38 +08:00
var _this = this;
var cm = this.cm;
var settings = this.settings;
var toolbarHandlers = editormd.toolbarHandlers;
var disabledKeyMaps = settings.disabledKeyMaps;
2017-04-26 18:17:38 +08:00
keyMap = keyMap || null;
2017-04-26 18:17:38 +08:00
if (keyMap)
{
for (var i in keyMap)
{
if ($.inArray(i, disabledKeyMaps) < 0)
{
var map = {};
map[i] = keyMap[i];
cm.addKeyMap(keyMap);
}
}
}
else
{
for (var k in editormd.keyMaps)
{
var _keyMap = editormd.keyMaps[k];
var handle = (typeof _keyMap === "string") ? $.proxy(toolbarHandlers[_keyMap], _this) : $.proxy(_keyMap, _this);
2017-04-26 18:17:38 +08:00
if ($.inArray(k, ["F9", "F10", "F11"]) < 0 && $.inArray(k, disabledKeyMaps) < 0)
{
var _map = {};
_map[k] = handle;
cm.addKeyMap(_map);
}
}
2017-04-26 18:17:38 +08:00
$(window).keydown(function(event) {
2017-04-26 18:17:38 +08:00
var keymaps = {
"120" : "F9",
"121" : "F10",
"122" : "F11"
};
2017-04-26 18:17:38 +08:00
if ( $.inArray(keymaps[event.keyCode], disabledKeyMaps) < 0 )
{
switch (event.keyCode)
{
case 120:
$.proxy(toolbarHandlers["watch"], _this)();
return false;
break;
2017-04-26 18:17:38 +08:00
case 121:
$.proxy(toolbarHandlers["preview"], _this)();
return false;
break;
2017-04-26 18:17:38 +08:00
case 122:
$.proxy(toolbarHandlers["fullscreen"], _this)();
2017-04-26 18:17:38 +08:00
return false;
break;
2017-04-26 18:17:38 +08:00
default:
break;
}
}
});
}
return this;
},
2017-04-26 18:17:38 +08:00
/**
*
*
2017-04-26 18:17:38 +08:00
* @returns {editormd} return this
*/
2017-04-26 18:17:38 +08:00
bindScrollEvent : function() {
2017-04-26 18:17:38 +08:00
var _this = this;
var preview = this.preview;
var settings = this.settings;
var codeMirror = this.codeMirror;
var mouseOrTouch = editormd.mouseOrTouch;
2017-04-26 18:17:38 +08:00
if (!settings.syncScrolling) {
return this;
}
var cmBindScroll = function() {
2017-04-26 18:17:38 +08:00
codeMirror.find(".CodeMirror-scroll").bind(mouseOrTouch("scroll", "touchmove"), function(event) {
var height = $(this).height();
var scrollTop = $(this).scrollTop();
2017-04-26 18:17:38 +08:00
var percent = (scrollTop / $(this)[0].scrollHeight);
2017-04-26 18:17:38 +08:00
var tocHeight = 0;
2017-04-26 18:17:38 +08:00
preview.find(".markdown-toc-list").each(function(){
tocHeight += $(this).height();
});
2017-04-26 18:17:38 +08:00
var tocMenuHeight = preview.find(".editormd-toc-menu").height();
tocMenuHeight = (!tocMenuHeight) ? 0 : tocMenuHeight;
if (scrollTop === 0)
2017-04-26 18:17:38 +08:00
{
preview.scrollTop(0);
}
2017-04-26 18:17:38 +08:00
else if (scrollTop + height >= $(this)[0].scrollHeight - 16)
{
preview.scrollTop(preview[0].scrollHeight);
}
2017-04-26 18:17:38 +08:00
else
{
preview.scrollTop((preview[0].scrollHeight + tocHeight + tocMenuHeight) * percent);
}
2017-04-26 18:17:38 +08:00
$.proxy(settings.onscroll, _this)(event);
});
};
var cmUnbindScroll = function() {
codeMirror.find(".CodeMirror-scroll").unbind(mouseOrTouch("scroll", "touchmove"));
};
var previewBindScroll = function() {
2017-04-26 18:17:38 +08:00
preview.bind(mouseOrTouch("scroll", "touchmove"), function(event) {
var height = $(this).height();
var scrollTop = $(this).scrollTop();
2017-04-26 18:17:38 +08:00
var percent = (scrollTop / $(this)[0].scrollHeight);
var codeView = codeMirror.find(".CodeMirror-scroll");
if(scrollTop === 0)
2017-04-26 18:17:38 +08:00
{
codeView.scrollTop(0);
}
else if (scrollTop + height >= $(this)[0].scrollHeight)
{
codeView.scrollTop(codeView[0].scrollHeight);
2017-04-26 18:17:38 +08:00
}
else
2017-04-26 18:17:38 +08:00
{
codeView.scrollTop(codeView[0].scrollHeight * percent);
}
2017-04-26 18:17:38 +08:00
$.proxy(settings.onpreviewscroll, _this)(event);
});
};
var previewUnbindScroll = function() {
preview.unbind(mouseOrTouch("scroll", "touchmove"));
};
2017-04-26 18:17:38 +08:00
codeMirror.bind({
mouseover : cmBindScroll,
mouseout : cmUnbindScroll,
touchstart : cmBindScroll,
touchend : cmUnbindScroll
});
2017-04-26 18:17:38 +08:00
if (settings.syncScrolling === "single") {
return this;
}
2017-04-26 18:17:38 +08:00
preview.bind({
mouseover : previewBindScroll,
mouseout : previewUnbindScroll,
touchstart : previewBindScroll,
touchend : previewUnbindScroll
});
return this;
},
2017-04-26 18:17:38 +08:00
bindChangeEvent : function() {
2017-04-26 18:17:38 +08:00
var _this = this;
var cm = this.cm;
var settings = this.settings;
2017-04-26 18:17:38 +08:00
if (!settings.syncScrolling) {
return this;
}
2017-04-26 18:17:38 +08:00
cm.on("change", function(_cm, changeObj) {
2017-04-26 18:17:38 +08:00
if (settings.watch)
{
_this.previewContainer.css("padding", settings.autoHeight ? "20px 20px 50px 40px" : "20px");
}
2017-04-26 18:17:38 +08:00
timer = setTimeout(function() {
clearTimeout(timer);
_this.save();
timer = null;
}, settings.delay);
});
return this;
},
2017-04-26 18:17:38 +08:00
/**
*
* Display handle of the module queues loaded after.
*
2017-04-26 18:17:38 +08:00
* @param {Boolean} recreate
* @returns {editormd} editormd
*/
2017-04-26 18:17:38 +08:00
loadedDisplay : function(recreate) {
2017-04-26 18:17:38 +08:00
recreate = recreate || false;
2017-04-26 18:17:38 +08:00
var _this = this;
var editor = this.editor;
var preview = this.preview;
var settings = this.settings;
2017-04-26 18:17:38 +08:00
this.containerMask.hide();
2017-04-26 18:17:38 +08:00
this.save();
2017-04-26 18:17:38 +08:00
if (settings.watch) {
preview.show();
}
2017-04-26 18:17:38 +08:00
editor.data("oldWidth", editor.width()).data("oldHeight", editor.height()); // 为了兼容Zepto
2017-04-26 18:17:38 +08:00
this.resize();
this.registerKeyMaps();
2017-04-26 18:17:38 +08:00
$(window).resize(function(){
_this.resize();
});
2017-04-26 18:17:38 +08:00
this.bindScrollEvent().bindChangeEvent();
2017-04-26 18:17:38 +08:00
if (!recreate)
{
$.proxy(settings.onload, this)();
}
2017-04-26 18:17:38 +08:00
this.state.loaded = true;
return this;
},
2017-04-26 18:17:38 +08:00
/**
*
* Set editor width
*
2017-04-26 18:17:38 +08:00
* @param {Number|String} width
* @returns {editormd} editormd
*/
2017-04-26 18:17:38 +08:00
width : function(width) {
this.editor.css("width", (typeof width === "number") ? width + "px" : width);
2017-04-26 18:17:38 +08:00
this.resize();
2017-04-26 18:17:38 +08:00
return this;
},
2017-04-26 18:17:38 +08:00
/**
*
* Set editor height
*
2017-04-26 18:17:38 +08:00
* @param {Number|String} height
* @returns {editormd} editormd
*/
2017-04-26 18:17:38 +08:00
height : function(height) {
this.editor.css("height", (typeof height === "number") ? height + "px" : height);
2017-04-26 18:17:38 +08:00
this.resize();
2017-04-26 18:17:38 +08:00
return this;
},
2017-04-26 18:17:38 +08:00
/**
*
* Resize editor layout
*
2017-04-26 18:17:38 +08:00
* @param {Number|String} [width=null]
* @param {Number|String} [height=null]
* @returns {editormd} editormd
*/
2017-04-26 18:17:38 +08:00
resize : function(width, height) {
2017-04-26 18:17:38 +08:00
width = width || null;
height = height || null;
2017-04-26 18:17:38 +08:00
var state = this.state;
var editor = this.editor;
var preview = this.preview;
var toolbar = this.toolbar;
var settings = this.settings;
var codeMirror = this.codeMirror;
2017-04-26 18:17:38 +08:00
if (width)
{
editor.css("width", (typeof width === "number") ? width + "px" : width);
}
2017-04-26 18:17:38 +08:00
if (settings.autoHeight && !state.fullscreen && !state.preview)
{
editor.css("height", "auto");
codeMirror.css("height", "auto");
}
else
2017-04-26 18:17:38 +08:00
{
if (height)
2017-04-26 18:17:38 +08:00
{
editor.css("height", (typeof height === "number") ? height + "px" : height);
}
2017-04-26 18:17:38 +08:00
if (state.fullscreen)
{
editor.height($(window).height());
}
if (settings.toolbar && !settings.readOnly)
2017-04-26 18:17:38 +08:00
{
codeMirror.css("margin-top", toolbar.height() + 1).height(editor.height() - toolbar.height());
}
2017-04-26 18:17:38 +08:00
else
{
codeMirror.css("margin-top", 0).height(editor.height());
}
}
if(settings.watch)
2017-04-26 18:17:38 +08:00
{
codeMirror.width(editor.width() / 2);
preview.width((!state.preview) ? editor.width() / 2 : editor.width());
2017-04-26 18:17:38 +08:00
this.previewContainer.css("padding", settings.autoHeight ? "20px 20px 50px 40px" : "20px");
if (settings.toolbar && !settings.readOnly)
2017-04-26 18:17:38 +08:00
{
preview.css("top", toolbar.height() + 1);
}
else
2017-04-26 18:17:38 +08:00
{
preview.css("top", 0);
}
2017-04-26 18:17:38 +08:00
if (settings.autoHeight && !state.fullscreen && !state.preview)
{
preview.height("");
}
else
{
2017-04-26 18:17:38 +08:00
var previewHeight = (settings.toolbar && !settings.readOnly) ? editor.height() - toolbar.height() : editor.height();
2017-04-26 18:17:38 +08:00
preview.height(previewHeight);
}
}
else
2017-04-26 18:17:38 +08:00
{
codeMirror.width(editor.width());
preview.hide();
}
if (state.loaded)
2017-04-26 18:17:38 +08:00
{
$.proxy(settings.onresize, this)();
}
return this;
},
2017-04-26 18:17:38 +08:00
/**
* Markdown
* Parse & Saving Markdown source code
*
2017-04-26 18:17:38 +08:00
* @returns {editormd} editormd
*/
2017-04-26 18:17:38 +08:00
save : function() {
2017-04-26 18:17:38 +08:00
if (timer === null)
{
return this;
}
2017-04-26 18:17:38 +08:00
var _this = this;
var state = this.state;
var settings = this.settings;
var cm = this.cm;
2017-04-26 18:17:38 +08:00
var cmValue = cm.getValue();
var previewContainer = this.previewContainer;
if (settings.mode !== "gfm" && settings.mode !== "markdown")
2017-04-26 18:17:38 +08:00
{
this.markdownTextarea.val(cmValue);
2017-04-26 18:17:38 +08:00
return this;
}
2017-04-26 18:17:38 +08:00
var marked = editormd.$marked;
var markdownToC = this.markdownToC = [];
var rendererOptions = this.markedRendererOptions = {
2017-04-26 18:17:38 +08:00
toc : settings.toc,
tocm : settings.tocm,
tocStartLevel : settings.tocStartLevel,
pageBreak : settings.pageBreak,
taskList : settings.taskList,
emoji : settings.emoji,
tex : settings.tex,
atLink : settings.atLink, // for @link
emailLink : settings.emailLink, // for mail address auto link
flowChart : settings.flowChart,
sequenceDiagram : settings.sequenceDiagram,
previewCodeHighlight : settings.previewCodeHighlight,
mermaid : settings.mermaid,
mindMap : settings.mindMap, // 思维导图
2017-04-26 18:17:38 +08:00
};
2017-04-26 18:17:38 +08:00
var markedOptions = this.markedOptions = {
renderer : editormd.markedRenderer(markdownToC, rendererOptions),
gfm : true,
tables : true,
breaks : true,
pedantic : false,
sanitize : (settings.htmlDecode) ? false : true, // 关闭忽略HTML标签即开启识别HTML标签默认为false
smartLists : true,
smartypants : true
};
2017-04-26 18:17:38 +08:00
marked.setOptions(markedOptions);
2017-04-26 18:17:38 +08:00
var newMarkdownDoc = editormd.$marked(cmValue, markedOptions);
if(settings.debug) {
console.info("cmValue", cmValue, newMarkdownDoc);
}
2017-04-26 18:17:38 +08:00
newMarkdownDoc = editormd.filterHTMLTags(newMarkdownDoc, settings.htmlDecode);
2017-04-26 18:17:38 +08:00
//console.error("cmValue", cmValue, newMarkdownDoc);
2017-04-26 18:17:38 +08:00
this.markdownTextarea.text(cmValue);
2017-04-26 18:17:38 +08:00
cm.save();
if (settings.saveHTMLToTextarea)
2017-04-26 18:17:38 +08:00
{
this.htmlTextarea.text(newMarkdownDoc);
}
2017-04-26 18:17:38 +08:00
if(settings.watch || (!settings.watch && state.preview))
{
previewContainer.html(newMarkdownDoc);
this.previewCodeHighlight();
if (settings.toc)
2017-04-26 18:17:38 +08:00
{
var tocContainer = (settings.tocContainer === "") ? previewContainer : $(settings.tocContainer);
var tocMenu = tocContainer.find("." + this.classPrefix + "toc-menu");
2017-04-26 18:17:38 +08:00
tocContainer.attr("previewContainer", (settings.tocContainer === "") ? "true" : "false");
2017-04-26 18:17:38 +08:00
if (settings.tocContainer !== "" && tocMenu.length > 0)
{
tocMenu.remove();
}
2017-04-26 18:17:38 +08:00
editormd.markdownToCRenderer(markdownToC, tocContainer, settings.tocDropdown, settings.tocStartLevel);
2017-04-26 18:17:38 +08:00
if (settings.tocDropdown || tocContainer.find("." + this.classPrefix + "toc-menu").length > 0)
{
editormd.tocDropdownMenu(tocContainer, (settings.tocTitle !== "") ? settings.tocTitle : this.lang.tocTitle);
}
2017-04-26 18:17:38 +08:00
if (settings.tocContainer !== "")
{
previewContainer.find(".markdown-toc").css("border", "none");
}
}
2017-04-26 18:17:38 +08:00
if (settings.tex)
{
if (!editormd.kaTeXLoaded && settings.autoLoadModules)
2017-04-26 18:17:38 +08:00
{
editormd.loadKaTeX(function() {
editormd.$katex = katex;
editormd.kaTeXLoaded = true;
_this.katexRender();
});
}
else
2017-04-26 18:17:38 +08:00
{
editormd.$katex = katex;
this.katexRender();
}
}
// 渲染脑图
if(settings.mindMap){
setTimeout(function(){
_this.mindmapRender();
},10)
}
if (settings.flowChart || settings.sequenceDiagram || settings.mermaid)
2017-04-26 18:17:38 +08:00
{
flowchartTimer = setTimeout(function(){
clearTimeout(flowchartTimer);
_this.flowChartAndSequenceDiagramRender();
flowchartTimer = null;
}, 10);
}
if (state.loaded)
2017-04-26 18:17:38 +08:00
{
$.proxy(settings.onchange, this)();
}
}
return this;
},
2017-04-26 18:17:38 +08:00
/**
*
* Focusing the cursor position
*
2017-04-26 18:17:38 +08:00
* @returns {editormd} editormd
*/
2017-04-26 18:17:38 +08:00
focus : function() {
this.cm.focus();
return this;
},
2017-04-26 18:17:38 +08:00
/**
*
* Set cursor position
*
2017-04-26 18:17:38 +08:00
* @param {Object} cursor {line:1, ch:0}
* @returns {editormd} editormd
*/
2017-04-26 18:17:38 +08:00
setCursor : function(cursor) {
this.cm.setCursor(cursor);
return this;
},
2017-04-26 18:17:38 +08:00
/**
*
* Get the current position of the cursor
*
2017-04-26 18:17:38 +08:00
* @returns {Cursor} Cursor
*/
2017-04-26 18:17:38 +08:00
getCursor : function() {
return this.cm.getCursor();
},
2017-04-26 18:17:38 +08:00
/**
*
* Set cursor selected ranges
*
2017-04-26 18:17:38 +08:00
* @param {Object} from {line:1, ch:0}
* @param {Object} to {line:1, ch:0}
* @returns {editormd} editormd
*/
2017-04-26 18:17:38 +08:00
setSelection : function(from, to) {
2017-04-26 18:17:38 +08:00
this.cm.setSelection(from, to);
2017-04-26 18:17:38 +08:00
return this;
},
2017-04-26 18:17:38 +08:00
/**
*
* Get the texts from cursor selected
*
2017-04-26 18:17:38 +08:00
* @returns {String}
*/
2017-04-26 18:17:38 +08:00
getSelection : function() {
return this.cm.getSelection();
},
2017-04-26 18:17:38 +08:00
/**
*
* Set the cursor selection ranges
*
2017-04-26 18:17:38 +08:00
* @param {Array} ranges cursor selection ranges array
* @returns {Array} return this
*/
2017-04-26 18:17:38 +08:00
setSelections : function(ranges) {
this.cm.setSelections(ranges);
2017-04-26 18:17:38 +08:00
return this;
},
2017-04-26 18:17:38 +08:00
/**
*
* Get the cursor selection ranges
*
2017-04-26 18:17:38 +08:00
* @returns {Array} return selection ranges array
*/
2017-04-26 18:17:38 +08:00
getSelections : function() {
return this.cm.getSelections();
},
2017-04-26 18:17:38 +08:00
/**
*
* Replace the text at the current cursor selected or insert a new character at the current cursor position
*
2017-04-26 18:17:38 +08:00
* @param {String} value
* @returns {editormd} editormd
*/
2017-04-26 18:17:38 +08:00
replaceSelection : function(value) {
this.cm.replaceSelection(value);
return this;
},
2017-04-26 18:17:38 +08:00
/**
*
* Insert a new character at the current cursor position
*
* replaceSelection()
* With the replaceSelection() method
*
2017-04-26 18:17:38 +08:00
* @param {String} value
* @returns {editormd} editormd
*/
2017-04-26 18:17:38 +08:00
insertValue : function(value) {
this.replaceSelection(value);
return this;
},
2017-04-26 18:17:38 +08:00
/**
* markdown
* append Markdown to editor
*
2017-04-26 18:17:38 +08:00
* @param {String} md markdown
* @returns {editormd} editormd
*/
2017-04-26 18:17:38 +08:00
appendMarkdown : function(md) {
var settings = this.settings;
var cm = this.cm;
2017-04-26 18:17:38 +08:00
cm.setValue(cm.getValue() + md);
2017-04-26 18:17:38 +08:00
return this;
},
2017-04-26 18:17:38 +08:00
/**
* markdown
* Set Markdown source document
*
2017-04-26 18:17:38 +08:00
* @param {String} md markdown
* @returns {editormd} editormd
*/
2017-04-26 18:17:38 +08:00
setMarkdown : function(md) {
this.cm.setValue(md || this.settings.markdown);
2017-04-26 18:17:38 +08:00
return this;
},
2017-04-26 18:17:38 +08:00
/**
* markdown
* Set Editor.md markdown/CodeMirror value
*
2017-04-26 18:17:38 +08:00
* @returns {editormd} editormd
*/
2017-04-26 18:17:38 +08:00
getMarkdown : function() {
return this.cm.getValue();
},
2017-04-26 18:17:38 +08:00
/**
*
* Get CodeMirror value
*
2017-04-26 18:17:38 +08:00
* @returns {editormd} editormd
*/
2017-04-26 18:17:38 +08:00
getValue : function() {
return this.cm.getValue();
},
2017-04-26 18:17:38 +08:00
/**
*
* Set CodeMirror value
*
2017-04-26 18:17:38 +08:00
* @param {String} value set code/value/string/text
* @returns {editormd} editormd
*/
2017-04-26 18:17:38 +08:00
setValue : function(value) {
this.cm.setValue(value);
2017-04-26 18:17:38 +08:00
return this;
},
2017-04-26 18:17:38 +08:00
/**
*
* Empty CodeMirror editor container
*
2017-04-26 18:17:38 +08:00
* @returns {editormd} editormd
*/
2017-04-26 18:17:38 +08:00
clear : function() {
this.cm.setValue("");
2017-04-26 18:17:38 +08:00
return this;
},
2017-04-26 18:17:38 +08:00
/**
* TextareaHTML
* Get parsed html code from Textarea
*
2017-04-26 18:17:38 +08:00
* @returns {String} HTML
*/
2017-04-26 18:17:38 +08:00
getHTML : function() {
if (!this.settings.saveHTMLToTextarea)
{
alert("Error: settings.saveHTMLToTextarea == false");
return false;
}
2017-04-26 18:17:38 +08:00
return this.htmlTextarea.val();
},
2017-04-26 18:17:38 +08:00
/**
* getHTML()
* getHTML (alias)
*
2017-04-26 18:17:38 +08:00
* @returns {String} Return html code HTML
*/
2017-04-26 18:17:38 +08:00
getTextareaSavedHTML : function() {
return this.getHTML();
},
2017-04-26 18:17:38 +08:00
/**
* HTML
* Get html from preview container
*
2017-04-26 18:17:38 +08:00
* @returns {editormd} editormd
*/
2017-04-26 18:17:38 +08:00
getPreviewedHTML : function() {
if (!this.settings.watch)
{
alert("Error: settings.watch == false");
return false;
}
2017-04-26 18:17:38 +08:00
return this.previewContainer.html();
},
2017-04-26 18:17:38 +08:00
/**
*
* Enable real-time watching
*
2017-04-26 18:17:38 +08:00
* @returns {editormd} editormd
*/
watch : function(callback) {
2017-04-26 18:17:38 +08:00
var settings = this.settings;
2017-04-26 18:17:38 +08:00
if ($.inArray(settings.mode, ["gfm", "markdown"]) < 0)
{
return this;
}
2017-04-26 18:17:38 +08:00
this.state.watching = settings.watch = true;
this.preview.show();
2017-04-26 18:17:38 +08:00
if (this.toolbar)
{
var watchIcon = settings.toolbarIconsClass.watch;
var unWatchIcon = settings.toolbarIconsClass.unwatch;
2017-04-26 18:17:38 +08:00
var icon = this.toolbar.find(".fa[name=watch]");
icon.parent().attr("title", settings.lang.toolbar.watch);
icon.removeClass(unWatchIcon).addClass(watchIcon);
}
this.codeMirror.css("border-right", "1px solid #ddd").width(this.editor.width() / 2);
2017-04-26 18:17:38 +08:00
timer = 0;
2017-04-26 18:17:38 +08:00
this.save().resize();
2017-04-26 18:17:38 +08:00
if (!settings.onwatch)
{
settings.onwatch = callback || function() {};
}
2017-04-26 18:17:38 +08:00
$.proxy(settings.onwatch, this)();
2017-04-26 18:17:38 +08:00
return this;
},
2017-04-26 18:17:38 +08:00
/**
*
* Disable real-time watching
*
2017-04-26 18:17:38 +08:00
* @returns {editormd} editormd
*/
2017-04-26 18:17:38 +08:00
unwatch : function(callback) {
var settings = this.settings;
this.state.watching = settings.watch = false;
this.preview.hide();
if (this.toolbar)
2017-04-26 18:17:38 +08:00
{
var watchIcon = settings.toolbarIconsClass.watch;
var unWatchIcon = settings.toolbarIconsClass.unwatch;
2017-04-26 18:17:38 +08:00
var icon = this.toolbar.find(".fa[name=watch]");
icon.parent().attr("title", settings.lang.toolbar.unwatch);
icon.removeClass(watchIcon).addClass(unWatchIcon);
}
2017-04-26 18:17:38 +08:00
this.codeMirror.css("border-right", "none").width(this.editor.width());
2017-04-26 18:17:38 +08:00
this.resize();
2017-04-26 18:17:38 +08:00
if (!settings.onunwatch)
{
settings.onunwatch = callback || function() {};
}
2017-04-26 18:17:38 +08:00
$.proxy(settings.onunwatch, this)();
2017-04-26 18:17:38 +08:00
return this;
},
2017-04-26 18:17:38 +08:00
/**
*
* Show editor
*
2017-04-26 18:17:38 +08:00
* @param {Function} [callback=function()]
* @returns {editormd} editormd
*/
2017-04-26 18:17:38 +08:00
show : function(callback) {
callback = callback || function() {};
2017-04-26 18:17:38 +08:00
var _this = this;
this.editor.show(0, function() {
$.proxy(callback, _this)();
});
2017-04-26 18:17:38 +08:00
return this;
},
2017-04-26 18:17:38 +08:00
/**
*
* Hide editor
*
2017-04-26 18:17:38 +08:00
* @param {Function} [callback=function()]
* @returns {editormd} editormd
*/
2017-04-26 18:17:38 +08:00
hide : function(callback) {
callback = callback || function() {};
2017-04-26 18:17:38 +08:00
var _this = this;
this.editor.hide(0, function() {
$.proxy(callback, _this)();
});
2017-04-26 18:17:38 +08:00
return this;
},
2017-04-26 18:17:38 +08:00
/**
* HTML
* Enter preview html state
*
2017-04-26 18:17:38 +08:00
* @returns {editormd} editormd
*/
2017-04-26 18:17:38 +08:00
previewing : function() {
2017-04-26 18:17:38 +08:00
var _this = this;
var editor = this.editor;
var preview = this.preview;
var toolbar = this.toolbar;
var settings = this.settings;
var codeMirror = this.codeMirror;
var previewContainer = this.previewContainer;
2017-04-26 18:17:38 +08:00
if ($.inArray(settings.mode, ["gfm", "markdown"]) < 0) {
return this;
}
2017-04-26 18:17:38 +08:00
if (settings.toolbar && toolbar) {
toolbar.toggle();
toolbar.find(".fa[name=preview]").toggleClass("active");
}
2017-04-26 18:17:38 +08:00
codeMirror.toggle();
2017-04-26 18:17:38 +08:00
var escHandle = function(event) {
if (event.shiftKey && event.keyCode === 27) {
_this.previewed();
}
};
if (codeMirror.css("display") === "none") // 为了兼容Zepto而不使用codeMirror.is(":hidden")
{
this.state.preview = true;
if (this.state.fullscreen) {
preview.css("background", "#fff");
}
2017-04-26 18:17:38 +08:00
editor.find("." + this.classPrefix + "preview-close-btn").show().bind(editormd.mouseOrTouch("click", "touchend"), function(){
_this.previewed();
});
2017-04-26 18:17:38 +08:00
if (!settings.watch)
{
this.save();
}
else
2017-04-26 18:17:38 +08:00
{
previewContainer.css("padding", "");
}
2017-04-26 18:17:38 +08:00
previewContainer.addClass(this.classPrefix + "preview-active");
preview.show().css({
position : "",
top : 0,
width : editor.width(),
height : (settings.autoHeight && !this.state.fullscreen) ? "auto" : editor.height()
});
2017-04-26 18:17:38 +08:00
if (this.state.loaded)
{
$.proxy(settings.onpreviewing, this)();
}
$(window).bind("keyup", escHandle);
}
else
2017-04-26 18:17:38 +08:00
{
$(window).unbind("keyup", escHandle);
this.previewed();
}
},
2017-04-26 18:17:38 +08:00
/**
* 退HTML
* Exit preview html state
*
2017-04-26 18:17:38 +08:00
* @returns {editormd} editormd
*/
2017-04-26 18:17:38 +08:00
previewed : function() {
2017-04-26 18:17:38 +08:00
var editor = this.editor;
var preview = this.preview;
var toolbar = this.toolbar;
var settings = this.settings;
var previewContainer = this.previewContainer;
var previewCloseBtn = editor.find("." + this.classPrefix + "preview-close-btn");
this.state.preview = false;
2017-04-26 18:17:38 +08:00
this.codeMirror.show();
2017-04-26 18:17:38 +08:00
if (settings.toolbar) {
toolbar.show();
}
2017-04-26 18:17:38 +08:00
preview[(settings.watch) ? "show" : "hide"]();
2017-04-26 18:17:38 +08:00
previewCloseBtn.hide().unbind(editormd.mouseOrTouch("click", "touchend"));
2017-04-26 18:17:38 +08:00
previewContainer.removeClass(this.classPrefix + "preview-active");
2017-04-26 18:17:38 +08:00
if (settings.watch)
{
previewContainer.css("padding", "20px");
}
preview.css({
2017-04-26 18:17:38 +08:00
background : null,
position : "absolute",
width : editor.width() / 2,
height : (settings.autoHeight && !this.state.fullscreen) ? "auto" : editor.height() - toolbar.height(),
top : (settings.toolbar) ? toolbar.height() : 0
});
if (this.state.loaded)
{
$.proxy(settings.onpreviewed, this)();
}
2017-04-26 18:17:38 +08:00
return this;
},
2017-04-26 18:17:38 +08:00
/**
*
* Fullscreen show
*
2017-04-26 18:17:38 +08:00
* @returns {editormd} editormd
*/
2017-04-26 18:17:38 +08:00
fullscreen : function() {
2017-04-26 18:17:38 +08:00
var _this = this;
var state = this.state;
var editor = this.editor;
var preview = this.preview;
var toolbar = this.toolbar;
var settings = this.settings;
var fullscreenClass = this.classPrefix + "fullscreen";
2017-04-26 18:17:38 +08:00
if (toolbar) {
toolbar.find(".fa[name=fullscreen]").parent().toggleClass("active");
2017-04-26 18:17:38 +08:00
}
2017-04-26 18:17:38 +08:00
var escHandle = function(event) {
if (!event.shiftKey && event.keyCode === 27)
2017-04-26 18:17:38 +08:00
{
if (state.fullscreen)
{
_this.fullscreenExit();
}
}
};
if (!editor.hasClass(fullscreenClass))
2017-04-26 18:17:38 +08:00
{
state.fullscreen = true;
$("html,body").css("overflow", "hidden");
2017-04-26 18:17:38 +08:00
editor.css({
width : $(window).width(),
height : $(window).height()
}).addClass(fullscreenClass);
this.resize();
2017-04-26 18:17:38 +08:00
$.proxy(settings.onfullscreen, this)();
$(window).bind("keyup", escHandle);
}
else
{
$(window).unbind("keyup", escHandle);
2017-04-26 18:17:38 +08:00
this.fullscreenExit();
}
return this;
},
2017-04-26 18:17:38 +08:00
/**
* 退
* Exit fullscreen state
*
2017-04-26 18:17:38 +08:00
* @returns {editormd} editormd
*/
2017-04-26 18:17:38 +08:00
fullscreenExit : function() {
2017-04-26 18:17:38 +08:00
var editor = this.editor;
var settings = this.settings;
var toolbar = this.toolbar;
var fullscreenClass = this.classPrefix + "fullscreen";
2017-04-26 18:17:38 +08:00
this.state.fullscreen = false;
2017-04-26 18:17:38 +08:00
if (toolbar) {
toolbar.find(".fa[name=fullscreen]").parent().removeClass("active");
2017-04-26 18:17:38 +08:00
}
$("html,body").css("overflow", "");
editor.css({
width : editor.data("oldWidth"),
height : editor.data("oldHeight")
}).removeClass(fullscreenClass);
this.resize();
2017-04-26 18:17:38 +08:00
$.proxy(settings.onfullscreenExit, this)();
return this;
},
2017-04-26 18:17:38 +08:00
/**
*
* Load and execute the plugin
*
2017-04-26 18:17:38 +08:00
* @param {String} name plugin name / function name
* @param {String} path plugin load path
* @returns {editormd} editormd
*/
2017-04-26 18:17:38 +08:00
executePlugin : function(name, path) {
2017-04-26 18:17:38 +08:00
var _this = this;
var cm = this.cm;
var settings = this.settings;
2017-04-26 18:17:38 +08:00
path = settings.pluginPath + path;
if (typeof define === "function")
{
2017-04-26 18:17:38 +08:00
if (typeof this[name] === "undefined")
{
alert("Error: " + name + " plugin is not found, you are not load this plugin.");
2017-04-26 18:17:38 +08:00
return this;
}
2017-04-26 18:17:38 +08:00
this[name](cm);
2017-04-26 18:17:38 +08:00
return this;
}
2017-04-26 18:17:38 +08:00
if ($.inArray(path, editormd.loadFiles.plugin) < 0)
{
editormd.loadPlugin(path, function() {
editormd.loadPlugins[name] = _this[name];
_this[name](cm);
});
}
else
{
$.proxy(editormd.loadPlugins[name], this)(cm);
}
2017-04-26 18:17:38 +08:00
return this;
},
2017-04-26 18:17:38 +08:00
/**
*
* Search & replace
*
2017-04-26 18:17:38 +08:00
* @param {String} command CodeMirror serach commands, "find, fintNext, fintPrev, clearSearch, replace, replaceAll"
* @returns {editormd} return this
*/
2017-04-26 18:17:38 +08:00
search : function(command) {
var settings = this.settings;
2017-04-26 18:17:38 +08:00
if (!settings.searchReplace)
{
alert("Error: settings.searchReplace == false");
return this;
}
2017-04-26 18:17:38 +08:00
if (!settings.readOnly)
{
this.cm.execCommand(command || "find");
}
2017-04-26 18:17:38 +08:00
return this;
},
searchReplace : function() {
2017-04-26 18:17:38 +08:00
this.search("replace");
2017-04-26 18:17:38 +08:00
return this;
},
searchReplaceAll : function() {
2017-04-26 18:17:38 +08:00
this.search("replaceAll");
2017-04-26 18:17:38 +08:00
return this;
}
};
editormd.fn.init.prototype = editormd.fn;
2017-04-26 18:17:38 +08:00
/**
*
* lock screen when dialog opening
*
2017-04-26 18:17:38 +08:00
* @returns {void}
*/
editormd.dialogLockScreen = function() {
var settings = this.settings || {dialogLockScreen : true};
if (settings.dialogLockScreen)
{
2017-04-26 18:17:38 +08:00
$("html,body").css("overflow", "hidden");
this.resize();
}
};
2017-04-26 18:17:38 +08:00
/**
*
* Display mask layer when dialog opening
*
2017-04-26 18:17:38 +08:00
* @param {Object} dialog dialog jQuery object
* @returns {void}
*/
2017-04-26 18:17:38 +08:00
editormd.dialogShowMask = function(dialog) {
var editor = this.editor;
var settings = this.settings || {dialogShowMask : true};
2017-04-26 18:17:38 +08:00
dialog.css({
top : ($(window).height() - dialog.height()) / 2 + "px",
left : ($(window).width() - dialog.width()) / 2 + "px"
});
if (settings.dialogShowMask) {
editor.children("." + this.classPrefix + "mask").css("z-index", parseInt(dialog.css("z-index")) - 1).show();
}
};
editormd.toolbarHandlers = {
undo : function() {
this.cm.undo();
},
2017-04-26 18:17:38 +08:00
redo : function() {
this.cm.redo();
},
2017-04-26 18:17:38 +08:00
bold : function() {
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getSelection();
cm.replaceSelection("**" + selection + "**");
if(selection === "") {
cm.setCursor(cursor.line, cursor.ch + 2);
}
},
2017-04-26 18:17:38 +08:00
del : function() {
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getSelection();
cm.replaceSelection("~~" + selection + "~~");
if(selection === "") {
cm.setCursor(cursor.line, cursor.ch + 2);
}
},
italic : function() {
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getSelection();
cm.replaceSelection("*" + selection + "*");
if(selection === "") {
cm.setCursor(cursor.line, cursor.ch + 1);
}
},
quote : function() {
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getSelection();
if (cursor.ch !== 0)
{
cm.setCursor(cursor.line, 0);
cm.replaceSelection("> " + selection);
cm.setCursor(cursor.line, cursor.ch + 2);
}
else
{
cm.replaceSelection("> " + selection);
}
//cm.replaceSelection("> " + selection);
//cm.setCursor(cursor.line, (selection === "") ? cursor.ch + 2 : cursor.ch + selection.length + 2);
},
2017-04-26 18:17:38 +08:00
ucfirst : function() {
var cm = this.cm;
var selection = cm.getSelection();
var selections = cm.listSelections();
cm.replaceSelection(editormd.firstUpperCase(selection));
cm.setSelections(selections);
},
2017-04-26 18:17:38 +08:00
ucwords : function() {
var cm = this.cm;
var selection = cm.getSelection();
var selections = cm.listSelections();
cm.replaceSelection(editormd.wordsFirstUpperCase(selection));
cm.setSelections(selections);
},
2017-04-26 18:17:38 +08:00
uppercase : function() {
var cm = this.cm;
var selection = cm.getSelection();
var selections = cm.listSelections();
cm.replaceSelection(selection.toUpperCase());
cm.setSelections(selections);
},
2017-04-26 18:17:38 +08:00
lowercase : function() {
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getSelection();
var selections = cm.listSelections();
2017-04-26 18:17:38 +08:00
cm.replaceSelection(selection.toLowerCase());
cm.setSelections(selections);
},
h1 : function() {
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getLine(cursor.line);
var patt1=new RegExp("^#{1}[ ]");//如果存在H1
var patt2=new RegExp("^#{1,6}[ ]");//如果存在H2-H6
//如果存在H1,取消H1的设置
if (patt1.test(selection)===true){
selection=selection.replace(/^#{1}[ ]/,"");
cm.setSelection({line:cursor.line, ch:0}, {line:cursor.line+1, ch:0 });
cm.replaceSelection(selection+"\n");
cm.setCursor(cursor.line, cursor.ch -2);
}
//如果存在H1-H6,取消H2-H6,并替换为H1
else if(patt2.test(selection)===true){
selection=selection.replace(/^#{1,6}[ ]/,"");
cm.setSelection({line:cursor.line, ch:0}, {line:cursor.line+1, ch:0 });
cm.replaceSelection("# "+selection+"\n");
cm.setCursor(cursor.line, cursor.ch +2);
}else
//设置为H1
2017-04-26 18:17:38 +08:00
{
cm.setSelection({line:cursor.line, ch:0}, {line:cursor.line+1, ch:0 });
cm.replaceSelection("# "+selection+"\n");
cm.setCursor(cursor.line, cursor.ch +2);
2017-04-26 18:17:38 +08:00
}
},
h2 : function() {
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getLine(cursor.line);
var patt1=new RegExp("^#{2}[ ]");//如果存在H1
var patt2=new RegExp("^#{1,6}[ ]");//如果存在H1-H6
//如果存在H2,取消H2的设置
if (patt1.test(selection)===true){
selection=selection.replace(/^#{2}[ ]/,"");
cm.setSelection({line:cursor.line, ch:0}, {line:cursor.line+1, ch:0 });
cm.replaceSelection(selection+"\n");
cm.setCursor(cursor.line, cursor.ch -3);
}else if(patt2.test(selection)===true){
selection=selection.replace(/^#{1,6}[ ]/,"");
cm.setSelection({line:cursor.line, ch:0}, {line:cursor.line+1, ch:0 });
cm.replaceSelection("## "+selection+"\n");
cm.setCursor(cursor.line, cursor.ch +3);
}else{
cm.setSelection({line:cursor.line, ch:0}, {line:cursor.line+1, ch:0 });
cm.replaceSelection("## "+selection+"\n");
cm.setCursor(cursor.line, cursor.ch +3);
2017-04-26 18:17:38 +08:00
}
},
h3 : function() {
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getLine(cursor.line);
var patt1=new RegExp("^#{3}[ ]");//如果存在H3
var patt2=new RegExp("^#{1,6}[ ]");//如果存在H1-H6
//如果存在H3,取消H3的设置
if (patt1.test(selection)===true){
selection=selection.replace(/^#{3}[ ]/,"");
cm.setSelection({line:cursor.line, ch:0}, {line:cursor.line+1, ch:0 });
cm.replaceSelection(selection+"\n");
cm.setCursor(cursor.line, cursor.ch -4);
}
//如果存在H1-H6,取消H1-H6,并替换为H3
else if(patt2.test(selection)===true){
selection=selection.replace(/^#{1,6}[ ]/,"");
cm.setSelection({line:cursor.line, ch:0}, {line:cursor.line+1, ch:0 });
cm.replaceSelection("### "+selection+"\n");
cm.setCursor(cursor.line, cursor.ch +4);
}else
//设置为H3
2017-04-26 18:17:38 +08:00
{
cm.setSelection({line:cursor.line, ch:0}, {line:cursor.line+1, ch:0 });
cm.replaceSelection("### "+selection+"\n");
cm.setCursor(cursor.line, cursor.ch +4);
2017-04-26 18:17:38 +08:00
}
},
h4 : function() {
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getLine(cursor.line);
var patt1=new RegExp("^#{4}[ ]");//如果存在H4
var patt2=new RegExp("^#{1,6}[ ]");//如果存在H1-H6
//如果存在H4,取消H4的设置
if (patt1.test(selection)===true){
selection=selection.replace(/^#{4}[ ]/,"");
cm.setSelection({line:cursor.line, ch:0}, {line:cursor.line+1, ch:0 });
cm.replaceSelection(selection+"\n");
cm.setCursor(cursor.line, cursor.ch -5);
}
//如果存在H1-H6,取消H1-H6,并替换为H4
else if(patt2.test(selection)===true){
selection=selection.replace(/^#{1,6}[ ]/,"");
cm.setSelection({line:cursor.line, ch:0}, {line:cursor.line+1, ch:0 });
cm.replaceSelection("#### "+selection+"\n");
cm.setCursor(cursor.line, cursor.ch +5);
}else
//设置为H4
2017-04-26 18:17:38 +08:00
{
cm.setSelection({line:cursor.line, ch:0}, {line:cursor.line+1, ch:0 });
cm.replaceSelection("#### "+selection+"\n");
cm.setCursor(cursor.line, cursor.ch +5);
2017-04-26 18:17:38 +08:00
}
},
h5 : function() {
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getLine(cursor.line);
var patt1=new RegExp("^#{5}[ ]");//如果存在H5
var patt2=new RegExp("^#{1,6}[ ]");//如果存在H1-H6
//如果存在H5,取消H5的设置
if (patt1.test(selection)===true){
selection=selection.replace(/^#{5}[ ]/,"");
cm.setSelection({line:cursor.line, ch:0}, {line:cursor.line+1, ch:0 });
cm.replaceSelection(selection+"\n");
cm.setCursor(cursor.line, cursor.ch -6);
}
//如果存在H1-H6,取消H1-H6,并替换为H5
else if(patt2.test(selection)===true){
selection=selection.replace(/^#{1,6}[ ]/,"");
cm.setSelection({line:cursor.line, ch:0}, {line:cursor.line+1, ch:0 });
cm.replaceSelection("##### "+selection+"\n");
cm.setCursor(cursor.line, cursor.ch +6);
}else
//设置为H5
2017-04-26 18:17:38 +08:00
{
cm.setSelection({line:cursor.line, ch:0}, {line:cursor.line+1, ch:0 });
cm.replaceSelection("##### "+selection+"\n");
cm.setCursor(cursor.line, cursor.ch +6);
2017-04-26 18:17:38 +08:00
}
},
h6 : function() {
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getLine(cursor.line);
var patt1=new RegExp("^#{6}[ ]");//如果存在H6
var patt2=new RegExp("^#{1,6}[ ]");//如果存在H1-H6
//如果存在H6,取消H6的设置
if (patt1.test(selection)===true){
selection=selection.replace(/^#{6}[ ]/,"");
cm.setSelection({line:cursor.line, ch:0}, {line:cursor.line+1, ch:0 });
cm.replaceSelection(selection+"\n");
cm.setCursor(cursor.line, cursor.ch -7);
}
//如果存在H1-H6,取消H1-H6,并替换为H6
else if(patt2.test(selection)===true){
selection=selection.replace(/^#{1,6}[ ]/,"");
cm.setSelection({line:cursor.line, ch:0}, {line:cursor.line+1, ch:0 });
cm.replaceSelection("###### "+selection+"\n");
cm.setCursor(cursor.line, cursor.ch +7);
}else
//设置为H6
2017-04-26 18:17:38 +08:00
{
cm.setSelection({line:cursor.line, ch:0}, {line:cursor.line+1, ch:0 });
cm.replaceSelection("###### "+selection+"\n");
cm.setCursor(cursor.line, cursor.ch +7);
2017-04-26 18:17:38 +08:00
}
},
"list-ul" : function() {
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getSelection();
var patt1=new RegExp("^-{1}[ ]");
var cnt =0;
//如果未选择,将该行设置为无序列表
if (selection === "")
2017-04-26 18:17:38 +08:00
{
cm.setCursor(cursor.line, 0);
2017-04-26 18:17:38 +08:00
cm.replaceSelection("- " + selection);
cm.setCursor(cursor.line, cursor.ch + 2);
}
else
2017-04-26 18:17:38 +08:00
{
var selectionText = selection.split("\n");
//判断取中内容是否已作无序列表标记
for (var i = 0, len = selectionText.length; i < len; i++)
2017-04-26 18:17:38 +08:00
{
if (patt1.test(selectionText[i])===true ){cnt++;}
2017-04-26 18:17:38 +08:00
}
//如果全作了无序列表标记,取消标记
if(cnt===selectionText.length){
for (var i = 0, len = selectionText.length; i < len; i++){
selectionText[i] = (selectionText[i] === "") ? "" : selectionText[i].replace(/^-{1}[ ]/,"");
}
}else
//对未打上无序列表标记,打上标记
{
for (var i = 0, len = selectionText.length; i < len; i++){
selectionText[i] = (selectionText[i] === "") ? "" : "- "+selectionText[i].replace(/^-{1}[ ]/,"");
}
2017-04-26 18:17:38 +08:00
}
2017-04-26 18:17:38 +08:00
cm.replaceSelection(selectionText.join("\n"));
}
},
"list-ol" : function() {
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getSelection();
var patt1=new RegExp("^[0-9]+[\.][ ]");
var cnt =0;
//如果未选择,将该行设置为有序列表
if (selection === "")
2017-04-26 18:17:38 +08:00
{
cm.setCursor(cursor.line, 0);
2017-04-26 18:17:38 +08:00
cm.replaceSelection("1. " + selection);
cm.setCursor(cursor.line, cursor.ch + 3);
2017-04-26 18:17:38 +08:00
}
else
{
var selectionText = selection.split("\n");
//判断取中内容是否已作有序列表标记
for (var i = 0, len = selectionText.length; i < len; i++)
2017-04-26 18:17:38 +08:00
{
if (patt1.test(selectionText[i])===true ){cnt++;}
2017-04-26 18:17:38 +08:00
}
//如果全作了有序列表标记,取消标记
if(cnt===selectionText.length){
for (var i = 0, len = selectionText.length; i < len; i++){
selectionText[i] = (selectionText[i] === "") ? "" : selectionText[i].replace(/^[0-9]+[\.][ ]/,"");
}
}else
//对未打上有序列表标记,打上标记
{
for (var i = 0, len = selectionText.length; i < len; i++){
selectionText[i] = (selectionText[i] === "") ? "" : (i+1)+". "+selectionText[i].replace(/^[0-9]+[\.][ ]/,"");
}
2017-04-26 18:17:38 +08:00
}
2017-04-26 18:17:38 +08:00
cm.replaceSelection(selectionText.join("\n"));
}
},
hr : function() {
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getSelection();
cm.replaceSelection(((cursor.ch !== 0) ? "\n\n" : "\n") + "------------\n\n");
},
tex : function() {
if (!this.settings.tex)
{
alert("settings.tex === false");
return this;
}
2017-04-26 18:17:38 +08:00
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getSelection();
cm.replaceSelection("$$" + selection + "$$");
if(selection === "") {
cm.setCursor(cursor.line, cursor.ch + 2);
}
},
link : function() {
this.executePlugin("linkDialog", "link-dialog/link-dialog");
},
"reference-link" : function() {
this.executePlugin("referenceLinkDialog", "reference-link-dialog/reference-link-dialog");
},
pagebreak : function() {
if (!this.settings.pageBreak)
{
alert("settings.pageBreak === false");
return this;
}
2017-04-26 18:17:38 +08:00
var cm = this.cm;
var selection = cm.getSelection();
cm.replaceSelection("\r\n[========]\r\n");
},
image : function() {
this.executePlugin("imageDialog", "image-dialog/image-dialog");
},
2017-04-26 18:17:38 +08:00
code : function() {
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getSelection();
cm.replaceSelection("`" + selection + "`");
if (selection === "") {
cm.setCursor(cursor.line, cursor.ch + 1);
}
},
"code-block" : function() {
this.executePlugin("codeBlockDialog", "code-block-dialog/code-block-dialog");
2017-04-26 18:17:38 +08:00
},
"preformatted-text" : function() {
this.executePlugin("preformattedTextDialog", "preformatted-text-dialog/preformatted-text-dialog");
},
2017-04-26 18:17:38 +08:00
table : function() {
this.executePlugin("tableDialog", "table-dialog/table-dialog");
2017-04-26 18:17:38 +08:00
},
2017-04-26 18:17:38 +08:00
datetime : function() {
var cm = this.cm;
var selection = cm.getSelection();
var date = new Date();
var langName = this.settings.lang.name;
var datefmt = editormd.dateFormat() + " " + editormd.dateFormat((langName === "zh-cn" || langName === "zh-tw") ? "cn-week-day" : "week-day");
cm.replaceSelection(datefmt);
},
2017-04-26 18:17:38 +08:00
emoji : function() {
this.executePlugin("emojiDialog", "emoji-dialog/emoji-dialog");
},
2017-04-26 18:17:38 +08:00
"html-entities" : function() {
this.executePlugin("htmlEntitiesDialog", "html-entities-dialog/html-entities-dialog");
},
2017-04-26 18:17:38 +08:00
"goto-line" : function() {
this.executePlugin("gotoLineDialog", "goto-line-dialog/goto-line-dialog");
},
watch : function() {
2017-04-26 18:17:38 +08:00
this[this.settings.watch ? "unwatch" : "watch"]();
},
preview : function() {
this.previewing();
},
fullscreen : function() {
this.fullscreen();
},
clear : function() {
this.clear();
},
2017-04-26 18:17:38 +08:00
search : function() {
this.search();
},
help : function() {
this.executePlugin("helpDialog", "help-dialog/help-dialog");
},
info : function() {
this.showInfoDialog();
}
};
2017-04-26 18:17:38 +08:00
editormd.keyMaps = {
"Ctrl-1" : "h1",
"Ctrl-2" : "h2",
"Ctrl-3" : "h3",
"Ctrl-4" : "h4",
"Ctrl-5" : "h5",
"Ctrl-6" : "h6",
"Ctrl-B" : "bold", // if this is string == editormd.toolbarHandlers.xxxx
"Ctrl-D" : "datetime",
2017-04-26 18:17:38 +08:00
"Ctrl-E" : function() { // emoji
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getSelection();
2017-04-26 18:17:38 +08:00
if (!this.settings.emoji)
{
alert("Error: settings.emoji == false");
return ;
}
cm.replaceSelection(":" + selection + ":");
if (selection === "") {
cm.setCursor(cursor.line, cursor.ch + 1);
}
},
"Ctrl-Alt-G" : "goto-line",
"Ctrl-H" : "hr",
"Ctrl-I" : "italic",
"Ctrl-K" : "code",
2017-04-26 18:17:38 +08:00
"Ctrl-L" : function() {
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getSelection();
2017-04-26 18:17:38 +08:00
var title = (selection === "") ? "" : " \""+selection+"\"";
cm.replaceSelection("[" + selection + "]("+title+")");
if (selection === "") {
cm.setCursor(cursor.line, cursor.ch + 1);
}
},
"Ctrl-U" : "list-ul",
2017-04-26 18:17:38 +08:00
"Shift-Ctrl-A" : function() {
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getSelection();
2017-04-26 18:17:38 +08:00
if (!this.settings.atLink)
{
alert("Error: settings.atLink == false");
return ;
}
cm.replaceSelection("@" + selection);
if (selection === "") {
cm.setCursor(cursor.line, cursor.ch + 1);
}
},
2017-04-26 18:17:38 +08:00
"Shift-Ctrl-C" : "code",
"Shift-Ctrl-Q" : "quote",
"Shift-Ctrl-S" : "del",
"Shift-Ctrl-K" : "tex", // KaTeX
2017-04-26 18:17:38 +08:00
"Shift-Alt-C" : function() {
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getSelection();
2017-04-26 18:17:38 +08:00
cm.replaceSelection(["```", selection, "```"].join("\n"));
if (selection === "") {
cm.setCursor(cursor.line, cursor.ch + 3);
}
2017-04-26 18:17:38 +08:00
},
2017-04-26 18:17:38 +08:00
"Shift-Ctrl-Alt-C" : "code-block",
"Shift-Ctrl-H" : "html-entities",
"Shift-Alt-H" : "help",
"Shift-Ctrl-E" : "emoji",
"Shift-Ctrl-U" : "uppercase",
"Shift-Alt-U" : "ucwords",
"Shift-Ctrl-Alt-U" : "ucfirst",
"Shift-Alt-L" : "lowercase",
2017-04-26 18:17:38 +08:00
"Shift-Ctrl-I" : function() {
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getSelection();
2017-04-26 18:17:38 +08:00
var title = (selection === "") ? "" : " \""+selection+"\"";
cm.replaceSelection("![" + selection + "]("+title+")");
if (selection === "") {
cm.setCursor(cursor.line, cursor.ch + 4);
}
},
2017-04-26 18:17:38 +08:00
"Shift-Ctrl-Alt-I" : "image",
"Shift-Ctrl-L" : "link",
"Shift-Ctrl-O" : "list-ol",
"Shift-Ctrl-P" : "preformatted-text",
"Shift-Ctrl-T" : "table",
"Shift-Alt-P" : "pagebreak",
"F9" : "watch",
"F10" : "preview",
"F11" : "fullscreen",
};
2017-04-26 18:17:38 +08:00
/**
*
* Clear the space of strings both sides.
*
2017-04-26 18:17:38 +08:00
* @param {String} str string
* @returns {String} trimed string
2017-04-26 18:17:38 +08:00
*/
2017-04-26 18:17:38 +08:00
var trim = function(str) {
return (!String.prototype.trim) ? str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "") : str.trim();
};
2017-04-26 18:17:38 +08:00
editormd.trim = trim;
2017-04-26 18:17:38 +08:00
/**
*
* Words first to uppercase
*
2017-04-26 18:17:38 +08:00
* @param {String} str string
* @returns {String} string
*/
2017-04-26 18:17:38 +08:00
var ucwords = function (str) {
return str.toLowerCase().replace(/\b(\w)|\s(\w)/g, function($1) {
2017-04-26 18:17:38 +08:00
return $1.toUpperCase();
});
};
2017-04-26 18:17:38 +08:00
editormd.ucwords = editormd.wordsFirstUpperCase = ucwords;
2017-04-26 18:17:38 +08:00
/**
*
* Only string first char to uppercase
*
2017-04-26 18:17:38 +08:00
* @param {String} str string
* @returns {String} string
*/
var firstUpperCase = function(str) {
2017-04-26 18:17:38 +08:00
return str.toLowerCase().replace(/\b(\w)/, function($1){
return $1.toUpperCase();
});
};
2017-04-26 18:17:38 +08:00
var ucfirst = firstUpperCase;
2017-04-26 18:17:38 +08:00
editormd.firstUpperCase = editormd.ucfirst = firstUpperCase;
2017-04-26 18:17:38 +08:00
editormd.urls = {
atLinkBase : "https://github.com/"
};
2017-04-26 18:17:38 +08:00
editormd.regexs = {
atLink : /@(\w+)/g,
email : /(\w+)@(\w+)\.(\w+)\.?(\w+)?/g,
emailLink : /(mailto:)?([\w\.\_]+)@(\w+)\.(\w+)\.?(\w+)?/g,
emoji : /:([\w\+-]+):/g,
emojiDatetime : /(\d{2}:\d{2}:\d{2})/g,
twemoji : /:(tw-([\w]+)-?(\w+)?):/g,
fontAwesome : /:(fa-([\w]+)(-(\w+)){0,}):/g,
editormdLogo : /:(editormd-logo-?(\w+)?):/g,
pageBreak : /^\[[=]{8,}\]$/
};
// Emoji graphics files url path
editormd.emoji = {
path : "http://www.emoji-cheat-sheet.com/graphics/emojis/",
ext : ".png"
};
// Twitter Emoji (Twemoji) graphics files url path
2017-04-26 18:17:38 +08:00
editormd.twemoji = {
path : "http://twemoji.maxcdn.com/36x36/",
ext : ".png"
};
/**
* marked
* Custom Marked renderer rules
*
2017-04-26 18:17:38 +08:00
* @param {Array} markdownToC TOC
* @returns {Renderer} markedRenderer markedRenderer
*/
editormd.markedRenderer = function(markdownToC, options) {
var defaults = {
toc : true, // Table of contents
tocm : false,
tocStartLevel : 1, // Said from H1 to create ToC
2017-04-26 18:17:38 +08:00
pageBreak : true,
atLink : true, // for @link
emailLink : true, // for mail address auto link
taskList : false, // Enable Github Flavored Markdown task lists
emoji : false, // :emoji: , Support Twemoji, fontAwesome, Editor.md logo emojis.
tex : false, // TeX(LaTeX), based on KaTeX
flowChart : false, // flowChart.js only support IE9+
sequenceDiagram : false, // sequenceDiagram.js only support IE9+
mermaid : true,
2017-04-26 18:17:38 +08:00
};
var settings = $.extend(defaults, options || {});
2017-04-26 18:17:38 +08:00
var marked = editormd.$marked;
var markedRenderer = new marked.Renderer();
markdownToC = markdownToC || [];
2017-04-26 18:17:38 +08:00
var regexs = editormd.regexs;
var atLinkReg = regexs.atLink;
var emojiReg = regexs.emoji;
var emailReg = regexs.email;
var emailLinkReg = regexs.emailLink;
var twemojiReg = regexs.twemoji;
var faIconReg = regexs.fontAwesome;
var editormdLogoReg = regexs.editormdLogo;
var pageBreakReg = regexs.pageBreak;
markedRenderer.blockquote = function($quote) {
var quoteBegin = "";
var ps = $quote.match(/<p\s.*?>/i);
if(ps !== null) {
quoteBegin = ps[0];
$quote = $quote.substr(quoteBegin.length);
}
var $class = "default";
2018-09-04 10:22:02 +08:00
if($quote.indexOf("[info]") === 0){
$class = "info";
$quote = $quote.substr(6);
}else if($quote.indexOf("[warning]") === 0){
$class = "warning";
$quote = $quote.substr(9);
}else if($quote.indexOf("[success]") === 0){
$class = "success";
$quote = $quote.substr(9);
}else if($quote.indexOf("[danger]") === 0){
$class = "danger";
$quote = $quote.substr(8);
}
return '<blockquote class="'+$class+'">\n' + quoteBegin + $quote + '</blockquote>\n';
};
markedRenderer.image = function(href,title,text) {
var attr = "";
2018-09-04 11:08:09 +08:00
var begin = "";
var end = "";
if(href && href !== ""){
var a = document.createElement('a');
a.href = href;
var attrs = a.hash.match(/size=\d+x\d+/i);
if(attrs !== null) {
a.hash = a.hash.replace(attrs[0],"");
href = a.href;
attrs = attrs[0].replace("size=","").split("x");
if(attrs[0] > 0) {
attr += " width=\"" + attrs[0] + "\""
}
if(attrs[1] > 0) {
attr += " height=\"" + attrs[1] + "\""
}
}
attrs = a.hash.match(/align=(center|left|right)/i)
2018-09-04 11:08:09 +08:00
if (attrs !== null) {
var hash = a.hash.replace(attrs[0],"");
if (hash.indexOf("#&") === 0) {
hash = "#" + hash.substr(2);
}
a.hash = hash;
href = a.href;
attrs = attrs[0].replace("align=","");
end = "</p>";
if(attrs === "center"){
begin = '<p align="center">';
}else if (attrs === "left") {
begin = '<p align="left">';
}else if (attrs === "right") {
begin = '<p align="right">';
}
}
}
2018-09-04 11:08:09 +08:00
return begin + "<img src=\""+href+"\" title=\""+title+"\" alt=\""+text+"\" "+attr+">" + end;
};
2017-04-26 18:17:38 +08:00
markedRenderer.emoji = function(text) {
text = text.replace(editormd.regexs.emojiDatetime, function($1) {
2017-04-26 18:17:38 +08:00
return $1.replace(/:/g, "&#58;");
});
2017-04-26 18:17:38 +08:00
var matchs = text.match(emojiReg);
if (!matchs || !settings.emoji) {
return text;
}
for (var i = 0, len = matchs.length; i < len; i++)
{
2017-04-26 18:17:38 +08:00
if (matchs[i] === ":+1:") {
matchs[i] = ":\\+1:";
}
text = text.replace(new RegExp(matchs[i]), function($1, $2){
var faMatchs = $1.match(faIconReg);
var name = $1.replace(/:/g, "");
if (faMatchs)
{
2017-04-26 18:17:38 +08:00
for (var fa = 0, len1 = faMatchs.length; fa < len1; fa++)
{
var faName = faMatchs[fa].replace(/:/g, "");
2017-04-26 18:17:38 +08:00
return "<i class=\"fa " + faName + " fa-emoji\" title=\"" + faName.replace("fa-", "") + "\"></i>";
}
}
else
{
var emdlogoMathcs = $1.match(editormdLogoReg);
var twemojiMatchs = $1.match(twemojiReg);
if (emdlogoMathcs)
{
2017-04-26 18:17:38 +08:00
for (var x = 0, len2 = emdlogoMathcs.length; x < len2; x++)
{
var logoName = emdlogoMathcs[x].replace(/:/g, "");
return "<i class=\"" + logoName + "\" title=\"Editor.md logo (" + logoName + ")\"></i>";
}
}
else if (twemojiMatchs)
2017-04-26 18:17:38 +08:00
{
for (var t = 0, len3 = twemojiMatchs.length; t < len3; t++)
{
var twe = twemojiMatchs[t].replace(/:/g, "").replace("tw-", "");
return "<img src=\"" + editormd.twemoji.path + twe + editormd.twemoji.ext + "\" title=\"twemoji-" + twe + "\" alt=\"twemoji-" + twe + "\" class=\"emoji twemoji\" />";
}
}
else
{
var src = (name === "+1") ? "plus1" : name;
src = (src === "black_large_square") ? "black_square" : src;
src = (src === "moon") ? "waxing_gibbous_moon" : src;
return "<img src=\"" + editormd.emoji.path + src + editormd.emoji.ext + "\" class=\"emoji\" title=\"&#58;" + name + "&#58;\" alt=\"&#58;" + name + "&#58;\" />";
}
}
});
}
return text;
};
markedRenderer.atLink = function(text) {
if (atLinkReg.test(text))
{
if (settings.atLink)
2017-04-26 18:17:38 +08:00
{
text = text.replace(emailReg, function($1, $2, $3, $4) {
return $1.replace(/@/g, "_#_&#64;_#_");
});
text = text.replace(atLinkReg, function($1, $2) {
return "<a href=\"" + editormd.urls.atLinkBase + "" + $2 + "\" title=\"&#64;" + $2 + "\" class=\"at-link\" target='_blank'>" + $1 + "</a>";
2017-04-26 18:17:38 +08:00
}).replace(/_#_&#64;_#_/g, "@");
}
2017-04-26 18:17:38 +08:00
if (settings.emailLink)
{
text = text.replace(emailLinkReg, function($1, $2, $3, $4, $5) {
return (!$2 && $.inArray($5, "jpg|jpeg|png|gif|webp|ico|icon|pdf".split("|")) < 0) ? "<a href=\"mailto:" + $1 + "\">"+$1+"</a>" : $1;
});
}
return text;
}
return text;
};
2017-04-26 18:17:38 +08:00
markedRenderer.link = function (href, title, text) {
if (this.options.sanitize) {
try {
var prot = decodeURIComponent(unescape(href)).replace(/[^\w:]/g,"").toLowerCase();
} catch(e) {
return "";
}
if (prot.indexOf("javascript:") === 0) {
return "";
}
}
if(href.indexOf("@") === 0){
return '<a name="'+ href.substr(1) + '"></a>';
}
2017-04-26 18:17:38 +08:00
var out = "<a href=\"" + href + "\"";
if(href.indexOf("http://") === 0 || href.indexOf("https://") === 0) {
out += "target=\"_blank\"";
}
2017-04-26 18:17:38 +08:00
if (atLinkReg.test(title) || atLinkReg.test(text))
{
if (title)
{
out += " title=\"" + title.replace(/@/g, "&#64;");
}
2017-04-26 18:17:38 +08:00
return out + "\">" + text.replace(/@/g, "&#64;") + "</a>";
}
if (title) {
out += " title=\"" + title + "\"";
}
out += ">" + text + "</a>";
return out;
};
2017-04-26 18:17:38 +08:00
markedRenderer.heading = function(text, level, raw) {
2017-04-26 18:17:38 +08:00
var linkText = text;
var hasLinkReg = /\s*\<a\s*href\=\"(.*)\"\s*([^\>]*)\>(.*)\<\/a\>\s*/;
var getLinkTextReg = /\s*\<a\s*([^\>]+)\>([^\>]*)\<\/a\>\s*/g;
if (hasLinkReg.test(text))
2017-04-26 18:17:38 +08:00
{
var tempText = [];
text = text.split(/\<a\s*([^\>]+)\>([^\>]*)\<\/a\>/);
for (var i = 0, len = text.length; i < len; i++)
{
tempText.push(text[i].replace(/\s*href\=\"(.*)\"\s*/g, ""));
}
text = tempText.join(" ");
}
2017-04-26 18:17:38 +08:00
text = trim(text);
2017-04-26 18:17:38 +08:00
var escapedText = text.toLowerCase().replace(/[^\w]+/g, "-");
2018-09-11 18:36:42 +08:00
// var isChinese = /^[\u4e00-\u9fa5]+$/.test(text);
// var id = (isChinese) ? escape(text).replace(/\%/g, "") : text.toLowerCase().replace(/[^\w]+/g, "-");
var id = Math.floor(Math.random() * 1000000000 ).toString(36);
2017-04-26 18:17:38 +08:00
var toc = {
text : text,
level : level,
2018-09-11 18:36:42 +08:00
slug : escapedText,
id : id
2017-04-26 18:17:38 +08:00
};
2017-04-26 18:17:38 +08:00
markdownToC.push(toc);
2018-09-11 18:36:42 +08:00
var headingHTML = "<h" + level + " id=\"" + id +"\" class=\"markdown-heading\">";
2018-09-11 18:36:42 +08:00
headingHTML += "<a name=\"" + id + "\" class=\"reference-link\"></a>";
2017-04-26 18:17:38 +08:00
headingHTML += "<span class=\"header-link octicon octicon-link\"></span>";
headingHTML += (hasLinkReg) ? this.atLink(this.emoji(linkText)) : this.atLink(this.emoji(text));
headingHTML += "</h" + level + ">";
return headingHTML;
};
2017-04-26 18:17:38 +08:00
markedRenderer.pageBreak = function(text) {
if (pageBreakReg.test(text) && settings.pageBreak)
{
text = "<hr style=\"page-break-after:always;\" class=\"page-break editormd-page-break\" />";
}
2017-04-26 18:17:38 +08:00
return text;
};
markedRenderer.paragraph = function(text) {
var isTeXInline = /\$\$(.*)\$\$/g.test(text);
var isTeXLine = /^\$\$(.*)\$\$$/.test(text);
var isTeXAddClass = (isTeXLine) ? " class=\"" + editormd.classNames.tex + "\"" : " class=\"line\"";
2017-04-26 18:17:38 +08:00
var isToC = (settings.tocm) ? /^(\[TOC\]|\[TOCM\])$/.test(text) : /^\[TOC\]$/.test(text);
var isToCMenu = /^\[TOCM\]$/.test(text);
if (!isTeXLine && isTeXInline)
2017-04-26 18:17:38 +08:00
{
text = text.replace(/(\$\$([^\$]*)\$\$)+/g, function($1, $2) {
return "<span class=\"" + editormd.classNames.tex + "\">" + $2.replace(/\$/g, "") + "</span>";
});
}
else
2017-04-26 18:17:38 +08:00
{
text = (isTeXLine) ? text.replace(/\$/g, "") : text;
}
2018-09-14 10:26:49 +08:00
var tocHTML = "<div class=\"markdown-toc editormd-markdown-toc\">" + text + "</div>";
2017-04-26 18:17:38 +08:00
return (isToC) ? ( (isToCMenu) ? "<div class=\"editormd-toc-menu\">" + tocHTML + "</div><br/>" : tocHTML )
: ( (pageBreakReg.test(text)) ? this.pageBreak(text) : "<p" + isTeXAddClass + ">" + this.atLink(this.emoji(text)) + "</p>\n" );
};
markedRenderer.code = function (code, lang, escaped) {
2017-04-26 18:17:38 +08:00
if (lang === "seq" || lang === "sequence")
{
return "<div class=\"sequence-diagram\">" + code + "</div>";
}
else if (lang === "mermaid"){
var $chars = 'ABCDEFGHJKLMNOPQRSTUVWXYZabcdefhijlkmnopqrstuvwxyz012345678';
var maxPos = $chars.length;
var id = '';
for (var i = 0; i < 4; i++) {
id += $chars.charAt(Math.floor(Math.random() * maxPos));
}
return "<div class=\"lang-mermaid hide\" data-anchor-id=\""+id+"\">" + code + "</div>";
}
2017-04-26 18:17:38 +08:00
else if ( lang === "flow")
{
return "<div class=\"flowchart\">" + code + "</div>";
}
2017-04-26 18:17:38 +08:00
else if ( lang === "math" || lang === "latex" || lang === "katex")
{
return "<p class=\"" + editormd.classNames.tex + "\">" + code + "</p>";
}
else if (/^mindmap/i.test(lang)){
var len = 9 || 32;
var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
var maxPos = $chars.length;
var map_id = '';
var custom_height;
var h = lang.split('>')[1];
if (h != undefined) {
custom_height = h;
} else {
custom_height = 150;
}
for (var i = 0; i < len; i++) {
map_id += $chars.charAt(Math.floor(Math.random() * maxPos));
}
return "<svg class='mindmap' style='width:100%;min-height=150px;height:"+custom_height+"px;' id='mindmap-"+ map_id +"'>"+code+"</svg>";
}
else
2017-04-26 18:17:38 +08:00
{
return marked.Renderer.prototype.code.apply(this, arguments);
}
};
markedRenderer.tablecell = function(content, flags) {
var type = (flags.header) ? "th" : "td";
var tag = (flags.align) ? "<" + type +" style=\"text-align:" + flags.align + "\">" : "<" + type + ">";
2017-04-26 18:17:38 +08:00
return tag + this.atLink(this.emoji(content)) + "</" + type + ">\n";
};
markedRenderer.listitem = function(text) {
if (settings.taskList && /^\s*\[[x\s]\]\s*/.test(text))
2017-04-26 18:17:38 +08:00
{
text = text.replace(/^\s*\[\s\]\s*/, "<input type=\"checkbox\" class=\"task-list-item-checkbox\" /> ")
.replace(/^\s*\[x\]\s*/, "<input type=\"checkbox\" class=\"task-list-item-checkbox\" checked disabled /> ");
return "<li style=\"list-style: none;\">" + this.atLink(this.emoji(text)) + "</li>";
}
else
2017-04-26 18:17:38 +08:00
{
return "<li>" + this.atLink(this.emoji(text)) + "</li>";
}
};
markedRenderer.checkbox = function(checked){
return checked ? '<i class="fa fa-check-square"></i> ' : '<i class="fa fa-square-o"></i> ';
};
2017-04-26 18:17:38 +08:00
return markedRenderer;
};
2017-04-26 18:17:38 +08:00
/**
*
* TOC(Table of Contents)
* Creating ToC (Table of Contents)
*
2017-04-26 18:17:38 +08:00
* @param {Array} toc markedTOC
* @param {Element} container TOC
* @param {Integer} startLevel Hx
* @returns {Object} tocContainer ToCjQuery
*/
2017-04-26 18:17:38 +08:00
editormd.markdownToCRenderer = function(toc, container, tocDropdown, startLevel) {
var html = "";
2017-04-26 18:17:38 +08:00
var lastLevel = 0;
var classPrefix = this.classPrefix;
2017-04-26 18:17:38 +08:00
startLevel = startLevel || 1;
for (var i = 0, len = toc.length; i < len; i++)
2017-04-26 18:17:38 +08:00
{
var text = toc[i].text;
var level = toc[i].level;
2018-09-11 18:36:42 +08:00
var id = toc[i].id;
2017-04-26 18:17:38 +08:00
if (level < startLevel) {
continue;
}
if (level > lastLevel)
2017-04-26 18:17:38 +08:00
{
html += "";
}
else if (level < lastLevel)
2017-04-26 18:17:38 +08:00
{
2018-09-11 18:36:42 +08:00
// html += (new Array(lastLevel - level + 2)).join("</ul></li>");
}
else
2017-04-26 18:17:38 +08:00
{
2018-09-11 18:36:42 +08:00
// html += "</ul></li>";
2017-04-26 18:17:38 +08:00
}
2018-09-11 18:36:42 +08:00
html += "<li class=\"directory-item\"><a class=\"directory-item-link directory-item-link-" + level + "\" href=\"#" + id + "\" level=\"" + level + "\">" + text + "</a></li>";
2017-04-26 18:17:38 +08:00
lastLevel = level;
}
2018-09-11 18:36:42 +08:00
console.log(html);
2017-04-26 18:17:38 +08:00
var tocContainer = container.find(".markdown-toc");
2017-04-26 18:17:38 +08:00
if ((tocContainer.length < 1 && container.attr("previewContainer") === "false"))
{
var tocHTML = "<div class=\"markdown-toc " + classPrefix + "markdown-toc\"></div>";
2017-04-26 18:17:38 +08:00
tocHTML = (tocDropdown) ? "<div class=\"" + classPrefix + "toc-menu\">" + tocHTML + "</div>" : tocHTML;
2017-04-26 18:17:38 +08:00
container.html(tocHTML);
2017-04-26 18:17:38 +08:00
tocContainer = container.find(".markdown-toc");
}
2017-04-26 18:17:38 +08:00
if (tocDropdown)
{
tocContainer.wrap("<div class=\"" + classPrefix + "toc-menu\"></div><br/>");
}
2017-04-26 18:17:38 +08:00
tocContainer.html("<ul class=\"markdown-toc-list\"></ul>").children(".markdown-toc-list").html(html.replace(/\r?\n?\<ul\>\<\/ul\>/g, ""));
2017-04-26 18:17:38 +08:00
return tocContainer;
};
2017-04-26 18:17:38 +08:00
/**
*
* TOC
* Creating ToC dropdown menu
*
2017-04-26 18:17:38 +08:00
* @param {Object} container TOCjQuery
* @param {String} tocTitle ToC title
* @returns {Object} return toc-menu object
*/
2017-04-26 18:17:38 +08:00
editormd.tocDropdownMenu = function(container, tocTitle) {
2017-04-26 18:17:38 +08:00
tocTitle = tocTitle || "Table of Contents";
2017-04-26 18:17:38 +08:00
var zindex = 400;
var tocMenus = container.find("." + this.classPrefix + "toc-menu");
tocMenus.each(function() {
var $this = $(this);
var toc = $this.children(".markdown-toc");
var icon = "<i class=\"fa fa-angle-down\"></i>";
var btn = "<a href=\"javascript:;\" class=\"toc-menu-btn\">" + icon + tocTitle + "</a>";
var menu = toc.children("ul");
2017-04-26 18:17:38 +08:00
var list = menu.find("li");
2017-04-26 18:17:38 +08:00
toc.append(btn);
2017-04-26 18:17:38 +08:00
list.first().before("<li><h1>" + tocTitle + " " + icon + "</h1></li>");
2017-04-26 18:17:38 +08:00
$this.mouseover(function(){
menu.show();
list.each(function(){
var li = $(this);
var ul = li.children("ul");
if (ul.html() === "")
{
ul.remove();
}
if (ul.length > 0 && ul.html() !== "")
{
var firstA = li.children("a").first();
if (firstA.children(".fa").length < 1)
{
firstA.append( $(icon).css({ float:"right", paddingTop:"4px" }) );
}
}
li.mouseover(function(){
ul.css("z-index", zindex).show();
zindex += 1;
}).mouseleave(function(){
ul.hide();
});
});
}).mouseleave(function(){
menu.hide();
});
});
2017-04-26 18:17:38 +08:00
return tocMenus;
};
2017-04-26 18:17:38 +08:00
/**
* HTML
* Filter custom html tags
*
2017-04-26 18:17:38 +08:00
* @param {String} html HTML
* @param {String} filters
* @returns {String} html HTML
*/
2017-04-26 18:17:38 +08:00
editormd.filterHTMLTags = function(html, filters) {
2017-04-26 18:17:38 +08:00
if (typeof html !== "string") {
html = new String(html);
}
2017-04-26 18:17:38 +08:00
if (typeof filters !== "string") {
return html;
}
var expression = filters.split("|");
var filterTags = expression[0].split(",");
var attrs = expression[1];
for (var i = 0, len = filterTags.length; i < len; i++)
{
var tag = filterTags[i];
html = html.replace(new RegExp("\<\s*" + tag + "\s*([^\>]*)\>([^\>]*)\<\s*\/" + tag + "\s*\>", "igm"), "");
}
2017-04-26 18:17:38 +08:00
//return html;
if (typeof attrs !== "undefined")
{
var htmlTagRegex = /\<(\w+)\s*([^\>]*)\>([^\>]*)\<\/(\w+)\>/ig;
if (attrs === "*")
{
html = html.replace(htmlTagRegex, function($1, $2, $3, $4, $5) {
return "<" + $2 + ">" + $4 + "</" + $5 + ">";
});
2017-04-26 18:17:38 +08:00
}
else if (attrs === "on*")
{
html = html.replace(htmlTagRegex, function($1, $2, $3, $4, $5) {
var el = $("<" + $2 + ">" + $4 + "</" + $5 + ">");
var _attrs = $($1)[0].attributes;
var $attrs = {};
2017-04-26 18:17:38 +08:00
$.each(_attrs, function(i, e) {
if (e.nodeName !== '"') $attrs[e.nodeName] = e.nodeValue;
});
$.each($attrs, function(i) {
2017-04-26 18:17:38 +08:00
if (i.indexOf("on") === 0) {
delete $attrs[i];
}
});
2017-04-26 18:17:38 +08:00
el.attr($attrs);
2017-04-26 18:17:38 +08:00
var text = (typeof el[1] !== "undefined") ? $(el[1]).text() : "";
return el[0].outerHTML + text;
});
}
else
{
html = html.replace(htmlTagRegex, function($1, $2, $3, $4) {
var filterAttrs = attrs.split(",");
var el = $($1);
el.html($4);
$.each(filterAttrs, function(i) {
el.attr(filterAttrs[i], null);
});
return el[0].outerHTML;
});
}
}
2017-04-26 18:17:38 +08:00
return html;
};
2017-04-26 18:17:38 +08:00
/**
* MarkdownHTML
* Parse Markdown to HTML for Font-end preview.
*
2017-04-26 18:17:38 +08:00
* @param {String} id HTMLID
* @param {Object} [options={}]
* @returns {Object} div jQuery
*/
2017-04-26 18:17:38 +08:00
editormd.markdownToHTML = function(id, options) {
var defaults = {
gfm : true,
toc : true,
tocm : false,
tocStartLevel : 1,
tocTitle : "目录",
tocDropdown : false,
tocContainer : "",
markdown : "",
markdownSourceCode : false,
htmlDecode : false,
autoLoadKaTeX : true,
pageBreak : true,
atLink : true, // for @link
emailLink : true, // for mail address auto link
tex : false,
taskList : false, // Github Flavored Markdown task lists
emoji : false,
flowChart : false,
sequenceDiagram : false,
previewCodeHighlight : true,
mermaid : true,
mindMap : true, //思维导图
2017-04-26 18:17:38 +08:00
};
2017-04-26 18:17:38 +08:00
editormd.$marked = marked;
var div = $("#" + id);
var settings = div.settings = $.extend(true, defaults, options || {});
var saveTo = div.find("textarea");
2017-04-26 18:17:38 +08:00
if (saveTo.length < 1)
{
div.append("<textarea></textarea>");
saveTo = div.find("textarea");
}
var markdownDoc = (settings.markdown === "") ? saveTo.val() : settings.markdown;
2017-04-26 18:17:38 +08:00
var markdownToC = [];
var rendererOptions = {
2017-04-26 18:17:38 +08:00
toc : settings.toc,
tocm : settings.tocm,
tocStartLevel : settings.tocStartLevel,
taskList : settings.taskList,
emoji : settings.emoji,
tex : settings.tex,
pageBreak : settings.pageBreak,
atLink : settings.atLink, // for @link
emailLink : settings.emailLink, // for mail address auto link
flowChart : settings.flowChart,
sequenceDiagram : settings.sequenceDiagram,
mermaid : settings.mermaid,
mindMap : settings.mindMap, // 思维导图
2017-04-26 18:17:38 +08:00
previewCodeHighlight : settings.previewCodeHighlight,
};
var markedOptions = {
renderer : editormd.markedRenderer(markdownToC, rendererOptions),
gfm : settings.gfm,
tables : true,
breaks : true,
pedantic : false,
sanitize : (settings.htmlDecode) ? false : true, // 是否忽略HTML标签即是否开启HTML标签解析为了安全性默认不开启
smartLists : true,
smartypants : true
};
2017-04-26 18:17:38 +08:00
markdownDoc = new String(markdownDoc);
2017-04-26 18:17:38 +08:00
var markdownParsed = marked(markdownDoc, markedOptions);
2017-04-26 18:17:38 +08:00
markdownParsed = editormd.filterHTMLTags(markdownParsed, settings.htmlDecode);
2017-04-26 18:17:38 +08:00
if (settings.markdownSourceCode) {
saveTo.text(markdownDoc);
} else {
saveTo.remove();
}
2017-04-26 18:17:38 +08:00
div.addClass("markdown-body " + this.classPrefix + "html-preview").append(markdownParsed);
2017-04-26 18:17:38 +08:00
var tocContainer = (settings.tocContainer !== "") ? $(settings.tocContainer) : div;
2017-04-26 18:17:38 +08:00
if (settings.tocContainer !== "")
{
tocContainer.attr("previewContainer", false);
}
if (settings.toc)
2017-04-26 18:17:38 +08:00
{
div.tocContainer = this.markdownToCRenderer(markdownToC, tocContainer, settings.tocDropdown, settings.tocStartLevel);
2017-04-26 18:17:38 +08:00
if (settings.tocDropdown || div.find("." + this.classPrefix + "toc-menu").length > 0)
{
this.tocDropdownMenu(div, settings.tocTitle);
}
2017-04-26 18:17:38 +08:00
if (settings.tocContainer !== "")
{
div.find(".editormd-toc-menu, .editormd-markdown-toc").remove();
}
}
if (settings.previewCodeHighlight)
2017-04-26 18:17:38 +08:00
{
div.find("pre").addClass("prettyprint");
2017-04-26 18:17:38 +08:00
prettyPrint();
}
if (!editormd.isIE8)
2017-04-26 18:17:38 +08:00
{
if (settings.flowChart) {
div.find(".flowchart").flowChart();
2017-04-26 18:17:38 +08:00
}
if (settings.sequenceDiagram) {
div.find(".sequence-diagram").sequenceDiagram({theme: "simple"});
}
if (settings.mermaid) {
window.mermaid.init(void 0, div.find(".lang-mermaid"));
}
2017-04-26 18:17:38 +08:00
}
if (settings.tex)
{
var katexHandle = function() {
div.find("." + editormd.classNames.tex).each(function(){
var tex = $(this);
katex.render(tex.html().replace(/&lt;/g, "<").replace(/&gt;/g, ">"), tex[0]);
2017-04-26 18:17:38 +08:00
tex.find(".katex").css("font-size", "1.6em");
});
};
2017-04-26 18:17:38 +08:00
if (settings.autoLoadKaTeX && !editormd.$katex && !editormd.kaTeXLoaded)
{
this.loadKaTeX(function() {
editormd.$katex = katex;
editormd.kaTeXLoaded = true;
katexHandle();
});
}
else
{
katexHandle();
}
}
// 前台渲染脑图
if(settings.mindMap){
var mindmapHandle = function(){
div.find(".mindmap").each(function(){
var mmap = $(this);
var md_data = window.markmap.transform(mmap.text().trim());
window.markmap.markmap("svg#"+this.id,md_data)
});
}
mindmapHandle();
}
div.getMarkdown = function() {
2017-04-26 18:17:38 +08:00
return saveTo.val();
};
2017-04-26 18:17:38 +08:00
return div;
};
2017-04-26 18:17:38 +08:00
// Editor.md themes, change toolbar themes etc.
// added @1.5.0
editormd.themes = ["default", "dark"];
2017-04-26 18:17:38 +08:00
// Preview area themes
// added @1.5.0
editormd.previewThemes = ["default", "dark"];
2017-04-26 18:17:38 +08:00
// CodeMirror / editor area themes
// @1.5.0 rename -> editorThemes, old version -> themes
editormd.editorThemes = [
"default", "3024-day", "3024-night",
"ambiance", "ambiance-mobile",
"base16-dark", "base16-light", "blackboard",
"cobalt",
"eclipse", "elegant", "erlang-dark",
"lesser-dark",
"mbo", "mdn-like", "midnight", "monokai",
"neat", "neo", "night",
"paraiso-dark", "paraiso-light", "pastel-on-dark",
"rubyblue",
"solarized",
"the-matrix", "tomorrow-night-eighties", "twilight",
"vibrant-ink",
"xq-dark", "xq-light"
];
editormd.loadPlugins = {};
2017-04-26 18:17:38 +08:00
editormd.loadFiles = {
js : [],
css : [],
plugin : []
};
2017-04-26 18:17:38 +08:00
/**
* Editor.md
* Load editor.md plugins
*
2017-04-26 18:17:38 +08:00
* @param {String} fileName
* @param {Function} [callback=function()]
* @param {String} [into="head"]
*/
2017-04-26 18:17:38 +08:00
editormd.loadPlugin = function(fileName, callback, into) {
callback = callback || function() {};
2017-04-26 18:17:38 +08:00
this.loadScript(fileName, function() {
editormd.loadFiles.plugin.push(fileName);
callback();
}, into);
};
2017-04-26 18:17:38 +08:00
/**
* CSS
* Load css file method
*
2017-04-26 18:17:38 +08:00
* @param {String} fileName CSS
* @param {Function} [callback=function()]
* @param {String} [into="head"]
*/
2017-04-26 18:17:38 +08:00
editormd.loadCSS = function(fileName, callback, into) {
into = into || "head";
2017-04-26 18:17:38 +08:00
callback = callback || function() {};
2017-04-26 18:17:38 +08:00
var css = document.createElement("link");
css.type = "text/css";
css.rel = "stylesheet";
css.onload = css.onreadystatechange = function() {
editormd.loadFiles.css.push(fileName);
callback();
};
css.href = fileName + ".css";
if(into === "head") {
document.getElementsByTagName("head")[0].appendChild(css);
} else {
document.body.appendChild(css);
}
};
2017-04-26 18:17:38 +08:00
editormd.isIE = (navigator.appName == "Microsoft Internet Explorer");
editormd.isIE8 = (editormd.isIE && navigator.appVersion.match(/8./i) == "8.");
/**
* JS
* Load javascript file method
*
2017-04-26 18:17:38 +08:00
* @param {String} fileName JS
* @param {Function} [callback=function()]
* @param {String} [into="head"]
*/
editormd.loadScript = function(fileName, callback, into) {
2017-04-26 18:17:38 +08:00
into = into || "head";
callback = callback || function() {};
var script = null;
2017-04-26 18:17:38 +08:00
script = document.createElement("script");
script.id = fileName.replace(/[\./]+/g, "-");
script.type = "text/javascript";
2017-04-26 18:17:38 +08:00
script.src = fileName + ".js";
if (editormd.isIE8)
{
2017-04-26 18:17:38 +08:00
script.onreadystatechange = function() {
if(script.readyState)
2017-04-26 18:17:38 +08:00
{
if (script.readyState === "loaded" || script.readyState === "complete")
2017-04-26 18:17:38 +08:00
{
script.onreadystatechange = null;
2017-04-26 18:17:38 +08:00
editormd.loadFiles.js.push(fileName);
callback();
}
}
2017-04-26 18:17:38 +08:00
};
}
else
{
script.onload = function() {
editormd.loadFiles.js.push(fileName);
callback();
};
}
if (into === "head") {
document.getElementsByTagName("head")[0].appendChild(script);
} else {
document.body.appendChild(script);
}
};
2017-04-26 18:17:38 +08:00
// 使用国外的CDN加载速度有时会很慢或者自定义URL
// You can custom KaTeX load url.
editormd.katexURL = {
css : "//cdnjs.cloudflare.com/ajax/libs/KaTeX/0.3.0/katex.min",
js : "//cdnjs.cloudflare.com/ajax/libs/KaTeX/0.3.0/katex.min"
};
2017-04-26 18:17:38 +08:00
editormd.kaTeXLoaded = false;
2017-04-26 18:17:38 +08:00
/**
* KaTeX
* load KaTeX files
*
2017-04-26 18:17:38 +08:00
* @param {Function} [callback=function()]
*/
2017-04-26 18:17:38 +08:00
editormd.loadKaTeX = function (callback) {
editormd.loadCSS(editormd.katexURL.css, function(){
editormd.loadScript(editormd.katexURL.js, callback || function(){});
});
};
2017-04-26 18:17:38 +08:00
/**
*
* lock screen
*
2017-04-26 18:17:38 +08:00
* @param {Boolean} lock Boolean
* @returns {void}
*/
2017-04-26 18:17:38 +08:00
editormd.lockScreen = function(lock) {
$("html,body").css("overflow", (lock) ? "hidden" : "");
};
2017-04-26 18:17:38 +08:00
/**
*
* Creating custom dialogs
*
2017-04-26 18:17:38 +08:00
* @param {Object} options Key/Value
* @returns {dialog} dialogjQuery
*/
editormd.createDialog = function(options) {
var defaults = {
name : "",
width : 420,
height: 240,
title : "",
drag : true,
closed : true,
content : "",
mask : true,
maskStyle : {
backgroundColor : "#fff",
opacity : 0.1
},
lockScreen : true,
footer : true,
buttons : false
};
options = $.extend(true, defaults, options);
2017-04-26 18:17:38 +08:00
var $this = this;
var editor = this.editor;
var classPrefix = editormd.classPrefix;
var guid = (new Date()).getTime();
var dialogName = ( (options.name === "") ? classPrefix + "dialog-" + guid : options.name);
var mouseOrTouch = editormd.mouseOrTouch;
var html = "<div class=\"" + classPrefix + "dialog " + dialogName + "\">";
if (options.title !== "")
{
html += "<div class=\"" + classPrefix + "dialog-header\"" + ( (options.drag) ? " style=\"cursor: move;\"" : "" ) + ">";
html += "<strong class=\"" + classPrefix + "dialog-title\">" + options.title + "</strong>";
html += "</div>";
}
if (options.closed)
{
html += "<a href=\"javascript:;\" class=\"fa fa-close " + classPrefix + "dialog-close\"></a>";
}
html += "<div class=\"" + classPrefix + "dialog-container\">" + options.content;
2017-04-26 18:17:38 +08:00
if (options.footer || typeof options.footer === "string")
2017-04-26 18:17:38 +08:00
{
html += "<div class=\"" + classPrefix + "dialog-footer\">" + ( (typeof options.footer === "boolean") ? "" : options.footer) + "</div>";
}
html += "</div>";
html += "<div class=\"" + classPrefix + "dialog-mask " + classPrefix + "dialog-mask-bg\"></div>";
html += "<div class=\"" + classPrefix + "dialog-mask " + classPrefix + "dialog-mask-con\"></div>";
html += "</div>";
editor.append(html);
var dialog = editor.find("." + dialogName);
dialog.lockScreen = function(lock) {
if (options.lockScreen)
{
2017-04-26 18:17:38 +08:00
$("html,body").css("overflow", (lock) ? "hidden" : "");
$this.resize();
}
return dialog;
};
dialog.showMask = function() {
if (options.mask)
{
editor.find("." + classPrefix + "mask").css(options.maskStyle).css("z-index", editormd.dialogZindex - 1).show();
}
return dialog;
};
dialog.hideMask = function() {
if (options.mask)
{
editor.find("." + classPrefix + "mask").hide();
}
return dialog;
};
dialog.loading = function(show) {
2017-04-26 18:17:38 +08:00
var loading = dialog.find("." + classPrefix + "dialog-mask");
loading[(show) ? "show" : "hide"]();
return dialog;
};
dialog.lockScreen(true).showMask();
dialog.show().css({
zIndex : editormd.dialogZindex,
border : (editormd.isIE8) ? "1px solid #ddd" : "",
width : (typeof options.width === "number") ? options.width + "px" : options.width,
height : (typeof options.height === "number") ? options.height + "px" : options.height
});
var dialogPosition = function(){
dialog.css({
top : ($(window).height() - dialog.height()) / 2 + "px",
left : ($(window).width() - dialog.width()) / 2 + "px"
});
};
dialogPosition();
$(window).resize(dialogPosition);
dialog.children("." + classPrefix + "dialog-close").bind(mouseOrTouch("click", "touchend"), function() {
dialog.hide().lockScreen(false).hideMask();
});
if (typeof options.buttons === "object")
{
var footer = dialog.footer = dialog.find("." + classPrefix + "dialog-footer");
for (var key in options.buttons)
{
var btn = options.buttons[key];
var btnClassName = classPrefix + key + "-btn";
footer.append("<button class=\"" + classPrefix + "btn " + btnClassName + "\">" + btn[0] + "</button>");
btn[1] = $.proxy(btn[1], dialog);
footer.children("." + btnClassName).bind(mouseOrTouch("click", "touchend"), btn[1]);
}
}
if (options.title !== "" && options.drag)
{
2017-04-26 18:17:38 +08:00
var posX, posY;
var dialogHeader = dialog.children("." + classPrefix + "dialog-header");
if (!options.mask) {
dialogHeader.bind(mouseOrTouch("click", "touchend"), function(){
editormd.dialogZindex += 2;
dialog.css("z-index", editormd.dialogZindex);
});
}
dialogHeader.mousedown(function(e) {
e = e || window.event; //IE
posX = e.clientX - parseInt(dialog[0].style.left);
posY = e.clientY - parseInt(dialog[0].style.top);
document.onmousemove = moveAction;
2017-04-26 18:17:38 +08:00
});
var userCanSelect = function (obj) {
obj.removeClass(classPrefix + "user-unselect").off("selectstart");
};
var userUnselect = function (obj) {
obj.addClass(classPrefix + "user-unselect").on("selectstart", function(event) { // selectstart for IE
2017-04-26 18:17:38 +08:00
return false;
});
};
var moveAction = function (e) {
e = e || window.event; //IE
var left, top, nowLeft = parseInt(dialog[0].style.left), nowTop = parseInt(dialog[0].style.top);
if( nowLeft >= 0 ) {
if( nowLeft + dialog.width() <= $(window).width()) {
left = e.clientX - posX;
} else {
2017-04-26 18:17:38 +08:00
left = $(window).width() - dialog.width();
document.onmousemove = null;
}
} else {
left = 0;
document.onmousemove = null;
}
if( nowTop >= 0 ) {
top = e.clientY - posY;
} else {
top = 0;
document.onmousemove = null;
}
document.onselectstart = function() {
return false;
};
userUnselect($("body"));
userUnselect(dialog);
dialog[0].style.left = left + "px";
dialog[0].style.top = top + "px";
};
document.onmouseup = function() {
2017-04-26 18:17:38 +08:00
userCanSelect($("body"));
userCanSelect(dialog);
document.onselectstart = null;
2017-04-26 18:17:38 +08:00
document.onmousemove = null;
};
dialogHeader.touchDraggable = function() {
var offset = null;
var start = function(e) {
var orig = e.originalEvent;
2017-04-26 18:17:38 +08:00
var pos = $(this).parent().position();
offset = {
x : orig.changedTouches[0].pageX - pos.left,
y : orig.changedTouches[0].pageY - pos.top
};
};
var move = function(e) {
e.preventDefault();
var orig = e.originalEvent;
$(this).parent().css({
top : orig.changedTouches[0].pageY - offset.y,
left : orig.changedTouches[0].pageX - offset.x
});
};
this.bind("touchstart", start).bind("touchmove", move);
};
dialogHeader.touchDraggable();
}
editormd.dialogZindex += 2;
return dialog;
};
2017-04-26 18:17:38 +08:00
/**
* /
* MouseEvent or TouchEvent type switch
*
2017-04-26 18:17:38 +08:00
* @param {String} [mouseEventType="click"]
* @param {String} [touchEventType="touchend"]
* @returns {String} EventType
*/
2017-04-26 18:17:38 +08:00
editormd.mouseOrTouch = function(mouseEventType, touchEventType) {
mouseEventType = mouseEventType || "click";
touchEventType = touchEventType || "touchend";
2017-04-26 18:17:38 +08:00
var eventType = mouseEventType;
try {
document.createEvent("TouchEvent");
eventType = touchEventType;
} catch(e) {}
return eventType;
};
2017-04-26 18:17:38 +08:00
/**
*
* Datetime format method
*
2017-04-26 18:17:38 +08:00
* @param {String} [format=""] PHP
* @returns {String} datefmt
*/
editormd.dateFormat = function(format) {
2017-04-26 18:17:38 +08:00
format = format || "";
var addZero = function(d) {
return (d < 10) ? "0" + d : d;
};
var date = new Date();
2017-04-26 18:17:38 +08:00
var year = date.getFullYear();
var year2 = year.toString().slice(2, 4);
var month = addZero(date.getMonth() + 1);
var day = addZero(date.getDate());
var weekDay = date.getDay();
var hour = addZero(date.getHours());
var min = addZero(date.getMinutes());
var second = addZero(date.getSeconds());
var ms = addZero(date.getMilliseconds());
2017-04-26 18:17:38 +08:00
var datefmt = "";
var ymd = year2 + "-" + month + "-" + day;
var fymd = year + "-" + month + "-" + day;
var hms = hour + ":" + min + ":" + second;
switch (format)
2017-04-26 18:17:38 +08:00
{
case "UNIX Time" :
datefmt = date.getTime();
break;
case "UTC" :
datefmt = date.toUTCString();
break;
2017-04-26 18:17:38 +08:00
case "yy" :
datefmt = year2;
break;
2017-04-26 18:17:38 +08:00
case "year" :
case "yyyy" :
datefmt = year;
break;
case "month" :
case "mm" :
datefmt = month;
break;
2017-04-26 18:17:38 +08:00
case "cn-week-day" :
case "cn-wd" :
var cnWeekDays = ["日", "一", "二", "三", "四", "五", "六"];
datefmt = "星期" + cnWeekDays[weekDay];
break;
case "week-day" :
case "wd" :
var weekDays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
datefmt = weekDays[weekDay];
break;
case "day" :
case "dd" :
datefmt = day;
break;
case "hour" :
case "hh" :
datefmt = hour;
break;
case "min" :
case "ii" :
datefmt = min;
break;
case "second" :
case "ss" :
datefmt = second;
break;
case "ms" :
datefmt = ms;
break;
case "yy-mm-dd" :
datefmt = ymd;
break;
case "yyyy-mm-dd" :
datefmt = fymd;
break;
case "yyyy-mm-dd h:i:s ms" :
case "full + ms" :
2017-04-26 18:17:38 +08:00
datefmt = fymd + " " + hms + " " + ms;
break;
case "full" :
case "yyyy-mm-dd h:i:s" :
default:
datefmt = fymd + " " + hms;
break;
}
return datefmt;
};
/**
*
* @param n
* @returns {*}
*/
editormd.getLine = function(n) {
return this.cm.getLine(n);
};
2017-04-26 18:17:38 +08:00
return editormd;
}));