Skip to content

Commit

Permalink
feat(umi-plugin): support to parse yaml from .tsx/.jsx file (#9)
Browse files Browse the repository at this point in the history
  • Loading branch information
PeachScript committed Nov 21, 2019
1 parent ca854a5 commit 985d38b
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 6 deletions.
2 changes: 2 additions & 0 deletions packages/umi-plugin-father-doc/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@
"remark-frontmatter": "^1.3.2",
"remark-parse": "^7.0.1",
"remark-rehype": "^5.0.0",
"sylvanas": "^0.4.2",
"umi-build-dev": "^1.16.5",
"umi-plugin-react": "^1.13.1",
"umi-types": "^0.5.4",
"unified": "^8.4.1",
Expand Down
23 changes: 22 additions & 1 deletion packages/umi-plugin-father-doc/src/transformer/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import { parseText } from 'sylvanas';
import getYamlConfig from 'umi-build-dev/lib/routes/getYamlConfig';
import remark from './remark';

const FRONT_COMMENT_EXP = /^\n*\/\*[^]+?\s*\*\/\n*/;

export interface TransformResult {
content: string;
config: {
Expand All @@ -21,5 +25,22 @@ export default {
...result.data as TransformResult['config'],
},
};
}
},
jsx(raw: string): TransformResult {
return {
// discard frontmatter for source code display
content: raw.replace(FRONT_COMMENT_EXP, ''),
config: {
frontmatter: getYamlConfig(raw),
},
};
},
tsx(raw: string): TransformResult {
const result = this.jsx(raw);

// parse tsx to jsx for source code display
result.config.jsx = parseText(raw);

return result;
},
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import fs from 'fs';
import path from 'path';
import visit from 'unist-util-visit';
import transformer, { TransformResult } from '../index';

const DEMO_TOKEN_EXP = /^\s*<(code)[^>]+src="?([^ ">]+)"?/;

Expand All @@ -14,13 +15,20 @@ export default (options: { [key: string]: any } = {}) => (ast) => {
const absPath = demoPath.startsWith('/') ? demoPath : path.join(options.fileAbsDir, demoPath);

if (fs.existsSync(absPath)) {
const lang = absPath.match(/\.(\w+)$/)[1];
const processer = transformer[lang];
// read external demo content and convert node to previewer
const content = fs.readFileSync(absPath).toString();
const result: TransformResult = transformer[lang](fs.readFileSync(absPath).toString());

node.type = 'previewer';
node.lang = absPath.match(/\.(\w+)$/)[1];
node.value = content;
node.basePath = path.parse(absPath).dir;
if (processer) {
node.type = 'previewer';
node.lang = lang;
node.value = result.content;
node.meta = result.config;
node.basePath = path.parse(absPath).dir;
} else {
throw new Error(`[External-Demo Error]: unsupported file type: ${lang}`);
}
} else {
throw new Error(`[External-Demo Error]: cannot find demo in ${absPath}`);
}
Expand Down

0 comments on commit 985d38b

Please sign in to comment.