Source: form.js

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

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

	this.observables = ["size"];
	wc.log(this.observables);

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

    /**
     * This function is called when this is attached to DOM
     * @connectedCallback. 
     */
    connectedCallback() {
        wc.group("Form.connectedCallback")
	
	let self = this;

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

	// FETCH ALL ATTRIBUTES
	this._fetchAttributes();

	this.name = $(this).attr("name");
	if (typeof this.name === "undefined") {this.name = this.id;}

	// REPLACE CONTENT IF NECESSARY WITH NEW STUFF
	this.innerHTML = `
		<form id='${this.id}-actual' name='${this.name}' class="${this.properties.class}" method='${this.properties.method}' action='${this.properties.action}'>
		    ${this.dom.content}
		    <div class="clearfix" id='${this.id}-results'></div>
		</form>`

	// IF JSON FILE IS PROVIDED
	if (typeof this.properties.cfg != "undefined") {
	    this.configure()
	}

	if (this.properties.action !== "undefined") {
	    this.form = this.querySelector("form");

	    $(this.form).validator().on('submit', function (e) {
		if (e.isDefaultPrevented()) {
		    // handle the invalid form...
		} else {
		    e.preventDefault();
		    
		    let values = $(this).serializeArray();
		    
		    wc.publish("wc-form", {
			time: new Date().getTime(),
			action: "submit",
			id: this.id,
			formid: self.id,
			values: values
		    });
		}
	    })
	}

	// REPLACE ALL PATTERNS WITH ACTUAL REGEX STRINGS
	let patterns = this.querySelectorAll("[pattern]");
	
	$(patterns).each(function() {
	    let pat = this.getAttribute("pattern")

	    let rval = wc.jfind(tkRegex, "name", pat)

	    let r = rval[0].regex;
	    
	    // REMOVE FIRST AND LAST CHAR
	    this.setAttribute("pattern", r.toString().slice(1,-1));
	});

	this._finalize();

	// 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("Form.disconnectedCallback")

	/* CLEAN UP NOW */

        wc.groupEnd();
    };

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

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

	let obs = Form.observedAttributes;

	for (let i = 0; i < obs.length; i++) {
	    if (newval) {
		this.properties[obs[i]] = newval;

		// YOUR CODE FOR CHANGES GO HERE 
		switch(attr) 
		{
		    case "size":
		    break;

		    default:
		    break;
		}
	    }
	}
	
        wc.groupEnd();
    };

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

	wc.groupEnd();
    };

    /**
     * Component attributes are _fetched and defaults are set if undefined
     * @private
     * @_fetchAttributes
     * @param {string} [method=POST] form method
     * @param {string} [name="NOTSET"] form action
     */
    _fetchAttributes() {
	wc.group("Form._fetchAttributes");
	
	this.properties = {
	    "cname"	  : "Form",
	    "author"      : "Mel Heravi",
	    "version"     : "1.0",
	    "method"      : "POST",
	    "showrequired": "true"
	};
	
	// SAVE WIDGET SPECIFIC PROPERTIES
	this.propertiesW = [];

	// SAVE ALL OTHER PROPERTIES
	let attrs = wc.getAttributes(this)

 	for (var key in attrs) {
	    this.properties[key]  = this.getAttribute(key);
	    this.propertiesW[key] = this.getAttribute(key);
	    wc.log(key + ": " + attrs[key]);
	}

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

	wc.groupEnd();
    };

    /**
     * Destroy the instance object and artifacts
     * @private
     * @_destroy
     */
    destroy() {
	wc.group("Form.destroy:", this.id);

	// FREE POINTER
	delete this;

	// REMOVE ITEM FROM DOM
	this.parentNode.removeChild(this);

	wc.groupEnd();
    };

    /**
     * SAVE DATA FOR ANALYTICS
     * @private
     * @_finalize
     */
    _finalize() {
	wc.group("Form._finalize:", this.id);

	let self = this;
	this.classList.add("wc");

	wc.timeout(e => {
	    if (this.properties.showrequired == "true") {
		// MARK ALL REQUIRED FIELS
		$("*[required]").each(function() {
		    let id = $(this).attr("id");
		    $("#" + id + "-label").addClass("required");
		});
	    }

	    // BIND ALL VARIABLES TO FIELDS
	    wc.binder();

	    $(this.form).validator("update");
	}, 300);

	// ADD ANALYTICS HERE
	wc.setStats(this, this.properties.cname, this.properties.version);

	wc.groupEnd();
    };

    /**
     * FOR TESTING PURPOSES
     * @test
     */
    static test() {
	wc.group("Form.test");

	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("Form.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("Form._process:", data);
	
	for (var key in data) {
	    switch(data[key].field) 
	    {
		case "text":
		let type = data[key].type    || ""
		let pat  = data[key].pattern || ""

		$(`#form-${key}`).html(`
			<wc-text
			id="${data[key].id || data[key].name}"
			type="${type}"
			name="${data[key].name}"
			data-key="${data[key].name}"
			pattern="${pat}"
			label="${data[key].label || ''}"
			columns="${data[key].columns || '12,12'}"
			placeholder="${data[key].placeholder || ''}"
			help="${data[key].help || ''}"
			data-error="${data[key].error || ''}"
			${data[key].required || ''}></wc-text>`);
		break;

		case "textarea":
		$(`#form-${key}`).html(`
			<wc-textarea
			id="${data[key].id || data[key].name}"
			name="${data[key].name}"
			data-key="${data[key].name}"
			label="${data[key].label || ''}"
			columns="${data[key].columns || '12,12'}"
			placeholder="${data[key].placeholder || ''}"
			help="${data[key].help || ''}"
			data-error="${data[key].error || ''}"
			${data[key].required || ''}></wc-textarea>`);
		break;

		case "calendar":
		$(`#form-${key}`).html(`
			<wc-calendar
			id="${data[key].id || data[key].name}"
			name="${data[key].name}"
			data-key="${data[key].name}"
			label="${data[key].label || ''}"
			columns="${data[key].columns || '12,12'}"
			placeholder="${data[key].placeholder || ''}"
			help="${data[key].help || ''}"
			data-error="${data[key].error || ''}"
			${data[key].required || ''}></wc-calendar>`);
		break;

		case "select":
		let options = "";
		for (var i = 0; i < data[key].options.length; i++) {
		    if (data[key].options[i].value == "") {
			options += `<option disabled selected></option>`;
		    } else {
			options += `<option value="${data[key].options[i].value}">${data[key].options[i].name}</option>`;
		    }
		}

		$(`#form-${key}`).html(`
			<wc-select
			id="${data[key].id || data[key].name}"
			name="${data[key].name}"
			data-key="${data[key].name}"
			label="${data[key].label || ''}"
			columns="${data[key].columns || '12,12'}"
			placeholder="${data[key].placeholder || ''}"
			help="${data[key].help || ''}"
			data-error="${data[key].error || ''}"
			searchable="${data[key].searchable || 'false'}"
			${data[key].required || ''}>${options}</wc-select>`);
		break;

		case "radio":
		$(`#form-${key}`).html(`
			<wc-radio
			id="${key}"
			name="${data[key].name}"
			data-key="${data[key].name}"
			label="${data[key].label || ''}"
			columns="${data[key].columns || '12,12'}"
			placeholder="${data[key].placeholder || ''}"
			help="${data[key].help || ''}"
			data-error="${data[key].error || ''}"
			${data[key].checked || ''}
			${data[key].required || ''}></wc-radio>`);
		break;

		case "check":
		$(`#form-${key}`).html(`
			<wc-check
			id="${data[key].id || data[key].name}"
			name="${data[key].name}"
			data-key="${data[key].name}"
			label="${data[key].label || ''}"
			columns="${data[key].columns || '12,12'}"
			placeholder="${data[key].placeholder || ''}"
			help="${data[key].help || ''}"
			data-error="${data[key].error || ''}"
			${data[key].checked || ''}
			${data[key].required || ''}></wc-check>`);
		break;

		default:
		break;
	    }
	}
	
	wc.groupEnd();
    };
}

window.customElements.define('wc-form', Form);

// SO I CAN CALL THE STATIC METHOD GLOBALLY
window.Form = Form;