Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(auto-init): Convert JS to TypeScript #4395

Merged
merged 13 commits into from
Feb 14, 2019
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 40 additions & 16 deletions packages/mdc-auto-init/index.js → packages/mdc-auto-init/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,32 @@
* THE SOFTWARE.
*/

const registry = Object.create(null);
// tslint:disable:only-arrow-functions

const CONSOLE_WARN = console.warn.bind(console);
import {MDCComponent} from '@material/base/component';
acdvorak marked this conversation as resolved.
Show resolved Hide resolved
import {MDCFoundation} from '@material/base/foundation';
import {MDCAutoInitElement, MDCAutoInitKey} from './types';

function _emit(evtType, evtData, shouldBubble = false) {
interface ComponentClass {
// tslint:disable-next-line:no-any a component can pass in anything it needs to the constructor
new<F extends MDCFoundation>(root: Element, foundation?: F, ...args: any[]): MDCComponent<F>;
attachTo<F extends MDCFoundation>(root: Element): MDCComponent<F>;
}

type Registry = {
[K in MDCAutoInitKey]?: ComponentClass;
};

const registry: Registry = {};

const CONSOLE_WARN = console.warn.bind(console); // tslint:disable-line:no-console

function _emit<T extends object>(evtType: string, evtData: T, shouldBubble = false) {
acdvorak marked this conversation as resolved.
Show resolved Hide resolved
let evt;
if (typeof CustomEvent === 'function') {
evt = new CustomEvent(evtType, {
detail: evtData,
evt = new CustomEvent<T>(evtType, {
bubbles: shouldBubble,
detail: evtData,
});
} else {
evt = document.createEvent('CustomEvent');
Expand All @@ -40,19 +56,21 @@ function _emit(evtType, evtData, shouldBubble = false) {
document.dispatchEvent(evt);
}

/* istanbul ignore next: optional argument is not a branch statement */
/**
* Auto-initializes all mdc components on a page.
* Auto-initializes all MDC components on a page.
*/
export default function mdcAutoInit(root = document, warn = CONSOLE_WARN) {
function mdcAutoInit(root = document, warn = CONSOLE_WARN) {
const components = [];
const nodes = root.querySelectorAll('[data-mdc-auto-init]');
for (let i = 0, node; (node = nodes[i]); i++) {
const ctorName = node.dataset.mdcAutoInit;
const nodes: MDCAutoInitElement[] = [].slice.call(root.querySelectorAll('[data-mdc-auto-init]'));

for (const node of nodes) {
const ctorName = node.getAttribute('data-mdc-auto-init') as MDCAutoInitKey | null;
if (!ctorName) {
throw new Error('(mdc-auto-init) Constructor name must be given.');
}

const Ctor = registry[ctorName];
const Ctor = registry[ctorName]; // tslint:disable-line:variable-name
if (typeof Ctor !== 'function') {
throw new Error(
`(mdc-auto-init) Could not find constructor in registry for ${ctorName}`);
Expand All @@ -64,12 +82,13 @@ export default function mdcAutoInit(root = document, warn = CONSOLE_WARN) {
}

// TODO: Should we make an eslint rule for an attachTo() static method?
// See https://github.com/Microsoft/TypeScript/issues/14600 for discussion of static interface support in TS
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is the TODO above this obsolete? (Like, would our build actually fail without an attachTo given the typings above? Plus we're using tslint now to reuse the Google configuration.)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unfortunately TypeScript won't catch that because it doesn't do static type checking.
See microsoft/TypeScript#14600.

attachTo() in the Component interface is only there to make TS happy when we try to call Constructor.attachTo() in mdcAutoInit(). It doesn't verify that static attachTo() exists on classes passed to register().

It does, however, verify that the required constructor signature exists (via new<F...>()) on classes passed to register().

const component = Ctor.attachTo(node);
Object.defineProperty(node, ctorName, {
configurable: true,
enumerable: false,
value: component,
writable: false,
enumerable: false,
configurable: true,
});
components.push(component);
}
Expand All @@ -78,7 +97,8 @@ export default function mdcAutoInit(root = document, warn = CONSOLE_WARN) {
return components;
}

mdcAutoInit.register = function(componentName, Ctor, warn = CONSOLE_WARN) {
// tslint:disable-next-line:variable-name
acdvorak marked this conversation as resolved.
Show resolved Hide resolved
mdcAutoInit.register = function(componentName: MDCAutoInitKey, Ctor: ComponentClass, warn = CONSOLE_WARN) {
if (typeof Ctor !== 'function') {
throw new Error(`(mdc-auto-init) Invalid Ctor value ${Ctor}. Expected function`);
}
Expand All @@ -90,10 +110,14 @@ mdcAutoInit.register = function(componentName, Ctor, warn = CONSOLE_WARN) {
registry[componentName] = Ctor;
};

mdcAutoInit.deregister = function(componentName) {
mdcAutoInit.deregister = function(componentName: MDCAutoInitKey) {
delete registry[componentName];
};

mdcAutoInit.deregisterAll = function() {
Object.keys(registry).forEach(this.deregister, this);
const keys = Object.keys(registry) as MDCAutoInitKey[];
keys.forEach(this.deregister, this);
};

export {mdcAutoInit as default, mdcAutoInit};
export * from './types';
3 changes: 3 additions & 0 deletions packages/mdc-auto-init/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,8 @@
"repository": {
"type": "git",
"url": "https://github.com/material-components/material-components-web.git"
},
"dependencies": {
"@material/base": "^0.41.0"
acdvorak marked this conversation as resolved.
Show resolved Hide resolved
}
}
55 changes: 55 additions & 0 deletions packages/mdc-auto-init/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/**
* @license
* Copyright 2019 Google Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/

export type MDCAutoInitKey = (
acdvorak marked this conversation as resolved.
Show resolved Hide resolved
'MDCCheckbox' |
'MDCChip' |
'MDCChipSet' |
'MDCDialog' |
'MDCDrawer' |
'MDCFloatingLabel' |
'MDCFormField' |
'MDCGridList' |
'MDCIconButtonToggle' |
'MDCIconToggle' |
'MDCLineRipple' |
'MDCLinearProgress' |
'MDCList' |
'MDCMenu' |
'MDCMenuSurface' |
'MDCNotchedOutline' |
'MDCRadio' |
'MDCRipple' |
'MDCSelect' |
'MDCSlider' |
'MDCSnackbar' |
'MDCSwitch' |
'MDCTabBar' |
'MDCTextField' |
'MDCToolbar' |
'MDCTopAppBar'
);

export type MDCAutoInitElement = HTMLElement & {
[K in MDCAutoInitKey]?: string;
};
2 changes: 1 addition & 1 deletion scripts/webpack/js-bundle-factory.js
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ class JsBundleFactory {
bundleName: 'main-js-a-la-carte',
chunks: {
animation: getAbsolutePath('/packages/mdc-animation/index.ts'),
autoInit: getAbsolutePath('/packages/mdc-auto-init/index.js'),
autoInit: getAbsolutePath('/packages/mdc-auto-init/index.ts'),
base: getAbsolutePath('/packages/mdc-base/index.ts'),
checkbox: getAbsolutePath('/packages/mdc-checkbox/index.ts'),
chips: getAbsolutePath('/packages/mdc-chips/index.ts'),
Expand Down