UNPKG

@chipta/libs-element

Version:
105 lines (75 loc) 2.14 kB
'use strict'; import { LitElement, html, css, unsafeCSS } from 'lit-element'; class Element extends LitElement { constructor() { super(); this.stateChangeCallbacks = {}; } connectedCallback() { super.connectedCallback(); this.initStateChangeListeners() } disconnectedCallback() { super.disconnectedCallback(); this.removeChangeListeners(); } initStateChangeListeners() { if (this.observedStates) { for (let state of this.observedStates) { this.stateChangeCallbacks[state] = prop => { //this.dev_flashUpdate(); this.requestUpdate(); this.stateChanged(state, prop); }; state.addChangeListener(this.stateChangeCallbacks[state]); } } } removeChangeListeners() { for (let callback of Object.values(this.stateChangeCallbacks)) { state.removeChangeListener(callback); } } stateChanged(state, prop) {} el(querySelector) { return this.shadowRoot.querySelector(querySelector); } els(querySelector) { return this.shadowRoot.querySelectorAll(querySelector); } triggerEvent(eventType) { this.dispatchEvent( new CustomEvent(eventType, { composed: true, bubbles: true }) ); } dev_flashUpdate() { // Shows an overlay over the elements that have been updated and also logs // them to the developer console. This is a useful tool for debugging and // optimizing. if (this.dev_flashing) { return } console.log('updating', this); this.dev_flashing = true; const flashEl = document.createElement('div'); Object.assign(flashEl.style, { position: 'absolute', top: this.offsetTop + 'px', left: this.offsetLeft + 'px', width: this.clientWidth + 'px', height: this.clientHeight + 'px', background: 'primary', zIndex: '9999', opacity: '0.5' }); document.body.appendChild(flashEl); window.setTimeout(() => { document.body.removeChild(flashEl); this.dev_flashing = false; }, 500); } } export {Element, html, css, unsafeCSS};