Skip to content

Commit 1e11f90

Browse files
authored
feat: support custom attrs (#29)
1 parent 087ee91 commit 1e11f90

File tree

1 file changed

+42
-1
lines changed

1 file changed

+42
-1
lines changed

src/component/Markdown/index.tsx

+42-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,48 @@ import MdEditor from 'react-markdown-editor-lite';
55

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

8-
const mdParser = new MarkdownIt();
8+
const mdParser = new MarkdownIt('commonmark', {
9+
html: true,
10+
});
11+
12+
const getAttributes = (content: string = 'image') => {
13+
const attrs = content.split(' ');
14+
const alt = attrs.shift();
15+
16+
const attributes = attrs.reduce((prev: string[], curr) => {
17+
const [key, value] = curr.split('=');
18+
19+
if (!key) {
20+
return prev;
21+
}
22+
23+
if (!value) {
24+
return prev.concat(`${key}`);
25+
}
26+
27+
return prev.concat(`${key}="${value}"`);
28+
}, []);
29+
30+
return {
31+
alt,
32+
attributes,
33+
};
34+
};
35+
36+
mdParser.renderer.rules.image = function (tokens, index) {
37+
const token = tokens[index];
38+
const srcIndex = token.attrIndex('src');
39+
40+
if (!token.attrs) {
41+
return '';
42+
}
43+
44+
const src = token.attrs[srcIndex][1];
45+
const content = mdParser.utils.escapeHtml(token.content);
46+
const { alt, attributes } = getAttributes(content);
47+
48+
return `<img src="${src}" alt="${alt}" ${attributes.join(' ')}/>`;
49+
};
950

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

0 commit comments

Comments
 (0)