mdToVue.js 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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. });
  170. });
  171. }
  172. isDoc(name) {
  173. return name == 'doc.md' ? true : false;
  174. }
  175. read(src) {
  176. return new Promise((resolve, reject) => {
  177. fs.readFile(src, 'utf-8', (err, data) => {
  178. resolve(data);
  179. });
  180. });
  181. }
  182. write(param) {
  183. let _that = this;
  184. return new Promise((resolve, reject) => {
  185. let outPath = path.join(param.outsrc, param.name);
  186. let contexts =
  187. `<template>
  188. <div @click="dsCode">
  189. <div v-if="content" class="layer">
  190. <pre><span class="close-box" @click="closelayer"></span><div v-html="content"></div></pre>
  191. </div>` +
  192. param.html +
  193. (_that.options.hasMarkList ? '<ul class="markList">' + _that.Articlehead + '</ul>' : '') +
  194. `<nut-backtop :right="50" :bottom="50"></nut-backtop>
  195. </div>
  196. </template><script>import root from '../root.js';
  197. export default {
  198. mixins:[root]
  199. }</script>`;
  200. _that.Articlehead = '';
  201. _that.Articleheadcount = 0;
  202. fs.writeFile(outPath, contexts, 'utf8', (err, res) => {});
  203. });
  204. }
  205. ishasOutFile(outPath) {
  206. return new Promise((resolve, reject) => {
  207. fs.stat(outPath, (err, res) => {
  208. if (err) {
  209. fs.mkdir(outPath, (err) => {
  210. if (err) {
  211. reject(err);
  212. } else {
  213. resolve(true);
  214. }
  215. });
  216. } else {
  217. resolve(true);
  218. }
  219. });
  220. });
  221. }
  222. headHandle() {
  223. let _that = this;
  224. let options = _that.options;
  225. _that.rendererMd.heading = function (text, level) {
  226. let headcode = '<i class="qrcode"><a :href="demourl"><span>请使用手机扫码体验</span><img :src="codeurl" alt=""></a></i>';
  227. let codeHead = `<h1>` + text + headcode + `</h1>`;
  228. let normal = `<h` + level + `>` + text + `</h` + level + `>`;
  229. let Articleheadcounts = null;
  230. if (level == 2 && _that.options.hasMarkList) {
  231. Articleheadcounts = _that.Articleheadcount;
  232. Articleheadcounts++;
  233. _that.Articleheadcount = Articleheadcounts;
  234. let headmsg = _that.Articlehead;
  235. headmsg +=
  236. `<li @click="leavelchose(` +
  237. Articleheadcounts +
  238. `)" :class="levalcur==` +
  239. Articleheadcounts +
  240. `?'cur':''" class="level` +
  241. Articleheadcounts +
  242. '"><a href="#head' +
  243. Articleheadcounts +
  244. '">' +
  245. text.substr(0, 10) +
  246. '</a></li>';
  247. _that.Articlehead = headmsg;
  248. }
  249. let maskIdHead = '<h' + level + " class='visibility' id='head" + Articleheadcounts + "'>" + text + '</h' + level + '>';
  250. //判断条件
  251. if (_that.options.hasMarkList && _that.options.needCode) {
  252. if (level == 1) {
  253. return codeHead;
  254. } else if (level == 2) {
  255. return maskIdHead;
  256. } else {
  257. return normal;
  258. }
  259. } else if (_that.options.hasMarkList && !_that.options.needCode) {
  260. if (level != 1) {
  261. return maskIdHead;
  262. } else {
  263. return normal;
  264. }
  265. } else if (!_that.options.hasMarkList && _that.options.needCode) {
  266. if (level == 1) {
  267. return codeHead;
  268. } else {
  269. return normal;
  270. }
  271. } else if (!_that.options.hasMarkList && !_that.options.needCode) {
  272. return normal;
  273. }
  274. };
  275. }
  276. codeHandle() {
  277. var that = this;
  278. this.rendererMd.code = function (code, infostring, escaped) {
  279. var lang = (infostring || '').match(/\S*/)[0];
  280. if (this.options.highlight) {
  281. var out = this.options.highlight(code, lang);
  282. if (out != null && out !== code) {
  283. escaped = true;
  284. code = out;
  285. }
  286. }
  287. if (!lang) {
  288. return '<pre><code>' + (escaped ? code : escape(code, true)) + '</code></pre>';
  289. }
  290. if (lang === 'html') {
  291. code = code.replace(/@latest/g, '@' + that.options.version);
  292. }
  293. return (
  294. '<hide><pre class="prettyprint"><span class="lang">' +
  295. lang +
  296. '</span><div class="code-wrapper"><code class="' +
  297. this.options.langPrefix +
  298. escape(lang, true) +
  299. '">' +
  300. (escaped ? code : escape(code, true)) +
  301. '</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'
  302. );
  303. };
  304. }
  305. markHandle() {
  306. let _that = this;
  307. this.marked.setOptions({
  308. renderer: _that.rendererMd,
  309. highlight: function (code) {
  310. return require('highlight.js').highlightAuto(code).value;
  311. },
  312. tables: true,
  313. });
  314. }
  315. }
  316. module.exports = mdVue;