markdown online editor editor.md secondary development detailed tutorial

Keywords: PHP html5 html

Secondary development of markdown online editor editor.md

demand

It is often necessary to publish articles in online forums for publicity, but the writing format of each forum is different, which brings great obstacles to the publication.

The recent rise of markdown format has brought good news to the majority of publishers. A document format is supported by most websites and can be published on multiple forums at one time.

How to write markdown online has become a requirement.

markdown editor

After searching and comparing, it is found that editor.md is an open source markdown editor, which is very good, rich in examples and easy to use.

After actual testing, editor.md found several small requirements:

  • Customize Toolbar
    Adding what you need is very helpful
  • You cannot quickly move the cursor to the end of a document
    If the document is large, it is troublesome to move to the end of the document
  • Unable to upload picture
    You need to configure the server php to support it
  • Unable to copy and paste pictures for upload
    This function is very useful
  • Save content to browser periodically
    Once the computer crashes, the content written is gone

Create an online markdown editor

Customize Toolbar

Add the following three configurations to the index.html file to add HTML code in the toolbar

toolbarIcons : function() {
      var toolBarIconArray=editormd.toolbarModes["full"];
	toolBarIconArray.push("aboutus");
    return toolBarIconArray;
        },

Custom html code

toolbarCustomIcons : {
            aboutus   :"<a href=\"http://u.720life.cn/s/75244496\" target=\"_ blank\"  onclick=\"window.location.href=' http://u.720life.cn/s/75244496 '\ "> AC Q group: 1142802013 < / a >" 
        },

editor.md move cursor quickly

After studying the editor.md function, it is found that there is the function of moving the cursor. You can specify how many lines to move the cursor. It is slightly more complex to use and needs to be input by the user

1. Add gfirst and GLAST in editormd.js

  full: [
          "undo",
          "redo",
    	  "|",
    	  "gfirst", //New addition
    	  "glast",  //New addition
          "|",

2. Add description information and the description when the mouse is put up

     toolbar: {
            undo: "Rescind( Ctrl+Z)",
            redo: "Redo( Ctrl+Y)",
    		gfirst: "Back to the top",
    		glast: "Bottom end",
            bold: "bold",

3. Definition of Icon

    toolbarIconsClass: {
          undo: "fa-undo",
          redo: "fa-repeat",
    	  gfirst: "fa-arrow-up",
    	  glast: "fa-arrow-down",
          bold: "fa-bold",

4. Specific implementation function code

     editormd.toolbarHandlers = {
        undo: function() {
          this.cm.undo()
        },
        redo: function() {
          this.cm.redo()
        },
    	gfirst: function() {
    		  this.gotoLine("first")
    	},
    	glast: function() {
    		  this.gotoLine("last")
    	},

Note: at first, I thought gotoLine was a function of this.cm.gotoLine, but it always reported errors. Finally, I found that the function under cm should be under \ lib\codemirror\lib\codemirror.js, so I can write this.gotoLine directly

File upload function modification

  • Support absolute path return
    php/upload.php
	$path     = getcwd() . DIRECTORY_SEPARATOR;
	//$url      = dirname($_SERVER['PHP_SELF']) . '/';
	$url = $_SERVER["REQUEST_SCHEME"] .'://'.$_SERVER['HTTP_HOST'] . '/';
	//Record by month
	$_time = date('Ym');
	//Whether the user is a free user free user pay_token
    $savePath = $path . '../../uploads/free/';
    // Create images directory
    if (!file_exists($savePath)) mkdir($savePath);
    $savePath = $savePath . $_time.DIRECTORY_SEPARATOR;

    // Create month directory
    if (!file_exists($savePath)) mkdir($savePath);

    $saveURL  = $url . 'uploads/free/'.$_time.DIRECTORY_SEPARATOR;
  • Failed to save changes to the file path
    php/upload.php
$imageUploader = new EditorMdUploader($savePath, $saveURL, $formats['image'],  1, 'H_i_s');

The browser js reads the clipboard image and uploads it to the server

document.addEventListener("paste", function (e) {
    var cbd = e.clipboardData;
    var ua = window.navigator.userAgent;

    // If it's Safari, return directly
    if ( !(e.clipboardData && e.clipboardData.items) ) {
        return;
    }
    
    // Copy the Bug Hack of the file in Finder under chrome 49 on Mac platform
    if(cbd.items && cbd.items.length === 2 && cbd.items[0].kind === "string" && cbd.items[1].kind === "file" &&
        cbd.types && cbd.types.length === 2 && cbd.types[0] === "text/plain" && cbd.types[1] === "Files" &&
        ua.match(/Macintosh/i) && Number(ua.match(/Chrome\/(\d{2})/i)[1]) < 49){
        return;
    }

    for(var i = 0; i < cbd.items.length; i++) {
        var item = cbd.items[i];
        if(item.kind == "file"){
            var blob = item.getAsFile();
            if (blob.size === 0) {
                return;
            }
			
            // blob is the file obtained from the clipboard, which can be uploaded or other operations
			
			var data = new FormData();
	        data.append("blob", blob);
	        $.ajax({
				url : "php/blob_upload.php",
				type : 'POST',
				cache : false,
				data : data,
				processData : false,
				contentType : false,
				success : function(result){
				
				var   json = (typeof JSON.parse !== "undefined") ? JSON.parse(result) : eval("(" + result + ")");
					if(json.success == 1){
					   //Upload succeeded
					
					   testEditor.cm.replaceSelection("![](" + json.url + ")");
						
					}
				}
	        });

			
        }
    }
}, false);		
			

The function can be realized by putting the code into the html page. At present, it is confirmed that chrome and Firefox can be supported. You can copy the screenshots from wechat, QQ and win7 and paste them directly on the page

Save the current document locally every 30 seconds

index.html sets a 30 second timer to save the current content to the local localstore. The code is as follows:

function save_content(){
       
	if (localStorage) {
		localStorage["content"] =$(".editormd-markdown-textarea").val();
	}
}
setInterval("save_content()",30000);  // Once in 30s 

When opening the web page, first judge whether there is localStorage. The code is as follows:

 $(document).ready(function(){
            
      
            var isHave = false;

            if (localStorage) {
              if(localStorage.content && localStorage.content.length > 0) {
                 md = localStorage.content;
            	 isHave = true;
              }
            }
            if(!isHave){                 
				$.ajax({
					url : 'test.md',
					cache : false,
					async : false,
					type : "GET",
					dataType : 'html',
					success : function (result){
					   md = result;
					}
				});
            } // endif isHave

Deployment scheme

Since most of the project are static resources and only have three API interfaces, it is recommended to separate the three API interfaces and host the static documents on the cloud

It can be placed in hosted warehouses such as qiniu cloud or gitee

markdown online document editor

Online markdown document editor

Tools are suitable for people

There are several scenarios for using this tool:

  • Temporary online preparation of markdown format record form
    For example, it is very convenient to write a work plan for this week and delete one after execution. It is automatically saved in less than 30 seconds
  • Write a markdown promotion article to preview the effect

Official QQ communication

If you have any questions, welcome to join the official exchange Q group discussion

Official communication Q group: 1142802013

thank

thank editor.md Project, very excellent

TODO

  • When the page is opened for the first time, a markdown document is randomly displayed
  • Speed up loading

Posted by Lord Brar on Fri, 15 Oct 2021 10:35:51 -0700