UNPKG

@navelpluisje/pcb-components

Version:

A library with native components. They are all pcb components, like a dip-switch, resitor etc.

78 lines (63 loc) 2.37 kB
import htmlTemplate from './ic.html'; import style from './ic.css'; export const ic = () => (customElements.define('np-ic', class Ic extends HTMLElement { constructor() { // Always call super first in constructor super(); this.currentDocument = document.currentScript.ownerDocument; // Get the template and substract the parts // const template = document.getElementById('np-dip-switch').import; const template = document.createElement('div'); template.innerHTML = htmlTemplate; const templateContent = template.querySelector('.ic'); this.pins = template.querySelector('.ic-step'); const styling = document.createElement('style'); styling.innerHTML = style; // Create the shadowRoot and append the content const shadowRoot = this.attachShadow({ mode: 'open' }); shadowRoot.appendChild(templateContent.cloneNode(true)); shadowRoot.appendChild(styling.cloneNode(true)); // Create Events this.changeEvent = new CustomEvent('change', { bubbles: true, cancelable: false, }); } connectedCallback() { this.ic = this.shadowRoot.querySelector('.ic-wrapper'); this.labelField = this.shadowRoot.querySelector('.label'); this.valueField = this.shadowRoot.querySelector('.value'); this.endPins = this.shadowRoot.querySelector('.ic-end'); // Get the attributes of our web-component this.label = this.getAttribute('label') || 'Label'; this.value = this.getAttribute('value'); this.pinCount = parseInt(this.getAttribute('pins'), 10) || 8; this.valueField.setAttribute( 'placeholder', this.getAttribute('placeholder') || 'Value', ); this.valueField.value = this.value; this.labelField.textContent = this.label; this.setEventBindings(); this.addPins(); } setEventBindings() { this.valueField.addEventListener('blur', this.handleValueBlur.bind(this)); } handleValueBlur() { this.setValue(this.valueField.value); } addPins() { const pinPair = Math.floor(this.pinCount / 2) - 2; new Array(pinPair).fill(null).forEach(() => { this.ic.insertBefore(this.pins.cloneNode(true), this.endPins); }); } setValue(value) { if (this.value === value) { return false; } this.value = value; this.dispatchEvent(this.changeEvent); return true; } })); export default null;