Skip to content

Commit

Permalink
feat: shape registry
Browse files Browse the repository at this point in the history
  • Loading branch information
bubkoo committed Feb 27, 2020
1 parent 5da0e77 commit 08be328
Show file tree
Hide file tree
Showing 3 changed files with 85 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/x6/src/research/registry/index.ts
@@ -0,0 +1 @@
export { registerNode } from './node'
52 changes: 52 additions & 0 deletions packages/x6/src/research/registry/node.ts
@@ -0,0 +1,52 @@
import { Node as NodeRaw } from '../core/node'
import { registerEntity } from './util'

export interface Options extends NodeRaw.Defaults {
init?: () => void
}

export type NodeClass = typeof NodeRaw

const nodes: { [name: string]: NodeClass } = {}

function register(name: string, node: NodeClass, force: boolean) {
registerEntity(nodes, name, node, force, () => {
throw new Error(`Shape with name '${name}' already registered.`)
})

return node
}

export function registerNode(
name: string,
shape: NodeClass,
force?: boolean,
): NodeClass
export function registerNode(
name: string,
options: Options,
force?: boolean,
): NodeClass
export function registerNode(
name: string,
options: Options | NodeClass,
force: boolean = false,
): NodeClass {
if (typeof options === 'function') {
return register(name, options, force)
}

const { init, ...defaults } = options
// tslint:disable-next-line
class Node extends NodeRaw {
init() {
if (typeof init === 'function') {
init.call(this)
}
}
}

Node.setDefaults(defaults)

return register(name, Node as any, force)
}
32 changes: 32 additions & 0 deletions packages/x6/src/research/registry/util.ts
@@ -0,0 +1,32 @@
function getHMRStatus() {
const mod = module as any
if (mod != null && mod.hot != null && mod.hot.status != null) {
return mod.hot.status()
}
return 'unkonwn'
}

function isApplyingHMR() {
return getHMRStatus() === 'apply'
}

export function registerEntity<T>(
registry: { [name: string]: T },
name: string,
entity: T,
force: boolean,
onError: () => void,
) {
if (registry[name] && !force && !isApplyingHMR()) {
onError()
}
registry[name] = entity
}

export function getEntityFromRegistry<T>(
registry: { [name: string]: T },
name: string,
): T | null {
const ret = registry[name]
return typeof ret === 'function' ? ret : null
}

0 comments on commit 08be328

Please sign in to comment.