ant-design/site/component/utils.js

79 lines
1.9 KiB
JavaScript
Raw Normal View History

2016-02-29 14:08:40 +08:00
import React from 'react';
2016-03-04 15:19:23 +08:00
import ReactDOM from 'react-dom';
2016-03-07 17:33:38 +08:00
import { Link } from 'react-router';
import hljs from 'highlight.js';
2016-03-07 10:32:14 +08:00
import antd from '../../';
2016-02-29 14:08:40 +08:00
2016-03-01 16:20:32 +08:00
function isHeading(type) {
return /h[1-6]/i.test(type);
}
2016-03-07 11:35:23 +08:00
function mdLangToHljsLang(lang) {
return lang.toLowerCase() === 'jsx' ?
'javascript' :
lang;
}
2016-03-07 17:33:38 +08:00
export function objectToComponent(pathname, object, index) {
if (object === null) return;
2016-02-29 14:08:40 +08:00
2016-03-02 17:12:43 +08:00
if (React.isValidElement(object)) {
return React.cloneElement(object, { key: index });
}
2016-03-03 17:23:08 +08:00
if (typeof object === 'function') {
2016-03-21 10:44:31 +08:00
return React.cloneElement(object(React, ReactDOM, antd, antd), { key: index });
2016-03-03 17:23:08 +08:00
}
2016-03-01 12:06:01 +08:00
if (typeof object === 'string') {
return <span key={index}>{ object }</span>;
}
2016-02-29 14:08:40 +08:00
const children = object.children;
if (object.type === 'html') {
return React.createElement('div', {
2016-03-07 11:35:23 +08:00
className: 'markdown',
2016-02-29 14:08:40 +08:00
key: index,
dangerouslySetInnerHTML: { __html: children }
});
}
2016-03-07 11:35:23 +08:00
if (isHeading(object.type)) {
return React.createElement(object.type, {
key: index,
2016-03-07 17:33:38 +08:00
id: children,
2016-03-07 11:35:23 +08:00
}, [
2016-03-21 10:44:31 +08:00
<span key="title" dangerouslySetInnerHTML={{ __html: object.children }} />,
2016-03-07 17:33:38 +08:00
<Link to={{ pathname, query: { scrollTo: object.children } }} className="anchor" key="anchor">#</Link>,
2016-03-07 11:35:23 +08:00
]);
}
if (object.type === 'code') {
2016-03-07 11:35:23 +08:00
const highlightedCode = hljs.highlight(
mdLangToHljsLang(object.props.lang),
children
).value;
return (
<div className="highlight" key={index}>
<pre>
<code className={object.props.lang}
dangerouslySetInnerHTML={{ __html: highlightedCode }} />
</pre>
</div>
);
}
2016-02-29 14:08:40 +08:00
if (typeof children === 'string') {
return React.createElement(object.type, {
key: index,
dangerouslySetInnerHTML: { __html: children }
});
}
2016-03-07 11:35:23 +08:00
2016-02-29 14:08:40 +08:00
return React.createElement(
object.type, { key: index },
2016-03-07 17:33:38 +08:00
children && children.map(objectToComponent.bind(null, pathname)) // `hr` has no children
2016-02-29 14:08:40 +08:00
);
}