MDSWC Base API

The MDSWCBase class accounts for common functionality that can be leveraged across all MDS web components. It extends HTMLElement and is in turn extended by all MDS web components.

Props

Prop
Type
Default
Description

attributeChangedCallbackEnabled

Boolean

false

Determines if the attributeChangedCallback should be suppressed or not.

componentConnected

Boolean

false

Determines if connectedCallback() has been called signaling that the element has inserted into the DOM.

defaultProps

Object

Props that were passed to the constructor

Stores the default props so they can be referenced later for slot overrides.

firstSlotRender

Object

{}

Stores an object that tracks if each existing slot has been already rendered once.

hasSlotContent

Object

{}

Stores an object that tracks if each existing slot has content.

hasSlots

Boolean

undefined

Determines if the component has slots.

rendered

Boolean

false

Determines if the component has been rendered or not.

renderEnabled

Boolean

true

Determines if the component render can be invoked.

renderTimeout

Number

1000ms

Stores the timeout value in milliseconds that determines how much time a component has available to render before the componentRendered Promise fails.

state

Object

{}

Object that stores the current key/value pairs for each of the props of the component.

Methods

The MDSWCBase class contains methods that are part of the native custom element lifecycle, instance methods that provide common base functionality, and static helper methods. All methods can further be classified as private or public depending on their intended use outside of the MDSWCBase class.

Status
Description
Private

Denotes an instance method that is used internally to MDSWC and should not be overwritten.

Public

Denotes a static helper method or instance method that can be invoked in components that extend MDSWCBase.

Native Custom Element Lifecycle Methods

The MDSWCBase class leverages a subset of the custom element lifecycle methods. These methods are used to track when an element has been inserted into the DOM and when changes to the element attributes occur.

Method Name
Type
Description

attributeChangedCallback(attributeName, oldValue, newValue)

Private

Called when an observed attribute has been added, removed, updated, or replaced. Also called for initial values when an element is created by the parser or upgraded.

Note: Only attributes listed in the observedAttributes static getter method will receive this callback.

connectedCallback

Private

Called every time the element is inserted into the DOM.

get observedAttributes

Public

Static getter method defined on each custom element. It returns the element attributes which should be watched for changes.

Instance Methods

MDSWCBase contains several instance methods that provide common functionality to components which extend from MDSWCBase.

Method Name
Type
Description

bindEventHandlers

Public

Fallback method meant to be overwritten at the child component level.

componentRendered

Public

Returns a Promise that is resolved once the component is rendered. If the component is not rendered within the time constraint set by this.renderTimeout, the Promise will be rejected with an error message.

configurePropGettersAndSetters(props)

Private

Configures a getter and setter for all defined props.

get defaultSlotContent

Private

Returns the default slot content. If no default slot content exists, it will return the Boolean value false.

firstConnectedCallback

Private

Invoked once from connectedCallback when the component is first injected into the DOM.

hasDefaultSlotContent

Public

Returns a Boolean value determined by the existence of default slot content.

hasNamedSlotContent(slotName)

Public

Returns a Boolean value determined by the existence of named slot content.

initialPropValues

Private

Returns an Object containing default and instance prop values. The default values are determined by the component, while the instance props are determined by values passed via HTML attributes.

initializeMwcLabeller

Private

Binds label functionality to MWC labeler if an MWC configuration and MWC id exist, otherwise it returns a placeholder labeler that always returns false.

initializeMwcLogger

Private

Bind logging functionality to the MWC logger via a deep clone.

removeAttributeWithoutRendering (attributeName)

Public

Suppresses the attributeChangedCallback before removing an attribute so that render is not invoked.

render

Public

Calls renderTemplate if the custom element has been inserted into the DOM and render is enabled.

renderTemplate

Private

A debounced method which renders the template and binds all events using the bindEventHandlers method.

If slots exist, the rendering process is delegated to the renderTemplateWithSlots method.

renderTemplateWithSlots

Private

Retrieves a copy of the template from the child component and checks for the existence of slots. If default slot content or named slot content is detected, it evaluates that content against possible slot prop overrides and creates the appropriate nodes needed to render the content. Once all slot content is evaluated and created, it removes all children from the currently rendered custom element and renders the newly created template.

setInitialComponentState

Private

Assigns the initial component state to the this.state instance property. State is determined by merging instance prop values with default prop settings. Instance values will take precedence over default values.

If an MWC Config is present, it will be merged and take precedence over instance and default values.

setDefaultSlotContentPresence

Private

Iterates through all the default and named slots and updates the this.hasSlotContent instance property with a key value pair. The key is determined by the slot name, and the value is a Boolean value determined by the existence of content for the specific slot being evaluated.

setPropWithoutRendering(p, newValue)

Public

Suppresses the render functionality while setting a new value for a property. All validation rules still apply on the set prop value.

triggerEvent(eventName, detail = '', bubbles = true)

Public

Creates and dispatches a CustomEvent based on the arguments passed.

triggerPropTypeErrorMessage(propName, propValue, expectedPropType, actualPropType)

Private

Composes and logs prop validation error messages based on the arguments it receives.

useMwcConfig

Private

Returns a Boolean value determined by the existence of an mwcId prop and an MWC configuration.

validateAllProps

Private

Iterates through all props and calls the validateProp method for each prop.

validateProp(propName, currentValue)

Private

Validates a prop against all validation rules (e.g., required, enum, type, custom validation) specified for it.

validatePropType(propName, propValue, expectedPropType)

Private

Validates that the prop value matches the specified prop type and returns a Boolean value.

Static Methods

MDSWCBase contains several static methods that are common utility functions used by multiple MDSWC components.

Method Name
Type
Description

get appLanguageId

Public

Returns the language id set in the MWC application helper. If no id is set, it will return en-US by default.

camelCase(string)

Public

Takes a kebab-cased string like lightsaber-color and converts it to a camelCased string like lightsaberColor. Use to convert kebab-cased HTML attributes into camelCased JavaScript properties.

generateRandomNumber(max = 1000000000000000)

Public

Returns a generated random number between 0 and max. This number can be used to build unique default id for HTML templates.

identifyPropType(prop)

Public

Returns the data type of the prop passed to it. The data type will be one of: number string, boolean, array, or object.

kebabCase(string)

Public

Converts a camelCased string like jediMaster to a kebab-cased string like jedi-master. Use to convert camelCased JavaScript properties into kebab-cased HTML attributes.

moveChildNodes(oldParent, newParent)

Public

Given two nodes that contain child nodes, this method moves child nodes from oldParent to newParent.

get propTypeErrorMessageArticles

Public

Returns an object containing prop type to grammatical articles for more grammatically correct error messages. For example, that prop is an array vs. that prop is a array.

Usage Examples

Extending from MDSWC Base:

class MyComponent extends MDSWCBase {
    static get defaultProps() {
        // List all props as camelCased object keys in alphabetical order
        return {
            myProp: {
                type: String, // type is required for all props 
            }
        };
    }

    // Observe all attributes
    static get observedAttributes() {
        const attributes = Object.keys(MyComponent.defaultProps).map(p => MDSWCBase.kebabCase(p));
        return attributes;
    }

    // Pass props to the MDSWC Constructor
    constructor() {
        super(MyComponent.defaultProps);
    }

    // define the component template that MDSWC Base
    get template() {
        return `
            <div>
                <h1>${this.myProp}</h1>
            </div>
        `;
    }
}
©2019 Morningstar, Inc. All rights reserved. Terms of Use