Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: 添加在codepen中打开 #1764

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/client/theme-api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ export { useSiteData } from './context';
export { DumiDemo } from './DumiDemo';
export { DumiDemoGrid } from './DumiDemoGrid';
export { DumiPage } from './DumiPage';
export { openCodePen } from './openCodePen';
export { openCodeSandbox } from './openCodeSandbox';
export { openStackBlitz } from './openStackBlitz';
export type { IPreviewerProps } from './types';
Expand Down
115 changes: 115 additions & 0 deletions src/client/theme-api/openCodePen.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
import type { IPreviewerProps } from 'dumi';

const CODEPEN_API = 'https://codepen.io/pen/define';

const getDependencyData = (opts: IPreviewerProps) => {
const isTSX = Boolean(opts.asset.dependencies?.['index.tsx']);
let dep: Record<string, string> = {};
let jsx = '';
Object.keys(opts.asset.dependencies).forEach((current) => {
const { type, value } = opts.asset.dependencies[current];
if (type === 'NPM') {
dep[current] = value;
} else {
jsx += value;
}

/** 引入不同的文件的时候需要把这些文件导入去掉 */
if (type === 'FILE') {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这里处理多文件引入

const [fileName] = current.split('.');
const regex = new RegExp(
`import\\s+[\\w\\s{},]+from\\s+'.*?\\/(${fileName})';?`,
'g',
);
jsx = jsx.replace(regex, ``);
}
});

/**
* 依赖的 npm 包, 将所有的npm 包转成cdn 引入
*/
const dependencyNpm = Object.keys(dep).map((name) => {
return `${name}@${dep[name]}/dist/${name}.min.js`;
});

/** codepen
* 需要替换成 const { Space } = antd
* */
const codepenPrefillConfig = {
title: `例子`,
html: `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#000000">
</head>
<body>
<div id="container" style="padding: 24px" />
<script>const mountNode = document.getElementById('container');</script>
</body>
</html>`,
js: `const { createRoot } = ReactDOM;\n${jsx
.replace(
/import\s+(?:React,\s+)?{(\s+[^}]*\s+)}\s+from\s+'react'/,
`const { $1 } = React;`,
)
.replace(
/import\s+{(\s+[^}]*\s+)}\s+from\s+'([\w\s]+)'/g,
'const { $1 } = $2;',
)
.replace(
/import\s+{(\s+[^}]*\s+)}\s+from\s+'@ant-design\/icons';/,
'const { $1 } = icons;',
)
.replace(/import\s+([\w]+)\s+from\s+'lodash'/g, '')
.replace("import moment from 'moment';", '')
.replace(/import\s+React\s+from\s+['"]react['"];?/g, '')
.replace(
/import\s+{\s+(.*)\s+}\s+from\s+'react-router';/,
'const { $1 } = ReactRouter;',
)
.replace(/([A-Za-z]*)\s+as\s+([A-Za-z]*)/, '$1:$2')
.replace(
/export default/,
'const ComponentDemo =',
)}\n\ncreateRoot(mountNode).render(<ComponentDemo />);\n`,
editors: '001',
css: '',
js_external: [
'react@18/umd/react.development.js',
'react-dom@18/umd/react-dom.development.js',
'dayjs@1/dayjs.min.js',
`@ant-design/icons/dist/index.umd.js`,
'react-router-dom/dist/umd/react-router-dom.production.min.js',
'react-router/dist/umd/react-router.production.min.js',
'[email protected]/lodash.js',
]
.concat(dependencyNpm)
.map((url) => `https://unpkg.com/${url}`)
.join(';'),
js_pre_processor: isTSX ? 'typescript' : 'javascript',
};
return codepenPrefillConfig;
};

export const openCodePen = (data: IPreviewerProps, opts?: { api?: string }) => {
const form = document.createElement('form');
const input = document.createElement('input');
const CSBData = getDependencyData(data);

form.method = 'POST';
form.target = '_blank';
form.style.display = 'none';
form.action = opts?.api || CODEPEN_API;
form.appendChild(input);
form.setAttribute('data-demo', data.assets?.id || '');

input.name = 'data';
input.value = JSON.stringify(CSBData);

document.body.appendChild(form);

form.submit();
form.remove();
};
2 changes: 1 addition & 1 deletion src/client/theme-default/locales/en-US.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
"previewer.actions.sketch.divider": "------------------------",
"previewer.actions.sketch.guide": "How to paste to Sketch?",
"previewer.actions.codesandbox": "Open in CodeSandbox",
"previewer.actions.codepen": "Open in CodePen (Not implemented)",
"previewer.actions.codepen": "Open in CodePen",
"previewer.actions.stackblitz": "Open in StackBlitz",
"previewer.actions.separate": "Open in separate page",
"404.title": "PAGE NOT FOUND",
Expand Down
1 change: 1 addition & 0 deletions src/client/theme-default/locales/zh-CN.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
"previewer.actions.sketch.symbol": "拷贝为 Sketch Symbol",
"previewer.actions.sketch.divider": "----------------------",
"previewer.actions.sketch.guide": "如何粘贴到 SKetch?",
"previewer.actions.codepen": "在 CodePen 中打开",
"previewer.actions.stackblitz": "在 StackBlitz 中打开",
"previewer.actions.separate": "在独立页面中打开",
"404.title": "页面未找到",
Expand Down
22 changes: 21 additions & 1 deletion src/client/theme-default/slots/PreviewerActions/index.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { ReactComponent as IconCheck } from '@ant-design/icons-svg/inline-svg/outlined/check.svg';
import { ReactComponent as IconCodeSandbox } from '@ant-design/icons-svg/inline-svg/outlined/code-sandbox.svg';
import { ReactComponent as IconCodePen } from '@ant-design/icons-svg/inline-svg/outlined/codepen.svg';
import { ReactComponent as IconSketch } from '@ant-design/icons-svg/inline-svg/outlined/sketch.svg';
import { ReactComponent as IconStackBlitz } from '@ant-design/icons-svg/inline-svg/outlined/thunderbolt.svg';
import copy from 'copy-to-clipboard';
import {
getSketchJSON,
openCodePen,
openCodeSandbox,
openStackBlitz,
useIntl,
Expand All @@ -19,7 +21,13 @@ export interface IPreviewerActionsProps extends IPreviewerProps {
/**
* disabled actions
*/
disabledActions?: ('CSB' | 'STACKBLITZ' | 'EXTERNAL' | 'HTML2SKETCH')[];
disabledActions?: (
| 'CSB'
| 'STACKBLITZ'
| 'EXTERNAL'
| 'HTML2SKETCH'
| 'CODEPEN'
)[];
extra?: ReactNode;
forceShowCode?: boolean;
demoContainer: HTMLDivElement | HTMLIFrameElement;
Expand Down Expand Up @@ -73,6 +81,18 @@ const PreviewerActions: FC<IPreviewerActionsProps> = (props) => {
<IconCodeSandbox />
</button>
)}
{!props.disabledActions?.includes('CODEPEN') && (
<button
className="dumi-default-previewer-action-btn"
type="button"
data-dumi-tooltip={intl.formatMessage({
id: 'previewer.actions.codepen',
})}
onClick={() => openCodePen(props)}
>
<IconCodePen />
</button>
)}
{!props.disabledActions?.includes('STACKBLITZ') && (
<button
className="dumi-default-previewer-action-btn"
Expand Down