license import { MDCComponent } from '@material/base/component' ; import { MDCFoundation } from '@material/base/foundation' ; import { strings } from './constants' ; const { AUTO_INIT_ATTR , AUTO_INIT_STATE_ATTR , INITIALIZED_STATE } = strings ; export interface MDCAttachable extends Function { attachTo ( root ) : MDCComponent < MDCFoundation > ; } interface InternalComponentRegistry { [ key ] : MDCAttachable ; } const registry = { } ; const CONSOLE_WARN = console . warn . bind ( console ) ; function emit < T extends object > ( evtType , evtData , shouldBubble = false ) { let evt ; if ( typeof CustomEvent === 'function' ) { evt = new CustomEvent < T > ( evtType , { bubbles : shouldBubble , detail : evtData , } ) ; } else { evt = document . createEvent ( 'CustomEvent' ) ; evt . initCustomEvent ( evtType , shouldBubble , false , evtData ) ; } document . dispatchEvent ( evt ) ; } /**
 * Auto-initializes all MDC components on a page.
 */ function mdcAutoInit ( root = document ) { const components = [ ] ; let nodes = [ ] . slice . call ( root . querySelectorAll ( `[${ AUTO_INIT_ATTR }]` ) ) ; nodes = nodes . filter ( ( node ) => node . getAttribute ( AUTO_INIT_STATE_ATTR ) !== INITIALIZED_STATE ) ; for ( const node of nodes ) { const ctorName = node . getAttribute ( AUTO_INIT_ATTR ) ; if ( ! ctorName ) { throw new Error ( '(mdc-auto-init) Constructor name must be given.' ) ; } const Constructor = registry [ ctorName ] ; if ( typeof Constructor !== 'function' ) { throw new Error ( `(mdc-auto-init) Could not find constructor in registry for ${ ctorName }` ) ; } const component = Constructor . attachTo ( node ) ; Object . defineProperty ( node , ctorName , { configurable : true , enumerable : false , value : component , writable : false , } ) ; components . push ( component ) ; node . setAttribute ( AUTO_INIT_STATE_ATTR , INITIALIZED_STATE ) ; } emit ( 'MDCAutoInit:End' , { } ) ; return components ; } mdcAutoInit . register = function ( componentName , Constructor , warn = CONSOLE_WARN ) { if ( typeof Constructor !== 'function' ) { throw new Error ( `(mdc-auto-init) Invalid Constructor value: ${ Constructor }. Expected function.` ) ; } const registryValue = registry [ componentName ] ; if ( registryValue ) { warn ( `(mdc-auto-init) Overriding registration for ${ componentName } with ${ Constructor }. Was: ${ registryValue }` ) ; } registry [ componentName ] = Constructor ; } ; mdcAutoInit . deregister = function ( componentName ) { delete registry [ componentName ] ; } ; nocollapse mdcAutoInit . deregisterAll = function ( ) { const keys = Object . keys ( registry ) as string [ ] ; keys . forEach ( this . deregister , this ) ; } ; export default mdcAutoInit ; export { mdcAutoInit } ;