ant-design/site/component/utils.js

95 lines
2.3 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';
import hljs from 'highlight.js';
2016-03-03 17:23:08 +08:00
import antd, { Menu } 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-02-29 14:08:40 +08:00
export function objectToComponent(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-04 15:19:23 +08:00
return object(React, ReactDOM, antd, antd);
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', {
key: index,
dangerouslySetInnerHTML: { __html: children }
});
}
if (object.type === 'code') {
const highlightedCode = hljs.highlight('javascript', children).value;
return (
<div className="highlight" key={index}>
<pre>
<code className={object.props.lang}
dangerouslySetInnerHTML={{ __html: highlightedCode }} />
</pre>
</div>
);
}
2016-03-01 16:20:32 +08:00
if (isHeading(object.type)) {
return React.createElement(object.type, {
key: index,
}, [
object.children,
<a className="anchor" key="anchor">#</a>,
]);
}
2016-02-29 14:08:40 +08:00
if (typeof children === 'string') {
return React.createElement(object.type, {
key: index,
dangerouslySetInnerHTML: { __html: children }
});
}
return React.createElement(
object.type, { key: index },
2016-02-29 14:08:40 +08:00
children && children.map(objectToComponent) // `hr` has no children
);
}
2016-03-01 11:46:18 +08:00
export function flattenMenu(menu) {
if (menu.type === Menu.Item) {
return menu;
}
if (Array.isArray(menu)) {
return menu.reduce((acc, item) => {
return acc.concat(flattenMenu(item));
}, []);
}
return flattenMenu(menu.props.children);
}
2016-03-01 17:05:24 +08:00
export function getActiveMenuItem(props, index) {
const routes = props.routes;
return routes[routes.length - 1].path || index;
}
export function getFooterNav(menuItems, activeMenuItem) {
const menuItemsList = flattenMenu(menuItems);
const activeMenuItemIndex = menuItemsList.findIndex((menuItem) => {
return menuItem.key === activeMenuItem;
});
const prev = menuItemsList[activeMenuItemIndex - 1];
const next = menuItemsList[activeMenuItemIndex + 1];
return { prev, next };
}