Home

Awesome

base-custom-webcomponent

Description

The base-custom-webcomponent is a simple base class for the use of webcomponents in typescript. It wraps the needed basic functionality and also allows you to optionally use some advanced technics like

Basic Feature

The base class does:

Planed features

Automatic Change Notification class fields via decorators are planed, but lack browser support at the moment: https://github.com/lit/lit/issues/2284 For now we removed the this._createObservableProperties(); cause it would not work if you compile to newer javascript.

Refresh Bindings - only for the changed value. At the moment the call refreshes all bindings, but this could (and should) be optimized.

Advanced Features

All the features are not enabled by default for performance reasons but you can call these methods to enable them.

Hot Reload

The Library supports Hotreload of Components created with it. This works mostly for the Templates and the Styles, for Javascript, it depends. Best is, if you try it yourself.

To use it, try following snippet:

HotModuleReplacement.initHMR(async () => {
    ...
    replace this with a function wich returns a list of your changed files, 
    or null if no files have changed since the last call, this function will be called every 100ms
    so this function for example could ask the dev server wich files have changed, and return them.
    The hotmodulereplacment will then try to reload them (If possible)
    ...
});

Bindings

The Bindings are heavily inspired by polymer

use [[expression]] for one way bindings

use {{this.property::change;paste}} for two way bindings which listens to events 'change 'and 'paste'

bcw:visible="[[bool-expression]]" to bind set css visiblity to visible when expression is true

css:cssPropertyName="[[expression]]" to bind to a css property

class:className="[[boolExpression]]" to set/remove a css class

$attribute="[[expression]]" to bind to Attributes instead of properties.

?booleanAttribute="[[expression]]" to bind to a boolean Attribute.

.property="[[expression]]" to bind to Proertys without using the attribute name (to disable side effects).

sub <template></template> elements are not bound, so elements like <iron-list> of polymer also work

css type adopted-css

use repeat:nameOfItem="[[enumerableExpression]]" on a template element to repeat it for every instance of the enumerable. You could also use 'index' variable in the repeat binding for the current number. The attribute "repeat-index" could be used to change the name of the index variable. on a repeat you could use the repeat-changed-item-callback="[[this.itemCreated(item, nodes)]] !!caution!! => the repeat binding is only a preview at the moment, it redraws all items on array change

use if="[[expression]]" an a template element to show it conditionally

Event Code Bindings

with for example @click="[[this.aa(event)]]" you could create a event binding wich could run any javascript code inside of the brackets. use @@ if you want to replace - with uppercase in events

Binding extensions

Declaritive Custom Element

With the node-projects-dce element you could create a custom elment declaritively, see:

Sample:

<node-projects-dce name="simple-dce-demo" properties='{"list":"Array", "list2":"Array", "ctx":{"type":"String","reflect":true}}' enable-bindings >
    <template>
        <style>h1 {color: red}</style>
        <h1>Hello World</h1>
        <div style="border: solid 3px black">Ctx: [[this.ctx]]</div>
        <template repeat:myitem="[[this.list]]">
            <button>[[myitem.toUpperCase()]] - <b>[[myitem.toLowerCase()]]</b> - [[index]]</button>
            <ul>
            <template repeat:myitem2="[[this.list2]]" repeat-index="inneridx">
                <button @click="[[this.ctx = myitem2]]" >[[myitem.toUpperCase()]] - <b>[[myitem2.toLowerCase()]]</b> - [[inneridx * 100]]</button>
            </template>
            </ul>
        </template>
    </template>
</node-projects-dce>
<simple-dce-demo list='["aa","bb","cc"]' list2='["hello", "you"]' ctx="TestCtx" style="position:absolute;left:184px;top:-53px;"></simple-dce-demo>

Developing

  $ npm install
  $ npm run build

Dependencies

none on chrome.

construct-style-sheets-polyfill on safari and firefox

Using

Simple Example Class in Typescript

import { BaseCustomWebComponentConstructorAppend, html } from '@node-projects/base-custom-webcomponent';

@customElement('test-element')
export class TestElement extends BaseCustomWebComponentConstructorAppend {

    static readonly style = css`
        `;

    static readonly template = html`
            <div id='root'>
                <div css:background="[[this.bprp ? 'red' : 'green']]">[[this.info]]</div>
                <template repeat:item="[[this.list]]">
                    <div>[[item]]</div><br>
                </template>
            </div>
            <button @click="buttonClick">click me</button>
        `;
    
    @property()
    list = ['aa', 'bb'];
    @property()
    info = 'hallo';
    @property()
    bprp = false;

    constructor() {
        super();
        this._restoreCachedInititalValues();
    }

    async ready() {
        this._root = this._getDomElement<HTMLDivElement>('root');
        this._parseAttributesToProperties();
        this._bindingsParse();
        this._assignEvents();

        setTimeout(() => {
            this.info = 'wie gehts?';
            brpp = true;
        }, 5000)
    }

    buttonClick() {
        alert('hallo');
    }
}

Online Sample

https://codesandbox.io/p/sandbox/wkopk

or here a repo

https://github.com/node-projects/base-custom-webcomponent-sample

ready method

The ready method will be called, when the component is connected the first time. Be aware, that there is no information about the child components. They could be still not ready. When you need to interact with child componets, then use the method _waitForChildrenReady.

  public async ready(): Promise<void> {
          await this._waitForChildrenReady();
          // now all children are ready!
          
          const myChild = this._getDomElement<CustomAutoCompleteBoxComponent>('XYZ');
  

VS Code Snippet

vscode-snippet-bcwc_3

How to use?

image

Articles

https://medium.com/@jochenkhner/a-idea-for-a-base-class-for-web-components-in-2020-b68e0fdf7bca

Size

The Size of the Base Component is around 25k as ts/js code, 10k minimized and 2.2k brotly compressed.