ant-design/site/theme/template/Content/Demo/index.jsx

357 lines
12 KiB
React
Raw Normal View History

/* eslint jsx-a11y/no-noninteractive-element-interactions: 0 */
2016-02-29 14:08:40 +08:00
import React from 'react';
import ReactDOM from 'react-dom';
2019-08-08 12:35:48 +08:00
import { FormattedMessage, injectIntl } from 'react-intl';
import CopyToClipboard from 'react-copy-to-clipboard';
import classNames from 'classnames';
2017-12-29 17:02:45 +08:00
import LZString from 'lz-string';
use ant design icons 4.0 (#18217) * feat: use @ant-design/icons@4.0 * feat: use createFromIconfontCN to make site works * feat: update doc for Icon * feat: use icon in component Alert * feat: use icon in component Avatar * feat: use icon in component Breadcrumb * feat: use icon in component Button * feat: use icon in component Cascader * feat: use icon in component Collapse * feat: use icon in component Datepicker * feat: use icon in component Dropdown * feat: use icon in component Form * feat: use icon in component Input * feat: use icon in component InputNumber * feat: use icon in component Layout * feat: use icon in component Mention * feat: use icon in component Message * feat: use icon in component Modal * feat: use icon in component Notification * feat: use icon in component PageHeader * feat: use icon in component Pagination * feat: use icon in component Popconfirm * feat: use icon in component Progress * feat: use icon in component Rate * feat: use icon in component Result * feat: use icon in component Select * feat: use icon in component Step * feat: use icon in component Switch * feat: use icon in component Table * feat: use icon in component Tab * feat: use icon in component Tag * feat: handle rest component which using Icon * fix: remove unused vars * feat: use latest alpha ant design icons * fix: failed test in uploadlist.test.js * test: update snapshot for icons * doc: add Icon for site * doc: use @ant-design/icons in site * chore: use latest icons * fix: tslint issue * fix: test cases * fix: types for react * fix: lint rules for import orders * fix: use @ant-design/icons@4.0.0-alpha.5 to avoid insert css in server render * fix: eslint error in demo/**.md * inject antd icons * update snapshot * fix site * doc: update docs * fix: code snippets icon in site * feat: use latest @ant-design/icons * fix: icon props in message
2019-08-13 14:07:17 +08:00
import { Tooltip } from 'antd';
import { SnippetsOutlined, CheckOutlined, ThunderboltOutlined } from '@ant-design/icons';
import stackblitzSdk from '@stackblitz/sdk';
import CodePreview from './CodePreview';
import EditButton from '../EditButton';
import ErrorBoundary from '../ErrorBoundary';
import BrowserFrame from '../../BrowserFrame';
2016-05-11 11:36:47 +08:00
2017-12-29 17:02:45 +08:00
function compress(string) {
return LZString.compressToBase64(string)
.replace(/\+/g, '-') // Convert '+' to '-'
.replace(/\//g, '_') // Convert '/' to '_'
.replace(/=+$/, ''); // Remove ending '='
}
2019-08-08 12:35:48 +08:00
class Demo extends React.Component {
2018-08-02 16:25:47 +08:00
state = {
codeExpand: false,
copied: false,
copyTooltipVisible: false,
};
2016-03-01 14:53:32 +08:00
componentDidMount() {
const { meta, location } = this.props;
if (meta.id === location.hash.slice(1)) {
this.anchor.click();
}
}
2018-11-28 15:00:03 +08:00
shouldComponentUpdate(nextProps, nextState) {
const { codeExpand, copied, copyTooltipVisible } = this.state;
const { expand } = this.props;
2018-12-07 16:17:45 +08:00
return (
(codeExpand || expand) !== (nextState.codeExpand || nextProps.expand) ||
copied !== nextState.copied ||
copyTooltipVisible !== nextState.copyTooltipVisible
);
2018-11-28 15:00:03 +08:00
}
getSourceCode() {
const { highlightedCode } = this.props;
2018-10-31 13:15:40 +08:00
if (typeof document !== 'undefined') {
const div = document.createElement('div');
div.innerHTML = highlightedCode[1].highlighted;
return div.textContent;
}
return '';
}
2019-04-04 15:33:56 +08:00
handleCodeExpand = demo => {
const { codeExpand } = this.state;
this.setState({ codeExpand: !codeExpand });
2019-04-04 15:33:56 +08:00
this.track({
type: 'expand',
demo,
});
2018-12-07 16:17:45 +08:00
};
2018-12-07 16:17:45 +08:00
saveAnchor = anchor => {
this.anchor = anchor;
2018-12-07 16:17:45 +08:00
};
2019-04-04 15:33:56 +08:00
handleCodeCopied = demo => {
2017-03-02 15:08:42 +08:00
this.setState({ copied: true });
2019-04-04 15:33:56 +08:00
this.track({
type: 'copy',
demo,
});
2018-12-07 16:17:45 +08:00
};
2017-03-02 15:08:42 +08:00
2018-12-07 16:17:45 +08:00
onCopyTooltipVisibleChange = visible => {
2017-03-02 15:08:42 +08:00
if (visible) {
this.setState({
copyTooltipVisible: visible,
copied: false,
});
return;
}
this.setState({
copyTooltipVisible: visible,
});
2018-12-07 16:17:45 +08:00
};
2017-03-02 15:08:42 +08:00
2019-04-04 15:33:56 +08:00
// eslint-disable-next-line
track({ type, demo }) {
if (!window.gtag) {
return;
}
window.gtag('event', 'demo', {
event_category: type,
event_label: demo,
});
}
2016-02-29 14:08:40 +08:00
render() {
2017-10-09 13:23:20 +08:00
const { state } = this;
const { props } = this;
const {
meta,
src,
content,
preview,
highlightedCodes,
style,
highlightedStyle,
expand,
2019-08-12 13:34:23 +08:00
utils,
intl: { locale },
} = props;
2019-08-12 13:34:23 +08:00
const { copied, copyTooltipVisible } = state;
if (!this.liveDemo) {
2018-12-07 16:17:45 +08:00
this.liveDemo = meta.iframe ? (
<BrowserFrame>
<iframe src={src} height={meta.iframe} title="demo" />
</BrowserFrame>
) : (
preview(React, ReactDOM)
);
}
2019-08-08 12:35:48 +08:00
const codeExpand = this.state.codeExpand || expand;
const codeBoxClass = classNames('code-box', {
expand: codeExpand,
'code-box-debug': meta.debug,
});
const localizedTitle = meta.title[locale] || meta.title;
const localizeIntro = content[locale] || content;
2019-08-08 12:35:48 +08:00
const introChildren = utils.toReactComponent(['div'].concat(localizeIntro));
const highlightClass = classNames({
'highlight-wrapper': true,
'highlight-wrapper-expand': codeExpand,
});
2018-12-07 16:17:45 +08:00
const prefillStyle = `@import 'antd/dist/antd.css';\n\n${style || ''}`.replace(
new RegExp(`#${meta.id}\\s*`, 'g'),
'',
);
2017-12-29 17:02:45 +08:00
const html = `<div id="container" style="padding: 24px"></div>
<script>
var mountNode = document.getElementById('container');
</script>`;
2017-07-10 22:17:52 +08:00
const sourceCode = this.getSourceCode();
const codepenPrefillConfig = {
title: `${localizedTitle} - Ant Design Demo`,
2017-12-29 17:02:45 +08:00
html,
js: sourceCode
.replace(/import\s+\{\s+(.*)\s+\}\s+from\s+'antd';/, 'const { $1 } = antd;')
.replace("import moment from 'moment';", '')
.replace(/import\s+\{\s+(.*)\s+\}\s+from\s+'react-router';/, 'const { $1 } = ReactRouter;')
2018-12-07 16:17:45 +08:00
.replace(
/import\s+\{\s+(.*)\s+\}\s+from\s+'react-router-dom';/,
'const { $1 } = ReactRouterDOM;',
)
.replace(/([a-zA-Z]*)\s+as\s+([a-zA-Z]*)/, '$1:$2'),
2017-07-10 22:17:52 +08:00
css: prefillStyle,
editors: '001',
css_external: 'https://unpkg.com/antd/dist/antd.css',
js_external: [
'react@16.x/umd/react.development.js',
'react-dom@16.x/umd/react-dom.development.js',
'moment/min/moment-with-locales.js',
'antd/dist/antd-with-locales.js',
'react-router-dom/umd/react-router-dom.min.js',
'react-router@3.x/umd/ReactRouter.min.js',
2018-12-07 16:17:45 +08:00
]
.map(url => `https://unpkg.com/${url}`)
.join(';'),
js_pre_processor: 'typescript',
};
2017-07-10 22:17:52 +08:00
const riddlePrefillConfig = {
title: `${localizedTitle} - Ant Design Demo`,
js: sourceCode,
2017-07-10 22:17:52 +08:00
css: prefillStyle,
};
2018-12-07 16:17:45 +08:00
const dependencies = sourceCode.split('\n').reduce(
(acc, line) => {
const matches = line.match(/import .+? from '(.+)';$/);
if (matches && matches[1] && !line.includes('antd')) {
const [dep] = matches[1].split('/');
if (dep) {
acc[dep] = 'latest';
}
2018-12-07 16:17:45 +08:00
}
return acc;
},
{ react: 'latest', 'react-dom': 'latest', antd: 'latest' },
2018-12-07 16:17:45 +08:00
);
const indexJsContent = `
2017-12-29 17:02:45 +08:00
import React from 'react';
import ReactDOM from 'react-dom';
import 'antd/dist/antd.css';
import './index.css';
2018-12-07 16:17:45 +08:00
${sourceCode.replace('mountNode', "document.getElementById('container')")}
`;
const indexCssContent = (style || '').replace(new RegExp(`#${meta.id}\\s*`, 'g'), '');
const codesanboxPrefillConfig = {
files: {
'package.json': { content: { dependencies } },
'index.css': { content: indexCssContent },
'index.js': { content: indexJsContent },
2017-12-29 17:02:45 +08:00
'index.html': {
content: html,
},
},
};
const stackblitzPrefillConfig = {
title: `${localizedTitle} - Ant Design Demo`,
template: 'create-react-app',
dependencies,
files: {
'index.css': indexCssContent,
'index.js': indexJsContent,
'index.html': html,
},
};
2016-02-29 14:08:40 +08:00
return (
<section className={codeBoxClass} id={meta.id}>
2016-02-29 14:08:40 +08:00
<section className="code-box-demo">
2018-12-07 16:17:45 +08:00
<ErrorBoundary>{this.liveDemo}</ErrorBoundary>
{style ? (
<style dangerouslySetInnerHTML={{ __html: style }} /> // eslint-disable-line
) : null}
2016-02-29 14:08:40 +08:00
</section>
<section className="code-box-meta markdown">
<div className="code-box-title">
<Tooltip title={meta.debug ? <FormattedMessage id="app.demo.debug" /> : ''}>
<a href={`#${meta.id}`} ref={this.saveAnchor}>
{localizedTitle}
</a>
</Tooltip>
2018-12-07 16:17:45 +08:00
<EditButton
2019-04-03 16:27:10 +08:00
title={<FormattedMessage id="app.content.edit-demo" />}
2018-12-07 16:17:45 +08:00
filename={meta.filename}
/>
2016-02-29 14:08:40 +08:00
</div>
2019-04-03 16:27:10 +08:00
<div className="code-box-description">{introChildren}</div>
<div className="code-box-actions">
2019-04-04 15:33:56 +08:00
<form
action="//riddle.alibaba-inc.com/riddles/define"
method="POST"
target="_blank"
onClick={() => this.track({ type: 'riddle', demo: meta.id })}
>
<input type="hidden" name="data" value={JSON.stringify(riddlePrefillConfig)} />
<Tooltip title={<FormattedMessage id="app.demo.riddle" />}>
<input
type="submit"
value="Create New Riddle with Prefilled Data"
className="code-box-riddle"
/>
</Tooltip>
</form>
2019-04-04 15:33:56 +08:00
<form
action="https://codepen.io/pen/define"
method="POST"
target="_blank"
onClick={() => this.track({ type: 'codepen', demo: meta.id })}
>
<input type="hidden" name="data" value={JSON.stringify(codepenPrefillConfig)} />
<Tooltip title={<FormattedMessage id="app.demo.codepen" />}>
<input
type="submit"
value="Create New Pen with Prefilled Data"
className="code-box-codepen"
/>
</Tooltip>
</form>
<form
action="https://codesandbox.io/api/v1/sandboxes/define"
method="POST"
target="_blank"
2019-04-04 15:33:56 +08:00
onClick={() => this.track({ type: 'codesandbox', demo: meta.id })}
>
<input
type="hidden"
name="parameters"
value={compress(JSON.stringify(codesanboxPrefillConfig))}
2017-08-15 21:00:31 +08:00
/>
<Tooltip title={<FormattedMessage id="app.demo.codesandbox" />}>
2018-12-07 16:17:45 +08:00
<input
type="submit"
value="Create New Sandbox with Prefilled Data"
className="code-box-codesandbox"
2018-12-07 16:17:45 +08:00
/>
</Tooltip>
</form>
<Tooltip title={<FormattedMessage id="app.demo.stackblitz" />}>
<span
className="code-box-code-action"
onClick={() => {
this.track({ type: 'stackblitz', demo: meta.id });
stackblitzSdk.openProject(stackblitzPrefillConfig);
}}
>
<ThunderboltOutlined />
</span>
</Tooltip>
2019-04-04 15:33:56 +08:00
<CopyToClipboard text={sourceCode} onCopy={() => this.handleCodeCopied(meta.id)}>
<Tooltip
2019-08-08 12:35:48 +08:00
visible={copyTooltipVisible}
onVisibleChange={this.onCopyTooltipVisibleChange}
title={<FormattedMessage id={`app.demo.${copied ? 'copied' : 'copy'}`} />}
>
{React.createElement(
copied && copyTooltipVisible ? CheckOutlined : SnippetsOutlined,
{
className: 'code-box-code-copy',
},
)}
</Tooltip>
</CopyToClipboard>
2019-04-03 16:27:10 +08:00
<Tooltip
title={<FormattedMessage id={`app.demo.code.${codeExpand ? 'hide' : 'show'}`} />}
>
<span className="code-expand-icon">
<img
alt="expand code"
src="https://gw.alipayobjects.com/zos/rmsportal/wSAkBuJFbdxsosKKpqyq.svg"
className={codeExpand ? 'code-expand-icon-hide' : 'code-expand-icon-show'}
2019-04-04 15:33:56 +08:00
onClick={() => this.handleCodeExpand(meta.id)}
/>
<img
alt="expand code"
src="https://gw.alipayobjects.com/zos/rmsportal/OpROPHYqWmrMDBFMZtKF.svg"
className={codeExpand ? 'code-expand-icon-show' : 'code-expand-icon-hide'}
2019-04-04 15:33:56 +08:00
onClick={() => this.handleCodeExpand(meta.id)}
/>
</span>
</Tooltip>
2016-03-25 17:07:00 +08:00
</div>
</section>
<section className={highlightClass} key="code">
<CodePreview toReactComponent={props.utils.toReactComponent} codes={highlightedCodes} />
2018-12-07 16:17:45 +08:00
{highlightedStyle ? (
<div key="style" className="highlight">
<pre>
<code className="css" dangerouslySetInnerHTML={{ __html: highlightedStyle }} />
2018-12-07 16:17:45 +08:00
</pre>
</div>
) : null}
2016-03-25 17:07:00 +08:00
</section>
2016-02-29 14:08:40 +08:00
</section>
);
}
}
2019-08-08 12:35:48 +08:00
export default injectIntl(Demo);