demo-preview.ts 4.4 KB

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