<commit_before>
var CHAR_MAX_LENGTH = 30;

// customized from RelatedObjectLoopups.js
function showRelatedObjectLookupPopup(triggeringLink) {
    var name = triggeringLink.id.replace(/^lookup_/, '');
    name = id_to_windowname(name);
    var href;
    if (triggeringLink.href.search(/\?/) >= 0) {
        href = triggeringLink.href + '&pop=1';
    } else {
        href = triggeringLink.href + '?pop=1';
    }
    //grappelli custom
    var win = window.open(href, name, 'height=500,width=980,resizable=yes,scrollbars=yes');
    // end
    win.focus();
    return false;
}

// customized from RelatedObjectLoopups.js
function dismissRelatedLookupPopup(win, chosenId) {
    var name = windowname_to_id(win.name);
    var elem = document.getElementById(name);
    if (elem.className.indexOf('vManyToManyRawIdAdminField') != -1 && elem.value) {
        elem.value += ',' + chosenId;
    } else {
        document.getElementById(name).value = chosenId;
    }
    //grappelli custom
    document.getElementById(name).focus();
    // end
    win.close();
}

// customized from RelatedObjectLoopups.js
function showAddAnotherPopup(triggeringLink) {
    var name = triggeringLink.id.replace(/^add_/, '');
    name = id_to_windowname(name);
    href = triggeringLink.href;
    if (href.indexOf('?') == -1) {
        href += '?_popup=1';
    } else {
        href  += '&_popup=1';
    }
    var win = window.open(href, name, 'height=500,width=1000,resizable=yes,scrollbars=yes');
    win.focus();
    return false;
}

// customized from RelatedObjectLoopups.js
// grappelli custom:
//  - trigger elem.click() to show submit/cancle footer in change_list;
function dismissAddAnotherPopup(win, newId, newRepr) {
    // newId and newRepr are expected to have previously been escaped by
    // django.utils.html.escape.
    newId = html_unescape(newId);
    newRepr = html_unescape(newRepr);
    var name = windowname_to_id(win.name);
    var elem = document.getElementById(name);
    if (elem) {
        if (elem.nodeName == 'SELECT') {
            var o = new Option(newRepr, newId);
            elem.options[elem.options.length] = o;
            o.selected = true;
        } else if (elem.nodeName == 'INPUT') {
            if (elem.className.indexOf('vManyToManyRawIdAdminField') != -1 && elem.value) {
                elem.value += ',' + newId;
            } else {
                elem.value = newId;
            }
        // NOTE: via http://code.djangoproject.com/attachment/ticket/10191/RelatedObjectLookups-updated.js.patch
        // check if the className contains radiolist - if it's HORIZONTAL, then it won't match if we compare explicitly
        } else if (elem.className.indexOf('radiolist') > -1) {
            var cnt = elem.getElementsByTagName('li').length;
            var idName = elem.id+'_'+cnt;
            var newLi = document.createElement('li');
            var newLabel = document.createElement('label');
            var newText = document.createTextNode(' '+newRepr);
            try {
                // IE doesn't support settings name, type, or class by setAttribute
                var newInput = document.createElement('<input type=\'radio\' name=\''+name.slice(3)+'\' checked=\'checked\' class=\''+elem.className+'\' />');
            } catch(err) {
                var newInput = document.createElement('input');
                newInput.setAttribute('class', elem.className);
                newInput.setAttribute('type', 'radio');
                newInput.setAttribute('name', name.slice(3));
            }
            newLabel.setAttribute('for', idName);
            newInput.setAttribute('id', idName);
            newInput.setAttribute('value', newId);
            newInput.setAttribute('checked', 'checked');
            newLabel.appendChild(newInput);
            // check if the content being added is a tag - useful for image lists
            if (newRepr.charAt(0) == '<' && newRepr.charAt(newRepr.length-1) == '>') {
                newLabel.innerHTML += newRepr;
            }
            else {
                newLabel.appendChild(newText);
            }
            newLi.appendChild(newLabel);
            elem.appendChild(newLi);
        }
    } else {
        var toId = name + "_to";
        elem = document.getElementById(toId);
        var o = new Option(newRepr, newId);
        SelectBox.add_to_cache(toId, o);
        SelectBox.redisplay(toId);
    }
    //grappelli custom
    if (elem.click) {
        elem.click();
    }
    // end
    win.close();
}

(function($) {
    function RelatedLookup(obj) {
        // check if val isn't empty string or the same value as before
        if (obj.val() == obj.data('old_val')) return;
        obj.data('old_val', obj.val());

        var link = obj.next();
        var text = obj.next().next();
        var app_label = link.attr('href').split('/')[2];
        var model_name= link.attr('href').split('/')[3];

        if (obj.val() == "") {
            text.text('');
            return;
        }

        text.text('loading ...');

        // get object
        $.get('/grappelli/lookup/related/', {
            object_id: obj.val(),
            app_label: app_label,
            model_name: model_name
        }, function(data) {
            var item = data;
            text.text('');
            if (item) {
                if (item.length > CHAR_MAX_LENGTH) {
                    text.text(decodeURI(item.substr(0, CHAR_MAX_LENGTH) + " ..."));
                } else {
                    text.text(decodeURI(item));
                }

            }
        });
    }

    function M2MLookup(obj) {
        // check if val isn't empty string or the same value as before
        if (obj.val() == obj.data('old_val')) return;
        obj.data('old_val', obj.val());

        var link = obj.next();
        var text = obj.next().next();
        var app_label = link.attr('href').split('/')[2];
        var model_name= link.attr('href').split('/')[3];

        if (obj.val() == "") {
            text.text('');
            return;
        }

        text.text('loading ...');

        // get object
        $.get('/grappelli/lookup/m2m/', {
            object_id: obj.val(),
            app_label: app_label,
            model_name: model_name
        }, function(data) {
            var item = data;
            text.text('');
            if (item) {
                if (item.length > CHAR_MAX_LENGTH) {
                    text.text(decodeURI(item.substr(0, CHAR_MAX_LENGTH) + " ..."));
                } else {
                    text.text(decodeURI(item));
                }
            }
        });
    }

    function GenericLookup(obj) {
        // check if val isn't empty string or the same value as before
        if (obj.val() == obj.data('old_val')) return;
        obj.data('old_val', obj.val());

        var link = obj.next();
        var text = obj.next().next();
        var app_label = link.attr('href').split('/')[2];
        var model_name= link.attr('href').split('/')[3];

        text.text('loading ...');

        // get object
        $.get('/grappelli/lookup/related/', {object_id: obj.val(), app_label: app_label, model_name: model_name}, function(data) {
            var item = data;
            text.text('');
            if (item) {
                if (item.length > CHAR_MAX_LENGTH) {
                    text.text(decodeURI(item.substr(0, CHAR_MAX_LENGTH) + " ..."));
                } else {
                    text.text(decodeURI(item));
                }
            }
        });
    }

    function RelatedHandler(obj) {
        // related lookup handler
        obj.bind("change focus keyup blur", function() {
            RelatedLookup($(this));
        });
    }

    function M2MHandler(obj) {
        // related lookup handler
        obj.bind("change focus keyup blur", function() {
            M2MLookup($(this));
        });
    }

    function InitObjectID(obj) {
        obj.each(function() {
            var ct = $(this).closest('div[class*="object_id"]').prev().find(':input[name*="content_type"]').val();
            if (ct) {
                var lookupLink = $('');
                lookupLink.attr('id', 'lookup_'+this.id);
                lookupLink.attr('href', ADMIN_URL + MODEL_URL_ARRAY[ct] + '/?t=id');
                lookupLink.attr('onClick', 'return showRelatedObjectLookupPopup(this);');
                var lookupText = ' ';
                $(this).after(lookupText).after(lookupLink);
                if ($(this).val() != "") {
                    lookupText = GenericLookup($(this));
                }
            }
        });
    }

    function InitContentType(obj) {
        obj.bind("change", function() {
            var node = $(this).closest('div[class*="content_type"]').next(),
                lookupLink = node.find('a.related-lookup'),
                obj_id = node.find('input[name*="object_id"]'),
                href = ADMIN_URL + MODEL_URL_ARRAY[$(this).val()].app + '/' + MODEL_URL_ARRAY[$(this).val()].model + "/?t=id";

            if ($(this).val()) {
                if (lookupLink.attr('href')) {
                    lookupLink.attr('href', href);
                } else {
                    lookupLink = $('');
                    lookupLink.attr('id', 'lookup_'+obj_id.attr('id'));
                    lookupLink.attr('href', href);
                    lookupLink.attr('onClick', 'return showRelatedObjectLookupPopup(this);');
                    var lookupText = ' ';
                    obj_id.after(lookupText).after(lookupLink);
                }
            } else {
                obj_id.val('');
                lookupLink.remove();
                node.find('strong').remove();
            }
        });
    }

    function GenericHandler(obj) {
        // related lookup handler
        obj.bind("change focus keyup", function() {
            GenericLookup($(this));
        });
    }
    $(document).ready(function() {
        // change related-lookups in order to get the right URL.
        $('a.related-lookup').each(function() {
           href = $(this).attr('href').replace('../../../', ADMIN_URL);
           $(this).attr('href', href);
        });

        // related lookup setup
        $("input.vForeignKeyRawIdAdminField").each(function() {
            // insert empty text-elements after all empty foreignkeys
            if ($(this).val() == "") {
                $(this).next().after(' ');
            }
        });

        // m2m lookup setup
        $("input.vManyToManyRawIdAdminField").each(function() {
            // insert empty text-elements after all m2m fields
            $(this).next().after('  ');
            M2MLookup($(this));
        });

        RelatedHandler($("input.vForeignKeyRawIdAdminField"));
        M2MHandler($("input.vManyToManyRawIdAdminField"));

        InitObjectID($('input[name*="object_id"]'));
        InitContentType($(':input[name*="content_type"]'));
        GenericHandler($('input[name*="object_id"]'));
    });
})(jQuery.noConflict());
<commit_msg>still missed a case.<commit_after>
var CHAR_MAX_LENGTH = 30;

// customized from RelatedObjectLoopups.js
function showRelatedObjectLookupPopup(triggeringLink) {
    var name = triggeringLink.id.replace(/^lookup_/, '');
    name = id_to_windowname(name);
    var href;
    if (triggeringLink.href.search(/\?/) >= 0) {
        href = triggeringLink.href + '&pop=1';
    } else {
        href = triggeringLink.href + '?pop=1';
    }
    //grappelli custom
    var win = window.open(href, name, 'height=500,width=980,resizable=yes,scrollbars=yes');
    // end
    win.focus();
    return false;
}

// customized from RelatedObjectLoopups.js
function dismissRelatedLookupPopup(win, chosenId) {
    var name = windowname_to_id(win.name);
    var elem = document.getElementById(name);
    if (elem.className.indexOf('vManyToManyRawIdAdminField') != -1 && elem.value) {
        elem.value += ',' + chosenId;
    } else {
        document.getElementById(name).value = chosenId;
    }
    //grappelli custom
    document.getElementById(name).focus();
    // end
    win.close();
}

// customized from RelatedObjectLoopups.js
function showAddAnotherPopup(triggeringLink) {
    var name = triggeringLink.id.replace(/^add_/, '');
    name = id_to_windowname(name);
    href = triggeringLink.href;
    if (href.indexOf('?') == -1) {
        href += '?_popup=1';
    } else {
        href  += '&_popup=1';
    }
    var win = window.open(href, name, 'height=500,width=1000,resizable=yes,scrollbars=yes');
    win.focus();
    return false;
}

// customized from RelatedObjectLoopups.js
// grappelli custom:
//  - trigger elem.click() to show submit/cancle footer in change_list;
function dismissAddAnotherPopup(win, newId, newRepr) {
    // newId and newRepr are expected to have previously been escaped by
    // django.utils.html.escape.
    newId = html_unescape(newId);
    newRepr = html_unescape(newRepr);
    var name = windowname_to_id(win.name);
    var elem = document.getElementById(name);
    if (elem) {
        if (elem.nodeName == 'SELECT') {
            var o = new Option(newRepr, newId);
            elem.options[elem.options.length] = o;
            o.selected = true;
        } else if (elem.nodeName == 'INPUT') {
            if (elem.className.indexOf('vManyToManyRawIdAdminField') != -1 && elem.value) {
                elem.value += ',' + newId;
            } else {
                elem.value = newId;
            }
        // NOTE: via http://code.djangoproject.com/attachment/ticket/10191/RelatedObjectLookups-updated.js.patch
        // check if the className contains radiolist - if it's HORIZONTAL, then it won't match if we compare explicitly
        } else if (elem.className.indexOf('radiolist') > -1) {
            var cnt = elem.getElementsByTagName('li').length;
            var idName = elem.id+'_'+cnt;
            var newLi = document.createElement('li');
            var newLabel = document.createElement('label');
            var newText = document.createTextNode(' '+newRepr);
            try {
                // IE doesn't support settings name, type, or class by setAttribute
                var newInput = document.createElement('<input type=\'radio\' name=\''+name.slice(3)+'\' checked=\'checked\' class=\''+elem.className+'\' />');
            } catch(err) {
                var newInput = document.createElement('input');
                newInput.setAttribute('class', elem.className);
                newInput.setAttribute('type', 'radio');
                newInput.setAttribute('name', name.slice(3));
            }
            newLabel.setAttribute('for', idName);
            newInput.setAttribute('id', idName);
            newInput.setAttribute('value', newId);
            newInput.setAttribute('checked', 'checked');
            newLabel.appendChild(newInput);
            // check if the content being added is a tag - useful for image lists
            if (newRepr.charAt(0) == '<' && newRepr.charAt(newRepr.length-1) == '>') {
                newLabel.innerHTML += newRepr;
            }
            else {
                newLabel.appendChild(newText);
            }
            newLi.appendChild(newLabel);
            elem.appendChild(newLi);
        }
    } else {
        var toId = name + "_to";
        elem = document.getElementById(toId);
        var o = new Option(newRepr, newId);
        SelectBox.add_to_cache(toId, o);
        SelectBox.redisplay(toId);
    }
    //grappelli custom
    if (elem.click) {
        elem.click();
    }
    // end
    win.close();
}

(function($) {
    function RelatedLookup(obj) {
        // check if val isn't empty string or the same value as before
        if (obj.val() == obj.data('old_val')) return;
        obj.data('old_val', obj.val());

        var link = obj.next();
        var text = obj.next().next();
        var app_label = link.attr('href').split('/')[2];
        var model_name= link.attr('href').split('/')[3];

        if (obj.val() == "") {
            text.text('');
            return;
        }

        text.text('loading ...');

        // get object
        $.get('/grappelli/lookup/related/', {
            object_id: obj.val(),
            app_label: app_label,
            model_name: model_name
        }, function(data) {
            var item = data;
            text.text('');
            if (item) {
                if (item.length > CHAR_MAX_LENGTH) {
                    text.text(decodeURI(item.substr(0, CHAR_MAX_LENGTH) + " ..."));
                } else {
                    text.text(decodeURI(item));
                }

            }
        });
    }

    function M2MLookup(obj) {
        // check if val isn't empty string or the same value as before
        if (obj.val() == obj.data('old_val')) return;
        obj.data('old_val', obj.val());

        var link = obj.next(),
            text = obj.next().next(),
            app_label = link.attr('href').split('/')[2],
            model_name= link.attr('href').split('/')[3];

        if (obj.val() == "") {
            text.text('');
            return;
        }

        text.text('loading ...');

        // get object
        $.get('/grappelli/lookup/m2m/', {
            object_id: obj.val(),
            app_label: app_label,
            model_name: model_name
        }, function(data) {
            var item = data;
            text.text('');
            if (item) {
                if (item.length > CHAR_MAX_LENGTH) {
                    text.text(decodeURI(item.substr(0, CHAR_MAX_LENGTH) + " ..."));
                } else {
                    text.text(decodeURI(item));
                }
            }
        });
    }

    function GenericLookup(obj) {
        // check if val isn't empty string or the same value as before
        if (obj.val() == obj.data('old_val')) return;
        obj.data('old_val', obj.val());

        var link = obj.next(),
            text = obj.next().next(),
            app_label = link.attr('href').split('/')[2],
            model_name= link.attr('href').split('/')[3];

        text.text('loading ...');

        // get object
        $.get('/grappelli/lookup/related/', {
            object_id: obj.val(),
            app_label: app_label,
            model_name: model_name
        }, function(data) {
            var item = data;
            text.text('');
            if (item) {
                if (item.length > CHAR_MAX_LENGTH) {
                    text.text(decodeURI(item.substr(0, CHAR_MAX_LENGTH) + " ..."));
                } else {
                    text.text(decodeURI(item));
                }
            }
        });
    }

    function RelatedHandler(obj) {
        // related lookup handler
        obj.bind("change focus keyup blur", function() {
            RelatedLookup($(this));
        });
    }

    function M2MHandler(obj) {
        // related lookup handler
        obj.bind("change focus keyup blur", function() {
            M2MLookup($(this));
        });
    }

    function InitObjectID(obj) {
        obj.each(function() {
            var ct = $(this).closest('div[class*="object_id"]').prev().find(':input[name*="content_type"]').val();
            if (ct) {
                var lookupLink = $('');
                lookupLink.attr('id', 'lookup_'+this.id);
                lookupLink.attr('href', ADMIN_URL + MODEL_URL_ARRAY[ct].app + '/' + MODEL_URL_ARRAY[ct].model + '/?t=id');
                lookupLink.attr('onClick', 'return showRelatedObjectLookupPopup(this);');
                var lookupText = ' ';
                $(this).after(lookupText).after(lookupLink);
                if ($(this).val() != "") {
                    lookupText = GenericLookup($(this));
                }
            }
        });
    }

    function InitContentType(obj) {
        obj.bind("change", function() {
            var node = $(this).closest('div[class*="content_type"]').next(),
                lookupLink = node.find('a.related-lookup'),
                obj_id = node.find('input[name*="object_id"]'),
                value = $(this).val();

            if (value) {
                var href = ADMIN_URL + MODEL_URL_ARRAY[value].app + '/' + MODEL_URL_ARRAY[value].model + "/?t=id";
                if (lookupLink.attr('href')) {
                    lookupLink.attr('href', href);
                } else {
                    lookupLink = $('');
                    lookupLink.attr('id', 'lookup_'+obj_id.attr('id'));
                    lookupLink.attr('href', href);
                    lookupLink.attr('onClick', 'return showRelatedObjectLookupPopup(this);');
                    var lookupText = ' ';
                    obj_id.after(lookupText).after(lookupLink);
                }
            } else {
                obj_id.val('');
                lookupLink.remove();
                node.find('strong').remove();
            }
        });
    }

    function GenericHandler(obj) {
        // related lookup handler
        obj.bind("change focus keyup", function() {
            GenericLookup($(this));
        });
    }
    $(document).ready(function() {
        // change related-lookups in order to get the right URL.
        $('a.related-lookup').each(function() {
           href = $(this).attr('href').replace('../../../', ADMIN_URL);
           $(this).attr('href', href);
        });

        // related lookup setup
        $("input.vForeignKeyRawIdAdminField").each(function() {
            // insert empty text-elements after all empty foreignkeys
            if ($(this).val() == "") {
                $(this).next().after(' ');
            }
        });

        // m2m lookup setup
        $("input.vManyToManyRawIdAdminField").each(function() {
            // insert empty text-elements after all m2m fields
            $(this).next().after('  ');
            M2MLookup($(this));
        });

        RelatedHandler($("input.vForeignKeyRawIdAdminField"));
        M2MHandler($("input.vManyToManyRawIdAdminField"));

        InitObjectID($('input[name*="object_id"]'));
        InitContentType($(':input[name*="content_type"]'));
        GenericHandler($('input[name*="object_id"]'));
    });
})(jQuery.noConflict());
<|endoftext|>


<commit_before>function xdiff_string_patch (originalStr, patch, flags, error) {
    // http://kevin.vanzonneveld.net
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // %        note 1: The XDIFF_PATCH_IGNORESPACE flag and the error argument are not currently supported
    // %        note 2: This has not been widely tested
    // *     example 1: xdiff_string_patch('', '@@ -0,0 +1,1 @@\n+Hello world!');
    // *     returns 1: 'Hello world!'

    var i = 0, ll = 0, ranges = [], lastLinePos = 0, firstChar = '',
        rangeExp = /^@@\s+-(\d+),(\d+)\s+\+(\d+),(\d+)\s+@@$/,
        lineBreaks = /\r?\n/,
        lines = patch.split(lineBreaks),
        origLines = originalStr.split(lineBreaks),
        newStrArr = [],
        linePos = 0,
		errors = '',
        // Both string & integer (constant) input is allowed
        optTemp = 0,
		OPTS = { // Unsure of actual PHP values, so better to rely on string
			'XDIFF_PATCH_NORMAL': 1,
			'XDIFF_PATCH_REVERSE': 2,
			'XDIFF_PATCH_IGNORESPACE': 4
        };

    // Input defaulting & sanitation
    if (typeof originalStr !== 'string' || !patch) {return false;}
    if (!flags) {flags = 'XDIFF_PATCH_NORMAL';}

    if (typeof flags !== 'number') { // Allow for a single string or an array of string flags
        flags = [].concat(flags);
        for (i=0; i < flags.length; i++) {
            // Resolve string input to bitwise e.g. 'XDIFF_PATCH_NORMAL' becomes 1
            if (OPTS[flags[i]]) {
                optTemp = optTemp | OPTS[flags[i]];
            }
        }
        flags = optTemp;
    }

	if (flags & OPTS.XDIFF_PATCH_NORMAL) {
		for (i=0, ll = lines.length; i < ll; i++) {
			ranges = lines[i].match(rangeExp);
			if (ranges) {
				lastLinePos = linePos;
				linePos = ranges[1] - 1;
				while (lastLinePos < linePos) {
					newStrArr[newStrArr.length] = origLines[lastLinePos++];
				}
				while (lines[++i] && (rangeExp.exec(lines[i])) == null) {
					firstChar = lines[i].charAt(0);
					switch (firstChar) {
						case '-':
							++linePos; // Skip including that line
							break;
						case '+':
							newStrArr[newStrArr.length] = lines[i].slice(1);
							break;
						case ' ':
							newStrArr[newStrArr.length] = origLines[linePos++];
							break;
						default:
							throw 'Unrecognized initial character in unidiff line'; // Reconcile with returning errrors arg?
					}
				}
				if (lines[i]) { i--; }
			}
		}
    }
	else if (flags & OPTS.XDIFF_PATCH_REVERSE) { // Only differs from above by a few lines
	    for (i=0, ll = lines.length; i < ll; i++) {
			ranges = lines[i].match(rangeExp);
			if (ranges) {
				lastLinePos = linePos;
				linePos = ranges[3] - 1;
				while (lastLinePos < linePos) {
					newStrArr[newStrArr.length] = origLines[lastLinePos++];
				}
				while (lines[++i] && (rangeExp.exec(lines[i])) == null) {
					firstChar = lines[i].charAt(0);
					switch (firstChar) {
						case '-':
							newStrArr[newStrArr.length] = lines[i].slice(1);
							break;
						case '+':
							++linePos; // Skip including that line
							break;
						case ' ':
							newStrArr[newStrArr.length] = origLines[linePos++];
							break;
						default:
							throw 'Unrecognized initial character in unidiff line'; // Reconcile with returning errrors arg?
					}
				}
				if (lines[i]) { i--; }
			}
		}
	}
	if (typeof (error === 'string')) {
		this.window[error] = errors;
	}
	return newStrArr.join('\n');
}
<commit_msg>Fix xdiff_string_patch to work in IE; needed cross-browser split() function (thanks Steven Levithan!)<commit_after>function xdiff_string_patch (originalStr, patch, flags, error) {
    // http://kevin.vanzonneveld.net
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: Steven Levithan (stevenlevithan.com)
    // %        note 1: The XDIFF_PATCH_IGNORESPACE flag and the error argument are not currently supported
    // %        note 2: This has not been widely tested
    // *     example 1: xdiff_string_patch('', '@@ -0,0 +1,1 @@\n+Hello world!');
    // *     returns 1: 'Hello world!'

    // First two functions were adapted from Steven Levithan, also under an MIT license
    // Adapted from XRegExp 1.5.0
    // (c) 2007-2010 Steven Levithan
    // MIT License
    // <http://xregexp.com>
    var getNativeFlags = function (regex) {
            return (regex.global     ? "g" : "") +
                   (regex.ignoreCase ? "i" : "") +
                   (regex.multiline  ? "m" : "") +
                   (regex.extended   ? "x" : "") + // Proposed for ES4; included in AS3
                   (regex.sticky     ? "y" : "");
        },
        cbSplit = function (str, s /* separator */) {
            // If separator `s` is not a regex, use the native `split`
            if (!(s instanceof RegExp)) { // Had problems to get it to work here using prototype test
                return String.prototype.split.apply(str, arguments);
            }
            str = str + '';
            var output = [],
                lastLastIndex = 0,
                match, lastLength, limit = Infinity;

            // This is required if not `s.global`, and it avoids needing to set `s.lastIndex` to zero
            // and restore it to its original value when we're done using the regex
            var x = s._xregexp;
            s = new RegExp(s.source, getNativeFlags(s) + 'g'); // Brett paring down
            if (x) {
                s._xregexp = {
                    source: x.source,
                    captureNames: x.captureNames ? x.captureNames.slice(0) : null
                };
            }

            while ((match = s.exec(str))) { // Run the altered `exec` (required for `lastIndex` fix, etc.)
                if (s.lastIndex > lastLastIndex) {
                    output.push(str.slice(lastLastIndex, match.index));

                    if (match.length > 1 && match.index < str.length)
                        Array.prototype.push.apply(output, match.slice(1));

                    lastLength = match[0].length;
                    lastLastIndex = s.lastIndex;

                    if (output.length >= limit)
                        break;
                }

                if (s.lastIndex === match.index)
                    s.lastIndex++;
            }

            if (lastLastIndex === str.length) {
                if (!s.test("") || lastLength)
                    output.push("");
            } else {
                output.push(str.slice(lastLastIndex));
            }

            return output.length > limit ? output.slice(0, limit) : output;
        },
        i = 0, ll = 0, ranges = [], lastLinePos = 0, firstChar = '',
            rangeExp = /^@@\s+-(\d+),(\d+)\s+\+(\d+),(\d+)\s+@@$/,
            lineBreaks = /\r?\n/,
            lines = cbSplit(patch.replace(/(\r?\n)+$/, ''), lineBreaks),
            origLines = cbSplit(originalStr, lineBreaks),
            newStrArr = [],
            linePos = 0,
            errors = '',
            // Both string & integer (constant) input is allowed
            optTemp = 0,
            OPTS = { // Unsure of actual PHP values, so better to rely on string
                'XDIFF_PATCH_NORMAL': 1,
                'XDIFF_PATCH_REVERSE': 2,
                'XDIFF_PATCH_IGNORESPACE': 4
            };

    // Input defaulting & sanitation
    if (typeof originalStr !== 'string' || !patch) {return false;}
    if (!flags) {flags = 'XDIFF_PATCH_NORMAL';}

    if (typeof flags !== 'number') { // Allow for a single string or an array of string flags
        flags = [].concat(flags);
        for (i=0; i < flags.length; i++) {
            // Resolve string input to bitwise e.g. 'XDIFF_PATCH_NORMAL' becomes 1
            if (OPTS[flags[i]]) {
                optTemp = optTemp | OPTS[flags[i]];
            }
        }
        flags = optTemp;
    }

    if (flags & OPTS.XDIFF_PATCH_NORMAL) {
        for (i=0, ll = lines.length; i < ll; i++) {
            ranges = lines[i].match(rangeExp);
            if (ranges) {
                lastLinePos = linePos;
                linePos = ranges[1] - 1;
                while (lastLinePos < linePos) {
                    newStrArr[newStrArr.length] = origLines[lastLinePos++];
                }
                while (lines[++i] && (rangeExp.exec(lines[i])) == null) {
                    firstChar = lines[i].charAt(0);
                    switch (firstChar) {
                        case '-':
                            ++linePos; // Skip including that line
                            break;
                        case '+':
                            newStrArr[newStrArr.length] = lines[i].slice(1);
                            break;
                        case ' ':
                            newStrArr[newStrArr.length] = origLines[linePos++];
                            break;
                        default:
                            throw 'Unrecognized initial character in unidiff line'; // Reconcile with returning errrors arg?
                    }
                }
                if (lines[i]) { i--; }
            }
        }
    }
    else if (flags & OPTS.XDIFF_PATCH_REVERSE) { // Only differs from above by a few lines
        for (i=0, ll = lines.length; i < ll; i++) {
            ranges = lines[i].match(rangeExp);
            if (ranges) {
                lastLinePos = linePos;
                linePos = ranges[3] - 1;
                while (lastLinePos < linePos) {
                    newStrArr[newStrArr.length] = origLines[lastLinePos++];
                }
                while (lines[++i] && (rangeExp.exec(lines[i])) == null) {
                    firstChar = lines[i].charAt(0);
                    switch (firstChar) {
                        case '-':
                            newStrArr[newStrArr.length] = lines[i].slice(1);
                            break;
                        case '+':
                            ++linePos; // Skip including that line
                            break;
                        case ' ':
                            newStrArr[newStrArr.length] = origLines[linePos++];
                            break;
                        default:
                            throw 'Unrecognized initial character in unidiff line'; // Reconcile with returning errrors arg?
                    }
                }
                if (lines[i]) { i--; }
            }
        }
    }
    if (typeof (error === 'string')) {
        this.window[error] = errors;
    }
    return newStrArr.join('\n');
}
<|endoftext|>


<commit_before><commit_msg>Improve consistency of endpoint urls<commit_after><|endoftext|>


<commit_before><commit_msg>upgraded structure for archives and documents to allow sorting<commit_after><|endoftext|>


<commit_before>"use strict";

var gulp = require("gulp");

var gulpSequence = require('gulp-sequence');

// Loads the plugins without having to list all of them, but you need
// to call them as $.pluginname
var $ = require("gulp-load-plugins")();
// "del" is used to clean out directories and such
var del = require("del");
// BrowserSync isn"t a gulp package, and needs to be loaded manually
var browserSync = require("browser-sync");

var elm  = require('gulp-elm');

var fs = require('fs');

// merge is used to merge the output from two different streams into the same stream
var merge = require("merge-stream");
// Need a command for reloading webpages using BrowserSync

var plumber = require("gulp-plumber");

var reload = browserSync.reload;
// And define a variable that BrowserSync uses in its function
var bs;

// Deletes the directory that is used to serve the site during development
gulp.task("clean:dev", function(cb) {
  return del(["serve"], cb);
});

// Deletes the directory that the optimized site is output to
gulp.task("clean:prod", function(cb) {
  return del(["dist"], cb);
});

// Compiles the SASS files and moves them into the "assets/stylesheets" directory
gulp.task("styles", function () {
  // Looks at the style.scss file for what to include and creates a style.css file
  return gulp.src("src/assets/scss/style.scss")
    .pipe(plumber())
    .pipe($.sass())
    .on('error', function(err){
      browserSync.notify("SASS error");

      console.error(err.message);

      // Save the error to index.html, with a simple HTML wrapper
      // so browserSync can inject itself in.
      fs.writeFileSync('serve/index.html', "<!DOCTYPE HTML>
" + err.message + "
");

      // No need to continue processing.
      this.emit('end');
    })
    // AutoPrefix your CSS so it works between browsers
    .pipe($.autoprefixer("last 1 version", { cascade: true }))
    // Directory your CSS file goes to
    .pipe(gulp.dest("serve/assets/stylesheets/"))
    // Outputs the size of the CSS file
    .pipe($.size({title: "styles"}))
    // Injects the CSS changes to your browser since Jekyll doesn"t rebuild the CSS
    .pipe(reload({stream: true}));
});

// Optimizes the images that exists
gulp.task("images", function () {
  return gulp.src("src/assets/images/**")
    .pipe($.changed("dist/assets/images"))
    .pipe($.imagemin({
      // Lossless conversion to progressive JPGs
      progressive: true,
      // Interlace GIFs for progressive rendering
      interlaced: true
    }))
    .pipe(gulp.dest("dist/assets/images"))
    .pipe($.size({title: "images"}));
});

// Copy over fonts to the "dist" directory
gulp.task("fonts", function () {
  return gulp.src("src/assets/fonts/**")
    .pipe(gulp.dest("dist/assets/fonts"))
    .pipe($.size({ title: "fonts" }));
});

// Copy index.html and CNAME files to the "serve" directory
gulp.task("copy:dev", function () {
  return gulp.src(["src/index.html", "src/CNAME"])
    .pipe(gulp.dest("serve"))
    .pipe($.size({ title: "index.html & CNAME" }))
});

gulp.task("cname", function () {
  return gulp.src(["serve/CNAME"])
    .pipe(gulp.dest("dist"))
    .pipe($.size({ title: "CNAME" }))
});

// Optimizes all the CSS, HTML and concats the JS etc
gulp.task("minify", ["styles"], function () {
  var assets = $.useref.assets({searchPath: "serve"});

  return gulp.src("serve/**/*.*")
    // Concatenate JavaScript files and preserve important comments
    .pipe($.if("*.js", $.uglify({preserveComments: "some"})))
    // Minify CSS
    .pipe($.if("*.css", $.minifyCss()))
    // Start cache busting the files
    .pipe($.revAll({ ignore: ["index.html", ".eot", ".svg", ".ttf", ".woff"] }))
    .pipe(assets.restore())
    // Replace the asset names with their cache busted names
    .pipe($.revReplace())
    // Minify HTML
    .pipe($.if("*.html", $.htmlmin({
      removeComments: true,
      removeCommentsFromCDATA: true,
      removeCDATASectionsFromCDATA: true,
      collapseWhitespace: true,
      collapseBooleanAttributes: true,
      removeAttributeQuotes: true,
      removeRedundantAttributes: true
    })))
    // Send the output to the correct folder
    .pipe(gulp.dest("dist"))
    .pipe($.size({title: "optimizations"}));
});

// Task to upload your site to your GH Pages repo
gulp.task("deploy", [], function () {
  // Deploys your optimized site, you can change the settings in the html task if you want to
  return gulp.src("dist/**/*")
    .pipe($.ghPages({branch: "gh-pages"}));
});

gulp.task('elm-init', elm.init);
gulp.task('elm', ['elm-init'], function(){
  return gulp.src('src/elm/Main.elm')
    .pipe(plumber())
    .pipe(elm())
    .on('error', function(err) {
        console.error(err.message);

        browserSync.notify("Elm compile error", 5000);

        // Save the error to index.html, with a simple HTML wrapper
        // so browserSync can inject itself in.
        fs.writeFileSync('serve/index.html', "<!DOCTYPE HTML>
" + err.message + "
");
    })
    .pipe(gulp.dest('serve'));
});

// BrowserSync will serve our site on a local server for us and other devices to use
// It will also autoreload across all devices as well as keep the viewport synchronized
// between them.
gulp.task("serve:dev", ["build"], function () {
  bs = browserSync({
    notify: true,
    // tunnel: "",
    server: {
      baseDir: "serve"
    }
  });
});

// These tasks will look for files that change while serving and will auto-regenerate or
// reload the website accordingly. Update or add other files you need to be watched.
gulp.task("watch", function () {
  // We need to copy dev, so index.html may be replaced by error messages.
  gulp.watch(["src/elm/*.elm"], ["elm", "copy:dev", reload]);
  gulp.watch(["src/assets/scss/**/*.scss"], ["styles", "copy:dev", reload]);
  // Watch JS folder
  gulp.watch(["src/index.html", "src/js/**/*.js"], ["copy:dev", reload]);
});

// Serve the site after optimizations to see that everything looks fine
gulp.task("serve:prod", function () {
  bs = browserSync({
    notify: false,
    // tunnel: true,
    server: {
      baseDir: "dist"
    }
  });
});

// Default task, run when just writing "gulp" in the terminal
gulp.task("default", ["serve:dev", "watch"]);

// Builds the site but doesn't serve it to you.
// Delete should run and complete before other tasks.
gulp.task("build", gulpSequence("clean:dev", ["styles", "copy:dev", "elm"]));

// Builds your site with the "build" command and then runs all the optimizations on
// it and outputs it to "./dist"
gulp.task("publish", ["build", "clean:prod"], function () {
  gulp.start("minify", "cname", "images", "fonts");
});
<commit_msg>Update gulp file.<commit_after>// Generated on 2015-05-04 using generator-jekyllized 0.7.3
"use strict";

var gulp = require("gulp");

var gulpSequence = require('gulp-sequence');

// Loads the plugins without having to list all of them, but you need
// to call them as $.pluginname
var $ = require("gulp-load-plugins")();
// "del" is used to clean out directories and such
var del = require("del");
// BrowserSync isn"t a gulp package, and needs to be loaded manually
var browserSync = require("browser-sync");

var elm  = require('gulp-elm');

var fs = require('fs');

// merge is used to merge the output from two different streams into the same stream
var merge = require("merge-stream");
// Need a command for reloading webpages using BrowserSync

var plumber = require("gulp-plumber");

var reload = browserSync.reload;
// And define a variable that BrowserSync uses in its function
var bs;

var wiredep = require('wiredep').stream;

// Deletes the directory that is used to serve the site during development
gulp.task("clean:dev", function(cb) {
  return del(["serve"], cb);
});

// Deletes the directory that the optimized site is output to
gulp.task("clean:prod", function(cb) {
  return del(["dist"], cb);
});

// Compiles the SASS files and moves them into the "assets/stylesheets" directory
gulp.task("styles", function () {
  // Looks at the style.scss file for what to include and creates a style.css file
  return gulp.src("src/assets/scss/style.scss")
    .pipe(plumber())
    .pipe($.sass())
    .on('error', function(err){
      browserSync.notify("SASS error");

      console.error(err.message);

      // Save the error to index.html, with a simple HTML wrapper
      // so browserSync can inject itself in.
      fs.writeFileSync('serve/index.html', "<!DOCTYPE HTML>
" + err.message + "
");

      // No need to continue processing.
      this.emit('end');
    })
    // AutoPrefix your CSS so it works between browsers
    .pipe($.autoprefixer("last 1 version", { cascade: true }))
    // Directory your CSS file goes to
    .pipe(gulp.dest("serve/assets/stylesheets/"))
    // Outputs the size of the CSS file
    .pipe($.size({title: "styles"}))
    // Injects the CSS changes to your browser since Jekyll doesn"t rebuild the CSS
    .pipe(reload({stream: true}));
});

// Optimizes the images that exists
gulp.task("images", function () {
  return gulp.src("src/assets/images/**")
    .pipe($.changed("dist/assets/images"))
    .pipe($.imagemin({
      // Lossless conversion to progressive JPGs
      progressive: true,
      // Interlace GIFs for progressive rendering
      interlaced: true
    }))
    .pipe(gulp.dest("dist/assets/images"))
    .pipe($.size({title: "images"}));
});

// Copy over fonts to the "dist" directory
gulp.task("fonts", function () {
  return gulp.src("src/assets/fonts/**")
    .pipe(gulp.dest("dist/assets/fonts"))
    .pipe($.size({ title: "fonts" }));
});

// Copy index.html and CNAME files to the "serve" directory
gulp.task("copy:dev", ["copy:bower"], function () {
  return gulp.src(["src/index.html", "src/CNAME", "src/js/**/*", "src/assets/images/**/*"])
    .pipe(gulp.dest("serve"))
    .pipe($.size({ title: "index.html & CNAME" }))
});

// Copy bower.
gulp.task("copy:bower", function () {
  return gulp.src(["bower_components/**/*"])
    .pipe(gulp.dest("serve/bower_components"))
    .pipe($.size({ title: "Bower" }))
});

// Copy images.
gulp.task("copy:images", function () {
  return gulp.src([])
    .pipe(gulp.dest("serve/assets/images"))
    .pipe($.size({ title: "Assets images" }))
});

gulp.task("cname", function () {
  return gulp.src(["serve/CNAME"])
    .pipe(gulp.dest("dist"))
    .pipe($.size({ title: "CNAME" }))
});

gulp.task('bower', function () {
  gulp.src("src/index.html")
    .pipe(wiredep())
    .pipe(gulp.dest("serve"));
});

// Optimizes all the CSS, HTML and concats the JS etc
gulp.task("minify", ["styles"], function () {
  var assets = $.useref.assets({searchPath: "serve"});

  return gulp.src("serve/**/*.*")
    // Concatenate JavaScript files and preserve important comments
    .pipe($.if("*.js", $.uglify({preserveComments: "some"})))
    // Minify CSS
    .pipe($.if("*.css", $.minifyCss()))
    // Start cache busting the files
    .pipe($.revAll({ ignore: ["index.html", ".eot", ".svg", ".ttf", ".woff"] }))
    .pipe(assets.restore())
    // Replace the asset names with their cache busted names
    .pipe($.revReplace())
    // Minify HTML
    .pipe($.if("*.html", $.htmlmin({
      removeComments: true,
      removeCommentsFromCDATA: true,
      removeCDATASectionsFromCDATA: true,
      collapseWhitespace: true,
      collapseBooleanAttributes: true,
      removeAttributeQuotes: true,
      removeRedundantAttributes: true
    })))
    // Send the output to the correct folder
    .pipe(gulp.dest("dist"))
    .pipe($.size({title: "optimizations"}));
});

// Task to upload your site to your GH Pages repo
gulp.task("deploy", [], function () {
  // Deploys your optimized site, you can change the settings in the html task if you want to
  return gulp.src("dist/**/*")
    .pipe($.ghPages({branch: "gh-pages"}));
});

gulp.task('elm-init', elm.init);
gulp.task('elm', ['elm-init'], function(){
  return gulp.src('src/elm/Main.elm')
    .pipe(plumber())
    .pipe(elm())
    .on('error', function(err) {
        console.error(err.message);

        browserSync.notify("Elm compile error", 5000);

        // Save the error to index.html, with a simple HTML wrapper
        // so browserSync can inject itself in.
        fs.writeFileSync('serve/index.html', "<!DOCTYPE HTML>
" + err.message + "
");
    })
    .pipe(gulp.dest('serve'));
});

// BrowserSync will serve our site on a local server for us and other devices to use
// It will also autoreload across all devices as well as keep the viewport synchronized
// between them.
gulp.task("serve:dev", ["build"], function () {
  bs = browserSync({
    notify: true,
    // tunnel: "",
    server: {
      baseDir: "serve"
    }
  });
});

// These tasks will look for files that change while serving and will auto-regenerate or
// reload the website accordingly. Update or add other files you need to be watched.
gulp.task("watch", function () {
  // We need to copy dev, so index.html may be replaced by error messages.
  gulp.watch(["src/index.html", "src/js/**/*.js"], ["copy:dev", reload]);
  gulp.watch(["src/elm/*.elm"], ["elm", "copy:dev", reload]);
  gulp.watch(["src/assets/scss/**/*.scss"], ["styles", "copy:dev", reload]);
});

// Serve the site after optimizations to see that everything looks fine
gulp.task("serve:prod", function () {
  bs = browserSync({
    notify: false,
    // tunnel: true,
    server: {
      baseDir: "dist"
    }
  });
});

// Default task, run when just writing "gulp" in the terminal
gulp.task("default", ["serve:dev", "watch"]);

// Builds the site but doesnt serve it to you
// @todo: Add "bower" here
gulp.task("build", gulpSequence("clean:dev", ["styles", "copy:dev", "elm"]));

// Builds your site with the "build" command and then runs all the optimizations on
// it and outputs it to "./dist"
gulp.task("publish", ["build", "clean:prod"], function () {
  gulp.start("minify", "cname", "images", "fonts");
});
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var rimraf = require('rimraf');
var browserSync = require('browser-sync');
var params = $.util.env;

var config = {
    src: {
        base: 'src',
        images: 'src/images',
        scripts: 'src/scripts',
        styles: 'src/styles'
    },
    dist: {
        base: 'dist',
        images: 'dist/images',
        scripts: 'dist/scripts',
        styles: 'dist/styles'
    },
    autoprefixer: ['last 2 versions', 'Explorer >= 10', 'Firefox >= 25']
};

gulp.task('styles', function () {
    return $.rubySass(config.src.styles + '/*.scss', {
            precision: 10,
            sourcemap: params.production ? false : true,
            style: params.production ? 'compressed' : 'expanded',
            loadPath: ['node_modules']
        })
        .on('error', function(error) {
            console.log(error);
        })
        .pipe($.plumber())
        .pipe($.autoprefixer(config.autoprefixer))
        .pipe($.sourcemaps.write('.'))
        .pipe(gulp.dest(config.dist.styles))
        .pipe($.size({title: 'styles'}));
});

gulp.task('images', function () {
    return gulp.src([config.src.images + '/**/*'])
        .pipe($.plumber())
        .pipe(gulp.dest(config.dist.scripts))
        .pipe($.size({title: 'images'}));
});

gulp.task('scripts', function () {
    return gulp.src([config.src.scripts + '/**/*.js'])
        .pipe($.plumber())
        .pipe(params.production ? $.uglify() : $.util.noop())
        .pipe(gulp.dest(config.dist.scripts))
        .pipe($.size({title: 'scripts'}));
});

gulp.task('html', function () {
    return gulp.src([config.src.base + '/**/*.html'])
        .pipe(gulp.dest(config.dist.base))
        .pipe($.size({title: 'html'}));
});

gulp.task('jshint', function () {
    gulp.src([config.src.scripts + '/**/*.js'])
        .pipe($.plumber())
        .pipe($.jshint())
        .pipe($.jshint.reporter('jshint-stylish'));
});

gulp.task('clean', function (cb) {
    rimraf(config.dist.base, cb);
});

gulp.task('watch', ['build'], function () {
    browserSync.init({
        reloadDelay: 100,
        server: {
            baseDir: './' + config.dist.base
        }
    });

    gulp.watch([config.src.images + '/**/*'], ['images']);
    gulp.watch([config.src.styles + '/**/*.scss'], ['styles']);
    gulp.watch([config.src.scripts + '/**/*.js'], ['scripts']);
    gulp.watch([config.src.base + '/**/*.html'], ['html']);

    gulp.watch(config.dist.base + '/**/*').on('change', browserSync.reload);
});

// deploy to Github Pages
gulp.task('deploy', ['build'], function() {
    params.message = params.m || params.message;

    var options = {};
    options.message = params.message || 'Update ' + new Date();

    return gulp.src(config.dist.base + '/**/*')
        .pipe($.ghPages(options));
});

gulp.task('build', ['jshint', 'scripts', 'images', 'styles', 'html']);

gulp.task('default', ['build']);
<commit_msg>Path fix for images<commit_after>'use strict';

var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var rimraf = require('rimraf');
var browserSync = require('browser-sync');
var params = $.util.env;

var config = {
    src: {
        base: 'src',
        images: 'src/images',
        scripts: 'src/scripts',
        styles: 'src/styles'
    },
    dist: {
        base: 'dist',
        images: 'dist/images',
        scripts: 'dist/scripts',
        styles: 'dist/styles'
    },
    autoprefixer: ['last 2 versions', 'Explorer >= 10', 'Firefox >= 25']
};

gulp.task('styles', function () {
    return $.rubySass(config.src.styles + '/*.scss', {
            precision: 10,
            sourcemap: params.production ? false : true,
            style: params.production ? 'compressed' : 'expanded',
            loadPath: ['node_modules']
        })
        .on('error', function(error) {
            console.log(error);
        })
        .pipe($.plumber())
        .pipe($.autoprefixer(config.autoprefixer))
        .pipe($.sourcemaps.write('.'))
        .pipe(gulp.dest(config.dist.styles))
        .pipe($.size({title: 'styles'}));
});

gulp.task('images', function () {
    return gulp.src([config.src.images + '/**/*'])
        .pipe($.plumber())
        .pipe(gulp.dest(config.dist.images))
        .pipe($.size({title: 'images'}));
});

gulp.task('scripts', function () {
    return gulp.src([config.src.scripts + '/**/*.js'])
        .pipe($.plumber())
        .pipe(params.production ? $.uglify() : $.util.noop())
        .pipe(gulp.dest(config.dist.scripts))
        .pipe($.size({title: 'scripts'}));
});

gulp.task('html', function () {
    return gulp.src([config.src.base + '/**/*.html'])
        .pipe(gulp.dest(config.dist.base))
        .pipe($.size({title: 'html'}));
});

gulp.task('jshint', function () {
    gulp.src([config.src.scripts + '/**/*.js'])
        .pipe($.plumber())
        .pipe($.jshint())
        .pipe($.jshint.reporter('jshint-stylish'));
});

gulp.task('clean', function (cb) {
    rimraf(config.dist.base, cb);
});

gulp.task('watch', ['build'], function () {
    browserSync.init({
        reloadDelay: 100,
        server: {
            baseDir: './' + config.dist.base
        }
    });

    gulp.watch([config.src.images + '/**/*'], ['images']);
    gulp.watch([config.src.styles + '/**/*.scss'], ['styles']);
    gulp.watch([config.src.scripts + '/**/*.js'], ['scripts']);
    gulp.watch([config.src.base + '/**/*.html'], ['html']);

    gulp.watch(config.dist.base + '/**/*').on('change', browserSync.reload);
});

// deploy to Github Pages
gulp.task('deploy', ['build'], function() {
    params.message = params.m || params.message;

    var options = {};
    options.message = params.message || 'Update ' + new Date();

    return gulp.src(config.dist.base + '/**/*')
        .pipe($.ghPages(options));
});

gulp.task('build', ['jshint', 'scripts', 'images', 'styles', 'html']);

gulp.task('default', ['build']);
<|endoftext|>


<commit_before>import React, { useCallback, useState } from "react";
import Button from "@agir/front/genericComponents/Button";
import styled from "styled-components";
import style from "@agir/front/genericComponents/_variables.scss";
import img1 from "@agir/front/genericComponents/images/introApp1.jpg";
import img2 from "@agir/front/genericComponents/images/introApp2.jpg";
import img3 from "@agir/front/genericComponents/images/introApp3.jpg";
import logo from "@agir/front/genericComponents/images/logoActionPopulaire.png";

const Mark = styled.span`
  width: 1.5rem;
  height: 0.25rem;
  margin: 0.188rem;
  display: inline-block;
  transition: ease 0.2s;
  background-color: ${(props) =>
    props.$active ? style.primary500 : style.black200};
`;

const Block = styled.div`
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  text-align: center;
  height: 100vh;
  justify-content: space-between;

  & > div:nth-child(2) {
    max-width: 100%;
    padding-left: 2rem;
    padding-right: 2rem;
  }
`;

const BlockConnexion = styled.div`
  display: flex;
  flex-direction: column;
  justify: center;
  align-items: center;
  height: 100vh;
`;

const ButtonContainer = styled.div`
  display: flex;
  flex-align: center;
  flex-direction: column;
  width: 100%;
  align-items: center;
  padding: 2rem;
`;

const BackgroundTriangle = styled.div`
  width: 100%;
  background-color: ${style.secondary500};
  margin-top: -1px;
  div {
    background-color: white;
    height: 80px;
    margin-bottom: -1px;
    clip-path: polygon(0px 100%, 100% 0px, 100% 100%, 0px 100%);
  }
`;

const WhiteTriangle = styled.div`
  width: 100%;
  height: 190px;
  height: calc(100vh - 345px);
  div {
    position: absolute;
    bottom: -1px;
    left: 0;
    width: 100%;
    background-color: white;
    height: 80px;
    clip-path: polygon(0px 100%, 100% 0px, 100% 100%, 0px 100%);
  }
`;

const HeaderImage = styled.div`
  background-size: cover;
  background-position: center;
  position: relative;
  width: 100%;
  display: flex;
  justify-content: center;
  flex-wrap: wrap;

  img {
    width: 90%;
    max-width: 330px;
    position: absolute;
    bottom: 0;
  }
`;

const FixedBlock = styled.div`
  padding-top: 0.5rem;
  background-color: #fff;
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 340px;
  z-index: 10;
  display: flex;
  flex-wrap: wrap;
  flex-direction: column;
  align-items: center;
  justify-content: center;

  p {
    max-width: 430px;
    display: inline-block;
    margin-bottom: 0;
    margin-top: 0;
  }
`;

const DescriptionContainer = styled.div`
  background-color: ${style.secondary500};
  padding: 1.4rem;
  width: 100%;
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
  position: relative;
  text-align: center;
  flex-grow: 1;
`;

const InlineBlock = styled.span`
  display: inline-block;
`;

const StyledButton = styled(Button)`
  max-width: 100%;
  width: 330px;
  height: 70px;
  font-size: 20px;
  justify-content: center;
  margin-top: 2rem;
`;

const items = [
  {
    name: "Rencontrez",
    description: (
      <>
        d'autres membres et <InlineBlock>agissez ensemble !</InlineBlock>
      </>
    ),
    image: img1,
  },
  {
    name: "Agissez concrètement",
    description: (
      <>
        participez aux actions, diffusez notre programme et commandez
        <InlineBlock>du matériel</InlineBlock>
      </>
    ),
    image: img2,
  },
  {
    name: "Rejoignez ou créer",
    description: (
      <>
        une équipe de soutien <InlineBlock>autour de vous !</InlineBlock>
      </>
    ),
    image: img3,
  },
];

const IntroApp = () => {
  const [index, setIndex] = useState(0);

  const showConnexion = index >= items.length;

  const handleClick = useCallback(() => {
    setIndex((index) => index + 1);
  }, []);

  return (
    <>
      {!showConnexion && (
        <Block>
          <HeaderImage
            style={{ backgroundImage: `url(${items[index].image})` }}
          >
            <WhiteTriangle>

            </WhiteTriangle>
          </HeaderImage>

          <FixedBlock>

              {items[index].name}

              {items[index].description}

          </FixedBlock>
        </Block>
      )}
      {showConnexion && (
        <BlockConnexion>
          <DescriptionContainer>

          </DescriptionContainer>

          <BackgroundTriangle>

          </BackgroundTriangle>

          <ButtonContainer>

          </ButtonContainer>
        </BlockConnexion>
      )}
    </>
  );
};

export default IntroApp;
<commit_msg>refactor uniformize last layout with first indexes<commit_after>import React, { useCallback, useState } from "react";
import Button from "@agir/front/genericComponents/Button";
import styled from "styled-components";
import style from "@agir/front/genericComponents/_variables.scss";
import img1 from "@agir/front/genericComponents/images/introApp1.jpg";
import img2 from "@agir/front/genericComponents/images/introApp2.jpg";
import img3 from "@agir/front/genericComponents/images/introApp3.jpg";
import logo from "@agir/front/genericComponents/images/logoActionPopulaire.png";

const Mark = styled.span`
  width: 1.5rem;
  height: 0.25rem;
  margin: 0.188rem;
  display: inline-block;
  transition: ease 0.2s;
  background-color: ${(props) =>
    props.$active ? style.primary500 : style.black200};
`;

const Block = styled.div`
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  text-align: center;
  height: 100vh;
  justify-content: space-between;

  & > div:nth-child(2) {
    max-width: 100%;
    padding-left: 2rem;
    padding-right: 2rem;
  }
`;

const WhiteTriangle = styled.div`
  width: 100%;
  height: 190px;
  height: calc(100vh - 345px);
  display: flex;
  justify-content: center;
  align-items: center;
  div:first-child {
    position: absolute;
    bottom: -1px;
    left: 0;
    width: 100%;
    background-color: white;
    height: 80px;
    clip-path: polygon(0px 100%, 100% 0px, 100% 100%, 0px 100%);
  }
`;

const HeaderImage = styled.div`
  background-size: cover;
  background-position: center;
  position: relative;
  width: 100%;
  display: flex;
  justify-content: center;
  flex-wrap: wrap;

  img {
    width: 90%;
    max-width: 330px;
    position: absolute;
    bottom: 0;
  }
`;

const FixedBlock = styled.div`
  padding-top: 0.5rem;
  background-color: #fff;
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 340px;
  z-index: 10;
  display: flex;
  flex-wrap: wrap;
  flex-direction: column;
  align-items: center;
  justify-content: center;

  p {
    max-width: 430px;
    display: inline-block;
    margin-bottom: 0;
    margin-top: 0;
  }
`;

const InlineBlock = styled.span`
  display: inline-block;
`;

const StyledButton = styled(Button)`
  max-width: 100%;
  width: 330px;
  height: 70px;
  font-size: 20px;
  justify-content: center;
  margin-top: 2rem;
`;

const items = [
  {
    name: "Rencontrez",
    description: (
      <>
        d'autres membres et <InlineBlock>agissez ensemble !</InlineBlock>
      </>
    ),
    image: img1,
  },
  {
    name: "Agissez concrètement",
    description: (
      <>
        participez aux actions, diffusez notre programme et commandez
        <InlineBlock>du matériel</InlineBlock>
      </>
    ),
    image: img2,
  },
  {
    name: "Rejoignez ou créer",
    description: (
      <>
        une équipe de soutien <InlineBlock>autour de vous !</InlineBlock>
      </>
    ),
    image: img3,
  },
];

const IntroApp = () => {
  const [index, setIndex] = useState(0);

  const showConnexion = index >= items.length;

  const handleClick = useCallback(() => {
    setIndex((index) => index + 1);
  }, []);

  return (
    <>
      {!showConnexion && (
        <Block>
          <HeaderImage
            style={{ backgroundImage: `url(${items[index].image})` }}
          >
            <WhiteTriangle>

            </WhiteTriangle>
          </HeaderImage>

          <FixedBlock>

              {items[index].name}

              {items[index].description}

          </FixedBlock>
        </Block>
      )}
      {showConnexion && (
        <Block>
          <HeaderImage style={{ backgroundColor: style.secondary500 }}>
            <WhiteTriangle>

            </WhiteTriangle>
          </HeaderImage>

          <FixedBlock>

          </FixedBlock>
        </Block>
      )}
    </>
  );
};

export default IntroApp;
<|endoftext|>


<commit_before>/**
 * Well,this is a plugin for autopromote a user when he join the room.
 * Made by NotAmerican and Luur98.
 * Feel free to use it for your server.
 */

exports.commands = {
	 autovoice: 'autorank',
	 autodriver: 'autorank',
	 automod: 'autorank',
	 autoowner: 'autorank',
	 autopromote: 'autorank',
	 autorank: function(target, room, user, connection, cmd) {
	 	switch (cmd) {
	 		case 'autovoice':
	 			target = '+';
	 			break;
	 		case 'autodriver':
	 			target = '%';
	 			break;
	 		case 'automod':
	 			target = '@';
	 			break;
	 		case 'autoowner':
	 			target = '#';
	 			break;
	 	}

	 	if (!target) return this.sendReply("Usage: /autorank [rank] - Automatically promotes user to the specified rank when they join the room.");
	 	if (!this.can('roommod', null, room)) return false;
	 	target = target.trim();

	 	if (target === 'off' && room.autorank) {
	 		delete room.autorank;
	 		delete room.chatRoomData.autorank;
	 		Rooms.global.writeChatRoomData();
	 		for (var u in room.users) Users.users[u].updateIdentity();
	 		return this.privateModCommand("(" + user.name + " has disabled autorank in this room.)");
	 	}
	 	if (room.autorank && room.autorank === target) return this.sendReply("Autorank is already set to \"" + target + "\".");

	 	if (Config.groups[target] && !Config.groups[target].globalonly) {
	 		if (target === '#' && user.userid !== room.founder) return this.sendReply("You can't set autorank to # unless you're the room founder.");
	 		room.autorank = target;
	 		room.chatRoomData.autorank = target;
	 		Rooms.global.writeChatRoomData();
	 		for (var u in room.users) Users.users[u].updateIdentity();
	 		return this.privateModCommand("(" + user.name + " has set autorank to \"" + target + "\" in this room.)");
	 	}
	 	return this.sendReply("Group \"" + target + "\" not found.");
	 }

};
<commit_msg>Delete autorank.js<commit_after><|endoftext|>


<commit_before>const gulp = require('gulp');
const $ = require('gulp-load-plugins')();

const GulpRegistry = require('undertaker-forward-reference');

const browserSync = require('browser-sync').create();

require('rootpath')();

module.exports = function() {
  gulp.registry(new GulpRegistry());
  $.loadAllTasks({
    browserSync,
  });

  gulp.task('default', gulp.series('build'));
};
<commit_msg>Remove unnecessary require<commit_after>const gulp = require('gulp');
const $ = require('gulp-load-plugins')();

const GulpRegistry = require('undertaker-forward-reference');

const browserSync = require('browser-sync').create();

module.exports = function() {
  gulp.registry(new GulpRegistry());
  $.loadAllTasks({
    browserSync,
  });

  gulp.task('default', gulp.series('build'));
};
<|endoftext|>


<commit_before>define([
	'marionette',
	'controller'
], function(Marionette, AppController)
{
	// Store the native, default sync method
	Backbone._nativeSync = Backbone.sync;

	// Create our default options object
	Backbone.defaultSyncOptions = {};

	// Ever so gingerly wrap the native sync
	// in a method that combines options
	Backbone.sync = function (method, model, options)
	{
		Backbone._nativeSync(method, model,
			_.extend({}, Backbone.defaultSyncOptions, options)
		);
	};

	// This will store the application session
	var session = null;

	// Declare the router
	var AppRouter = Marionette.AppRouter.extend(
	{
		appRoutes: {
			'login': 'doLogin',
			'logout': 'doLogout',
			'': 'doWelcome',
			'*action': 'doDefault'
		},

		controller: AppController,

		/**
		 * Initialize this router
		 */
		initialize: function(options)
		{
			// Get the application
			var app = options.app;

			// Get the application url
			var url = options.url;

			// Initialize the controller
			this.controller.initialize(options);

			// Initialize the session
			session = new APP.Session(null, {remote: false});

			// Catch login event
			app.vent.on('login:success', this.login, this);

			// Catch logout event
			app.vent.on('logout:success', this.logout, this);

			// Module load event
			app.vent.on('module:load', this.loadModule, this);

			// Module load post event
			app.vent.on('module:boot:success', this.startSession, this);

			// Catch clicks on every a links
			$(document).on('click', 'a[href^="/"]:not([data-bypass])', function (evt)
			{
				if (!evt.altKey && !evt.ctrlKey && !evt.metaKey && !evt.shiftKey)
				{
					evt.preventDefault();

					var regexp = new RegExp(url, 'g');
					var href = $(evt.currentTarget).attr('href').replace(regexp, '/').replace(/^\/+/, '/');
					//var href = $(evt.currentTarget).attr('href').replace(regexp, '').replace(/^\//, '');

					app.router.navigate(href, {trigger: true});
				}
			});

			// Load modules
			this.controller.loadModules();

			// Start history
			Backbone.history.start({
				pushState: true,
				root: url
			});
		},

		/**
		 * Load fragment
		 */
		loadFragment: function(fragment)
		{
			Backbone.history.loadUrl(fragment);
		},

		/**
		 * Load module
		 */
		loadModule: function(path)
		{
			var self = this;

			// Default request
			var request = {
				'loadFragment': true,
				'request': null,
				'route': 'unknow'
			};

			// Build coming request
			if (typeof path == 'object')
				request = path;
			else
				request = $.extend({}, request, {module: request});

			// If module, load it
			if (request.module)
			{
				require([request.module], function (Module)
				{
					new Module(self.options);

					if (request.loadFragment)
						self.loadFragment(request.route);
				});
			}
		},

		/**
		 * Load page
		 */
		loadPage: function(page)
		{
			var app = this.options.app;

			app.vent.trigger('page:'+page);
		},

		/**
		 * Login user by storing its token into session
		 */
		login: function (data, navigate)
		{
			// Get the application
			var app = this.options.app;

			// Store token into session
			session.set('auth', true);
			session.set('token', data.token);

			// Add token to every backbone request
			Backbone.defaultSyncOptions = {headers: {
				'Authorization': data.token
			}};

			// Trigger a post success event
			app.vent.trigger('login:success:post', data, navigate);
		},

		/**
		 * Logout the user
		 */
		logout: function (navigate)
		{
			// Get the application
			var app = this.options.app;

			// Delete token into session
			session.logout();

			// Delete token from every backbone request
			Backbone.defaultSyncOptions = {};

			// Trigger a post success event
			app.vent.trigger('logout:success:post', navigate);
		},

		/**
		 * Start session
		 */
		startSession: function ()
		{
			// Get the application
			var app = this.options.app;

			// Get the token from session ?
			var token = session.get('token');

			// If token found, use it and login the user
			if (token)
				app.vent.trigger('login:success', {'token': token}, false);
		}
	});

	return AppRouter;
});
<commit_msg>remove event and launch action directly if defined<commit_after>define([
	'marionette',
	'controller'
], function(Marionette, AppController)
{
	// Store the native, default sync method
	Backbone._nativeSync = Backbone.sync;

	// Create our default options object
	Backbone.defaultSyncOptions = {};

	// Ever so gingerly wrap the native sync
	// in a method that combines options
	Backbone.sync = function (method, model, options)
	{
		Backbone._nativeSync(method, model,
			_.extend({}, Backbone.defaultSyncOptions, options)
		);
	};

	// This will store the application session
	var session = null;

	// Declare the router
	var AppRouter = Marionette.AppRouter.extend(
	{
		appRoutes: {
			'login': 'doLogin',
			'logout': 'doLogout',
			'': 'doWelcome',
			'*action': 'doDefault'
		},

		controller: AppController,

		/**
		 * Initialize this router
		 */
		initialize: function(options)
		{
			// Get the application
			var app = options.app;

			// Get the application url
			var url = options.url;

			// Initialize the controller
			this.controller.initialize(options);

			// Initialize the session
			session = new APP.Session(null, {remote: false});

			// Catch login event
			app.vent.on('login:success', this.login, this);

			// Catch logout event
			app.vent.on('logout:success', this.logout, this);

			// Module load event
			app.vent.on('module:load', this.loadModule, this);

			// Module load post event
			app.vent.on('module:boot:success', this.startSession, this);

			// Catch clicks on every a links
			$(document).on('click', 'a[href^="/"]:not([data-bypass])', function (evt)
			{
				if (!evt.altKey && !evt.ctrlKey && !evt.metaKey && !evt.shiftKey)
				{
					evt.preventDefault();

					var regexp = new RegExp(url, 'g');
					var href = $(evt.currentTarget).attr('href').replace(regexp, '/').replace(/^\/+/, '/');
					//var href = $(evt.currentTarget).attr('href').replace(regexp, '').replace(/^\//, '');

					app.router.navigate(href, {trigger: true});
				}
			});

			// Load modules
			this.controller.loadModules();

			// Start history
			Backbone.history.start({
				pushState: true,
				root: url
			});
		},

		/**
		 * Load fragment
		 */
		loadFragment: function(fragment)
		{
			Backbone.history.loadUrl(fragment);
		},

		/**
		 * Load module
		 */
		loadModule: function(path)
		{
			var self = this;

			// Default request
			var request = {
				'loadFragment': true,
				'request': null,
				'route': 'unknow'
			};

			// Build coming request
			if (typeof path == 'object')
				request = path;
			else
				request = $.extend({}, request, {module: request});

			// If module, load it
			if (request.module)
			{
				require([request.module], function (Module)
				{
					new Module(self.options);

					if (request.loadFragment)
						self.loadFragment(request.route);
				});
			}
		},

		/**
		 * Load page
		 */
		loadPage: function(page)
		{
			var action = 'do' + page.charAt(0).toUpperCase() + page.slice(1);

			if (typeof this.controller[action] !== 'undefined')
				this.controller[action]();
		},

		/**
		 * Login user by storing its token into session
		 */
		login: function (data, navigate)
		{
			// Get the application
			var app = this.options.app;

			// Store token into session
			session.set('auth', true);
			session.set('token', data.token);

			// Add token to every backbone request
			Backbone.defaultSyncOptions = {headers: {
				'Authorization': data.token
			}};

			// Trigger a post success event
			app.vent.trigger('login:success:post', data, navigate);
		},

		/**
		 * Logout the user
		 */
		logout: function (navigate)
		{
			// Get the application
			var app = this.options.app;

			// Delete token into session
			session.logout();

			// Delete token from every backbone request
			Backbone.defaultSyncOptions = {};

			// Trigger a post success event
			app.vent.trigger('logout:success:post', navigate);
		},

		/**
		 * Start session
		 */
		startSession: function ()
		{
			// Get the application
			var app = this.options.app;

			// Get the token from session ?
			var token = session.get('token');

			// If token found, use it and login the user
			if (token)
				app.vent.trigger('login:success', {'token': token}, false);
		}
	});

	return AppRouter;
});
<|endoftext|>