<commit_before>//      RiotEmbed tool.js 1.0.5
//      https://kring.co.uk
//      (c) 2016 Simon Jackson, K Ring Technologies Ltd
//      MIT, like as he said. And underscored :D

//===============================================
// Might as well start with __ libs for use
// This does imply $$ is very sexy :D
//===============================================

function riotEmbed(ob) {

    if(ob) {
        //maybe some semantic?
        //the following should be same as trimmed code text?
        alert('Object checksum: ' + makeHash(ob.toString()));
        return riotEmbed;
    }
    riotEmbed.VERSION = '1.0.5g';
    riotEmbed._saveState = __;
    riotEmbed.url = 'https://www.kring.co.uk/dbase.php';//CHANGE IF NEEDED

//====================================
// PON handling
//====================================

function appPON(json, hash, callback) {
    forkPON(json, eval, function(script) {
        if(hashCode(script.innerHTML) == hash) {
            run(script, callback);
        }
    });
}

function hashCode(input) { //CH-32
    var gen = tally(input);
    gen.zz = input.length;
    var acc = 0;
    gen = _.reduce(gen, function(memo, val) {
        memo += String.fromCharCode((val << (acc % 17)) % 40763 + acc % 9473);
        acc += val % 98 + input.charCodeAt(acc * 65341 % input.length);
    }, '');
    gen = JSON.stringify(pack(gen));
    gen = _.reduce(gen.split(''), function(memo, val) {
        val = val.charCodeAt();
        memo += String.fromCharCode((val << (acc % 18)) % 45563 + acc % 6923);
        acc += val % 37 + input.charCodeAt(acc * 63371 % input.length);;
    }, '');
    gen = btoa(encodeUTF(gen));
    var genMax = gen.length - 32;
    var genStart = input.length % genMax;
    return gen.substring(genStart, genStart + 32);
}

function makeHash(input) {
    return hashCode('eval(' + stringifyPreJS(input) + ');');
}

function run(script, callback) {
    document.body.appendChild(script);//RUN!!
    script.onload = function() {
        script.parent.removeChild(script);//GC!!
        callback && callback(_.now());
    }
}

//a little Java hashCode lib
function fastHash(e){for(var r=0,i=0;i<e.length;i++)r=(r<<5)-r+e.charCodeAt(i),r&=r;return r};

function loadPON(json, callback) {//gets packed object at url
    savePON(json, callback, true);
}

function forkPON(json, exec, callback) {
    var script = document.createElement('script');
    script.type = 'text/javascript';
    loadPON(json, function(result) {
        script.innerHTML = exec + '(' + stringifyPreJS(result) + ');';
        callback && callback(script);
    });
}

function stringifyPreJS(s) {
    return s.
        replace(/\u2028/g, '\\u2028').
        replace(/\u2029/g, '\\u2029');
}

function savePON(json, callback, load) {
    json.tx = _.now();
    var http = new XMLHttpRequest();
    var id = json.id;//special
    var rest = load ? 'GET' : 'PUT';
    json = _.omit(json, 'id');
    http.open(rest, url + '?' + fastHash(JSON.stringify(id)), true);
    //fastHash for page caches
    //Send the proper header information along with the request
    http.setRequestHeader("Content-type", "application/json");
    http.onreadystatechange = function() {//Call a function when the state changes.
        if(http.readyState == 4 && http.status == 200) {
            var tr = unpack(JSON.parse(http.responseText));
            tr.id.__ = id;
            tr.rx = _.now();
            callback && callback(tr);
        }
    }
    var pj = pack(json);
    pj.id = id;
    http.send(JSON.stringify(pj));
}

// LZW-compress a string
//==============================================================================
// The bounce parameter if true adds extra entries for faster dictionary growth.
// Usually LZW dictionary grows sub linear on input chars, and it is of note
// that after a BWT, the phrase contains a good MTF estimate and so maybe fine
// to append each of its chars to many dictionary entries. In this way the
// growth of entries becomes "almost" linear. The dictionary memory foot print
// becomes quadratic. Short to medium inputs become even smaller. Long input
// lengths may become slightly larger on not using dictionary entries integrated
// over input length, but will most likely be slightly smaller.

// DO NOT USE bounce (=false) IF NO BWT BEFORE.
// Under these conditions many unused dictionary entries will be wasted on long
// highly redundant inputs. It is a feature for pre BWT packed PONs.
//===============================================================================
function encodeLZW(data, bounce) {
    var dict = {};
    data = encodeSUTF(data);
    var out = [];
    var currChar;
    var phrase = data[0];
    var codeL = 0;
    var code = 256;
    for (var i=1; i<data.length; i++) {
        currChar=data[i];
        if (dict['_' + phrase + currChar] != null) {
            phrase += currChar;
        }
        else {
            out.push(codeL = phrase.length > 1 ? dict['_'+phrase] : phrase.charCodeAt(0));
            if(code < 65536) {//limit
                dict['_' + phrase + currChar] = code;
                code++;
                if(bounce && codeL != code - 2) {//code -- and one before would be last symbol out
                    _.each(phrase.split(''), function (chr) {
                        if(code < 65536) {
                        	while(dict['_' + phrase + chr]) phrase += chr;
                            	dict['_' + phrase + chr] = code;
                            	code++;
                        }
                    });
                }
            }
            phrase=currChar;
        }
    }
    out.push(phrase.length > 1 ? dict['_'+phrase] : phrase.charCodeAt(0));
    for (var i=0; i<out.length; i++) {
        out[i] = String.fromCharCode(out[i]);
    }
    return out.join('');
}

function encodeSUTF(s) {
	s = mangleUTF(encodeUTF(s).split(''));
    var out = [];
    var last = 0;
    var flag = false;
    var first = true;
    _.each(s, function(val) {
        k = val.charCodeAt();
	    if(k > 127) {
    		if(k & 64 == 0) {
    		    if(first && flag) {
    		        first = false;
    		        if(k == last) {
    		            return;////1st extension byte
    		        } else {
    		            last = k;
    		            flag = false;;//1st extension
    		        }
    		    } else {
    		        if(flag) k += 64;
    		        first = true;//extension byte
    		        flag = false;
    		    }
    		} else {
    			flag = (k & 32 != 0);//hi page byte (flag two extensions)
    		}
        } else {
            //ascii byte
	    }
	    out.push(String.fromCharCode(k));
    });
    return out;
}

function encodePON(s) {
    return encodeLZW(s, true);
}

// Decompress an LZW-encoded string
function decodeLZW(s, bounce) {
    var dict = {};
    var dictI = {};
    var data = (s + '').split('');
    var currChar = data[0];
    var oldPhrase = currChar;
    var out = [currChar];
    var code = 256;
    var phrase;
    for (var i=1; i<data.length; i++) {
        var currCode = data[i].charCodeAt(0);
        if (currCode < 256) {
            phrase = data[i];
        }
        else {
           phrase = dict['_'+currCode] ? dict['_'+currCode] : (oldPhrase + currChar);
        }
        out.push(phrase);
        currChar = phrase.charAt(0);
        if(code < 65536) {
            dict['_'+code] = oldPhrase + currChar;
            dictI['_' + oldPhrase + currChar] = code;
            code++;
            if(bounce && !dict['_'+currCode]) {//the special lag
                _.each(oldPhrase.split(''), function (chr) {
                    if(code < 65536) {
                    	while(dictI['_' + oldPhrase + chr]) oldPhrase += chr;
                        dict['_' + code] = oldPhrase + chr;
                        dictI['_' + oldPhrase + chr] = code;
                        code++;
                    }
                });
            }
        }
        oldPhrase = phrase;
    }
    out = decodeSUTF(out);
    return out.join('');
}

function decodeSUTF(s) {
    var out = [];
    var last = 0;
    var flag = false;
    var first = true;
    _.each(s, function(val) {
        k = val.charCodeAt();
	    if(k > 127) {
	        if(first) {
	            first = false;
	            flag = (k & 32 != 0);
	        } else {
	            if(k & 64 != 0 && flag) {
	                out.push(String.fromCharCode(last));
	                k -= 64;
	                first = true;
	            } else {
	                if(flag) {
	                    last = k;
	                    flag = false;
	                } else {
	                    first = true;
	                }
	            }
	        }
        } else {
            //ascii byte
	    }
	    out.push(String.fromCharCode(k));
    });
    out = decodeUTF(mangleUTF(out).join(''));
    return out;
}

function decodePON(s) {
    return decodeLZW(s, true);
}

//UTF mangling
function encodeUTF(s) {
    return unescape(encodeURIComponent(s));
}

function decodeUTF(s) {
    return decodeURIComponent(escape(s));
}

function toBuffer(str) {
	arr = encodeSUTF(str);
	var buf = new ArrayBuffer(arr.length);
	var bufView = new Uint8Array(buf);
	for (var i = 0, arrLen = arr.length; i < arrLen; i++) {
		bufView[i] = arr[i];
	}
	return buf;
}

function fromBuffer(arr) {
	var buf = new Array(arr.length);
	for (var i = 0, arrLen = arr.length; i < arrLen; i++) {
		buf[i] = arr[i];
	}
	return decodeSUTF(arr);
}

function mangleUTF(s) {
	var temp = 0;
	_.each(s, function(v, k) {
		if(v & 128 == 0 || v & 32 == 0 || v & 64 == 0) return;//aux or 2 byte or ascii
		//must be 1st of 3 byte
		temp = v & 15;//lower nibble
		v &= 240;//255 - 15
		v |= (s[k + 1] & 63) >> 2;
		s[k + 1] &= 195;//3 + 64 + 128
		s[k + 1] |= temp << 2;
	});
	return s;//just in case
}

//A BWT
function encodeBWT(data) {
    var size = data.length;
    var buff = data + data;
    var idx = _.range(size).sort(function(x, y){
        for (var i = 0; i < size; i++) {
            var r = buff[x + i].charCodeAt() - buff[y + i].charCodeAt();
            if (r !== 0) return r;
        }
        return 0;
    });

    var top;
    var work = _.reduce(_.range(size), function(memo, k){
        var p = idx[k];
        if (p === 0) top = k;
        memo.push(buff[p + size - 1]);
        return memo;
    }, []).join('');

    return { top: top, data: work };
}

function decodeBWT(top, data) { //JSON

    var size = data.length;
    var idx = _.range(size).sort(function(x, y){
        var c = data[x].charCodeAt() - data[y].charCodeAt();
        if (c === 0) return x - y;
        return c;
    });

    var p = idx[top];
    return _.reduce(_.range(size), function(memo){
        memo.push(data[p]);
        p = idx[p];
        return memo;
    }, []).join('');
}

function tally(data) {
    return _.reduce(data.split(), function(memo, charAt) {
        memo[charAt]++;//increase
    }, {});
}

function splice(data) {
    var acc = 0;
    var counts = tally(data);
    return _.reduce(counts, function(memo, count, key) {
        memo.push(key + data.substring(acc, count + acc));
        /* adds a seek char:
        This assists in DB seek performance as it's the ordering char for the lzw block */
        acc += count;
    }, []);
}

//a packer and unpacker with good efficiency
function pack(data) {
    var bwt = encodeBWT(JSON.stringify(data));
    var mix = splice(bwt.data);

    mix = _.map(mix, encodePON);
    data = _.extendOwn({}, data, {
        top: bwt.top,
        /* tally: encode_tally(tally), */
        mix: mix
    });
    return data;
}

function unpack(got) {
    var top = got.top || 0;
    /* var tally = got.tally; */
    var mix = got.mix || [];

    mix = _.map(mix, decodePON);
    mix.sort(function(a, b) {
        return a.charCodeAt(0) - b.charCodeAt(0);
    });
    mix = _.reduce(mix, function(memo, lzw) {
        /* var key = lzw.charAt(0);//get seek char */
        memo += lzw.substring(1, lzw.length);//concat
    }, '');
    return _.extendOwn(JSON.parse(decodeBWT(top, mix)), _.omit(got, 'top', 'mix'));
}

function noConflict() {
    __ = _saveState;
    return riotEmbed;//ok give it a new name
}

//============================================
// And end the __ library
//============================================
__ = riotEmbed;
}//close object

riotEmbed();//activate
<commit_msg>should save some<commit_after>//      RiotEmbed tool.js 1.0.5
//      https://kring.co.uk
//      (c) 2016 Simon Jackson, K Ring Technologies Ltd
//      MIT, like as he said. And underscored :D

//===============================================
// Might as well start with __ libs for use
// This does imply $$ is very sexy :D
//===============================================

function riotEmbed(ob) {

    if(ob) {
        //maybe some semantic?
        //the following should be same as trimmed code text?
        alert('Object checksum: ' + makeHash(ob.toString()));
        return riotEmbed;
    }
    riotEmbed.VERSION = '1.0.5g';
    riotEmbed._saveState = __;
    riotEmbed.url = 'https://www.kring.co.uk/dbase.php';//CHANGE IF NEEDED

//====================================
// PON handling
//====================================

function appPON(json, hash, callback) {
    forkPON(json, eval, function(script) {
        if(hashCode(script.innerHTML) == hash) {
            run(script, callback);
        }
    });
}

function hashCode(input) { //CH-32
    var gen = tally(input);
    gen.zz = input.length;
    var acc = 0;
    gen = _.reduce(gen, function(memo, val) {
        memo += String.fromCharCode((val << (acc % 17)) % 40763 + acc % 9473);
        acc += val % 98 + input.charCodeAt(acc * 65341 % input.length);
    }, '');
    gen = JSON.stringify(pack(gen));
    gen = _.reduce(gen.split(''), function(memo, val) {
        val = val.charCodeAt();
        memo += String.fromCharCode((val << (acc % 18)) % 45563 + acc % 6923);
        acc += val % 37 + input.charCodeAt(acc * 63371 % input.length);;
    }, '');
    gen = btoa(encodeUTF(gen));
    var genMax = gen.length - 32;
    var genStart = input.length % genMax;
    return gen.substring(genStart, genStart + 32);
}

function makeHash(input) {
    return hashCode('eval(' + stringifyPreJS(input) + ');');
}

function run(script, callback) {
    document.body.appendChild(script);//RUN!!
    script.onload = function() {
        script.parent.removeChild(script);//GC!!
        callback && callback(_.now());
    }
}

//a little Java hashCode lib
function fastHash(e){for(var r=0,i=0;i<e.length;i++)r=(r<<5)-r+e.charCodeAt(i),r&=r;return r};

function loadPON(json, callback) {//gets packed object at url
    savePON(json, callback, true);
}

function forkPON(json, exec, callback) {
    var script = document.createElement('script');
    script.type = 'text/javascript';
    loadPON(json, function(result) {
        script.innerHTML = exec + '(' + stringifyPreJS(result) + ');';
        callback && callback(script);
    });
}

function stringifyPreJS(s) {
    return s.
        replace(/\u2028/g, '\\u2028').
        replace(/\u2029/g, '\\u2029');
}

function savePON(json, callback, load) {
    json.tx = _.now();
    var http = new XMLHttpRequest();
    var id = json.id;//special
    var rest = load ? 'GET' : 'PUT';
    json = _.omit(json, 'id');
    http.open(rest, url + '?' + fastHash(JSON.stringify(id)), true);
    http.responseType = "arraybuffer";
    //fastHash for page caches
    //Send the proper header information along with the request
    http.setRequestHeader("Content-type", "application/json");
    http.onreadystatechange = function() {//Call a function when the state changes.
        if(http.readyState == 4 && http.status == 200) {
            var tr = unpack(JSON.parse(fromBuffer(http.response)));
            tr.id.__ = id;
            tr.rx = _.now();
            callback && callback(tr);
        }
    }
    var pj = pack(json);
    pj.id = id;
    http.send(toBuffer(JSON.stringify(pj)));
}

// LZW-compress a string
//==============================================================================
// The bounce parameter if true adds extra entries for faster dictionary growth.
// Usually LZW dictionary grows sub linear on input chars, and it is of note
// that after a BWT, the phrase contains a good MTF estimate and so maybe fine
// to append each of its chars to many dictionary entries. In this way the
// growth of entries becomes "almost" linear. The dictionary memory foot print
// becomes quadratic. Short to medium inputs become even smaller. Long input
// lengths may become slightly larger on not using dictionary entries integrated
// over input length, but will most likely be slightly smaller.

// DO NOT USE bounce (=false) IF NO BWT BEFORE.
// Under these conditions many unused dictionary entries will be wasted on long
// highly redundant inputs. It is a feature for pre BWT packed PONs.
//===============================================================================
function encodeLZW(data, bounce) {
    var dict = {};
    data = encodeSUTF(data);
    var out = [];
    var currChar;
    var phrase = data[0];
    var codeL = 0;
    var code = 256;
    for (var i=1; i<data.length; i++) {
        currChar=data[i];
        if (dict['_' + phrase + currChar] != null) {
            phrase += currChar;
        }
        else {
            out.push(codeL = phrase.length > 1 ? dict['_'+phrase] : phrase.charCodeAt(0));
            if(code < 65536) {//limit
                dict['_' + phrase + currChar] = code;
                code++;
                if(bounce && codeL != code - 2) {//code -- and one before would be last symbol out
                    _.each(phrase.split(''), function (chr) {
                        if(code < 65536) {
                        	while(dict['_' + phrase + chr]) phrase += chr;
                            	dict['_' + phrase + chr] = code;
                            	code++;
                        }
                    });
                }
            }
            phrase=currChar;
        }
    }
    out.push(phrase.length > 1 ? dict['_'+phrase] : phrase.charCodeAt(0));
    for (var i=0; i<out.length; i++) {
        out[i] = String.fromCharCode(out[i]);
    }
    return out.join('');
}

function encodeSUTF(s) {
	s = mangleUTF(encodeUTF(s).split(''));
    var out = [];
    var last = 0;
    var flag = false;
    var first = true;
    _.each(s, function(val) {
        k = val.charCodeAt();
	    if(k > 127) {
    		if(k & 64 == 0) {
    		    if(first && flag) {
    		        first = false;
    		        if(k == last) {
    		            return;////1st extension byte
    		        } else {
    		            last = k;
    		            flag = false;;//1st extension
    		        }
    		    } else {
    		        if(flag) k += 64;
    		        first = true;//extension byte
    		        flag = false;
    		    }
    		} else {
    			flag = (k & 32 != 0);//hi page byte (flag two extensions)
    		}
        } else {
            //ascii byte
	    }
	    out.push(String.fromCharCode(k));
    });
    return out;
}

function encodePON(s) {
    return encodeLZW(s, true);
}

// Decompress an LZW-encoded string
function decodeLZW(s, bounce) {
    var dict = {};
    var dictI = {};
    var data = (s + '').split('');
    var currChar = data[0];
    var oldPhrase = currChar;
    var out = [currChar];
    var code = 256;
    var phrase;
    for (var i=1; i<data.length; i++) {
        var currCode = data[i].charCodeAt(0);
        if (currCode < 256) {
            phrase = data[i];
        }
        else {
           phrase = dict['_'+currCode] ? dict['_'+currCode] : (oldPhrase + currChar);
        }
        out.push(phrase);
        currChar = phrase.charAt(0);
        if(code < 65536) {
            dict['_'+code] = oldPhrase + currChar;
            dictI['_' + oldPhrase + currChar] = code;
            code++;
            if(bounce && !dict['_'+currCode]) {//the special lag
                _.each(oldPhrase.split(''), function (chr) {
                    if(code < 65536) {
                    	while(dictI['_' + oldPhrase + chr]) oldPhrase += chr;
                        dict['_' + code] = oldPhrase + chr;
                        dictI['_' + oldPhrase + chr] = code;
                        code++;
                    }
                });
            }
        }
        oldPhrase = phrase;
    }
    out = decodeSUTF(out);
    return out.join('');
}

function decodeSUTF(s) {
    var out = [];
    var last = 0;
    var flag = false;
    var first = true;
    _.each(s, function(val) {
        k = val.charCodeAt();
	    if(k > 127) {
	        if(first) {
	            first = false;
	            flag = (k & 32 != 0);
	        } else {
	            if(k & 64 != 0 && flag) {
	                out.push(String.fromCharCode(last));
	                k -= 64;
	                first = true;
	            } else {
	                if(flag) {
	                    last = k;
	                    flag = false;
	                } else {
	                    first = true;
	                }
	            }
	        }
        } else {
            //ascii byte
	    }
	    out.push(String.fromCharCode(k));
    });
    out = decodeUTF(mangleUTF(out).join(''));
    return out;
}

function decodePON(s) {
    return decodeLZW(s, true);
}

//UTF mangling
function encodeUTF(s) {
    return unescape(encodeURIComponent(s));
}

function decodeUTF(s) {
    return decodeURIComponent(escape(s));
}

function toBuffer(str) {
	arr = encodeSUTF(str);
	var buf = new ArrayBuffer(arr.length);
	var bufView = new Uint8Array(buf);
	for (var i = 0, arrLen = arr.length; i < arrLen; i++) {
		bufView[i] = arr[i];
	}
	return buf;
}

function fromBuffer(arr) {
	arr = new UInt8Array(arr);
	var buf = new Array(arr.length);
	for (var i = 0, arrLen = arr.length; i < arrLen; i++) {
		buf[i] = arr[i];
	}
	return decodeSUTF(arr);
}

function mangleUTF(s) {
	var temp = 0;
	_.each(s, function(v, k) {
		if(v & 128 == 0 || v & 32 == 0 || v & 64 == 0) return;//aux or 2 byte or ascii
		//must be 1st of 3 byte
		temp = v & 15;//lower nibble
		v &= 240;//255 - 15
		v |= (s[k + 1] & 63) >> 2;
		s[k + 1] &= 195;//3 + 64 + 128
		s[k + 1] |= temp << 2;
	});
	return s;//just in case
}

//A BWT
function encodeBWT(data) {
    var size = data.length;
    var buff = data + data;
    var idx = _.range(size).sort(function(x, y){
        for (var i = 0; i < size; i++) {
            var r = buff[x + i].charCodeAt() - buff[y + i].charCodeAt();
            if (r !== 0) return r;
        }
        return 0;
    });

    var top;
    var work = _.reduce(_.range(size), function(memo, k){
        var p = idx[k];
        if (p === 0) top = k;
        memo.push(buff[p + size - 1]);
        return memo;
    }, []).join('');

    return { top: top, data: work };
}

function decodeBWT(top, data) { //JSON

    var size = data.length;
    var idx = _.range(size).sort(function(x, y){
        var c = data[x].charCodeAt() - data[y].charCodeAt();
        if (c === 0) return x - y;
        return c;
    });

    var p = idx[top];
    return _.reduce(_.range(size), function(memo){
        memo.push(data[p]);
        p = idx[p];
        return memo;
    }, []).join('');
}

function tally(data) {
    return _.reduce(data.split(), function(memo, charAt) {
        memo[charAt]++;//increase
    }, {});
}

function splice(data) {
    var acc = 0;
    var counts = tally(data);
    return _.reduce(counts, function(memo, count, key) {
        memo.push(key + data.substring(acc, count + acc));
        /* adds a seek char:
        This assists in DB seek performance as it's the ordering char for the lzw block */
        acc += count;
    }, []);
}

//a packer and unpacker with good efficiency
function pack(data) {
    var bwt = encodeBWT(JSON.stringify(data));
    var mix = splice(bwt.data);

    mix = _.map(mix, encodePON);
    data = _.extendOwn({}, data, {
        top: bwt.top,
        /* tally: encode_tally(tally), */
        mix: mix
    });
    return data;
}

function unpack(got) {
    var top = got.top || 0;
    /* var tally = got.tally; */
    var mix = got.mix || [];

    mix = _.map(mix, decodePON);
    mix.sort(function(a, b) {
        return a.charCodeAt(0) - b.charCodeAt(0);
    });
    mix = _.reduce(mix, function(memo, lzw) {
        /* var key = lzw.charAt(0);//get seek char */
        memo += lzw.substring(1, lzw.length);//concat
    }, '');
    return _.extendOwn(JSON.parse(decodeBWT(top, mix)), _.omit(got, 'top', 'mix'));
}

function noConflict() {
    __ = _saveState;
    return riotEmbed;//ok give it a new name
}

//============================================
// And end the __ library
//============================================
__ = riotEmbed;
}//close object

riotEmbed();//activate
<|endoftext|>


<commit_before>var gulp = require('gulp');
var less = require('gulp-less');
var postcss = require('gulp-postcss');
var autoprefixer = require('autoprefixer');
var shorthand = require('gulp-shorthand');
var csso = require('gulp-csso');
var babel = require('gulp-babel');
var babelify = require('babelify');
var browserify = require('browserify');
var vinylbuffer = require('vinyl-buffer');
var vinylsource = require('vinyl-source-stream');
var uglify = require('gulp-uglify');
var sourcemaps = require('gulp-sourcemaps');
var plumber = require('gulp-plumber');
var del = require('del');
var sass = require('gulp-sass');
var gutil = require('gulp-util');
var jasmine = require('gulp-jasmine');
var runSequence = require('run-sequence');
var notify = require('gulp-notify');
var through = require('gulp-through');
var watchify = require('watchify');
var bpolyfill = require('babel-polyfill');

/* Config */
var SRC = './src';
var DIST = './dist';

/** HTML Tasks */

/**
 * Copies index.html from source to dist
 */
gulp.task('html', function() {
  return gulp.src(SRC + '/index.html')
    .pipe(gulp.dest(DIST));
});

/** Styles */

/**
 * Compiles LESS to CSS ready for production.
 * Applies the following transformations (in order):
 * - Reads from main.less file
 * - Generates sourcemaps
 * - Compiles LESS to CSS
 * - Autoprefixes CSS with vendor prefixes for last 2 browser versions
 * - Shorthands CSS properties
 * - Minifies CSS (removes whitespace and comments)
 * - Sends the transformed file to dist/styles
 */

gulp.task('less:production', function () {
  return gulp.src(SRC + '/less/main.less')
    .pipe(sourcemaps.init())
    .pipe(less())
    .pipe(postcss([ autoprefixer({ browsers: ['last 2 version'] }) ]))
    .pipe(shorthand())
    .pipe(csso())
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest(DIST + '/styles'));
});

/**
 * Compiles LESS to CSS for development.
 * Applies the following transformations (in order):
 * - Reads main.less file
 * - Generates sourcemaps
 * - Prevents task crashing Gulp on Error
 * - Notifies OS and console on error
 * - Compiles LESS to CSS
 * - Sends the transformed file to dist/styles
*/

gulp.task('less', function () {
  return gulp.src(SRC + '/less/main.less')
    .pipe(sourcemaps.init())
    .pipe(plumber({ errorHandler: notify.onError('Error <%= error.message %>') }))
    .pipe(less())
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest(DIST + '/styles'));
});

/**
 * Compiles SASS/SCSS to CSS ready for production.
 * Applies the following transformations (in order):
 * - Reads from main.scss file
 * - Generates sourcemaps
 * - Compiles SASS/SCSS to CSS
 * - Autoprefixes CSS with vendor prefixes for last 2 browser versions
 * - Shorthands CSS properties
 * - Minifies CSS (removes whitespace and comments)
 * - Sends the transformed file to dist/styles
 */

gulp.task('sass:production', function() {
  return gulp.src(SRC + '/sass/main.scss')
    .pipe(sourcemaps.init())
    .pipe(sass())
    .pipe(postcss([ autoprefixer({ browsers: ['last 2 version'] }) ]))
    .pipe(shorthand())
    .pipe(csso())
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest(DIST + '/styles'));
});

/**
 * Compiles SASS/SCSS to CSS for development.
 * Applies the following transformations (in order):
 * - Reads from main.scss file
 * - Generates sourcemaps
 * - Prevents task crashing Gulp on Error
 * - Notifies OS and console on error
 * - Compiles SASS/SCSS to CSS
 * - Sends the transformed file to dist/styles
 */

gulp.task('sass', function() {
  return gulp.src(SRC + '/sass/main.scss')
    .pipe(sourcemaps.init())
    .pipe(plumber({ errorHandler: notify.onError('Error <%= error.message %>') }))
    .pipe(sass())
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest(DIST + '/styles'))
});

/** Scripts */

/**
 * Compiles ES6, JSX to supported JavaScript
 * Applies the following transformations (in order):
 * - Reads /scripts/main.js
 * - Modularizes JS code using CommonJS modules
 * - Compiles ES6, JSX
 * - Generates sourcemaps
 * - Minifies JavaScript
 * - Sends the transformed file to dist/scripts
*/
(function() {
  var props = {
    entries: [SRC + '/scripts/main.js'],
    debug: true,
    cache: {},
    packageCache: {},
    fullPaths: true
  };

  gulp.task('js:production', function() {
    var bundler = browserify(SRC + '/scripts/main.js', props);
    bundler.transform(babelify, { sourceMaps: true });
    var stream = bundler.bundle();

    return stream
      .pipe(vinylsource('bundle.js'))
      .pipe(vinylbuffer())
      .pipe(sourcemaps.init({ loadMaps: true }))
      .pipe(uglify())
      .pipe(sourcemaps.write('./'))
      .pipe(gulp.dest('dist/scripts'));
  });

  var bundler = watchify(browserify(props));
  bundler.transform(babelify, { sourceMaps: true });
  bundler.on('update', bundle);
  bundler.on('log', gutil.log);

  function bundle() {
    var stream = bundler.bundle();

    return stream
      .on('error', notify.onError('Error <%= error.message %>'))
      .pipe(plumber())
      .pipe(vinylsource('bundle.js'))
      .pipe(vinylbuffer())
      .pipe(sourcemaps.init({ loadMaps: true }))
      .pipe(sourcemaps.write('./'))
      .pipe(gulp.dest('dist/scripts'));
  }

  gulp.task('js', function() {
    return bundle();
  });
}());

/** Tests */
gulp.task('test', function() {
  gulp.src(SRC + '/tests/spec/test.js')
    .pipe(jasmine({ verbose: true }));
});

/** Misc */
/**
 * Cleans (deletes) contents of the dist folder
*/
gulp.task('clean', function() {
  return del(['dist/**', '!dist']);
});

/** Watching */

/**
 * Runs 'sass' task first as a dependency.
 * Watches SASS files and runs 'sass' task on change.
 * Watch every .scss file in /sass folder and run 'less' task on change
*/

gulp.task('watch:sass', ['sass'], function() {
  gulp.watch(SRC + '/sass/**/*.scss', ['sass']);
});

/**
 * Runs 'less' task first as a dependency.
 * Watches LESS files and runs 'less' task on change.
 * Watch every .less file in /less folder and run 'less' task on change
*/

gulp.task('watch:less', ['less'], function() {
  gulp.watch(SRC + '/less/**/*.less', ['less']);
});

/**
 * Runs 'html' task first as a dependency.
 * Watches HTML files and runs 'html' task on change.
 * Watch every .html file in source folder and run 'html' task on change
*/

gulp.task('watch:html', ['html'], function() {
  gulp.watch(SRC + '/**/*.html', ['html']);
});

/** Pipeline */
gulp.task('default', function (done) {
  // Check environment
  if (!!gutil.env.production) {
    runSequence('clean', ['js:production', 'less:production', 'html'], done);
  } else {
    runSequence('clean', ['js', 'watch:less', 'watch:html'], done);
  }
});<commit_msg>Del all<commit_after>var gulp = require('gulp');
var less = require('gulp-less');
var postcss = require('gulp-postcss');
var autoprefixer = require('autoprefixer');
var shorthand = require('gulp-shorthand');
var csso = require('gulp-csso');
var babel = require('gulp-babel');
var babelify = require('babelify');
var browserify = require('browserify');
var vinylbuffer = require('vinyl-buffer');
var vinylsource = require('vinyl-source-stream');
var uglify = require('gulp-uglify');
var sourcemaps = require('gulp-sourcemaps');
var plumber = require('gulp-plumber');
var del = require('del');
var sass = require('gulp-sass');
var gutil = require('gulp-util');
var jasmine = require('gulp-jasmine');
var runSequence = require('run-sequence');
var notify = require('gulp-notify');
var through = require('gulp-through');
var watchify = require('watchify');
var bpolyfill = require('babel-polyfill');

/* Config */
var SRC = './src';
var DIST = './dist';

/** HTML Tasks */

/**
 * Copies index.html from source to dist
 */
gulp.task('html', function() {
  return gulp.src(SRC + '/index.html')
    .pipe(gulp.dest(DIST));
});

/** Styles */

/**
 * Compiles LESS to CSS ready for production.
 * Applies the following transformations (in order):
 * - Reads from main.less file
 * - Generates sourcemaps
 * - Compiles LESS to CSS
 * - Autoprefixes CSS with vendor prefixes for last 2 browser versions
 * - Shorthands CSS properties
 * - Minifies CSS (removes whitespace and comments)
 * - Sends the transformed file to dist/styles
 */

gulp.task('less:production', function () {
  return gulp.src(SRC + '/less/main.less')
    .pipe(sourcemaps.init())
    .pipe(less())
    .pipe(postcss([ autoprefixer({ browsers: ['last 2 version'] }) ]))
    .pipe(shorthand())
    .pipe(csso())
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest(DIST + '/styles'));
});

/**
 * Compiles LESS to CSS for development.
 * Applies the following transformations (in order):
 * - Reads main.less file
 * - Generates sourcemaps
 * - Prevents task crashing Gulp on Error
 * - Notifies OS and console on error
 * - Compiles LESS to CSS
 * - Sends the transformed file to dist/styles
*/

gulp.task('less', function () {
  return gulp.src(SRC + '/less/main.less')
    .pipe(sourcemaps.init())
    .pipe(plumber({ errorHandler: notify.onError('Error <%= error.message %>') }))
    .pipe(less())
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest(DIST + '/styles'));
});

/**
 * Compiles SASS/SCSS to CSS ready for production.
 * Applies the following transformations (in order):
 * - Reads from main.scss file
 * - Generates sourcemaps
 * - Compiles SASS/SCSS to CSS
 * - Autoprefixes CSS with vendor prefixes for last 2 browser versions
 * - Shorthands CSS properties
 * - Minifies CSS (removes whitespace and comments)
 * - Sends the transformed file to dist/styles
 */

gulp.task('sass:production', function() {
  return gulp.src(SRC + '/sass/main.scss')
    .pipe(sourcemaps.init())
    .pipe(sass())
    .pipe(postcss([ autoprefixer({ browsers: ['last 2 version'] }) ]))
    .pipe(shorthand())
    .pipe(csso())
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest(DIST + '/styles'));
});

/**
 * Compiles SASS/SCSS to CSS for development.
 * Applies the following transformations (in order):
 * - Reads from main.scss file
 * - Generates sourcemaps
 * - Prevents task crashing Gulp on Error
 * - Notifies OS and console on error
 * - Compiles SASS/SCSS to CSS
 * - Sends the transformed file to dist/styles
 */

gulp.task('sass', function() {
  return gulp.src(SRC + '/sass/main.scss')
    .pipe(sourcemaps.init())
    .pipe(plumber({ errorHandler: notify.onError('Error <%= error.message %>') }))
    .pipe(sass())
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest(DIST + '/styles'))
});

/** Scripts */

/**
 * Compiles ES6, JSX to supported JavaScript
 * Applies the following transformations (in order):
 * - Reads /scripts/main.js
 * - Modularizes JS code using CommonJS modules
 * - Compiles ES6, JSX
 * - Generates sourcemaps
 * - Minifies JavaScript
 * - Sends the transformed file to dist/scripts
*/
(function() {
  var props = {
    entries: [SRC + '/scripts/main.js'],
    debug: true,
    cache: {},
    packageCache: {},
    fullPaths: true
  };

  gulp.task('js:production', function() {
    var bundler = browserify(SRC + '/scripts/main.js', props);
    bundler.transform(babelify, { sourceMaps: true });
    var stream = bundler.bundle();

    return stream
      .pipe(vinylsource('bundle.js'))
      .pipe(vinylbuffer())
      .pipe(sourcemaps.init({ loadMaps: true }))
      .pipe(uglify())
      .pipe(sourcemaps.write('./'))
      .pipe(gulp.dest('dist/scripts'));
  });

  var bundler = watchify(browserify(props));
  bundler.transform(babelify, { sourceMaps: true });
  bundler.on('update', bundle);
  bundler.on('log', gutil.log);

  function bundle() {
    var stream = bundler.bundle();

    return stream
      .on('error', notify.onError('Error <%= error.message %>'))
      .pipe(plumber())
      .pipe(vinylsource('bundle.js'))
      .pipe(vinylbuffer())
      .pipe(sourcemaps.init({ loadMaps: true }))
      .pipe(sourcemaps.write('./'))
      .pipe(gulp.dest('dist/scripts'));
  }

  gulp.task('js', function() {
    return bundle();
  });
}());

/** Tests */
gulp.task('test', function() {
  gulp.src(SRC + '/tests/spec/test.js')
    .pipe(jasmine({ verbose: true }));
});

/** Misc */
/**
 * Cleans (deletes) contents of the dist folder
*/
gulp.task('clean', function() {
  return del(['dist/**/*', '!dist']);
});

/** Watching */

/**
 * Runs 'sass' task first as a dependency.
 * Watches SASS files and runs 'sass' task on change.
 * Watch every .scss file in /sass folder and run 'less' task on change
*/

gulp.task('watch:sass', ['sass'], function() {
  gulp.watch(SRC + '/sass/**/*.scss', ['sass']);
});

/**
 * Runs 'less' task first as a dependency.
 * Watches LESS files and runs 'less' task on change.
 * Watch every .less file in /less folder and run 'less' task on change
*/

gulp.task('watch:less', ['less'], function() {
  gulp.watch(SRC + '/less/**/*.less', ['less']);
});

/**
 * Runs 'html' task first as a dependency.
 * Watches HTML files and runs 'html' task on change.
 * Watch every .html file in source folder and run 'html' task on change
*/

gulp.task('watch:html', ['html'], function() {
  gulp.watch(SRC + '/**/*.html', ['html']);
});

/** Pipeline */
gulp.task('default', function (done) {
  // Check environment
  if (!!gutil.env.production) {
    runSequence('clean', ['js:production', 'less:production', 'html'], done);
  } else {
    runSequence('clean', ['js', 'watch:less', 'watch:html'], done);
  }
});<|endoftext|>


<commit_before>/* eslint max-len: 0 */
import gulp from 'gulp';
import babel from 'gulp-babel';
import sass from 'gulp-sass';
import server from 'gulp-server-livereload';
import { exec } from 'child_process';
import dotenv from 'dotenv';
import sassVariables from 'gulp-sass-variables';
import { moveSync, removeSync } from 'fs-extra';
import kebabCase from 'kebab-case';
import hexRgb from 'hex-rgb';
import path from 'path';

import config from './package.json';

import * as rawStyleConfig from './src/theme/default/legacy.js';

dotenv.config();

const styleConfig = Object.keys(rawStyleConfig).map((key) => {
  const isHex = /^#[0-9A-F]{6}$/i.test(rawStyleConfig[key]);
  return ({ [`$raw_${kebabCase(key)}`]: isHex ? hexRgb(rawStyleConfig[key], { format: 'array' }).splice(0, 3).join(',') : rawStyleConfig[key] });
});

const paths = {
  src: 'src',
  dest: 'build',
  tmp: '.tmp',
  dictionaries: 'dictionaries',
  package: `out/${config.version}`,
  html: {
    src: 'src/**/*.html',
    dest: 'build/',
    watch: 'src/**/*.html',
  },
  styles: {
    src: 'src/styles/main.scss',
    dest: 'build/styles',
    watch: 'src/styles/**/*.scss',
  },
  scripts: {
    src: 'src/**/*.js',
    dest: 'build/',
    watch: 'src/**/*.js',
  },
};

function _shell(cmd, cb) {
  console.log('executing', cmd);
  exec(cmd, {
    cwd: paths.dest,
  }, (error, stdout, stderr) => {
    if (error) {
      console.error(`exec error: ${error}`);
      return;
    }
    console.log(`stdout: ${stdout}`);
    console.log(`stderr: ${stderr}`);

    cb();
  });
}

const clean = (done) => {
  removeSync(paths.tmp);
  removeSync(paths.dest);

  done();
};
export { clean };

export function mvSrc() {
  return gulp.src(
    [
      `${paths.src}/*`,
      `${paths.src}/*/**`,
      `!${paths.scripts.watch}`,
      `!${paths.src}/styles/**`,
    ], { since: gulp.lastRun(mvSrc) },
  )
    .pipe(gulp.dest(paths.dest));
}

export function mvPackageJson() {
  return gulp.src(
    [
      './package.json',
    ],
  )
    .pipe(gulp.dest(paths.dest));
}

export function html() {
  return gulp.src(paths.html.src, { since: gulp.lastRun(html) })
    .pipe(gulp.dest(paths.html.dest));
}

export function styles() {
  return gulp.src(paths.styles.src)
    .pipe(sassVariables(Object.assign({
      $env: process.env.NODE_ENV === 'development' ? 'development' : 'production',
    }, ...styleConfig)))
    .pipe(sass({
      includePaths: [
        './node_modules',
        '../node_modules',
      ],
    }).on('error', sass.logError))
    .pipe(gulp.dest(paths.styles.dest));
}

export function scripts() {
  return gulp.src(paths.scripts.src, { since: gulp.lastRun(scripts) })
    .pipe(babel({
      comments: false,
    }))
    .pipe(gulp.dest(paths.scripts.dest));
}

export function watch() {
  gulp.watch(paths.scripts.watch, scripts);
  gulp.watch(paths.styles.watch, styles);

  gulp.watch([
    paths.src,
    `${paths.scripts.src}`,
    `${paths.styles.src}`,
  ], mvSrc);
}

export function webserver() {
  gulp.src([
    paths.dest,
  ])
    .pipe(server({
      livereload: true,
    }));
}

export function dictionaries(done) {
  const { SPELLCHECKER_LOCALES } = require('./build/i18n/languages');

  let packages = '';
  Object.keys(SPELLCHECKER_LOCALES).forEach((key) => { packages = `${packages} hunspell-dict-${key}`; });

  _shell(`npm install --prefix ${path.join(__dirname, 'temp')} ${packages}`, () => {
    moveSync(
      path.join(__dirname, 'temp', 'node_modules'),
      path.join(__dirname, 'build', paths.dictionaries),
    );

    removeSync(path.join(__dirname, 'temp'));

    done();
  });
}

export function sign(done) {
  _shell(`codesign --verbose=4 --deep --strict --force --sign "${process.env.SIGNING_IDENTITY}" "${__dirname}/node_modules/electron/dist/Electron.app"`, done);
}

const build = gulp.series(
  clean,
  gulp.parallel(mvSrc, mvPackageJson),
  gulp.parallel(html, scripts, styles),
  dictionaries,
);
export { build };

const dev = gulp.series(build, gulp.parallel(webserver, watch));
export { dev };
<commit_msg>Fix missing packages in build<commit_after>/* eslint max-len: 0 */
import gulp from 'gulp';
import babel from 'gulp-babel';
import sass from 'gulp-sass';
import server from 'gulp-server-livereload';
import { exec } from 'child_process';
import dotenv from 'dotenv';
import sassVariables from 'gulp-sass-variables';
import { moveSync, removeSync } from 'fs-extra';
import kebabCase from 'kebab-case';
import hexRgb from 'hex-rgb';
import path from 'path';

import config from './package.json';

import * as rawStyleConfig from './src/theme/default/legacy.js';

dotenv.config();

const styleConfig = Object.keys(rawStyleConfig).map((key) => {
  const isHex = /^#[0-9A-F]{6}$/i.test(rawStyleConfig[key]);
  return ({ [`$raw_${kebabCase(key)}`]: isHex ? hexRgb(rawStyleConfig[key], { format: 'array' }).splice(0, 3).join(',') : rawStyleConfig[key] });
});

const paths = {
  src: 'src',
  dest: 'build',
  tmp: '.tmp',
  dictionaries: 'dictionaries',
  package: `out/${config.version}`,
  html: {
    src: 'src/**/*.html',
    dest: 'build/',
    watch: 'src/**/*.html',
  },
  styles: {
    src: 'src/styles/main.scss',
    dest: 'build/styles',
    watch: 'src/styles/**/*.scss',
  },
  scripts: {
    src: 'src/**/*.js',
    dest: 'build/',
    watch: 'src/**/*.js',
  },
};

function _shell(cmd, cb) {
  console.log('executing', cmd);
  exec(cmd, {
    cwd: paths.dest,
  }, (error, stdout, stderr) => {
    if (error) {
      console.error(`exec error: ${error}`);
      return;
    }
    console.log(`stdout: ${stdout}`);
    console.log(`stderr: ${stderr}`);

    cb();
  });
}

const clean = (done) => {
  removeSync(paths.tmp);
  removeSync(paths.dest);

  done();
};
export { clean };

export function mvSrc() {
  return gulp.src(
    [
      `${paths.src}/*`,
      `${paths.src}/*/**`,
      `!${paths.scripts.watch}`,
      `!${paths.src}/styles/**`,
    ], { since: gulp.lastRun(mvSrc) },
  )
    .pipe(gulp.dest(paths.dest));
}

export function mvPackageJson() {
  return gulp.src(
    [
      './package.json',
    ],
  )
    .pipe(gulp.dest(paths.dest));
}

export function mvPackages() {
  return gulp.src(
    [
      'packages/**',
    ],
  )
    .pipe(gulp.dest(`${paths.dest}/packages`));
}

export function html() {
  return gulp.src(paths.html.src, { since: gulp.lastRun(html) })
    .pipe(gulp.dest(paths.html.dest));
}

export function styles() {
  return gulp.src(paths.styles.src)
    .pipe(sassVariables(Object.assign({
      $env: process.env.NODE_ENV === 'development' ? 'development' : 'production',
    }, ...styleConfig)))
    .pipe(sass({
      includePaths: [
        './node_modules',
        '../node_modules',
      ],
    }).on('error', sass.logError))
    .pipe(gulp.dest(paths.styles.dest));
}

export function scripts() {
  return gulp.src(paths.scripts.src, { since: gulp.lastRun(scripts) })
    .pipe(babel({
      comments: false,
    }))
    .pipe(gulp.dest(paths.scripts.dest));
}

export function watch() {
  gulp.watch(paths.scripts.watch, scripts);
  gulp.watch(paths.styles.watch, styles);

  gulp.watch([
    paths.src,
    `${paths.scripts.src}`,
    `${paths.styles.src}`,
  ], mvSrc);
}

export function webserver() {
  gulp.src([
    paths.dest,
  ])
    .pipe(server({
      livereload: true,
    }));
}

export function dictionaries(done) {
  const { SPELLCHECKER_LOCALES } = require('./build/i18n/languages');

  let packages = '';
  Object.keys(SPELLCHECKER_LOCALES).forEach((key) => { packages = `${packages} hunspell-dict-${key}`; });

  _shell(`npm install --prefix ${path.join(__dirname, 'temp')} ${packages}`, () => {
    moveSync(
      path.join(__dirname, 'temp', 'node_modules'),
      path.join(__dirname, 'build', paths.dictionaries),
    );

    removeSync(path.join(__dirname, 'temp'));

    done();
  });
}

export function sign(done) {
  _shell(`codesign --verbose=4 --deep --strict --force --sign "${process.env.SIGNING_IDENTITY}" "${__dirname}/node_modules/electron/dist/Electron.app"`, done);
}

const build = gulp.series(
  clean,
  gulp.parallel(mvSrc, mvPackageJson, mvPackages),
  gulp.parallel(html, scripts, styles),
  dictionaries,
);
export { build };

const dev = gulp.series(build, gulp.parallel(webserver, watch));
export { dev };
<|endoftext|>


<commit_before>import path from 'path';
import gulp from 'gulp';
import loadPlugins from 'gulp-load-plugins';
import runSequence from 'run-sequence';
import del from 'del';
import webpack from 'webpack';
import WebpackDevServer from 'webpack-dev-server';
import swig from 'gulp-swig';
import gbrowser from 'gulp-browser-basedir';
import plumber from 'gulp-plumber';
import benchmark from 'gulp-benchmark';
import {config, light_config} from './webpack.config.babel.js';

const isProduction = process.env.NODE_ENV === 'production';

const $ = loadPlugins();
const webpackCompiler = webpack(config({production: isProduction}));
const lightWebpackCompiler = webpack(light_config({production: isProduction}));

// Globals.
const src = 'src/**/*',
  dest = 'lib',
  examplesDev = 'src-examples',
  examplesSources = `${examplesDev}/**/*`,
  examplesDest = 'examples',
  swigOpts = {
    defaults: {
      cache: false,

      locals: {
        assets: '../../_assets',
        libs: '../../_libs'
      }
    }
  },
  testFile = 'test/benchmark/benchmark.js';

// Browser.
process.env.BABEL_ENV = 'node';

gulp.task('default', ['build']);

gulp.task('build', (callback) => {
  runSequence('clean', 'babel', 'webpack', callback);
});

gulp.task('babel', () => {
  return gulp.src(src)
    .pipe($.cached('babel', {optimizeMemory: true}))
    .pipe($.if(!isProduction, $.sourcemaps.init()))
    .pipe($.babel())
    .on('error', makeBuildErrorHandler('babel'))
    .pipe($.if(!isProduction, $.sourcemaps.write('.')))
    .pipe(gulp.dest(dest));
});

gulp.task('webpack', (callback) => {
  webpackCompiler.run((error, stats) => {
    if (error) throw new $.util.PluginError('webpack', error);
    $.util.log('[webpack]', stats.toString({colors: true}));

    lightWebpackCompiler.run((error, stats) => {
      if (error) throw new $.util.PluginError('webpack', error);
      $.util.log('[webpack]', stats.toString({colors: true}));
      callback();
    });
  });
});

gulp.task('dev', ['examples:watch'], () => {
  const server = new WebpackDevServer(webpackCompiler, {
    contentBase: examplesDest,
    publicPath: '/build/',

    stats: {colors: true}
  });

  server.listen(8080, 'localhost', () => {});
});

gulp.task('examples:watch', () => {
  const watcher = gulp.watch(examplesSources, (obj) => {
    if (obj.type === 'changed') {
      if (path.extname(obj.path) === '.js') {
        console.log('.js change detected.');
        const filePath = path.relative(path.resolve('./'), obj.path);

        gulp.src([
          obj.path,
          `!${examplesDev}/_libs/**/*`,
          `!${examplesDev}/_assets/**/*.js`
        ])
          .pipe(plumber())
          .pipe(swig(Object.assign({}, swigOpts, {ext: '.js'})))
          .pipe(gbrowser.browserify({basedir: path.resolve(examplesDev)}, {
            transform: 'babelify',
            options: {presets: ['es2015']}
          }))
          .pipe(
            gulp.dest(
              path.join(
                path.relative(path.resolve('./'), path.resolve(examplesDest)),
                path.relative(path.resolve(examplesDev), path.dirname(obj.path))
              )
            )
          );

        console.log(`Swig, babelify & browserify: ${filePath}`);
      } else if (path.extname(obj.path) === '.html') {
        console.log('.html change detected.');
        const filePath = path.relative(path.resolve('./'), obj.path);

        if (obj.path.indexOf('layout') > -1) {
          gulp.src([
            `${examplesDev}/**/*.html`
          ])
            .pipe(plumber())
            .pipe(swig(swigOpts))
            .pipe(
              gulp.dest(
                path.join(
                  path.relative(path.resolve('./'), path.resolve(examplesDest)),
                  path.relative(path.resolve(examplesDev), path.dirname(obj.path))
                )
              )
            );

          console.log(`Swig LAYOUT: ${filePath}`);
        } else {
          gulp.src(filePath)
            .pipe(plumber())
            .pipe(swig(swigOpts))
            .pipe(
              gulp.dest(
                path.join(
                  path.relative(path.resolve('./'), path.resolve(examplesDest)),
                  path.relative(path.resolve(examplesDev), path.dirname(obj.path))
                )
              )
            );
        }

        console.log(`Swig: ${filePath}`);
      } else {
        console.log('Other file change detected.');
        const filePath = path.relative(path.resolve('./'), obj.path);

        gulp.src([
          filePath,
          `!${examplesDev}/**/*.html`,
          `!${examplesDev}/!(_libs)/*.js`,
          `!${examplesDev}/**/script.js`,
          `${examplesDev}/_libs/**/*`,
          `${examplesDev}/_assets/**/*.js`
        ])
          .pipe(plumber())
          .pipe(
            gulp.dest(
              path.join(
                path.relative(path.resolve('./'), path.resolve(examplesDest)),
                path.relative(path.resolve(examplesDev), path.dirname(obj.path))
              )
            )
          );

        console.log(`File copied: ${filePath}`);
      }
    }
  });

  watcher.on('change', (event) => {
    if (event.type === 'deleted') {
      // Simulating the {base: 'src'} used with gulp.src in the scripts task
      const filePathFromSrc = path.relative(path.resolve(examplesDev), event.path);

      // Concatenating the 'build' absolute path used by gulp.dest in the scripts task
      const destFilePath = path.resolve(examplesDest, filePathFromSrc);

      del.sync(destFilePath);
    }
  });
});

gulp.task('examples', () => {
  del(examplesDest).then(() => {
    gulp.src([
      `${examplesDev}/**/*`,
      `!${examplesDev}/**/*.html`,
      `!${examplesDev}/!(_libs)/*.js`,
      `!${examplesDev}/**/script.js`,
      `${examplesDev}/_libs/**/*`,
      `${examplesDev}/_assets/**/*.js`
    ])
      .pipe(plumber())
      .pipe(gulp.dest(examplesDest));

    gulp.src([
      `${examplesDev}/**/*.js`,
      `!${examplesDev}/**/*.html`,
      `!${examplesDev}/_libs/*.js`,
      `!${examplesDev}/_assets/**/*.js`
    ])
      .pipe(plumber())
      .pipe(swig(Object.assign({}, swigOpts, {ext: '.js'})))
      .pipe(gbrowser.browserify({basedir: path.resolve(examplesDev)}, {
        transform: 'babelify',
        options: {presets: ['es2015']}
      }))
      .pipe(gulp.dest(examplesDest));

    gulp.src(`${examplesDev}/**/*.html`)
      .pipe(plumber())
      .pipe(swig(swigOpts))
      .pipe(gulp.dest(examplesDest));
  });
});

gulp.task('test', () => {
  gulp.src(testFile, {read: false})
    .pipe(
      benchmark({
        reporters: [
          benchmark.reporters.etalon('RegExp#test')
        ]
    }))
    .pipe(gulp.dest('.'));
});

gulp.task('lint', () => {
  gulp.src(src)
    .pipe($.cached('lint', {optimizeMemory: true}))
    .pipe($.xo())
    .on('error', makeBuildErrorHandler('lint'));
});

gulp.task('clean', (callback) => {
  del(dest).then(() => callback());
});

function makeBuildErrorHandler(taskName) {
  return function ({name, message, codeFrame}) {
    $.util.log(`[${taskName}]`, `${$.util.colors.red(name)} ${message}${codeFrame ? `\n${codeFrame}` : ''}`);
    this.emit('end');
  };
}
<commit_msg>CSF.<commit_after>import path from 'path';
import gulp from 'gulp';
import loadPlugins from 'gulp-load-plugins';
import runSequence from 'run-sequence';
import del from 'del';
import webpack from 'webpack';
import WebpackDevServer from 'webpack-dev-server';
import swig from 'gulp-swig';
import gbrowser from 'gulp-browser-basedir';
import plumber from 'gulp-plumber';
import benchmark from 'gulp-benchmark';
import {config, light_config} from './webpack.config.babel.js';

const isProduction = process.env.NODE_ENV === 'production';

const $ = loadPlugins();
const webpackCompiler = webpack(config({production: isProduction}));
const lightWebpackCompiler = webpack(light_config({production: isProduction}));

// Globals.
const src = 'src/**/*',
  dest = 'lib',
  examplesDev = 'src-examples',
  examplesSources = `${examplesDev}/**/*`,
  examplesDest = 'examples',
  swigOpts = {
    defaults: {
      cache: false,

      locals: {
        assets: '../../_assets',
        libs: '../../_libs'
      }
    }
  },
  testFile = 'test/benchmark/benchmark.js';

// Browser.
process.env.BABEL_ENV = 'node';

gulp.task('default', ['build']);

gulp.task('build', (callback) => {
  runSequence('clean', 'babel', 'webpack', callback);
});

gulp.task('babel', () => {
  return gulp.src(src)
    .pipe($.cached('babel', {optimizeMemory: true}))
    .pipe($.if(!isProduction, $.sourcemaps.init()))
    .pipe($.babel())
    .on('error', makeBuildErrorHandler('babel'))
    .pipe($.if(!isProduction, $.sourcemaps.write('.')))
    .pipe(gulp.dest(dest));
});

gulp.task('webpack', (callback) => {
  webpackCompiler.run((error, stats) => {
    if (error) throw new $.util.PluginError('webpack', error);
    $.util.log('[webpack]', stats.toString({colors: true}));

    lightWebpackCompiler.run((error, stats) => {
      if (error) throw new $.util.PluginError('webpack', error);
      $.util.log('[webpack]', stats.toString({colors: true}));
      callback();
    });
  });
});

gulp.task('dev', ['examples:watch'], () => {
  const server = new WebpackDevServer(webpackCompiler, {
    contentBase: examplesDest,
    publicPath: '/build/',

    stats: {colors: true}
  });

  server.listen(8080, 'localhost', () => {});
});

gulp.task('examples:watch', () => {
  const watcher = gulp.watch(examplesSources, (obj) => {
    if (obj.type === 'changed') {
      if (path.extname(obj.path) === '.js') {
        console.log('.js change detected.');
        const filePath = path.relative(path.resolve('./'), obj.path);

        gulp.src([
          obj.path,
          `!${examplesDev}/_libs/**/*`,
          `!${examplesDev}/_assets/**/*.js`
        ])
          .pipe(plumber())
          .pipe(swig(Object.assign({}, swigOpts, {ext: '.js'})))
          .pipe(gbrowser.browserify({basedir: path.resolve(examplesDev)}, {
            transform: 'babelify',
            options: {presets: ['es2015']}
          }))
          .pipe(
            gulp.dest(
              path.join(
                path.relative(path.resolve('./'), path.resolve(examplesDest)),
                path.relative(path.resolve(examplesDev), path.dirname(obj.path))
              )
            )
          );

        console.log(`Swig, babelify & browserify: ${filePath}`);
      } else if (path.extname(obj.path) === '.html') {
        console.log('.html change detected.');
        const filePath = path.relative(path.resolve('./'), obj.path);

        if (obj.path.indexOf('layout') > -1) {
          gulp.src([
            `${examplesDev}/**/*.html`
          ])
            .pipe(plumber())
            .pipe(swig(swigOpts))
            .pipe(
              gulp.dest(
                path.join(
                  path.relative(path.resolve('./'), path.resolve(examplesDest)),
                  path.relative(path.resolve(examplesDev), path.dirname(obj.path))
                )
              )
            );

          console.log(`Swig LAYOUT: ${filePath}`);
        } else {
          gulp.src(filePath)
            .pipe(plumber())
            .pipe(swig(swigOpts))
            .pipe(
              gulp.dest(
                path.join(
                  path.relative(path.resolve('./'), path.resolve(examplesDest)),
                  path.relative(path.resolve(examplesDev), path.dirname(obj.path))
                )
              )
            );
        }

        console.log(`Swig: ${filePath}`);
      } else {
        console.log('Other file change detected.');
        const filePath = path.relative(path.resolve('./'), obj.path);

        gulp.src([
          filePath,
          `!${examplesDev}/**/*.html`,
          `!${examplesDev}/!(_libs)/*.js`,
          `!${examplesDev}/**/script.js`,
          `${examplesDev}/_libs/**/*`,
          `${examplesDev}/_assets/**/*.js`
        ])
          .pipe(plumber())
          .pipe(
            gulp.dest(
              path.join(
                path.relative(path.resolve('./'), path.resolve(examplesDest)),
                path.relative(path.resolve(examplesDev), path.dirname(obj.path))
              )
            )
          );

        console.log(`File copied: ${filePath}`);
      }
    }
  });

  watcher.on('change', (event) => {
    if (event.type === 'deleted') {
      // Simulating the {base: 'src'} used with gulp.src in the scripts task
      const filePathFromSrc = path.relative(path.resolve(examplesDev), event.path);

      // Concatenating the 'build' absolute path used by gulp.dest in the scripts task
      const destFilePath = path.resolve(examplesDest, filePathFromSrc);

      del.sync(destFilePath);
    }
  });
});

gulp.task('examples', () => {
  del(examplesDest).then(() => {
    gulp.src([
      `${examplesDev}/**/*`,
      `!${examplesDev}/**/*.html`,
      `!${examplesDev}/!(_libs)/*.js`,
      `!${examplesDev}/**/script.js`,
      `${examplesDev}/_libs/**/*`,
      `${examplesDev}/_assets/**/*.js`
    ])
      .pipe(plumber())
      .pipe(gulp.dest(examplesDest));

    gulp.src([
      `${examplesDev}/**/*.js`,
      `!${examplesDev}/**/*.html`,
      `!${examplesDev}/_libs/*.js`,
      `!${examplesDev}/_assets/**/*.js`
    ])
      .pipe(plumber())
      .pipe(swig(Object.assign({}, swigOpts, {ext: '.js'})))
      .pipe(gbrowser.browserify({basedir: path.resolve(examplesDev)}, {
        transform: 'babelify',
        options: {presets: ['es2015']}
      }))
      .pipe(gulp.dest(examplesDest));

    gulp.src(`${examplesDev}/**/*.html`)
      .pipe(plumber())
      .pipe(swig(swigOpts))
      .pipe(gulp.dest(examplesDest));
  });
});

gulp.task('test', () => {
  gulp.src(testFile, {read: false})
    .pipe(
      benchmark({
        reporters: [
          benchmark.reporters.etalon('RegExp#test')
        ]
      })
    )
    .pipe(gulp.dest('.'));
});

gulp.task('lint', () => {
  gulp.src(src)
    .pipe($.cached('lint', {optimizeMemory: true}))
    .pipe($.xo())
    .on('error', makeBuildErrorHandler('lint'));
});

gulp.task('clean', (callback) => {
  del(dest).then(() => callback());
});

function makeBuildErrorHandler(taskName) {
  return function ({name, message, codeFrame}) {
    $.util.log(`[${taskName}]`, `${$.util.colors.red(name)} ${message}${codeFrame ? `\n${codeFrame}` : ''}`);
    this.emit('end');
  };
}
<|endoftext|>


<commit_before>function initTour(introJs) {
    var tours = window.tours,
        tour_actions = window.tour_actions;

    function getCurrentSteps() {
        var path = window.location.pathname;
        for (var tour in tours) {
            if (new RegExp(tour).test(path)) {
                return tours[tour].steps;
            }
        }
    }

    function startIntro(steps) {
        var intro = introJs();

        intro.setOptions({
            steps: steps
        });
        intro.executeCurrentStepCb = function(phase) {
            if (this._options && this._options.steps && this._currentStep) {
                var step = this._options.steps[this._currentStep];
                if (step && step[phase] && tour_actions[step[phase]]) {
                    tour_actions[step[phase]]();
                }
            }
        };
        intro.onbeforechange(function(element) {
            // Reset any menus opened
            jQuery('body').trigger('click');
            this.executeCurrentStepCb('pre');
            console.log('onbeforechange');
        });
        intro.onchange(function(element) {
            console.log('onchange');
        });
        intro.onafterchange(function(element) {
            this.executeCurrentStepCb('post');
            console.log('onafterchange');
        });
        intro.oncomplete(function() {
            console.log('oncomplete');
        });
        intro.onexit(function() {
            console.log('onexit');
        });
        intro.start();
    }

    function createTourButton(steps) {
        var tourBtn = document.createElement('a');
        tourBtn.className = 'btn tour-btn';
        tourBtn.onclick = function() {
            startIntro(steps);
        };
        document.body.appendChild(tourBtn);
    }

    var currentSteps = getCurrentSteps();
    if (currentSteps) {
        createTourButton(currentSteps);
    }
}
var introJsSrc = '//cdn.jsdelivr.net/intro.js/0.9.0/intro.min.js';
if (typeof require !== 'undefined') {
    require([introJsSrc], initTour);
} else {
    jQuery.getScript(introJsSrc, function() {
        initTour(window.introJs);
    });
}
<commit_msg>force change<commit_after>function initTour(introJs) {
    var tours = window.tours,
        tour_actions = window.tour_actions;

    function getCurrentSteps() {
        var path = window.location.pathname;
        for (var tour in tours) {
            if (new RegExp(tour).test(path)) {
                return tours[tour].steps;
            }
        }
    }

    function startIntro(steps) {
        var intro = introJs();

        intro.setOptions({
            steps: steps
        });
        intro.executeCurrentStepCb = function(phase) {
            if (this._options && this._options.steps && this._currentStep) {
                var step = this._options.steps[this._currentStep];
                if (step && step[phase] && tour_actions[step[phase]]) {
                    tour_actions[step[phase]]();
                }
            }
        };
        intro.onbeforechange(function(element) {
            // Reset any menus opened
            jQuery('body').trigger('click');
            this.executeCurrentStepCb('pre');
            console.log('onbeforechange');
        });
        intro.onchange(function(element) {
            console.log('onchange');
        });
        intro.onafterchange(function(element) {
            this.executeCurrentStepCb('post');
            console.log('onafterchange');
        });
        intro.start();
    }

    function createTourButton(steps) {
        var tourBtn = document.createElement('a');
        tourBtn.className = 'btn tour-btn';
        tourBtn.onclick = function() {
            startIntro(steps);
        };
        document.body.appendChild(tourBtn);
    }

    var currentSteps = getCurrentSteps();
    if (currentSteps) {
        createTourButton(currentSteps);
    }
}
var introJsSrc = '//cdn.jsdelivr.net/intro.js/0.9.0/intro.min.js';
if (typeof require !== 'undefined') {
    require([introJsSrc], initTour);
} else {
    jQuery.getScript(introJsSrc, function() {
        initTour(window.introJs);
    });
}
<|endoftext|>


<commit_before>if (!Kwf.Utils) Kwf.Utils = {};
if (!Kwf.Utils.Element) Kwf.Utils.Element = {};

Kwf.Utils.Element._cachedWidthEls = [];
Kwf.Utils.Element.getCachedWidth = function(e) {
    if (typeof Ext2 != 'undefined' && Ext2.Element && e instanceof Ext2.Element) e = e.dom;
    if (e instanceof jQuery) e = e.get(0);
    var ret = false;
    while (e) {
        if (e.getAttribute('data-width') == '100%') {
        } else if (typeof e.kwfWidthCache != 'undefined') {
            ret = e.kwfWidthCache;
            break;
        } else {
            var t = Kwf.Utils.BenchmarkBox.now();
            ret = e.clientWidth;
            Kwf.Utils.BenchmarkBox.time('getWidth uncached', Kwf.Utils.BenchmarkBox.now()-t);
            e.kwfWidthCache = ret;
            Kwf.Utils.Element._cachedWidthEls.push(e);
            break;
        }
        e = e.parentNode;
    }
    return ret;
};
Kwf.Utils.Element.isVisible = function elementIsVisible(el) {
    if (typeof Ext2 != 'undefined' && Ext2.Element && el instanceof Ext2.Element) el = el.dom;
    var t = Kwf.Utils.BenchmarkBox.now();

    /* variant 1: Ext2: has dependency on ext2
    //var ret = Ext2.fly(el).isVisible();
    */

    /* variant 2: jquery: not always correct
    //var ret = $(el).is(':visible');
    */

    /* variant 3: manuallycheck visiblity+display, basically what ext2 does */
    var ret = true;
    while (el && el.tagName.toLowerCase() != "body") {
        var vis = !($(el).css('visibility') == 'hidden' || $(el).css('display') == 'none');
        if (!vis) {
            ret = false;
            break;
        }
        el = el.parentNode;
    }

    Kwf.Utils.BenchmarkBox.time('isVisible uncached', Kwf.Utils.BenchmarkBox.now()-t);
    return ret;
};

Kwf.onContentReady(function clearCachedWidth(el, options) {
    if (options.action == 'widthChange' || options.action == 'show') {
        for (var i=0; i<Kwf.Utils.Element._cachedWidthEls.length; i++) {
            var e = Kwf.Utils.Element._cachedWidthEls[i];
            if (el == e || $.contains(el, e)) {
                delete e.kwfWidthCache;
                Kwf.Utils.Element._cachedWidthEls.splice(i, 1);
                i--; //decrement because e was removed from array
            }
        }
    }
}, { defer: false, priority: -10 });
<commit_msg>IE8 fix when isVisible() is called on an Element that has no tagname<commit_after>if (!Kwf.Utils) Kwf.Utils = {};
if (!Kwf.Utils.Element) Kwf.Utils.Element = {};

Kwf.Utils.Element._cachedWidthEls = [];
Kwf.Utils.Element.getCachedWidth = function(e) {
    if (typeof Ext2 != 'undefined' && Ext2.Element && e instanceof Ext2.Element) e = e.dom;
    if (e instanceof jQuery) e = e.get(0);
    var ret = false;
    while (e) {
        if (e.getAttribute('data-width') == '100%') {
        } else if (typeof e.kwfWidthCache != 'undefined') {
            ret = e.kwfWidthCache;
            break;
        } else {
            var t = Kwf.Utils.BenchmarkBox.now();
            ret = e.clientWidth;
            Kwf.Utils.BenchmarkBox.time('getWidth uncached', Kwf.Utils.BenchmarkBox.now()-t);
            e.kwfWidthCache = ret;
            Kwf.Utils.Element._cachedWidthEls.push(e);
            break;
        }
        e = e.parentNode;
    }
    return ret;
};
Kwf.Utils.Element.isVisible = function elementIsVisible(el) {
    if (typeof Ext2 != 'undefined' && Ext2.Element && el instanceof Ext2.Element) el = el.dom;
    var t = Kwf.Utils.BenchmarkBox.now();

    /* variant 1: Ext2: has dependency on ext2
    //var ret = Ext2.fly(el).isVisible();
    */

    /* variant 2: jquery: not always correct
    //var ret = $(el).is(':visible');
    */

    /* variant 3: manuallycheck visiblity+display, basically what ext2 does */
    var ret = true;
    while (el && el.tagName && el.tagName.toLowerCase() != "body") {
        var vis = !($(el).css('visibility') == 'hidden' || $(el).css('display') == 'none');
        if (!vis) {
            ret = false;
            break;
        }
        el = el.parentNode;
    }

    Kwf.Utils.BenchmarkBox.time('isVisible uncached', Kwf.Utils.BenchmarkBox.now()-t);
    return ret;
};

Kwf.onContentReady(function clearCachedWidth(el, options) {
    if (options.action == 'widthChange' || options.action == 'show') {
        for (var i=0; i<Kwf.Utils.Element._cachedWidthEls.length; i++) {
            var e = Kwf.Utils.Element._cachedWidthEls[i];
            if (el == e || $.contains(el, e)) {
                delete e.kwfWidthCache;
                Kwf.Utils.Element._cachedWidthEls.splice(i, 1);
                i--; //decrement because e was removed from array
            }
        }
    }
}, { defer: false, priority: -10 });
<|endoftext|>