-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
index.tsx
105 lines (90 loc) · 2.02 KB
/
index.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
97
98
99
100
101
102
103
104
105
/**
* External dependencies
*/
import type { ComponentType, HTMLProps, SVGProps } from 'react';
/**
* WordPress dependencies
*/
import {
cloneElement,
createElement,
Component,
isValidElement,
} from '@wordpress/element';
import { SVG } from '@wordpress/primitives';
/**
* Internal dependencies
*/
import Dashicon from '../dashicon';
import type { IconKey as DashiconIconKey } from '../dashicon/types';
type IconType< P > = DashiconIconKey | ComponentType< P > | JSX.Element;
interface BaseProps< P > {
/**
* The icon to render. Supported values are: Dashicons (specified as
* strings), functions, Component instances and `null`.
*
* @default null
*/
icon?: IconType< P > | null;
/**
* The size (width and height) of the icon.
*
* @default 24
*/
size?: number;
}
type AdditionalProps< T > = T extends ComponentType< infer U >
? U
: T extends DashiconIconKey
? SVGProps< SVGSVGElement >
: {};
export type Props< P > = BaseProps< P > & AdditionalProps< IconType< P > >;
function Icon< P >( {
icon = null,
size = 24,
...additionalProps
}: Props< P > ) {
if ( 'string' === typeof icon ) {
return (
<Dashicon
icon={ icon }
{ ...( additionalProps as HTMLProps< HTMLSpanElement > ) }
/>
);
}
if ( isValidElement( icon ) && Dashicon === icon.type ) {
return cloneElement( icon, {
...additionalProps,
} );
}
if ( 'function' === typeof icon ) {
if ( icon.prototype instanceof Component ) {
return createElement( icon, ( {
size,
...additionalProps,
} as unknown ) as P );
}
return ( icon as ( ...args: any[] ) => JSX.Element )( {
size,
...additionalProps,
} );
}
if ( icon && ( icon.type === 'svg' || icon.type === SVG ) ) {
const appliedProps = {
width: size,
height: size,
...icon.props,
...additionalProps,
};
return <SVG { ...appliedProps } />;
}
if ( isValidElement( icon ) ) {
return cloneElement( icon, {
// @ts-ignore Just forwarding the size prop along
size,
...additionalProps,
} );
}
return icon;
}
export default Icon;