mdToVue.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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. if(/\.md$/.test(eventPath)){
  76. _that.vueDesWrite(eventPath)
  77. }
  78. // "d:\workplace\nutui\docs\international.md"
  79. // _that.read(eventPath).then(res=>{
  80. // _that.headHandle();
  81. // _that.markHandle();
  82. // let html = _that.marked(res);
  83. // _that.write({
  84. // outsrc:_that.options.output,
  85. // name:fileName + '.vue',
  86. // html:html
  87. // });
  88. // })
  89. }
  90. watcher.on('change', path => watchAction({event: 'change', eventPath: path}))
  91. .on('unlink', path => watchAction({event: 'remove', eventPath: path}));
  92. }
  93. star(){
  94. let _that = this;
  95. hashElement(_that.options.entry, {
  96. folders: { exclude: ['.*', 'node_modules', 'test_coverage'] },
  97. files: { include: ['*.md']},
  98. matchBasename: true
  99. }).then(hash => {
  100. nodeFilelist.read([_that.options.entry],{"ext":'md'}, res => {
  101. res.map((item,index) =>{
  102. _that.vueDesWrite(item.path)
  103. // let fileSplits = item.path.split(path.sep);
  104. // let fileName = fileSplits.pop();
  105. // if(_that.isDoc(fileName)){
  106. // fileName = fileSplits.pop();
  107. // }else{
  108. // fileName = fileName.replace(/\.md/,'');
  109. // }
  110. // if(_that.needHandleFiles[fileName]){
  111. // // _that.read(item.path).then(res=>{
  112. // // _that.headHandle();
  113. // // _that.markHandle();
  114. // // let html = _that.marked(res);
  115. // // _that.write({
  116. // // outsrc:_that.options.output,
  117. // // name:fileName + '.vue',
  118. // // html:html
  119. // // });
  120. // // })
  121. // }
  122. // _that.read(item.path).then(res=>{
  123. // _that.headHandle();
  124. // _that.markHandle();
  125. // let html = _that.marked(res);
  126. // _that.write({
  127. // outsrc:_that.options.output,
  128. // name:fileName + '.vue',
  129. // html:html
  130. // });
  131. // })
  132. });
  133. });
  134. })
  135. }
  136. vueDesWrite(getpath){
  137. let _that = this;
  138. let fileSplits = getpath.split(path.sep);
  139. let fileName = fileSplits.pop();
  140. if(_that.isDoc(fileName)){
  141. fileName = fileSplits.pop();
  142. }else{
  143. fileName = fileName.replace(/\.md/,'');
  144. }
  145. if(_that.needHandleFiles[fileName]){
  146. // _that.read(item.path).then(res=>{
  147. // _that.headHandle();
  148. // _that.markHandle();
  149. // let html = _that.marked(res);
  150. // _that.write({
  151. // outsrc:_that.options.output,
  152. // name:fileName + '.vue',
  153. // html:html
  154. // });
  155. // })
  156. }
  157. _that.read(getpath).then(res=>{
  158. _that.headHandle();
  159. _that.markHandle();
  160. let html = _that.marked(res);
  161. _that.write({
  162. outsrc:_that.options.output,
  163. name:fileName + '.vue',
  164. html:html
  165. });
  166. })
  167. }
  168. isDoc(name){
  169. return (name == "doc.md") ? true : false;
  170. }
  171. read(src){
  172. return new Promise((resolve,reject)=>{
  173. fs.readFile(src, 'utf-8', (err, data) => {
  174. resolve(data)
  175. })
  176. })
  177. }
  178. write(param){
  179. let _that = this;
  180. return new Promise((resolve,reject)=>{
  181. let outPath = path.join(param.outsrc,param.name);
  182. let contexts = `<template>
  183. <div @click="dsCode">
  184. <div v-if="content" class="layer">
  185. <pre><span class="close-box" @click="closelayer"></span><div v-html="content"></div></pre>
  186. </div>`+ param.html + (_that.options.hasMarkList ? '<ul class="markList">' + _that.Articlehead + '</ul>' : '')+
  187. `<nut-backtop :right="50" :bottom="50"></nut-backtop>
  188. </div>
  189. </template><script>import root from '../root.js';
  190. export default {
  191. mixins:[root]
  192. }</script>`;
  193. _that.Articlehead = "";
  194. _that.Articleheadcount = 0;
  195. fs.writeFile(outPath ,contexts,'utf8',(err,res)=>{ })
  196. })
  197. }
  198. ishasOutFile(outPath){
  199. return new Promise((resolve,reject)=>{
  200. fs.stat(outPath,(err,res)=>{
  201. if(err){
  202. fs.mkdir(outPath,err=>{
  203. if(err){
  204. reject(err)
  205. }else{
  206. resolve(true)
  207. }
  208. })
  209. }else{
  210. resolve(true)
  211. }
  212. })
  213. })
  214. }
  215. headHandle(){
  216. let _that = this;
  217. let options = _that.options;
  218. _that.rendererMd.heading = function (text,level){
  219. let headcode = '<i class="qrcode"><a :href="demourl"><span>请使用手机扫码体验</span><img :src="codeurl" alt=""></a></i>';
  220. let codeHead = `<h1>` + text +headcode+`</h1>`;
  221. let normal = `<h`+level+`>`+text+`</h`+level+`>`;
  222. let Articleheadcounts = null;
  223. if(level==2&&_that.options.hasMarkList){
  224. Articleheadcounts = _that.Articleheadcount;
  225. Articleheadcounts++;
  226. _that.Articleheadcount = Articleheadcounts;
  227. let headmsg = _that.Articlehead;
  228. headmsg +=`<li @click="leavelchose(`+Articleheadcounts+`)" :class="levalcur==`+Articleheadcounts+`?'cur':''" class="level`+Articleheadcounts+'"><a href="#head'+Articleheadcounts+'">'+text.substr(0,10)+'</a></li>';
  229. _that.Articlehead = headmsg;
  230. }
  231. let maskIdHead = "<h"+level+" class='visibility' id='head"+Articleheadcounts+"'>"+ text +"</h"+level+">";
  232. //判断条件
  233. if(_that.options.hasMarkList && _that.options.needCode){
  234. if(level == 1){
  235. return codeHead;
  236. }else if(level == 2){
  237. return maskIdHead;
  238. } else{
  239. return normal;
  240. }
  241. }else if(_that.options.hasMarkList && !_that.options.needCode){
  242. if(level !=1){
  243. return maskIdHead;
  244. } else{
  245. return normal;
  246. }
  247. }else if(!_that.options.hasMarkList && _that.options.needCode){
  248. if(level == 1){
  249. return codeHead;
  250. } else{
  251. return normal;
  252. }
  253. }else if(!_that.options.hasMarkList && !_that.options.needCode){
  254. return normal;
  255. }
  256. };
  257. }
  258. codeHandle(){
  259. this.rendererMd.code = function (code, infostring, escaped) {
  260. var lang = (infostring || '').match(/\S*/)[0];
  261. if (this.options.highlight) {
  262. var out = this.options.highlight(code, lang);
  263. if (out != null && out !== code) {
  264. escaped = true;
  265. code = out;
  266. }
  267. }
  268. if (!lang) {
  269. return '<pre><code>'
  270. + (escaped ? code : escape(code, true))
  271. + '</code></pre>';
  272. }
  273. if (lang === 'html') {
  274. code = code.replace(/@latest/g, '@' + version)
  275. }
  276. return '<hide><pre class="prettyprint"><span class="lang">' + lang + '</span><div class="code-wrapper"><code class="'
  277. + this.options.langPrefix
  278. + escape(lang, true)
  279. + '">'
  280. + (escaped ? code : escape(code, true))
  281. + '</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';
  282. };
  283. }
  284. markHandle(){
  285. let _that = this;
  286. this.marked.setOptions({
  287. renderer: _that.rendererMd,
  288. highlight: function (code) {
  289. return require('highlight.js').highlightAuto(code).value;
  290. },
  291. tables: true
  292. });
  293. }
  294. };
  295. module.exports = mdVue;