mdToVue.js 12 KB

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