Skip to content

Commit

Permalink
docs: move copy button into code previewer (ant-design#45099)
Browse files Browse the repository at this point in the history
  • Loading branch information
afc163 authored Sep 26, 2023
1 parent e91abf3 commit 07eb5ba
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 44 deletions.
40 changes: 4 additions & 36 deletions .dumi/theme/builtins/Previewer/CodePreviewer.tsx
Original file line number Diff line number Diff line change
@@ -1,19 +1,12 @@
import React, { useContext, useEffect, useRef, useState } from 'react';
import {
CheckOutlined,
LinkOutlined,
SnippetsOutlined,
ThunderboltOutlined,
UpOutlined,
} from '@ant-design/icons';
import { LinkOutlined, ThunderboltOutlined, UpOutlined } from '@ant-design/icons';
import type { Project } from '@stackblitz/sdk';
import stackblitzSdk from '@stackblitz/sdk';
import { Alert, Badge, Space, Tooltip } from 'antd';
import { createStyles, css } from 'antd-style';
import classNames from 'classnames';
import { FormattedMessage, useSiteData } from 'dumi';
import LZString from 'lz-string';
import CopyToClipboard from 'react-copy-to-clipboard';

import type { AntdPreviewerProps } from '.';
import useLocation from '../../../hooks/useLocation';
Expand Down Expand Up @@ -125,8 +118,6 @@ const CodePreviewer: React.FC<AntdPreviewerProps> = (props) => {
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);

Expand All @@ -147,18 +138,6 @@ const CodePreviewer: React.FC<AntdPreviewerProps> = (props) => {
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 (asset.id === hash.slice(1)) {
anchorRef.current?.click();
Expand Down Expand Up @@ -483,17 +462,6 @@ createRoot(document.getElementById('container')).render(<Demo />);
<ThunderboltOutlined className="code-box-stackblitz" />
</span>
</Tooltip>
<CopyToClipboard text={parsedSourceCode} onCopy={() => handleCodeCopied(asset.id)}>
<Tooltip
open={copyTooltipOpen as boolean}
onOpenChange={onCopyTooltipOpenChange}
title={<FormattedMessage id={`app.demo.${copied ? 'copied' : 'copy'}`} />}
>
{React.createElement(copied && copyTooltipOpen ? CheckOutlined : SnippetsOutlined, {
className: 'code-box-code-copy code-box-code-action',
})}
</Tooltip>
</CopyToClipboard>
<Tooltip title={<FormattedMessage id="app.demo.separate" />}>
<a
className="code-box-code-action"
Expand Down Expand Up @@ -564,10 +532,10 @@ createRoot(document.getElementById('container')).render(<Demo />);
if (!style) {
return;
}
const styleTag = document.createElement('style');
const styleTag = document.createElement('style') as HTMLStyleElement;
styleTag.type = 'text/css';
styleTag.innerHTML = style;
styleTag['data-demo-url'] = demoUrl;
(styleTag as any)['data-demo-url'] = demoUrl;
document.head.appendChild(styleTag);
return () => {
document.head.removeChild(styleTag);
Expand All @@ -576,7 +544,7 @@ createRoot(document.getElementById('container')).render(<Demo />);

if (version) {
return (
<Badge.Ribbon text={version} color={version.includes('<') ? 'red' : null}>
<Badge.Ribbon text={version} color={version.includes('<') ? 'red' : undefined}>
{codeBox}
</Badge.Ribbon>
);
Expand Down
2 changes: 1 addition & 1 deletion .dumi/theme/builtins/Previewer/DesignPreviewer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { CheckOutlined, SketchOutlined } from '@ant-design/icons';
import { nodeToGroup } from 'html2sketch';
import copy from 'copy-to-clipboard';
import { App } from 'antd';
import type { AntdPreviewerProps } from '.';
import type { AntdPreviewerProps } from './Previewer';

const useStyle = createStyles(({ token, css }) => ({
wrapper: css`
Expand Down
67 changes: 60 additions & 7 deletions .dumi/theme/common/CodePreview.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,43 @@
import React, { useEffect, useMemo } from 'react';
import { Tabs } from 'antd';
import { Tabs, Typography, Button } from 'antd';
import toReactElement from 'jsonml-to-react-element';
import JsonML from 'jsonml.js/lib/utils';
import Prism from 'prismjs';
import { createStyles } from 'antd-style';

const useStyle = createStyles(({ token, css }) => {
const { colorIcon, colorBgTextHover, antCls } = token;

return {
code: css`
position: relative;
`,

copyButton: css`
color: ${colorIcon};
position: absolute;
top: 0;
inset-inline-end: 16px;
width: 32px;
text-align: center;
background: ${colorBgTextHover};
padding: 0;
`,

copyIcon: css`
${antCls}-typography-copy {
margin-inline-start: 0;
}
${antCls}-typography-copy:not(${antCls}-typography-copy-success) {
color: ${colorIcon};
&:hover {
color: ${colorIcon};
}
}
`,
};
});

const LANGS = {
tsx: 'TypeScript',
Expand Down Expand Up @@ -40,7 +75,7 @@ const CodePreview: React.FC<CodePreviewProps> = ({
onCodeTypeChange,
}) => {
// 避免 Tabs 数量不稳定的闪动问题
const initialCodes = {};
const initialCodes = {} as Record<'tsx' | 'jsx' | 'style', string>;
if (sourceCode) {
initialCodes.tsx = '';
}
Expand All @@ -51,15 +86,19 @@ const CodePreview: React.FC<CodePreviewProps> = ({
initialCodes.style = '';
}
const [highlightedCodes, setHighlightedCodes] = React.useState(initialCodes);

const sourceCodes = {
tsx: sourceCode,
jsx: jsxCode,
style: styleCode,
} as Record<'tsx' | 'jsx' | 'style', string>;
useEffect(() => {
const codes = {
tsx: Prism.highlight(sourceCode, Prism.languages.javascript, 'jsx'),
jsx: Prism.highlight(jsxCode, Prism.languages.javascript, 'jsx'),
style: Prism.highlight(styleCode, Prism.languages.css, 'css'),
};
// 去掉空的代码类型
Object.keys(codes).forEach((key) => {
Object.keys(codes).forEach((key: keyof typeof codes) => {
if (!codes[key]) {
delete codes[key];
}
Expand All @@ -68,12 +107,22 @@ const CodePreview: React.FC<CodePreviewProps> = ({
}, [jsxCode, sourceCode, styleCode]);

const langList = Object.keys(highlightedCodes);

const { styles } = useStyle();

const items = useMemo(
() =>
langList.map((lang) => ({
langList.map((lang: keyof typeof LANGS) => ({
label: LANGS[lang],
key: lang,
children: toReactComponent(['pre', { lang, highlighted: highlightedCodes[lang] }]),
children: (
<div className={styles.code}>
{toReactComponent(['pre', { lang, highlighted: highlightedCodes[lang] }])}
<Button type="text" className={styles.copyButton}>
<Typography.Text className={styles.copyIcon} copyable={{ text: sourceCodes[lang] }} />
</Button>
</div>
),
})),
[JSON.stringify(highlightedCodes)],
);
Expand All @@ -85,7 +134,11 @@ const CodePreview: React.FC<CodePreviewProps> = ({
if (langList.length === 1) {
return toReactComponent([
'pre',
{ lang: langList[0], highlighted: highlightedCodes[langList[0]], className: 'highlight' },
{
lang: langList[0],
highlighted: highlightedCodes[langList[0] as keyof typeof LANGS],
className: 'highlight',
},
]);
}

Expand Down

0 comments on commit 07eb5ba

Please sign in to comment.