-
-
Notifications
You must be signed in to change notification settings - Fork 631
/
Copy pathComponentRegistry.ts
56 lines (48 loc) · 1.83 KB
/
ComponentRegistry.ts
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
import type { RegisteredComponent, ReactComponentOrRenderFunction, RenderFunction } from './types/index';
import isRenderFunction from './isRenderFunction';
const registeredComponents = new Map<string, RegisteredComponent>();
export default {
/**
* @param components { component1: component1, component2: component2, etc. }
*/
register(components: { [id: string]: ReactComponentOrRenderFunction }): void {
Object.keys(components).forEach(name => {
if (registeredComponents.has(name)) {
console.warn('Called register for component that is already registered', name);
}
const component = components[name];
if (!component) {
throw new Error(`Called register with null component named ${name}`);
}
const renderFunction = isRenderFunction(component);
const isRenderer = renderFunction && (component as RenderFunction).length === 3;
registeredComponents.set(name, {
name,
component,
renderFunction,
isRenderer,
});
});
},
/**
* @param name
* @returns { name, component, isRenderFunction, isRenderer }
*/
get(name: string): RegisteredComponent {
const registeredComponent = registeredComponents.get(name);
if (registeredComponent !== undefined) {
return registeredComponent;
}
const keys = Array.from(registeredComponents.keys()).join(', ');
throw new Error(`Could not find component registered with name ${name}. \
Registered component names include [ ${keys} ]. Maybe you forgot to register the component?`);
},
/**
* Get a Map containing all registered components. Useful for debugging.
* @returns Map where key is the component name and values are the
* { name, component, renderFunction, isRenderer}
*/
components(): Map<string, RegisteredComponent> {
return registeredComponents;
},
};