mdToVue.js 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. const path = require('path');
  2. const fs = require('fs');
  3. const nodeFilelist = require('node-filelist');
  4. let { hashElement } = require('folder-hash');
  5. let marked = require('marked');
  6. let contrast = require('./contrast');
  7. let rimraf = require('rimraf');
  8. let Chokidar = require('chokidar');
  9. if (!marked) {
  10. console.log('you need npm i marked -D!');
  11. }
  12. class mdVue {
  13. constructor(options) {
  14. let defaultSetting = {
  15. needCode: true,
  16. isbuild: true,
  17. hasMarkList: true
  18. };
  19. this.options = Object.assign(defaultSetting, options);
  20. this.rendererMd = new marked.Renderer();
  21. this.marked = marked;
  22. let _that = this;
  23. this.Articlehead = '';
  24. this.Articleheadcount = 0;
  25. this.needHandleFiles = null;
  26. this.cachePath = path.join('./cache', options.entry.split(path.sep).pop() + '.cache');
  27. this.codeHandle();
  28. this.checkSelf().then(res => {
  29. // 检查要编译的文件
  30. let ct = new contrast({
  31. entry: this.options.entry
  32. })
  33. .run()
  34. .then(res => {
  35. _that.needHandleFiles = res;
  36. _that.ishasOutFile(_that.options.output).then(res => {
  37. _that.star();
  38. _that.filelisten();
  39. });
  40. });
  41. });
  42. }
  43. checkSelf() {
  44. let _that = this;
  45. return new Promise((resolve, reject) => {
  46. new contrast({
  47. entry: path.join(__dirname, 'mdToVue.js'),
  48. include: ['*.js']
  49. })
  50. .run()
  51. .then(res => {
  52. if (JSON.stringify(res) != '{}') {
  53. //有变动清除当前entry缓存,重新渲染
  54. rimraf(_that.cachePath, err => {
  55. console.log(err);
  56. resolve();
  57. });
  58. } else {
  59. resolve();
  60. }
  61. });
  62. });
  63. }
  64. apply() {}
  65. filelisten() {
  66. let _that = this;
  67. let watcher = Chokidar.watch(_that.options.entry, {
  68. persistent: true,
  69. usePolling: true
  70. });
  71. let log = console.dir.bind(console);
  72. let watchAction = function({ event, eventPath }) {
  73. // 这里进行文件更改后的操作
  74. // fileReadStar(eventPath,(res)=>{
  75. // createdFile(param.output + res.mdName + '.vue', res.html, param.needCode)
  76. // })
  77. console.log(path.join(__dirname, JSON.stringify(eventPath)));
  78. if (/\.md$/.test(eventPath)) {
  79. _that.vueDesWrite(eventPath);
  80. }
  81. // "d:\workplace\nutui\docs\international.md"
  82. // _that.read(eventPath).then(res=>{
  83. // _that.headHandle();
  84. // _that.markHandle();
  85. // let html = _that.marked(res);
  86. // _that.write({
  87. // outsrc:_that.options.output,
  88. // name:fileName + '.vue',
  89. // html:html
  90. // });
  91. // })
  92. };
  93. watcher
  94. .on('change', path => watchAction({ event: 'change', eventPath: path }))
  95. .on('unlink', path => watchAction({ event: 'remove', eventPath: path }));
  96. }
  97. star() {
  98. let _that = this;
  99. hashElement(_that.options.entry, {
  100. folders: { exclude: ['.*', 'node_modules', 'test_coverage'] },
  101. files: { include: ['*.md'] },
  102. matchBasename: true
  103. }).then(hash => {
  104. nodeFilelist.read([_that.options.entry], { ext: 'md' }, res => {
  105. res.map((item, index) => {
  106. _that.vueDesWrite(item.path);
  107. // let fileSplits = item.path.split(path.sep);
  108. // let fileName = fileSplits.pop();
  109. // if(_that.isDoc(fileName)){
  110. // fileName = fileSplits.pop();
  111. // }else{
  112. // fileName = fileName.replace(/\.md/,'');
  113. // }
  114. // if(_that.needHandleFiles[fileName]){
  115. // // _that.read(item.path).then(res=>{
  116. // // _that.headHandle();
  117. // // _that.markHandle();
  118. // // let html = _that.marked(res);
  119. // // _that.write({
  120. // // outsrc:_that.options.output,
  121. // // name:fileName + '.vue',
  122. // // html:html
  123. // // });
  124. // // })
  125. // }
  126. // _that.read(item.path).then(res=>{
  127. // _that.headHandle();
  128. // _that.markHandle();
  129. // let html = _that.marked(res);
  130. // _that.write({
  131. // outsrc:_that.options.output,
  132. // name:fileName + '.vue',
  133. // html:html
  134. // });
  135. // })
  136. });
  137. });
  138. });
  139. }
  140. vueDesWrite(getpath) {
  141. let _that = this;
  142. let fileSplits = getpath.split(path.sep);
  143. let fileName = fileSplits.pop();
  144. if (_that.isDoc(fileName)) {
  145. fileName = fileSplits.pop();
  146. } else {
  147. fileName = fileName.replace(/\.md/, '');
  148. }
  149. if (_that.needHandleFiles[fileName]) {
  150. // _that.read(item.path).then(res=>{
  151. // _that.headHandle();
  152. // _that.markHandle();
  153. // let html = _that.marked(res);
  154. // _that.write({
  155. // outsrc:_that.options.output,
  156. // name:fileName + '.vue',
  157. // html:html
  158. // });
  159. // })
  160. }
  161. _that.read(getpath).then(res => {
  162. _that.headHandle();
  163. _that.markHandle();
  164. let html = _that.marked(res);
  165. _that.write({
  166. outsrc: _that.options.output,
  167. name: fileName + '.vue',
  168. html: html,
  169. vname: fileName
  170. });
  171. });
  172. }
  173. isDoc(name) {
  174. return name == 'doc.md' ? true : false;
  175. }
  176. read(src) {
  177. return new Promise((resolve, reject) => {
  178. fs.readFile(src, 'utf-8', (err, data) => {
  179. resolve(data);
  180. });
  181. });
  182. }
  183. write(param) {
  184. let _that = this;
  185. return new Promise((resolve, reject) => {
  186. let outPath = path.join(param.outsrc, param.name);
  187. let contexts =
  188. `<template>
  189. <div @click="dsCode">
  190. <div v-if="content" class="layer">
  191. <pre><span class="close-box" @click="closelayer"></span><div v-html="content"></div></pre>
  192. </div>` +
  193. param.html +
  194. (_that.options.hasMarkList ? '<ul class="markList">' + _that.Articlehead + '</ul>' : '') +
  195. `<nut-backtop :right="50" :bottom="50"></nut-backtop>
  196. </div>
  197. </template><script>import root from '../root.js';
  198. export default {
  199. mixins:[root],
  200. name:${param.vname}
  201. }</script>`;
  202. _that.Articlehead = '';
  203. _that.Articleheadcount = 0;
  204. fs.writeFile(outPath, contexts, 'utf8', (err, res) => {});
  205. });
  206. }
  207. ishasOutFile(outPath) {
  208. return new Promise((resolve, reject) => {
  209. fs.stat(outPath, (err, res) => {
  210. if (err) {
  211. fs.mkdir(outPath, err => {
  212. if (err) {
  213. reject(err);
  214. } else {
  215. resolve(true);
  216. }
  217. });
  218. } else {
  219. resolve(true);
  220. }
  221. });
  222. });
  223. }
  224. headHandle() {
  225. let _that = this;
  226. let options = _that.options;
  227. _that.rendererMd.heading = function(text, level) {
  228. let headcode = '<i class="qrcode"><a :href="demourl"><span>请使用手机扫码体验</span><img :src="codeurl" alt=""></a></i>';
  229. let codeHead = `<h1>` + text + headcode + `</h1>`;
  230. let normal = `<h` + level + `>` + text + `</h` + level + `>`;
  231. let Articleheadcounts = null;
  232. if (level == 2 && _that.options.hasMarkList) {
  233. Articleheadcounts = _that.Articleheadcount;
  234. Articleheadcounts++;
  235. _that.Articleheadcount = Articleheadcounts;
  236. let headmsg = _that.Articlehead;
  237. headmsg +=
  238. `<li @click="leavelchose(` +
  239. Articleheadcounts +
  240. `)" :class="levalcur==` +
  241. Articleheadcounts +
  242. `?'cur':''" class="level` +
  243. Articleheadcounts +
  244. '"><a href="#head' +
  245. Articleheadcounts +
  246. '">' +
  247. text.substr(0, 10) +
  248. '</a></li>';
  249. _that.Articlehead = headmsg;
  250. }
  251. let maskIdHead = '<h' + level + " class='visibility' id='head" + Articleheadcounts + "'>" + text + '</h' + level + '>';
  252. //判断条件
  253. if (_that.options.hasMarkList && _that.options.needCode) {
  254. if (level == 1) {
  255. return codeHead;
  256. } else if (level == 2) {
  257. return maskIdHead;
  258. } else {
  259. return normal;
  260. }
  261. } else if (_that.options.hasMarkList && !_that.options.needCode) {
  262. if (level != 1) {
  263. return maskIdHead;
  264. } else {
  265. return normal;
  266. }
  267. } else if (!_that.options.hasMarkList && _that.options.needCode) {
  268. if (level == 1) {
  269. return codeHead;
  270. } else {
  271. return normal;
  272. }
  273. } else if (!_that.options.hasMarkList && !_that.options.needCode) {
  274. return normal;
  275. }
  276. };
  277. }
  278. codeHandle() {
  279. var that = this;
  280. this.rendererMd.code = function(code, infostring, escaped) {
  281. var lang = (infostring || '').match(/\S*/)[0];
  282. if (this.options.highlight) {
  283. var out = this.options.highlight(code, lang);
  284. if (out != null && out !== code) {
  285. escaped = true;
  286. code = out;
  287. }
  288. }
  289. if (!lang) {
  290. return '<pre><code>' + (escaped ? code : escape(code, true)) + '</code></pre>';
  291. }
  292. if (lang === 'html') {
  293. code = code.replace(/@latest/g, '@' + that.options.version);
  294. }
  295. return (
  296. '<hide><pre class="prettyprint"><span class="lang">' +
  297. lang +
  298. '</span><div class="code-wrapper"><code class="' +
  299. this.options.langPrefix +
  300. escape(lang, true) +
  301. '">' +
  302. (escaped ? code : escape(code, true)) +
  303. '</code></div><i class="copy" copy="copy" data-clipboard-action="copy" data-clipboard-target="code" title="复制代码"></i><i toast="toast" title="全屏"></i></pre></hide>\n'
  304. );
  305. };
  306. }
  307. markHandle() {
  308. let _that = this;
  309. this.marked.setOptions({
  310. renderer: _that.rendererMd,
  311. highlight: function(code) {
  312. return require('highlight.js').highlightAuto(code).value;
  313. },
  314. tables: true
  315. });
  316. }
  317. }
  318. module.exports = mdVue;