Skip to content

Commit

Permalink
feat(umi-plugin): support to import external demo (#8)
Browse files Browse the repository at this point in the history
  • Loading branch information
PeachScript committed Nov 13, 2019
1 parent 36b0496 commit e63d847
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import fs from 'fs';
import path from 'path';
import visit from 'unist-util-visit';

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

export default (options: { [key: string]: any } = {}) => (ast) => {
visit(ast, 'html', (node) => {
if (typeof node.value === 'string') {
const matches = node.value.match(DEMO_TOKEN_EXP) || [];
const demoPath = matches[1];

if (demoPath) {
const absPath = demoPath.startsWith('/') ? demoPath : path.join(options.fileAbsDir, demoPath);

if (fs.existsSync(absPath)) {
// read external demo content and convert node to previewer
const content = fs.readFileSync(absPath).toString();

node.type = 'previewer';
node.lang = absPath.match(/\.(\w+)$/)[1];
node.value = content;
node.basePath = path.parse(absPath).dir;
} else {
throw new Error(`[External-Demo Error]: cannot find demo in ${absPath}`);
}
} else {
throw new Error(`[External-Demo Error]: expected a code element with valid src property but got ${node.value}`);
}
}
});
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,17 @@ import prism from '@mapbox/rehype-prism';
import parse from './parse';
import rehype from './rehype';
import yaml from './yaml';
import externalDemo from './externalDemo';
import jsx from './jsx';
import isolation from './isolation';

export default (raw: string, dir: string) => {
export default (raw: string, fileAbsDir: string) => {
const processor = unified()
.use(parse)
.use(frontmatter)
.use(yaml)
.use(rehype, { dir })
.use(externalDemo, { fileAbsDir })
.use(rehype, { dir: fileAbsDir })
.use(stringify, { allowDangerousHTML: true })
.use(slug)
.use(headings, {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import transformer, { PREVIEWER_NAME } from '../previewer';
*/
function previewerHandler(h, node) {
const code = `{(function () {
${transformer(node.value, this.dir, node.lang === 'tsx')}
${transformer(node.value, node.basePath || this.dir, node.lang === 'tsx')}
return <${PREVIEWER_NAME} />;
})()}`
;
Expand All @@ -20,5 +20,6 @@ export default (options: { [key: string]: any } = {}) => {
handlers: {
previewer: previewerHandler.bind({ dir: options.dir }),
},
allowDangerousHTML: true,
}, options));
}

0 comments on commit e63d847

Please sign in to comment.