site: refactor CC => FC (#40043)

* fix

* fix

* fix
This commit is contained in:
lijianan 2023-01-05 20:10:03 +08:00 committed by GitHub
parent 46d733447a
commit e4dd7096af
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -4,7 +4,7 @@ import type { Project } from '@stackblitz/sdk';
import { Alert, Badge, Tooltip, Space } from 'antd';
import classNames from 'classnames';
import LZString from 'lz-string';
import React from 'react';
import React, { useContext, useEffect, useRef, useState } from 'react';
import CopyToClipboard from 'react-copy-to-clipboard';
import ReactDOM from 'react-dom';
import { FormattedMessage } from 'dumi';
@ -29,151 +29,105 @@ function compress(string: string): string {
.replace(/=+$/, ''); // Remove ending '='
}
const track = ({ type, demo }: { type: string; demo: string }) => {
if (!window.gtag) {
return;
}
window.gtag('event', 'demo', { event_category: type, event_label: demo });
};
interface DemoProps {
meta: any;
intl: any;
utils?: any;
src: string;
content: string;
preview: (react: typeof React, reactDOM: typeof ReactDOM) => React.ReactNode;
highlightedCodes: Record<PropertyKey, string>;
style: string;
highlightedStyle: string;
expand: boolean;
intl: any;
sourceCodes: Record<'jsx' | 'tsx', string>;
location: Location;
showRiddleButton: boolean;
utils?: any;
preview: (react: typeof React, reactDOM: typeof ReactDOM) => React.ReactNode;
}
interface DemoState {
codeType?: string;
copied?: boolean;
codeExpand?: boolean;
copyTooltipOpen?: boolean | string;
}
class Demo extends React.Component<DemoProps, DemoState> {
static contextType = SiteContext;
declare context: SiteContextProps;
liveDemo: any;
iframeRef = React.createRef<HTMLIFrameElement>();
anchorRef = React.createRef<HTMLAnchorElement>();
codeSandboxIconRef = React.createRef<HTMLFormElement>();
riddleIconRef = React.createRef<HTMLFormElement>();
codepenIconRef = React.createRef<HTMLFormElement>();
state: DemoState = {
codeExpand: false,
copied: false,
copyTooltipOpen: false,
codeType: 'tsx',
};
componentDidMount() {
const { meta, location } = this.props;
if (meta.id === location.hash.slice(1)) {
this.anchorRef.current?.click();
}
}
shouldComponentUpdate(nextProps: DemoProps, nextState: DemoState) {
const { codeExpand, copied, copyTooltipOpen, codeType } = this.state;
const { expand, showRiddleButton } = this.props;
return (
(codeExpand || expand) !== (nextState.codeExpand || nextProps.expand) ||
copied !== nextState.copied ||
copyTooltipOpen !== nextState.copyTooltipOpen ||
codeType !== nextState.copyTooltipOpen ||
nextProps.showRiddleButton !== showRiddleButton
);
}
getSourceCode = () => {
const { sourceCodes } = this.props;
return [sourceCodes.jsx, sourceCodes.tsx];
};
handleCodeExpand = (demo: string) => {
const { codeExpand } = this.state;
this.setState({ codeExpand: !codeExpand });
this.track({ type: 'expand', demo });
};
handleCodeCopied = (demo: string) => {
this.setState({ copied: true });
this.track({ type: 'copy', demo });
};
onCopyTooltipOpenChange = (open: boolean) => {
if (open) {
this.setState({ copyTooltipOpen: open, copied: false });
return;
}
this.setState({ copyTooltipOpen: open });
};
track = ({ type, demo }: { type: string; demo: string }) => {
if (!window.gtag) {
return;
}
window.gtag('event', 'demo', {
event_category: type,
event_label: demo,
});
};
render() {
const { state } = this;
const { props } = this;
const site = this.context;
const Demo: React.FC<DemoProps> = (props) => {
const {
location,
sourceCodes,
meta,
src,
utils,
content,
preview,
highlightedCodes,
style,
highlightedStyle,
expand,
intl: { locale },
showRiddleButton,
preview,
} = props;
const { copied, copyTooltipOpen, codeType } = state;
if (!this.liveDemo) {
this.liveDemo = meta.iframe ? (
const liveDemo = useRef<React.ReactNode>(null);
const anchorRef = useRef<HTMLAnchorElement>(null);
const codeSandboxIconRef = useRef<HTMLFormElement>(null);
const riddleIconRef = useRef<HTMLFormElement>(null);
const codepenIconRef = useRef<HTMLFormElement>(null);
const [codeExpand, setCodeExpand] = useState<boolean>(false);
const [copyTooltipOpen, setCopyTooltipOpen] = useState<boolean>(false);
const [copied, setCopied] = useState<boolean>(false);
const [codeType, setCodeType] = useState<string>('tsx');
const { theme } = useContext<SiteContextProps>(SiteContext);
const handleCodeExpand = (demo: string) => {
setCodeExpand(!codeExpand);
track({ type: 'expand', demo });
};
const handleCodeCopied = (demo: string) => {
setCopied(true);
track({ type: 'copy', demo });
};
const onCopyTooltipOpenChange = (open: boolean) => {
setCopyTooltipOpen(open);
if (open) {
setCopied(false);
}
};
useEffect(() => {
if (meta.id === location.hash.slice(1)) {
anchorRef.current?.click();
}
}, []);
if (!liveDemo.current) {
liveDemo.current = meta.iframe ? (
<BrowserFrame>
<iframe
ref={this.iframeRef}
src={src}
height={meta.iframe}
title="demo"
className="iframe-demo"
/>
<iframe src={src} height={meta.iframe} title="demo" className="iframe-demo" />
</BrowserFrame>
) : (
preview(React, ReactDOM)
);
}
const codeExpand = this.state.codeExpand || expand;
const codeBoxClass = classNames('code-box', {
expand: codeExpand,
expand: codeExpand || expand,
'code-box-debug': meta.debug,
});
const localizedTitle = meta?.title[locale] || meta?.title;
const localizeIntro = content[locale] || content;
const introChildren = <div dangerouslySetInnerHTML={{ __html: localizeIntro }} />;
const highlightClass = classNames('highlight-wrapper', {
'highlight-wrapper-expand': codeExpand,
});
const html = `<!DOCTYPE html>
const html = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
@ -184,9 +138,11 @@ class Demo extends React.Component<DemoProps, DemoState> {
<div id="container" style="padding: 24px" />
<script>const mountNode = document.getElementById('container');</script>
</body>
</html>`;
</html>
`;
const tsconfig = `{
const tsconfig = `
{
"compilerOptions": {
"jsx": "react-jsx",
"target": "esnext",
@ -194,17 +150,16 @@ class Demo extends React.Component<DemoProps, DemoState> {
"esModuleInterop": true,
"moduleResolution": "node",
}
}`;
}
`;
const [sourceCode, sourceCodeTyped] = this.getSourceCode();
const suffix = codeType === 'tsx' ? 'tsx' : 'js';
const dependencies: Record<PropertyKey, string> = sourceCode.split('\n').reduce(
(acc: Record<string, string>, line) => {
const dependencies: Record<PropertyKey, string> = sourceCodes?.jsx.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';
@ -216,17 +171,19 @@ class Demo extends React.Component<DemoProps, DemoState> {
);
dependencies['@ant-design/icons'] = 'latest';
if (suffix === 'tsx') {
dependencies['@types/react'] = '^18.0.0';
dependencies['@types/react-dom'] = '^18.0.0';
}
dependencies.react = '^18.0.0';
dependencies['react-dom'] = '^18.0.0';
const codepenPrefillConfig = {
title: `${localizedTitle} - antd@${dependencies.antd}`,
html,
js: `${'const { createRoot } = ReactDOM;\n'}${sourceCode
js: `${'const { createRoot } = ReactDOM;\n'}${sourceCodes?.jsx
.replace(/import\s+(?:React,\s+)?{(\s+[^}]*\s+)}\s+from\s+'react'/, `const { $1 } = React;`)
.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;')
@ -261,33 +218,24 @@ class Demo extends React.Component<DemoProps, DemoState> {
const riddlePrefillConfig = {
title: `${localizedTitle} - antd@${dependencies.antd}`,
js: `${
/import React(\D*)from 'react';/.test(sourceCode) ? '' : `import React from 'react';\n`
}import { createRoot } from 'react-dom/client';\n${sourceCode.replace(
/import React(\D*)from 'react';/.test(sourceCodes?.jsx) ? '' : `import React from 'react';\n`
}import { createRoot } from 'react-dom/client';\n${sourceCodes?.jsx.replace(
/export default/,
'const ComponentDemo =',
)}\n\ncreateRoot(mountNode).render(<ComponentDemo />);\n`,
css: '',
json: JSON.stringify(
{
name: 'antd-demo',
dependencies,
},
null,
2,
),
json: JSON.stringify({ name: 'antd-demo', dependencies }, null, 2),
};
// Reorder source code
let parsedSourceCode = suffix === 'tsx' ? sourceCodeTyped : sourceCode;
let parsedSourceCode = suffix === 'tsx' ? sourceCodes?.tsx : sourceCodes?.jsx;
let importReactContent = "import React from 'react';";
const importReactReg = /import React(\D*)from 'react';/;
const matchImportReact = parsedSourceCode.match(importReactReg);
if (matchImportReact) {
[importReactContent] = matchImportReact;
parsedSourceCode = parsedSourceCode.replace(importReactReg, '').trim();
}
const demoJsContent = `
${importReactContent}
import './index.css';
@ -327,6 +275,7 @@ createRoot(document.getElementById('container')).render(<Demo />);
},
browserslist: ['>0.2%', 'not dead'],
};
const codesanboxPrefillConfig = {
files: {
'package.json': { content: codesandboxPackage },
@ -338,6 +287,7 @@ createRoot(document.getElementById('container')).render(<Demo />);
},
},
};
const stackblitzPrefillConfig: Project = {
title: `${localizedTitle} - antd@${dependencies.antd}`,
template: 'create-react-app',
@ -350,30 +300,21 @@ createRoot(document.getElementById('container')).render(<Demo />);
'index.html': html,
},
};
if (suffix === 'tsx') {
stackblitzPrefillConfig.files['tsconfig.json'] = tsconfig;
}
const backgroundGrey = site.theme.includes('dark') ? '#303030' : '#f0f2f5';
const codeBoxDemoStyle: React.CSSProperties = {
padding: meta.iframe || meta.compact ? 0 : undefined,
overflow: meta.iframe || meta.compact ? 'hidden' : undefined,
background: meta.background === 'grey' ? backgroundGrey : undefined,
};
const codeBox = (
let codeBox: React.ReactNode = (
<section className={codeBoxClass} id={meta.id}>
<section className="code-box-demo" style={codeBoxDemoStyle}>
<section className="code-box-demo" data-compact={meta.compact}>
<ErrorBoundary>
<React.StrictMode>{this.liveDemo}</React.StrictMode>
<React.StrictMode>{liveDemo.current}</React.StrictMode>
</ErrorBoundary>
{style ? <style dangerouslySetInnerHTML={{ __html: style }} /> : null}
</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.anchorRef}>
<a href={`#${meta.id}`} ref={anchorRef}>
{localizedTitle}
</a>
</Tooltip>
@ -390,10 +331,10 @@ createRoot(document.getElementById('container')).render(<Demo />);
action="//riddle.alibaba-inc.com/riddles/define"
method="POST"
target="_blank"
ref={this.riddleIconRef}
ref={riddleIconRef}
onClick={() => {
this.track({ type: 'riddle', demo: meta.id });
this.riddleIconRef.current?.submit();
track({ type: 'riddle', demo: meta.id });
riddleIconRef.current?.submit();
}}
>
<input type="hidden" name="data" value={JSON.stringify(riddlePrefillConfig)} />
@ -407,10 +348,10 @@ createRoot(document.getElementById('container')).render(<Demo />);
action="https://codesandbox.io/api/v1/sandboxes/define"
method="POST"
target="_blank"
ref={this.codeSandboxIconRef}
ref={codeSandboxIconRef}
onClick={() => {
this.track({ type: 'codesandbox', demo: meta.id });
this.codeSandboxIconRef.current?.submit();
track({ type: 'codesandbox', demo: meta.id });
codeSandboxIconRef.current?.submit();
}}
>
<input
@ -427,10 +368,10 @@ createRoot(document.getElementById('container')).render(<Demo />);
action="https://codepen.io/pen/define"
method="POST"
target="_blank"
ref={this.codepenIconRef}
ref={codepenIconRef}
onClick={() => {
this.track({ type: 'codepen', demo: meta.id });
this.codepenIconRef.current?.submit();
track({ type: 'codepen', demo: meta.id });
codepenIconRef.current?.submit();
}}
>
<input type="hidden" name="data" value={JSON.stringify(codepenPrefillConfig)} />
@ -442,7 +383,7 @@ createRoot(document.getElementById('container')).render(<Demo />);
<span
className="code-box-code-action"
onClick={() => {
this.track({ type: 'stackblitz', demo: meta.id });
track({ type: 'stackblitz', demo: meta.id });
stackblitzSdk.openProject(stackblitzPrefillConfig, {
openFile: [`demo.${suffix}`],
});
@ -451,10 +392,10 @@ createRoot(document.getElementById('container')).render(<Demo />);
<ThunderboltOutlined className="code-box-stackblitz" />
</span>
</Tooltip>
<CopyToClipboard text={sourceCodeTyped} onCopy={() => this.handleCodeCopied(meta.id)}>
<CopyToClipboard text={sourceCodes?.tsx} onCopy={() => handleCodeCopied(meta.id)}>
<Tooltip
open={copyTooltipOpen as boolean}
onOpenChange={this.onCopyTooltipOpenChange}
onOpenChange={onCopyTooltipOpenChange}
title={<FormattedMessage id={`app.demo.${copied ? 'copied' : 'copy'}`} />}
>
{React.createElement(copied && copyTooltipOpen ? CheckOutlined : SnippetsOutlined, {
@ -475,22 +416,22 @@ createRoot(document.getElementById('container')).render(<Demo />);
<img
alt="expand code"
src={
site.theme.includes('dark')
theme?.includes('dark')
? 'https://gw.alipayobjects.com/zos/antfincdn/btT3qDZn1U/wSAkBuJFbdxsosKKpqyq.svg'
: 'https://gw.alipayobjects.com/zos/antfincdn/Z5c7kzvi30/expand.svg'
}
className={codeExpand ? 'code-expand-icon-hide' : 'code-expand-icon-show'}
onClick={() => this.handleCodeExpand(meta.id)}
onClick={() => handleCodeExpand(meta.id)}
/>
<img
alt="expand code"
src={
site.theme.includes('dark')
theme?.includes('dark')
? 'https://gw.alipayobjects.com/zos/antfincdn/CjZPwcKUG3/OpROPHYqWmrMDBFMZtKF.svg'
: 'https://gw.alipayobjects.com/zos/antfincdn/4zAaozCvUH/unexpand.svg'
}
className={codeExpand ? 'code-expand-icon-show' : 'code-expand-icon-hide'}
onClick={() => this.handleCodeExpand(meta.id)}
onClick={() => handleCodeExpand(meta.id)}
/>
</div>
</Tooltip>
@ -499,8 +440,8 @@ createRoot(document.getElementById('container')).render(<Demo />);
<section className={highlightClass} key="code">
<CodePreview
codes={highlightedCodes}
toReactComponent={props.utils?.toReactComponent}
onCodeTypeChange={(type) => this.setState({ codeType: type })}
toReactComponent={utils?.toReactComponent}
onCodeTypeChange={(type) => setCodeType(type)}
/>
{highlightedStyle ? (
<div key="style" className="highlight">
@ -514,15 +455,14 @@ createRoot(document.getElementById('container')).render(<Demo />);
);
if (meta.version) {
return (
<Badge.Ribbon text={meta.version} color={meta.version.includes('<') ? 'red' : undefined}>
codeBox = (
<Badge.Ribbon text={meta.version} color={meta.version.includes('<') ? 'red' : null}>
{codeBox}
</Badge.Ribbon>
);
}
return codeBox;
}
}
};
export default fromDumiProps(Demo);