demo-preview.ts 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. import type { MarkdownEnv, MarkdownRenderer } from 'vitepress';
  2. import crypto from 'node:crypto';
  3. import { readdirSync } from 'node:fs';
  4. import { join } from 'node:path';
  5. export const rawPathRegexp =
  6. /^(.+?(?:\.([\da-z]+))?)(#[\w-]+)?(?: ?{(\d+(?:[,-]\d+)*)? ?(\S+)?})? ?(?:\[(.+)])?$/;
  7. function rawPathToToken(rawPath: string) {
  8. const [
  9. filepath = '',
  10. extension = '',
  11. region = '',
  12. lines = '',
  13. lang = '',
  14. rawTitle = '',
  15. ] = (rawPathRegexp.exec(rawPath) || []).slice(1);
  16. const title = rawTitle || filepath.split('/').pop() || '';
  17. return { extension, filepath, lang, lines, region, title };
  18. }
  19. export const demoPreviewPlugin = (md: MarkdownRenderer) => {
  20. md.core.ruler.after('inline', 'demo-preview', (state) => {
  21. const insertComponentImport = (importString: string) => {
  22. const index = state.tokens.findIndex(
  23. (i) => i.type === 'html_block' && i.content.match(/<script setup>/g),
  24. );
  25. if (index === -1) {
  26. const importComponent = new state.Token('html_block', '', 0);
  27. importComponent.content = `<script setup>\n${importString}\n</script>\n`;
  28. state.tokens.splice(0, 0, importComponent);
  29. } else {
  30. if (state.tokens[index]) {
  31. const content = state.tokens[index].content;
  32. state.tokens[index].content = content.replace(
  33. '</script>',
  34. `${importString}\n</script>`,
  35. );
  36. }
  37. }
  38. };
  39. // Define the regular expression to match the desired pattern
  40. const regex = /<DemoPreview[^>]*\sdir="([^"]*)"/g;
  41. // Iterate through the Markdown content and replace the pattern
  42. state.src = state.src.replaceAll(regex, (_match, dir) => {
  43. const componentDir = join(process.cwd(), 'src', dir).replaceAll(
  44. '\\',
  45. '/',
  46. );
  47. let childFiles: string[] = [];
  48. let dirExists = true;
  49. try {
  50. childFiles =
  51. readdirSync(componentDir, {
  52. encoding: 'utf8',
  53. recursive: false,
  54. withFileTypes: false,
  55. }) || [];
  56. } catch {
  57. dirExists = false;
  58. }
  59. if (!dirExists) {
  60. return '';
  61. }
  62. const uniqueWord = generateContentHash(componentDir);
  63. const ComponentName = `DemoComponent_${uniqueWord}`;
  64. insertComponentImport(
  65. `import ${ComponentName} from '${componentDir}/index.vue'`,
  66. );
  67. const { path: _path } = state.env as MarkdownEnv;
  68. const index = state.tokens.findIndex((i) => i.content.match(regex));
  69. if (!state.tokens[index]) {
  70. return '';
  71. }
  72. const firstString = 'index.vue';
  73. childFiles = childFiles.toSorted((a, b) => {
  74. if (a === firstString) return -1;
  75. if (b === firstString) return 1;
  76. return a.localeCompare(b, 'en', { sensitivity: 'base' });
  77. });
  78. state.tokens[index].content =
  79. `<DemoPreview files="${encodeURIComponent(JSON.stringify(childFiles))}" ><${ComponentName}/>
  80. `;
  81. const _dummyToken = new state.Token('', '', 0);
  82. const tokenArray: Array<typeof _dummyToken> = [];
  83. childFiles.forEach((filename) => {
  84. // const slotName = filename.replace(extname(filename), '');
  85. const templateStart = new state.Token('html_inline', '', 0);
  86. templateStart.content = `<template #${filename}>`;
  87. tokenArray.push(templateStart);
  88. const resolvedPath = join(componentDir, filename);
  89. const { extension, filepath, lang, lines, title } =
  90. rawPathToToken(resolvedPath);
  91. // Add code tokens for each line
  92. const token = new state.Token('fence', 'code', 0);
  93. token.info = `${lang || extension}${lines ? `{${lines}}` : ''}${
  94. title ? `[${title}]` : ''
  95. }`;
  96. token.content = `<<< ${filepath}`;
  97. (token as any).src = [resolvedPath];
  98. tokenArray.push(token);
  99. const templateEnd = new state.Token('html_inline', '', 0);
  100. templateEnd.content = '</template>';
  101. tokenArray.push(templateEnd);
  102. });
  103. const endTag = new state.Token('html_inline', '', 0);
  104. endTag.content = '</DemoPreview>';
  105. tokenArray.push(endTag);
  106. state.tokens.splice(index + 1, 0, ...tokenArray);
  107. // console.log(
  108. // state.md.renderer.render(state.tokens, state?.options ?? [], state.env),
  109. // );
  110. return '';
  111. });
  112. });
  113. };
  114. function generateContentHash(input: string, length: number = 10): string {
  115. // 使用 SHA-256 生成哈希值
  116. const hash = crypto.createHash('sha256').update(input).digest('hex');
  117. // 将哈希值转换为 Base36 编码,并取指定长度的字符作为结果
  118. return Number.parseInt(hash, 16).toString(36).slice(0, length);
  119. }