利用Electron简单撸一个Markdown编辑器的方法

2020-06-14 06:02:16易采站长站整理

this.estore.set('footercontent', `<hr>
<strong>coding01 期待您继续关注</strong>
<img src="http://bimage.coding01.cn/coding01_me.GIF" alt="qrcode">`)
}

// This will just return the property on the `data` object
get(key, val) {
return this.estore.get('windowBounds', val)
}

// ...and this will set it
set(key, val) {
this.estore.set(key, val)
}

getContent(content) {
return this.headerContent + content + this.footerContent
}

getHeaderContent() {
return this.estore.get('headercontent', '')
}

getFooterContent() {
return this.estore.get('footercontent', '')
}
}

// expose the class
export default Content

注:这里只是写死的头部和尾部内容。

有了头尾部内容,和编辑器的 Markdown 内容,我们就可以将这些内容整合,然后输出给我们的右侧

Preview
组件了。


ipcMain.on('newContentToRender', function(event, content) {
const rendered = renderContent(headerContent, footerContent, content, cssContent, 'layout1.html');

const previewURL = newContent(rendered);
mainWindow.webContents.send('newContentToPreview', previewURL);
});

其中,

renderContent(headerContent, footerContent, content, cssContent, 'layout1.html')
方法就是将我们的头部、尾部、Markdown内容、css 样式和我们的模板
layout1.html
载入。这个就比较简单了,直接看代码:


import mdit from 'markdown-it';
import ejs from 'ejs';

const mditConfig = {
html: true, // Enable html tags in source
xhtmlOut: true, // Use '/' to close single tags (<br />)
breaks: false, // Convert 'n' in paragraphs into <br>
// langPrefix: 'language-', // CSS language prefix for fenced blocks
linkify: true, // Autoconvert url-like texts to links
typographer: false, // Enable smartypants and other sweet transforms

// Highlighter function. Should return escaped html,
// or '' if input not changed
highlight: function (/*str, , lang*/) { return ''; }
};
const md = mdit(mditConfig);

const layouts = [];

export function renderContent(headerContent, footerContent, content, cssContent, layoutFile) {
const text = md.render(content);
const layout = layouts[layoutFile];
const rendered = ejs.render(layout, {
title: 'Page Title',
content: text,
cssContent: cssContent,
headerContent: headerContent,
footerContent: footerContent,
});
return rendered;
}

layouts['layout1.html'] = `
<html>