Skip to content

Commit

Permalink
feat: support custom attrs (#29)
Browse files Browse the repository at this point in the history
  • Loading branch information
thonatos authored Jan 17, 2022
1 parent 087ee91 commit 1e11f90
Showing 1 changed file with 42 additions and 1 deletion.
43 changes: 42 additions & 1 deletion src/component/Markdown/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,48 @@ import MdEditor from 'react-markdown-editor-lite';

import * as styles from './index.less';

const mdParser = new MarkdownIt();
const mdParser = new MarkdownIt('commonmark', {
html: true,
});

const getAttributes = (content: string = 'image') => {
const attrs = content.split(' ');
const alt = attrs.shift();

const attributes = attrs.reduce((prev: string[], curr) => {
const [key, value] = curr.split('=');

if (!key) {
return prev;
}

if (!value) {
return prev.concat(`${key}`);
}

return prev.concat(`${key}="${value}"`);
}, []);

return {
alt,
attributes,
};
};

mdParser.renderer.rules.image = function (tokens, index) {
const token = tokens[index];
const srcIndex = token.attrIndex('src');

if (!token.attrs) {
return '';
}

const src = token.attrs[srcIndex][1];
const content = mdParser.utils.escapeHtml(token.content);
const { alt, attributes } = getAttributes(content);

return `<img src="${src}" alt="${alt}" ${attributes.join(' ')}/>`;
};

const Markdown: React.FC<Props> = (props) => {
const { value = '', type, onChange, customClassName = '' } = props;
Expand Down

0 comments on commit 1e11f90

Please sign in to comment.