-
Notifications
You must be signed in to change notification settings - Fork 37
/
registry.ts
53 lines (46 loc) · 1.27 KB
/
registry.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
/*!
* Copyright (c) Microsoft. All rights reserved.
* Licensed under the MIT license. See LICENSE file in the project.
*/
import { Item } from './elements'
export interface ItemConstructor {
ITEM_TYPE: string
new (): Item
}
const itemTypeRegistry = new Map<string, ItemConstructor>()
const restrictedPropNames = new Set<string>()
restrictedPropNames.add('marktype')
/**
* Registers an item type for use in parsing scene-graphs.
*
* @param itemType the name of the item type to register
* @param ctor The item class representing the item type
*/
export function registerItemType(ctor: ItemConstructor) {
itemTypeRegistry.set(ctor.ITEM_TYPE, ctor)
}
/**
* Creates a new Item-Type instance
* @param itemType
*/
export function createItemType(
itemType: string,
props: { [key: string]: any } = {},
) {
if (!itemTypeRegistry.has(itemType)) {
throw new Error(`item type ${itemType} not found`)
}
const ctor = itemTypeRegistry.get(itemType)
if (ctor === undefined) {
throw new Error(`item type ${itemType} constructor not valid`)
}
// Create the new instance
const instance: any = new ctor()
// Transfer properties over
Object.keys(props).forEach(propName => {
if (!restrictedPropNames.has(propName)) {
instance[propName] = props[propName]
}
})
return instance
}