File size: 1,169 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { findKey } from 'lodash';
import format from 'react-element-to-jsx-string';
import * as scope from './playground-scope';

// Figure out a React element's display name, with the help of the `playground-scope` map.
function displayName( element ) {
	// if `type` is a string, then it's a DOM element like `div`
	if ( typeof element.type === 'string' ) {
		return element.type;
	}

	// find the component (by value) in the `playground-scope` map
	const scopeName = findKey( scope, ( type ) => element.type === type );
	if ( scopeName ) {
		return scopeName;
	}

	// fall back to classic (potentially minified) constructor function name
	if ( typeof element.type === 'function' ) {
		return element.type.displayName || element.type.name;
	}

	return 'No Display Name';
}

export const getExampleCodeFromComponent = ( ExampleComponent ) => {
	if ( ! ExampleComponent.props.exampleCode ) {
		return null;
	}

	if ( typeof ExampleComponent.props.exampleCode === 'string' ) {
		return ExampleComponent.props.exampleCode;
	}

	return format( ExampleComponent.props.exampleCode, {
		showDefaultProps: false,
		displayName,
	} ).replace( /Localized\((\w+)\)/g, '$1' );
};