/* eslint jsx-a11y/no-noninteractive-element-interactions: 0 */
import React from 'react';
import ReactDOM from 'react-dom';
import { FormattedMessage, injectIntl } from 'react-intl';
import CopyToClipboard from 'react-copy-to-clipboard';
import classNames from 'classnames';
import LZString from 'lz-string';
import { Tooltip, Alert } from 'antd';
import { SnippetsOutlined, CheckOutlined, ThunderboltOutlined } from '@ant-design/icons';
import stackblitzSdk from '@stackblitz/sdk';
import CodePreview from './CodePreview';
import EditButton from '../EditButton';
import BrowserFrame from '../../BrowserFrame';
const { ErrorBoundary } = Alert;
function compress(string) {
return LZString.compressToBase64(string)
.replace(/\+/g, '-') // Convert '+' to '-'
.replace(/\//g, '_') // Convert '/' to '_'
.replace(/=+$/, ''); // Remove ending '='
}
class Demo extends React.Component {
iframeRef = React.createRef();
state = {
codeExpand: false,
copied: false,
copyTooltipVisible: false,
};
componentDidMount() {
const { meta, location } = this.props;
if (meta.id === location.hash.slice(1)) {
this.anchor.click();
}
}
shouldComponentUpdate(nextProps, nextState) {
const { codeExpand, copied, copyTooltipVisible } = this.state;
const { expand, theme } = this.props;
return (
(codeExpand || expand) !== (nextState.codeExpand || nextProps.expand) ||
copied !== nextState.copied ||
copyTooltipVisible !== nextState.copyTooltipVisible ||
nextProps.theme !== theme
);
}
getSourceCode() {
const { highlightedCodes } = this.props;
if (typeof document !== 'undefined') {
const div = document.createElement('div');
div.innerHTML = highlightedCodes.jsx;
return div.textContent;
}
return '';
}
handleCodeExpand = demo => {
const { codeExpand } = this.state;
this.setState({ codeExpand: !codeExpand });
this.track({
type: 'expand',
demo,
});
};
saveAnchor = anchor => {
this.anchor = anchor;
};
handleCodeCopied = demo => {
this.setState({ copied: true });
this.track({
type: 'copy',
demo,
});
};
onCopyTooltipVisibleChange = visible => {
if (visible) {
this.setState({
copyTooltipVisible: visible,
copied: false,
});
return;
}
this.setState({
copyTooltipVisible: visible,
});
};
// eslint-disable-next-line class-methods-use-this
track({ type, demo }) {
if (!window.gtag) {
return;
}
window.gtag('event', 'demo', {
event_category: type,
event_label: demo,
});
}
handleIframeReady = () => {
const { theme, setIframeTheme } = this.props;
if (this.iframeRef.current) {
setIframeTheme(this.iframeRef.current, theme);
}
};
render() {
const { state } = this;
const { props } = this;
const {
meta,
src,
content,
preview,
highlightedCodes,
style,
highlightedStyle,
expand,
utils,
intl: { locale },
theme,
} = props;
const { copied, copyTooltipVisible } = state;
if (!this.liveDemo) {
this.liveDemo = meta.iframe ? (
) : (
preview(React, ReactDOM)
);
}
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;
const introChildren = utils.toReactComponent(['div'].concat(localizeIntro));
const highlightClass = classNames({
'highlight-wrapper': true,
'highlight-wrapper-expand': codeExpand,
});
const prefillStyle = `@import 'antd/dist/antd.css';\n\n${style || ''}`.replace(
new RegExp(`#${meta.id}\\s*`, 'g'),
'',
);
const html = `
`;
const sourceCode = this.getSourceCode();
const codepenPrefillConfig = {
title: `${localizedTitle} - Ant Design Demo`,
html,
js: sourceCode
.replace(/import\s+{(\s+[^}]*\s+)}\s+from\s+'antd';/, 'const { $1 } = antd;')
.replace(
/import\s+{(\s+[^}]*\s+)}\s+from\s+'@ant-design\/icons';/,
'const { $1 } = icons;',
)
.replace("import moment from 'moment';", '')
.replace(/import\s+{\s+(.*)\s+}\s+from\s+'react-router';/, 'const { $1 } = ReactRouter;')
.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'),
css: prefillStyle,
editors: '001',
// eslint-disable-next-line no-undef
css_external: `https://unpkg.com/antd@${antdReproduceVersion}/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',
// eslint-disable-next-line no-undef
`antd@${antdReproduceVersion}/dist/antd-with-locales.js`,
`@ant-design/icons/dist/index.umd.js`,
'react-router-dom/umd/react-router-dom.min.js',
'react-router@3.x/umd/ReactRouter.min.js',
]
.map(url => `https://unpkg.com/${url}`)
.join(';'),
js_pre_processor: 'typescript',
};
const riddlePrefillConfig = {
title: `${localizedTitle} - Ant Design Demo`,
js: sourceCode,
css: prefillStyle,
};
const dependencies = sourceCode.split('\n').reduce(
(acc, line) => {
const matches = line.match(/import .+? from '(.+)';$/);
if (matches && matches[1] && !line.includes('antd')) {
const paths = matches[1].split('/');
if (paths.length) {
const dep = paths[0].startsWith('@') ? `${paths[0]}/${paths[1]}` : paths[0];
acc[dep] = 'latest';
}
}
return acc;
},
// eslint-disable-next-line no-undef
{ antd: antdReproduceVersion },
);
dependencies['@ant-design/icons'] = 'latest';
// Reorder source code
let parsedSourceCode = sourceCode;
let importReactContent = "import React from 'react';";
const importReactReg = /import(\D*)from 'react';/;
const matchImportReact = parsedSourceCode.match(importReactReg);
if (matchImportReact) {
importReactContent = matchImportReact[0];
parsedSourceCode = parsedSourceCode.replace(importReactReg, '').trim();
}
const indexJsContent = `
${importReactContent}
import ReactDOM from 'react-dom';
import 'antd/dist/antd.css';
import './index.css';
${parsedSourceCode.replace('mountNode', "document.getElementById('container')")}
`.trim();
const indexCssContent = (style || '').replace(new RegExp(`#${meta.id}\\s*`, 'g'), '');
const codesandboxPackage = {
name: `${localizedTitle} - Ant Design Demo`,
version: '1.0.0',
main: 'index.js',
dependencies: {
...dependencies,
react: '^16.12.0',
'react-dom': '^16.12.0',
'react-scripts': '^3.0.1',
},
devDependencies: {
typescript: '^3.8.2',
},
scripts: {
start: 'react-scripts start',
build: 'react-scripts build',
test: 'react-scripts test --env=jsdom',
eject: 'react-scripts eject',
},
browserslist: ['>0.2%', 'not dead', 'not ie <= 11', 'not op_mini all'],
};
const codesanboxPrefillConfig = {
files: {
'package.json': { content: codesandboxPackage },
'index.css': { content: indexCssContent },
'index.js': { content: indexJsContent },
'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,
},
};
return (
);
}
}
export default injectIntl(Demo);