There are usually two ways to edit a template

  • Rich text editor
  • markdown

whileSimpleMDEMarkdown is a simple, embeddable and beautiful JS markdown editor that can be extended with scenarios in addition to regular use.

We can see the NuggetsmarkdownEditor support picture drag upload, after the completion of the upload to their own cloud storage space, and generated link address automatically filled up. Is not very convenient, let’s combineSimpleMDETo achieve the same functional effect.

Technology stack selectionuni-app

Rely on

"dependencies": {
    "font-awesome": "^ 4.7.0"."github-markdown-css": "^ 4.0.0"."marked": "^ 2.0.0." "."simplemde": "^ 1.11.2." "
},
Copy the code

To achieve the idea, it is recommended to extract components

First take a look attemplatePart of it. Easy. Prepare onetextareaLabels are fine.
<template>
  <view class="simple-mde" :class="classes">
    <textarea ref="mde"></textarea>
  </view>
</template>
Copy the code
Be sure to instantiate our DOM after it is mountedSimpleMDE.
this.mde = newSimpleMDE({ ... config,// This can be interpreted as the parent component passing in the configuration
  initialValue: this.value,	// Edit the contents of the box
  element: this.$refs.mde.$el.querySelector('textarea'),	//el
})
Copy the code
mayelIt’s kind of a weird way to get it becauseuni-appCompile time putstextareaPack another layer, so mountelMake sure it’s browsertextareaThe label

Take a look at the effect of our reference, and the style can be used to suit your preferences.

And you can see that although we didn’t find the corresponding onedropEvent callback, howeverSimpleMDEProvides a clickableloadThe imageimage icon, justloadIs an empty link, now all we have to do is upload the image we want to use to our own cloud storage space and display it.

To find theSimpleMDESource code to find click on the image of the event here.

/** * Action for drawing an img. */
function drawImage(editor) {
	var cm = editor.codemirror;
	var stat = getState(cm);
	var options = editor.options;
	var url = "http://";
	if(options.promptURLs) {
		url = prompt(options.promptTexts.image);
		if(! url) {return false;
		}
	}
	_replaceSelection(cm, stat.image, options.insertTexts.image, url);
}
Copy the code

Let’s adapt it accordingly

function drawImage (editor) {
	let { uploadCallBack } = editor.options
	uni.chooseImage({
	   sizeType: ['compressed'].sourceType: ['album'].success(res){
             console.log(res)
             typeof uploadCallBack == 'function' && uploadCallBack.call(editor, res)
           }
	})
}
Copy the code
Through source code analysiseditorIs the context of the current constructor,editor.optionsThat is, we instantiate the parameter that is passed in and the parameter that it defines itself, so we define oneuploadCallBackThe callback takes care of receiving our instantiation, plus our upload operation. (the current isuni-appUpload API, if other technology stack can define one<input type="file" accept="image/*"/>To assist in uploading)

Receive the upload success callback we defined

this.mde = new SimpleMDE({
    initialValue: this.value,
    element: this.$refs.mde.$el.querySelector('textarea'),
    autoDownloadFontAwesome: false.promptURLs: true.uploadCallBack(res) {
      let editor = this
      uniCloud
        .uploadFile({
          filePath: res.tempFilePaths[0].cloudPath: `mm_The ${new Date().getTime()}.jpg`,
        })
        .then((res) = > {
          let { fileID } = res
          return uniCloud.getTempFileURL({
            fileList: [fileID],
          })
        })
        .then((res) = > {
          let { download_url } = res.fileList[0]
          editor.options.promptTexts['image'] = download_url
          editor.createImageUrl(editor)
        })
    },
  })
Copy the code
The uploaded picture can be stored in our cloud storage space, or it can be uploaded according to its own file server. Finally, the effective address of the successful upload can be re-assignededitor.options.promptTexts['image'] = download_url

Where does createImageUrl come from?

SimpleMDE.prototype.createImageUrl = function(editor){
	var cm = editor.codemirror;
	var stat = getState(cm);
	var options = editor.options;
	var url = "http://";
	if(options.promptURLs) {
		url = options.promptTexts.image;
		if(! url) {return false;
		}
	}
	_replaceSelection(cm, stat.image, options.insertTexts.image, url);
}
Copy the code
That’s what we replaceddrawImageLogic, only when executed againurl = options.promptTexts.imageIs no longer an empty link, but the real one we just uploaded to the serverurl. (Note: at this timepromptURLs:trueIs required, related explanation can be read 🙂

Github.com/sparksuite/…

And let’s see what happens

Isn’t it comfortable? Now you can happily edit markdown.

If you modify the source code of the dependency package, it will be overwritten the next time you install it.

Don’t worry, there are a lot of plan, details refer to segmentfault.com/q/101000002…

Code address: github.com/wumaimai/co…