index.js 2.2 KB

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