Source: bookmarker.js

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

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

	this.observables = [];

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

    /**
     * Called when this is attached to DOM
     * @connectedCallback. 
     */
    connectedCallback() {
        wc.group("Bookmarker.connectedCallback")
	
	let self = this;

	// 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();

	tkloading.show();

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

	this.SQL = SQL.init(this.properties.db, function() {
	    wc.log("SQLITE IS READY...")
	});

	wc.wait4(".wc-bookmarker-search", () => {
	    self._query();

	    wc.enterKey(".wc-bookmarker-search", function() {
		tkloading.show();

		self._query();
	    });

	    $("[type=checkbox]").on("click", function() {
		self._checkbox($(this).attr("id"))
	    });

	    $(".wc-bookmarker-btn-add, .wc-bookmarker-btn-cancel").on("click", function() {
		$(".wc-boorkarker-add").slideToggle();
	    });

	    $(".wc-bookmarker-btn-submit").on("click", function() {
		self._submit();
	    });
	});

	// 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})});

	tkloading.hide();

        wc.groupEnd();
    };

    /**
     * Initial Markup
     * @private
     * @_template
     */
    _template() {
        wc.group("Bookmarker.template");
	
	var temp = `
	    <div><wc-msg id="my-msg" parent="wc-bookmarker-marker"></wc-msg></div>
	    <div><wc-include href="/tk/lib/components/misc/webpack/src/w/html/parts/bookmarker/main.html"></wc-include></div>`

        wc.groupEnd();
        return temp;
    };

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

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

	let obs = Bookmarker.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("Bookmarker._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("Bookmarker._fetchAttributes");
	
	this.properties = {
	    uparam	: "",
	    cname	: "Bookmarker",
	    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();
    };

    /**
     * configure the instance object and artifacts
     * @configure
     * @param {string} data use data if exist else use 'this.properties.cfg' parameter
     */
    configure(data) {
	wc.group("Bookmarker.configure:", data);

	// IF JSON VARIABLE (data) IS PROVIDED
	if (data) {
	    this._process(data);
	} else {
	    let self = this;

	    $.getJSON(this.properties.cfg, function(data) {
		self._process(data);
	    }).fail(function(jqXHR, textStatus, errorThrown) {
		alert("ERROR: INCOMING TEXT " + jqXHR.responseText);
	    });
	}

	wc.groupEnd();
    };

    /**
     * _process the instance object and artifacts
     * @private
     * @_process
     */
    _process(data) {
	wc.group("Bookmarker._process:", data);
	
	// DO WHATEVER WITH THE DATA
	
	wc.groupEnd();
    };

    /**
     * Initialize component
     * @private
     * @_initialize
     */
    _initialize() {
	wc.group("Bookmarker._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("Bookmarker._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("Bookmarker.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("Bookmarker.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();
    };

    /**
     * @_request
     */
    _request(e) {
	wc.group("Bookmarker._request:", this.id, JSON.stringify(e.detail));
	
	switch(e.detail.request) 
	{
	    case "label":
	    let h1 = this.querySelector("h1");
	    h1.innerHTML = e.detail.str;
	    this._publish("labelChanged");
	    break;

	    default:
	    alert("DO NOT HAVE SUCH REQUEST: " + e.detail.request);
	    break;
	}

	wc.groupEnd();
	return true;
    };

    /**
     * @_query
     */
    _query() {
	wc.group("Bookmarker._query");

	$(`.wc-bookmarker-table tbody`).empty();

	let str = $(".wc-bookmarker-search").val();

	var r = this.SQL.exec(`select * from bookmarks where (tag like '%${str}%' OR description like '%${str}%')`);

	try {
	    let cols = r[0].columns
	    let vals = r[0].values;

	    for (var i = 0; i < cols.length; i++) {
		if (typeof vals[i] != "undefined") {
		    let id   = vals[i][0];
		    let url  = vals[i][1];
		    let desc = vals[i][2];
		    let tags = vals[i][3].replace(/"/g,"");
		    let ip   = vals[i][4];
		    let ts   = vals[i][5];

		    $(".wc-bookmarker-table tbody").append(`
			<tr>
			    <td class="td-id">${id}</td>
			    <td class="td-description"><a href="${url}" target="_blank">${desc}</a></td>
			    <td class="td-tags">${tags}</td>
			</tr>
		`);
		}
	    }
	}
	catch(e) {
	    let msg = this.querySelector("wc-msg");
	    msg.show({id:"M2011: ", type:"error",html:`Nothing found for: <strong>${str}</strong>`, timer: 3000})
	    console.error(e.name + ' > ' + e.message);
	}
	
	tkloading.hide();

	wc.groupEnd();
	return true;
    }

    /**
     * @_checkbox
     */
    _checkbox(id) {
	wc.group("Bookmarker._checkbox:", id);

	$(`.wc-bookmarker-table .td-${id}`).toggle();

	wc.groupEnd();
	return true;
    }

    /**
     * @_submit
     */
    _submit(id) {
	wc.group("Bookmarker._submit:", id);

	let input = ["url","des","tag"];
	let success = true;
	let istr = "null,";

	for (var i = 0; i < input.length; i++) {
	    let val = $("[name=" + input[i]+ "]").val().trim();

	    if (val == "") {
		$("[name=" + input[i]+ "]").focus();
		success = false;
	    } else {
		istr += `'${val}',`;
	    }
	}

	istr = istr.substring(0, istr.length - 1);

	this.SQL.exec(`insert into bookmarks values (${istr})`);
	var binaryArray = this.SQL.export();
	console.log("-------------", binaryArray);

	$(".wc-boorkarker-add").slideToggle();

	wc.groupEnd();
	return true;
    }
}

window.customElements.define('wc-bookmarker', Bookmarker);