JavaScript library that wraps the W3C standard Web Components family of APIs to provide a compact, feature-rich interface for Custom Elements development.
Smart Custom Element provides a set of useful API, Data Binding, Templates, Device Agnostic Event Handling, Resize handling, Style Change Notifications, Property and Attribute Change Notifications, Property Value and Type validation, Localization, Lifecycle callback functions and much more. Our framework allows you to easily build Custom HTML Elements. Custom Elements are the web platform's native solution for component-based development. With Custom Elements, you get reusable HTML tags that can be used just like the browser’s built-in native html elements, or break your app up into small pieces, making your code cleaner and easier to maintain.
Installation
npm install smart-custom-element --save
In your web page, include
<script src="source/smart.element.js"></script>
Optional polyfill for browsers without custom elements support: webcomponents-lite.js
Version and Deployment
Browser Support and Compatibility
Requires ES2015 classes. Edge, Chrome, Safari and Firefox. Requires Webcomponents polyfill for Edge and Safari
How to Use?
Include HTML tag (e.g. <my-button id='button'></my-button>) in any time of document lifecycle. You can use your elements in e.g. SPA application just by including HTML tag. Custom Elements will auto initialize when added into document. You can include them in e.g. Vue, Angular or React projects and browser will take care of detecting it and initialization. You use it just like a native HTML Element, by changing attributes with button.setAttribute(attributeName, attributeValue);, setting properties with button.disabled = true; or listening to events with button.addEventListener('click', function(event) { });.
You also take advantage of features like lazy-loading, that allows for loading components on demand, only when user add them to document
Introduction
A basic element definition looks like this:
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/webcomponentsjs/1.0.22/webcomponents-lite.js"></script>
<script type="text/javascript" src="source/smart.element.js"></script>
<script>
Smart('smart-test', class TestElement extends Smart.BaseElement {
// properties.
static get properties() {
return {
'content': {
type: 'string'
}
};
}
/** Element's template. */
template() {
return '<div inner-h-t-m-l=\'[[content]]\'></div>';
}
ready() {
super.ready();
}
propertyChangedHandler(propertyName, oldValue, newValue) {
super.propertyChangedHandler(propertyName, oldValue, newValue);
}
});
</script>
<style>
.smart-container {
box-sizing: border-box;
font-family: inherit;
font-size: inherit;
display: block;
width: 100%;
height: 100%;
outline: none;
margin: 0;
padding: 0;
}
.smart-container * {
box-sizing: border-box;
}
smart-test {
background: #ddd;
color: #333;
display: inline-block;
border-radius: 5px;
border: 1px solid #aaa;
width: 100px;
text-align: center;
}
</style>
</head>
<body>
<smart-test content="Test Element"></smart-test>
</body>
</html>
An extended element definition looks like this:
Smart('smart-button', class Button extends Smart.ContentElement {
// Button's properties.
static get properties() {
return {
'value': {
type: 'string'
},
'name': {
type: 'string'
},
'type': {
type: 'string'
},
'clickMode': {
allowedValues: ['hover', 'press', 'release'],
type: 'string',
value: 'release'
}
};
}
/** Button's template. */
template() {
return '<button class=\'smart-button\' inner-h-t-m-l=\'[[innerHTML]]\' id=\'button\' type=\'[[type]]\' name=\'[[name]]\' value=\'[[value]]\' disabled=\'[[disabled]]\' role=\'button\'></button>';
}
static get listeners() {
return {
'button.mousedown': '_mouseDownHandler',
'button.mouseenter': '_mouseEnterHandler',
'button.click': '_clickHandler'
};
}
_clickHandler(event) {
const that = this;
if (that.clickMode !== 'release') {
event.preventDefault();
event.stopPropagation();
}
}
_mouseDownHandler() {
const that = this;
if (that.clickMode === 'press') {
that.$.fireEvent('click');
}
}
_mouseEnterHandler() {
const that = this;
if (that.clickMode === 'hover') {
that.$.fireEvent('click');
}
}
});
The base custom element class is called BaseElement and is accessible through Smart.BaseElement. Most elements derive from Smart.BaseElement. Smart.ContentElement extends the Smart.BaseElement by adding content and innerHTML properties to it. It is useful when you need to append a child element by setting a single property.
Register a Custom Element
To register a custom element, use the Smart function and pass in the element's tag name and class. By specification, the custom element's name must contain a dash (-). The library internally checks whether Custom Elements v1 is supported and uses its lifecycle callbacks and customElements.define. Otherwise, it uses document.registerElement and the v0 lifecycle callbacks. To use custom elements, you will need a browser which natively supports Custom Elements or you will need to load polyfills such as webcomponentsjs.
Resources:
Lifecycle callbacks
- created - Called when the element has been created, but before property values are set and local DOM is initialized.
Use for one-time set-up before property values are set.
- attached - Called after the element is attached to the document. Can be called multiple times during the lifetime of an element.
- ready - Called when the element is ready. Use for one-time configuration of your element.
- detached - Called after the element is detached from the document. Can be called multiple times during the lifetime of an element.
- completed - Called after the element and any custom elements in its template are ready, rendered and attached to the DOM. Completed is called once.
Properties
To add properties on your custom element, you can use the properties object. All properties part of the properties object are automatically serialized and deserialized by the element and can also be set through attributes by using the dash(-) syntax in the HTML markup. Each property can have the following members:
- reflectToAttribute - Type: Boolean. Set to
true to cause the corresponding attribute to be set on the host node when the property value changes. If the property value is Boolean, the attribute is created as a standard HTML boolean attribute (set if true, not set if false). For other property types, the attribute value is a string representation of the property value. The default value of this member is true.
- defaultReflectToAttribute - Type: Boolean. Set to
true when we want a default attribute value to be set on the host node.
- readOnly - Type: Boolean. Determines whether the property is readyonly. if
true the property can't be set by the user.
- type - Type: String. Used for deserializing from an attribute.
- any - allows assigning any value to a property.
- string - allows assigning a
String to a property.
- string? - allows assigning a 'String' or null to a property.
- boolean or bool - allows assigning a
Boolean to a property.
- boolean? or bool? - allows assigning a 'Boolean' or null to a property.
- number or float - allows assigning a 'Number' to a property.
- number? or float? - allows assigning a 'Number' or null to a property.
- int or integer - allows assigning an 'Integer' to a property.
- int? or integer? - allows assigning an 'Integer' or null to a property.
- date - allows assigning a 'Date' to a property.
- date? - allows assigning a 'Date' or null to a property.
- array - allows assigning an 'Array' to a property.
- object - allows assigning an 'Object' to a property.
- allowedValues - Type: Array. Used for defining a set of values which are allowed to be set. For other values, an exception is thrown.
- notify - Type: Boolean. Determines whether an event is raised when a property is changed. The event name is: property's attribute name + - 'changed'. Example: Property's name is 'clickMode', the event's name will be 'click-mode-changed'.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="styles/smart.default.css" type="text/css" />
<script type="text/javascript" src="smart.elements.js"></script>
<script>
window.onload = function () {
var list = document.getElementById('list');
var data = [
{
label: "Andrew",
value: 1,
group: "A"
},
{
label: "Natalia",
value: 5,
group: "B"
},
{
label: "Michael",
value: 4,
group: "B"
},
{
label: "Angel",
value: 2,
group: "A"
},
{
label: "Hristo",
value: 6,
group: "C"
},
{
label: "Peter",
value: 3,
group: "A"
},
{
label: "Albert",
value: 4,
group: "A"
},
{
label: "Boyko",
value: 8,
group: "A"
},
{
label: "Dimitar",
value: 9,
group: "B"
},
{
label: "George",
value: 10,
group: "C"
}
];
list.dataSource = data;
list.addEventListener('disabled-changed', function (event) {
if (event.target === list) {
alert('disabled changed');
}
});
document.getElementById("disabled").onclick = function () {
list.disabled = !list.disabled;
}
list.properties['disabled'].notify = true;
}
</script>
</head>
<body>
<smart-list-box style="float:left;" selection-mode="checkBox" id="list"></smart-list-box>
<div style="float: left; margin-left:100px;">
<smart-button style="width:auto;" id="disabled">Enable/Disable</smart-button>
</div>
</body>
</html>
- value - Default value for the property.
- observer - Type: String. A name of a function called within the Element when the property is changed. The arguments passed to your observer are the property's
oldValue and newValue.
- validator - Type: String. A name of a function called within the Element when the property is changing. The arguments passed to your validator are the property's
oldValue and newValue. The function returns the updated value. If it returns undefined, the newValue remains unchanged.
propertyChangedHandler(propertyName, oldValue, newValue) method is called when a property is changed by the user. This method is useful for updating the element when the user makes some changes.
The user may watch for property changes by using the element's instance. watch(propertiesArray, propertyChangedCallback). The arguments passed to the propertyChangedCallback function are propertyName, oldValue, newValue.
Template
The template object determines the internal HTML structure of the Element. Within that structure you can data bind properties by using two-way or one-way data binding.
template() {
return '<button class=\'smart-button\' inner-h-t-m-l=\'[[innerHTML]]\' id=\'button\' type=\'[[type]]\' name=\'[[name]]\' value=\'[[value]]\' disabled=\'[[disabled]]\' role=\'button\'></button>';
}