Source: websocket.js

/**
 * Websocket Component<BR>
 * <BR><BR><img src=/tk/lib/components/w/img/ws.png width=30% style="border:1px lime dashed;padding:20px">
 * <BR><BR><a href="/tk/lib/components/w/html/ws.html">DEMO</a>
 */
class WS extends HTMLElement {
    constructor() {
        wc.group("WS.constructor")
	
        super();

        wc.groupEnd();
    };
    
    /**
     * Set observable values here. When Changed, attributeChangedCallback is invoked
     * @observedAttributes
     */
    static get observedAttributes() {
        wc.group("WS.observedAttributes");

	this.observables = [];

        wc.groupEnd();
        return this.observables;
    };

    /**
     * Called when this is attached to DOM
     * @connectedCallback. 
     */
    connectedCallback() {
        wc.group("WS.connectedCallback")
	
	// ADD A RANDOM ID IF NONE EXIST
	if (!this.id) {
	    this.id = this.constructor.name.toLowerCase() + "-" + wc.uid();
	}

	// GET PROPERTIES AND INTERESTING ELEMENTS
	this._initialize();

	// ADD COMPONENT MARKTOP
	this.innerHTML = this._template()

	this.start();

	// ADD STATS AND OTHER FINAL STUFF
	this._finalize();

	ga('send', {'hitType': 'event','eventCategory': 'wc-connected','eventAction': 'connected','eventLabel': this.properties.cname, 'eventValue':JSON.stringify({'env':wcENV,'app':wcAPP,'url':wcURL})});

        wc.groupEnd();
    };

    /**
     * Initial Markup
     * @private
     * @_template
     */
    _template() {
        wc.group("WS.template");
	
	var temp = this.dom.content;

        wc.groupEnd();
        return temp;
    };

    /**
     * Called with .setAttribute(...) function call
     * @attributeChangedCallback
     */
    attributeChangedCallback(attr, oldval, newval) {
        wc.group("WS.attributeChangedCallback:", attr, oldval, newval);

	this.properties = this.properties || [];

	let obs = WS.observedAttributes;

	for (let i = 0; i < obs.length; i++) {
	    if (newval) {
		this.properties[obs[i]] = newval;
	    }
	}
	
	// YOUR CODE FOR CHANGES GO HERE (MAYBE NULL FIRST TIME THROUGH)
	try {
	    switch(attr) 
	    {
		case "header":
		//this.querySelector("h1").innerHTML = newval;
		break;
		
		default:
		break;
	    }
	} catch(e) {
	    wc.warn(e.name + ' > ' + e.message);
	}

        wc.groupEnd();
    };

    /**
     * Stores DOM elements of interest for future use
     * @private
     * @_fetchElements
     */
    _fetchElements() {
	wc.group("WS._fetchElements");
	
	this.dom = this.dom || [];
	this.dom.content = this.innerHTML;

	wc.groupEnd();
    };

    /**
     * Component attributes are _fetched and defaults are set if undefined
     * @private
     * @_fetchAttributes
     */
    _fetchAttributes() {
	wc.group("WS._fetchAttributes");
	
	this.properties = {
	    uparam	: "",
	    cname	: "ws",
	    author	: "Mel M. Heravi, Ph.D.",
	    version	: "1.0"
	};
	
	// SAVE WIDGET SPECIFIC PROPERTIES
	this.propertiesW = [];
	
	// SAVE ALL OTHER PROPERTIES
	let attrs = wc.getAttributes(this)
	
 	for (var key in attrs) {
	    let attr = this.getAttribute(key) || this.properties.key;
	    this.properties[key]  = this.getAttribute(key);
	    this.propertiesW[key] = this.getAttribute(key);
	    wc.log(key + ": " + attrs[key]);
	}

	// SET ALL INITIAL ATTRIBUTES
 	for (var key in this.properties) {
	    switch(key) 
	    {
		case "header":
		break;
		
		default:
		break;
	    }
	}

	wc.log("ATTRIBUTES: ", this.properties);

	wc.groupEnd();
    };

    /**
     * Initialize component
     * @private
     * @_initialize
     */
    _initialize() {
	wc.group("WS._initialize:", this.id);

	// FETCH ALL INTERESTING ELEMENTS
	this._fetchElements();

	// FETCH ALL ATTRIBUTES
	this._fetchAttributes();
	
	wc.groupEnd();
    };

    /**
     * Save data for analytics and final wrap up
     * @private
     * @_finalize
     */
    _finalize() {
	wc.group("WS._finalize:", this.id);

	this.classList.add("wc");

	// ADD ANALYTICS HERE
	wc.setStats(this, this.properties.cname, this.properties.version);
	
	// SHOW IT NOW (NO FLICKERS) 
	this.style.visibility = "visible";

	wc.groupEnd();
    };

    /**
     * Invoked When component is removed. Usually with a .remove() function call
     * @disconnectedCallback
     */
    disconnectedCallback() {
        wc.group("WS.disconnectedCallback")

	ga('send', {'hitType': 'event','eventCategory': 'wc-disconnected','eventAction': 'disconnected','eventLabel': this.properties.cname, 'eventValue':JSON.stringify({'env':wcENV,'app':wcAPP,'url':wcURL})});

        wc.groupEnd();
    };

    /**
     * Destroy the instance object and artifacts
     * @destroy
     */
    destroy() {
	wc.group("WS.destroy");

	// FREE ALL MEMORY
	// you should delete all created objects here
	
	// FREE POINTER
	delete this;
	
	// REMOVE ITEM FROM DOM
	this.parentNode.removeChild(this);

	ga('send', {'hitType': 'event','eventCategory': 'wc-destroyed','eventAction': 'distroy','eventLabel': this.properties.cname, 'eventValue':JSON.stringify({'env':wcENV,'app':wcAPP,'url':wcURL})});

	wc.groupEnd();
    };

    /**
     * Start the instance object and artifacts
     * @start
     */
    start() {
	wc.group("WS.start");

	let self = this;

	window.ws = new WebSocket(this.properties.url);

	////////////////////////////////////////////////////////////
	////
	////////////////////////////////////////////////////////////
	ws.onopen = () => {
	    wc.group("ws.onopen");

	    let time = new Date().getTime();

	    ws.send("ping")

	    wc.publish("wc-websocket", {
		time: new Date().getTime(),
		type: "info",
		msg: "CONNECTED",
		id: self.id
	    });

	    wc.groupEnd();
	}

	////////////////////////////////////////////////////////////
	////
	////////////////////////////////////////////////////////////
	ws.onerror = (error) => {
	    wc.group("ws.onerror");

	    var msg = "UNKNOWN ERROR..."

	    if (error.target.readyState == 3) {
		msg = `DISCONNECTED. will try again in ${this.properties.reconnect/1000} seconds...`
	    }

	    wc.error("C ERROR:", error.target.readyState, msg)

	    wc.publish("wc-websocket", {
		time: new Date().getTime(),
		type: "error",
		msg: msg,
		id: self.id
	    });
	    
	    wc.groupEnd();
	}

	////////////////////////////////////////////////////////////
	////
	////////////////////////////////////////////////////////////
	ws.onmessage = (e) => {
	    wc.group("ws.onmessage");

	    let msg = e.data;
	    let x = msg.split(" ");

	    switch(x[0])
	    {
		case "pong":
		wc.log(`C < ${msg}`);

		wc.publish("wc-websocket", {
		    time: new Date().getTime(),
		    type: "msg",
		    msg: msg,
		    id: self.id
		});
		break;

		default:
		let error = `ERROR: DO NOT UNDERSTAND COMMAND: ${msg}`;
		wc.error(error);

		wc.publish("wc-websocket", {
		    time: new Date().getTime(),
		    type: "error",
		    msg: error,
		    id: self.id
		});
		break;
	    }

	    // CONFIRM
	    ws.send("ready");
	    
	    wc.groupEnd();
	}

	////////////////////////////////////////////////////////////
	//// RESTART IF DISCONNECTED
	////////////////////////////////////////////////////////////
	ws.onclose = function(e) {
	    wc.group("ws.onclose");

	    wc.log("DISCONNECTED!");
	    
	    wc.publish("wc-websocket", {
		time: new Date().getTime(),
		type: "info",
		msg: "CONNECTION CLOSED",
		id: self.id
	    });

	    setTimeout(() => {
		self.start()
	    }, self.properties.reconnect);

	    wc.groupEnd();
	};

	wc.groupEnd();
    }
}

window.customElements.define('wc-websocket', WS);