index.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. const {
  2. stripScript,
  3. stripTemplate,
  4. genInlineComponentText
  5. } = require('./util');
  6. const md = require('./config');
  7. module.exports = function(source) {
  8. const content = md.render(source);
  9. const startTag = '<!--element-demo:';
  10. const startTagLen = startTag.length;
  11. const endTag = ':element-demo-->';
  12. const endTagLen = endTag.length;
  13. let componenetsString = '';
  14. let id = 0; // demo 的 id
  15. let output = []; // 输出的内容
  16. let start = 0; // 字符串开始位置
  17. let commentStart = content.indexOf(startTag);
  18. let commentEnd = content.indexOf(endTag, commentStart + startTagLen);
  19. while (commentStart !== -1 && commentEnd !== -1) {
  20. output.push(content.slice(start, commentStart));
  21. const commentContent = content.slice(commentStart + startTagLen, commentEnd);
  22. const html = stripTemplate(commentContent);
  23. const script = stripScript(commentContent);
  24. let demoComponentContent = genInlineComponentText(html, script);
  25. const demoComponentName = `element-demo${id}`;
  26. output.push(`<template slot="source"><${demoComponentName} /></template>`);
  27. componenetsString += `${JSON.stringify(demoComponentName)}: ${demoComponentContent},`;
  28. // 重新计算下一次的位置
  29. id++;
  30. start = commentEnd + endTagLen;
  31. commentStart = content.indexOf(startTag, start);
  32. commentEnd = content.indexOf(endTag, commentStart + startTagLen);
  33. }
  34. // 仅允许在 demo 不存在时,才可以在 Markdown 中写 script 标签
  35. // todo: 优化这段逻辑
  36. let pageScript = '';
  37. if (componenetsString) {
  38. pageScript = `<script>
  39. export default {
  40. name: 'component-doc',
  41. components: {
  42. ${componenetsString}
  43. }
  44. }
  45. </script>`;
  46. } else if (content.indexOf('<script>') === 0) { // 硬编码,有待改善
  47. start = content.indexOf('</script>') + '</script>'.length;
  48. pageScript = content.slice(0, start);
  49. }
  50. output.push(content.slice(start));
  51. return `
  52. <template>
  53. <section class="content element-doc">
  54. ${output.join('')}
  55. </section>
  56. </template>
  57. ${pageScript}
  58. `;
  59. };