-
-
Notifications
You must be signed in to change notification settings - Fork 46.7k
/
fromDumiProps.tsx
96 lines (88 loc) · 2.91 KB
/
fromDumiProps.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import React, { useEffect, useState } from 'react';
// @ts-ignore
import JsonML from 'jsonml.js/lib/utils';
// @ts-ignore
import toReactComponent from 'jsonml-to-react-element';
import Prism from 'prismjs';
import { useLocation, useIntl, type IPreviewerProps } from 'dumi';
import { ping } from '../../utils';
let pingDeferrer: PromiseLike<boolean>;
function useShowRiddleButton() {
const [showRiddleButton, setShowRiddleButton] = useState(false);
useEffect(() => {
pingDeferrer ??= new Promise<boolean>((resolve) => {
ping((status) => {
if (status !== 'timeout' && status !== 'error') {
return resolve(true);
}
return resolve(false);
});
});
pingDeferrer.then(setShowRiddleButton);
}, []);
return showRiddleButton;
}
/**
* HOC for convert dumi previewer props to bisheng previewer props
*/
export default function fromDumiProps<P extends object>(
WrappedComponent: React.ComponentType<P>,
): React.FC<IPreviewerProps> {
const hoc = function DumiPropsAntdPreviewer(props: IPreviewerProps) {
const showRiddleButton = useShowRiddleButton();
const location = useLocation();
const { asset, children, demoUrl, expand, description = '', ...meta } = props;
const intl = useIntl();
const entryCode = asset.dependencies['index.tsx'].value;
const transformedProps = {
meta: {
id: asset.id,
title: '',
filename: meta.filePath,
...meta,
},
content: description,
preview: () => children,
utils: {
toReactComponent(jsonML: any) {
return toReactComponent(jsonML, [
[
(node: any) => JsonML.isElement(node) && JsonML.getTagName(node) === 'pre',
(node: any, index: any) => {
// @ts-ignore
// ref: https://github.com/benjycui/bisheng/blob/master/packages/bisheng/src/bisheng-plugin-highlight/lib/browser.js#L7
const attr = JsonML.getAttributes(node);
return React.createElement(
'pre',
{
key: index,
className: `language-${attr.lang}`,
},
React.createElement('code', {
dangerouslySetInnerHTML: { __html: attr.highlighted },
}),
);
},
],
]);
},
},
intl: { locale: intl.locale },
showRiddleButton,
highlightedCodes: {
jsx: Prism.highlight(meta.jsx, Prism.languages.javascript, 'jsx'),
tsx: Prism.highlight(entryCode, Prism.languages.javascript, 'tsx'),
},
style: meta.style,
location,
src: demoUrl,
expand,
// FIXME: confirm is there has any case?
highlightedStyle: '',
// FIXME: dumi support usePrefersColor
theme: 'light',
} as P;
return <WrappedComponent {...transformedProps} />;
};
return hoc;
}