markdown-vetur
Version:
simple parse markdown to vue component description for vetur auto-completion
71 lines (57 loc) • 1.67 kB
text/typescript
import { Artical } from './md-parser';
const FLAG_REG = /(.*?)\s*(API|Event)/i;
export interface Tag {
attributes: object;
description: string;
defaults?: Array<string>;
subtags?: Array<string>;
}
interface Attribute {
description: string;
type?: string;
options?: Array<string>;
}
export default function codegen(artical: Artical) {
const tags = {};
// const attributes = {};
let tagDescription = '';
for (let i = 0, len = artical.length; i < len; i++) {
const item = artical[i];
if (item.type === 'title' && item.level === 2) {
tagDescription = item.content;
} else if (item.type === 'table') {
const before = artical[i - 1];
if (!before) {
continue;
}
const { table } = item;
const match = FLAG_REG.exec(before.content);
if (!match) {
continue;
}
const key = camelCaseToKebabCase(match[1] || 'default');
const tag: Tag = tags[key] || {
description: tagDescription,
attributes: {}
};
tags[key] = tag;
const isProp = /API/i.test(match[2]);
table.body.forEach(td => {
const attrName = td[0];
const attr: Attribute = {
description: `${td[1]}, ${
isProp ? 'default: ' + td[3].replace(/`/g, '') : 'params: ' + td[2]
}`,
type: isProp ? td[2].replace(/`/g, '').toLowerCase() : 'event'
};
tag.attributes[attrName] = attr;
});
}
}
return tags;
}
function camelCaseToKebabCase(input: string): string {
return input.replace(/[A-Z]/g, function(val, index) {
return (index === 0 ? '' : '-') + val.toLowerCase();
});
}