<commit_before>/*! H5F
* https://github.com/ryanseddon/H5F/
* Copyright (c) Ryan Seddon | Licensed MIT */

(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(factory);
    } else if (typeof module === 'object' && module.exports)  {
        // CommonJS
        module.exports = factory();
    } else {
        // Browser globals
        root.H5F = factory();
    }
}(this, function () {

    var d = document,
        field = d.createElement("input"),
        emailPatt = /^[a-zA-Z0-9.!#$%&'*+-\/=?\^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/,
        urlPatt = /[a-z][\-\.+a-z]*:\/\//i,
        nodes = /^(input|select|textarea)$/i,
        hasInteractiveFormValidation = false,
        isSubmit, bypassSubmit, usrPatt, curEvt, args,
        // Methods
        setup, validation, validity, checkField, bypassChecks, checkValidity, setCustomValidity, support, pattern, placeholder, range, required, valueMissing, listen, unlisten, preventActions, getTarget, addClass, removeClass, isHostMethod, isSiblingChecked;

    // Big shouts to Modernizr for this code.
    // create a hidden form to test for interactive validation
    var testForm = document.createElement('form');
    testForm.hidden = true;
    testForm.innerHTML = '<input name="test" required><button></button>';
    document.body.appendChild(testForm);

    testForm.addEventListener('submit', function (e) {
        e.preventDefault();
        e.stopPropagation();
    }, false);

    var testInput = testForm.getElementsByTagName('input')[0];
    // Record whether "invalid" event is fired
    testInput.addEventListener('invalid', function (e) {
        document.body.removeChild(testForm);
        hasInteractiveFormValidation = true;
        e.preventDefault();
        e.stopPropagation();
    }, false);

    // Submit form by clicking submit button
    testForm.getElementsByTagName('button')[0].click();

    setup = function(form, settings) {

        // don't do anything if the browser already has support
        if (hasInteractiveFormValidation) {
            return;
        }

        var isCollection = !form.nodeType || false;

        var opts = {
            validClass : "valid",
            invalidClass : "error",
            requiredClass : "required",
            placeholderClass : "placeholder",
            onSubmit : Function.prototype,
            onInvalid : Function.prototype
        };

        if(typeof settings === "object") {
            for (var i in opts) {
                if(typeof settings[i] === "undefined") { settings[i] = opts[i]; }
            }
        }

        args = settings || opts;

        if(isCollection) {
            for(var k=0,len=form.length;k<len;k++) {
                validation(form[k]);
            }
        } else {
            validation(form);
        }
    };

    validation = function(form) {
        var f = form.elements,
            flen = f.length,
            isRequired,
            noValidate = !!(form.attributes["novalidate"]);

        listen(form,"invalid",checkField,true);
        listen(form,"blur",checkField,true);
        listen(form,"input",checkField,true);
        listen(form,"keyup",checkField,true);
        listen(form,"focus",checkField,true);
        listen(form,"change",checkField,true);
        listen(form,"click",bypassChecks,true);

        listen(form,"submit",function(e){
            isSubmit = true;
            if(!bypassSubmit && !noValidate && !form.checkValidity()) {
                preventActions(e);
                return;
            }
            args.onSubmit.call(form, e);
        },false);

        if(!support()) {
            form.checkValidity = function() { return checkValidity(form); };

            while(flen--) {
                isRequired = !!(f[flen].attributes["required"]);
                // Firefox includes fieldsets inside elements nodelist so we filter it out.
                if(f[flen].nodeName.toLowerCase() !== "fieldset") {
                    validity(f[flen]); // Add validity object to field
                }
            }
        }

    };
    validity = function(el) {
        var elem = el,
            missing = valueMissing(elem),
            attrs = {
                type: elem.getAttribute("type"),
                pattern: elem.getAttribute("pattern"),
                placeholder: elem.getAttribute("placeholder")
            },
            isType = /^(email|url)$/i,
            evt = /^(input|keyup)$/i,
            fType = ((isType.test(attrs.type)) ? attrs.type : ((attrs.pattern) ? attrs.pattern : false)),
            patt = pattern(elem,fType),
            step = range(elem,"step"),
            min = range(elem,"min"),
            max = range(elem,"max"),
            customError = !( elem.validationMessage === "" || elem.validationMessage === undefined );

        elem.checkValidity = function() { return checkValidity.call(this,elem); };
        elem.setCustomValidity = function(msg) { setCustomValidity.call(elem,msg); };

        elem.validity = {
            valueMissing: missing,
            patternMismatch: patt,
            rangeUnderflow: min,
            rangeOverflow: max,
            stepMismatch: step,
            customError: customError,
            valid: (!missing && !patt && !step && !min && !max && !customError)
        };

        if(attrs.placeholder && !evt.test(curEvt)) { placeholder(elem); }
    };
    checkField = function(e) {
        var el = getTarget(e) || e, // checkValidity method passes element not event
            events = /^(input|keyup|focusin|focus|change)$/i,
            ignoredTypes = /^(submit|image|button|reset)$/i,
            specialTypes = /^(checkbox|radio)$/i,
            checkForm = true;

        if(nodes.test(el.nodeName) && !(ignoredTypes.test(el.type) || ignoredTypes.test(el.nodeName))) {
            curEvt = e.type;

            if(!support()) {
                validity(el);
            }

            if(el.validity.valid && (el.value !== "" || specialTypes.test(el.type)) || (el.value !== el.getAttribute("placeholder") && el.validity.valid)) {
                removeClass(el,[args.invalidClass,args.requiredClass]);
                addClass(el,args.validClass);
            } else if(!events.test(curEvt)) {
                if(el.validity.valueMissing) {
                    removeClass(el,[args.invalidClass,args.validClass]);
                    addClass(el,args.requiredClass);
                } else if(!el.validity.valid) {
                    removeClass(el,[args.validClass,args.requiredClass]);
                    addClass(el,args.invalidClass);
                }
            } else if(el.validity.valueMissing) {
                removeClass(el,[args.requiredClass,args.invalidClass,args.validClass]);
            }
            if(curEvt === "input" && checkForm) {
                // If input is triggered remove the keyup event
                unlisten(el.form,"keyup",checkField,true);
                checkForm = false;
            }
        }
    };
    checkValidity = function(el) {
        var f, ff, isDisabled, isRequired, hasPattern, invalid = false;

        if(el.nodeName.toLowerCase() === "form") {
            f = el.elements;

            for(var i = 0,len = f.length;i < len;i++) {
                ff = f[i];

                isDisabled = !!(ff.attributes["disabled"]);
                isRequired = !!(ff.attributes["required"]);
                hasPattern = !!(ff.attributes["pattern"]);

                if(ff.nodeName.toLowerCase() !== "fieldset" && !isDisabled && (isRequired || hasPattern && isRequired)) {
                    checkField(ff);
                    if(!ff.validity.valid && !invalid) {
                        if(isSubmit) { // If it's not a submit event the field shouldn't be focused
                            ff.focus();
                        }
                        invalid = true;
                        args.onInvalid.call(el, ff);
                    }
                }
            }
            return !invalid;
        } else {
            checkField(el);
            return el.validity.valid;
        }
    };
    setCustomValidity = function(msg) {
        var el = this;

        el.validationMessage = msg;
    };

    bypassChecks = function(e) {
        // handle formnovalidate attribute
        var el = getTarget(e);

        if(el.attributes["formnovalidate"] && el.type === "submit") {
            bypassSubmit = true;
        }
    };

    support = function() {
        return (isHostMethod(field,"validity") && isHostMethod(field,"checkValidity"));
    };

    // Create helper methods to emulate attributes in older browsers
    pattern = function(el, type) {
        if(type === "email") {
            return !emailPatt.test(el.value);
        } else if(type === "url") {
            return !urlPatt.test(el.value);
        } else if(!type) {
            return false;
        } else {
            var placeholder = el.getAttribute("placeholder"),
                val = el.value;

            usrPatt = new RegExp('^(?:' + type + ')$');

            if(val === placeholder) {
                return false;
            } else if(val === "") {
                return false;
            } else {
                return !usrPatt.test(el.value);
            }
        }
    };
    placeholder = function(el) {
        var attrs = { placeholder: el.getAttribute("placeholder") },
            focus = /^(focus|focusin|submit)$/i,
            node = /^(input|textarea)$/i,
            ignoredType = /^password$/i,
            isNative = !!("placeholder" in field);

        if(!isNative && node.test(el.nodeName) && !ignoredType.test(el.type)) {
            if(el.value === "" && !focus.test(curEvt)) {
                el.value = attrs.placeholder;
                listen(el.form,'submit', function () {
                  curEvt = 'submit';
                  placeholder(el);
                }, true);
                addClass(el,args.placeholderClass);
            } else if(el.value === attrs.placeholder && focus.test(curEvt)) {
                el.value = "";
                removeClass(el,args.placeholderClass);
            }
        }
    };
    range = function(el, type) {
        // Emulate min, max and step
        var min = parseInt(el.getAttribute("min"),10) || 0,
            max = parseInt(el.getAttribute("max"),10) || false,
            step = parseInt(el.getAttribute("step"),10) || 1,
            val = parseInt(el.value,10),
            mismatch = (val-min)%step;

        if(!valueMissing(el) && !isNaN(val)) {
            if(type === "step") {
                return (el.getAttribute("step")) ? (mismatch !== 0) : false;
            } else if(type === "min") {
                return (el.getAttribute("min")) ? (val < min) : false;
            } else if(type === "max") {
                return (el.getAttribute("max")) ? (val > max) : false;
            }
        } else if(el.getAttribute("type") === "number") {
            return true;
        } else {
            return false;
        }
    };
    required = function(el) {
        var required = !!(el.attributes["required"]);

        return (required) ? valueMissing(el) : false;
    };
    valueMissing = function(el) {
        var placeholder = el.getAttribute("placeholder"),
            specialTypes = /^(checkbox|radio)$/i,
            isRequired = !!(el.attributes["required"]);
        return !!(isRequired && (el.value === "" || el.value === placeholder || (specialTypes.test(el.type) && !isSiblingChecked(el))));
    };

    /* Util methods */
    listen = function (node,type,fn,capture) {
        if(isHostMethod(window,"addEventListener")) {
            /* FF & Other Browsers */
            node.addEventListener( type, fn, capture );
        } else if(isHostMethod(window,"attachEvent") && typeof window.event !== "undefined") {
            /* Internet Explorer way */
            if(type === "blur") {
                type = "focusout";
            } else if(type === "focus") {
                type = "focusin";
            }
            node.attachEvent( "on" + type, fn );
        }
    };
    unlisten = function (node,type,fn,capture) {
        if(isHostMethod(window,"removeEventListener")) {
            /* FF & Other Browsers */
            node.removeEventListener( type, fn, capture );
        } else if(isHostMethod(window,"detachEvent") && typeof window.event !== "undefined") {
            /* Internet Explorer way */
            node.detachEvent( "on" + type, fn );
        }
    };
    preventActions = function (evt) {
        evt = evt || window.event;

        if(evt.stopImmediatePropagation && evt.preventDefault) {
            evt.stopImmediatePropagation();
            evt.preventDefault();
        } else {
            evt.cancelBubble = true;
            evt.returnValue = false;
        }
    };
    getTarget = function (evt) {
        evt = evt || window.event;
        return evt.target || evt.srcElement;
    };
    addClass = function (e,c) {
        var re;
        if (!e.className) {
            e.className = c;
        }
        else {
            re = new RegExp('(^|\\s)' + c + '(\\s|$)');
            if (!re.test(e.className)) { e.className += ' ' + c; }
        }
    };
    removeClass = function (e,c) {
        var re, m, arr = (typeof c === "object") ? c.length : 1, len = arr;
        if (e.className) {
            if (e.className === c) {
                e.className = '';
            } else {
                while(arr--) {
                    re = new RegExp('(^|\\s)' + ((len > 1) ? c[arr] : c) + '(\\s|$)');
                    m = e.className.match(re);
                    if (m && m.length === 3) { e.className = e.className.replace(re, (m[1] && m[2])?' ':''); }
                }
            }
        }
    };
    isHostMethod = function(o, m) {
        var t = typeof o[m], reFeaturedMethod = new RegExp('^function|object$', 'i');
        return !!((reFeaturedMethod.test(t) && o[m]) || t === 'unknown');
    };
    /* Checking if one of the radio siblings is checked */
    isSiblingChecked = function(el) {
        var siblings = document.getElementsByName(el.name);
        for(var i=0; i<siblings.length; i++){
            if(siblings[i].checked){
                return true;
            }
        }
        return false;
    };

    // Since all methods are only used internally no need to expose globally
    return {
        setup: setup
    };

}));
<commit_msg>Remove the test form when submit event fires, removing it on invalid means that for browsers that don't have support still have a random form floating around in the DOM<commit_after>/*! H5F
* https://github.com/ryanseddon/H5F/
* Copyright (c) Ryan Seddon | Licensed MIT */

(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(factory);
    } else if (typeof module === 'object' && module.exports)  {
        // CommonJS
        module.exports = factory();
    } else {
        // Browser globals
        root.H5F = factory();
    }
}(this, function () {

    var d = document,
        field = d.createElement("input"),
        emailPatt = /^[a-zA-Z0-9.!#$%&'*+-\/=?\^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/,
        urlPatt = /[a-z][\-\.+a-z]*:\/\//i,
        nodes = /^(input|select|textarea)$/i,
        hasInteractiveFormValidation = false,
        isSubmit, bypassSubmit, usrPatt, curEvt, args,
        // Methods
        setup, validation, validity, checkField, bypassChecks, checkValidity, setCustomValidity, support, pattern, placeholder, range, required, valueMissing, listen, unlisten, preventActions, getTarget, addClass, removeClass, isHostMethod, isSiblingChecked;

    // Big shouts to Modernizr for this code.
    // create a hidden form to test for interactive validation
    var testForm = document.createElement('form');
    testForm.hidden = true;
    testForm.innerHTML = '<input name="test" required><button></button>';
    document.body.appendChild(testForm);

    testForm.addEventListener('submit', function (e) {
        document.body.removeChild(testForm);
        e.preventDefault();
        e.stopPropagation();
    }, false);

    var testInput = testForm.getElementsByTagName('input')[0];
    // Record whether "invalid" event is fired
    testInput.addEventListener('invalid', function (e) {
        hasInteractiveFormValidation = true;
        e.preventDefault();
        e.stopPropagation();
    }, false);

    // Submit form by clicking submit button
    testForm.getElementsByTagName('button')[0].click();

    setup = function(form, settings) {

        // don't do anything if the browser already has support
        if (hasInteractiveFormValidation) {
            return;
        }

        var isCollection = !form.nodeType || false;

        var opts = {
            validClass : "valid",
            invalidClass : "error",
            requiredClass : "required",
            placeholderClass : "placeholder",
            onSubmit : Function.prototype,
            onInvalid : Function.prototype
        };

        if(typeof settings === "object") {
            for (var i in opts) {
                if(typeof settings[i] === "undefined") { settings[i] = opts[i]; }
            }
        }

        args = settings || opts;

        if(isCollection) {
            for(var k=0,len=form.length;k<len;k++) {
                validation(form[k]);
            }
        } else {
            validation(form);
        }
    };

    validation = function(form) {
        var f = form.elements,
            flen = f.length,
            isRequired,
            noValidate = !!(form.attributes["novalidate"]);

        listen(form,"invalid",checkField,true);
        listen(form,"blur",checkField,true);
        listen(form,"input",checkField,true);
        listen(form,"keyup",checkField,true);
        listen(form,"focus",checkField,true);
        listen(form,"change",checkField,true);
        listen(form,"click",bypassChecks,true);

        listen(form,"submit",function(e){
            isSubmit = true;
            if(!bypassSubmit && !noValidate && !form.checkValidity()) {
                preventActions(e);
                return;
            }
            args.onSubmit.call(form, e);
        },false);

        if(!support()) {
            form.checkValidity = function() { return checkValidity(form); };

            while(flen--) {
                isRequired = !!(f[flen].attributes["required"]);
                // Firefox includes fieldsets inside elements nodelist so we filter it out.
                if(f[flen].nodeName.toLowerCase() !== "fieldset") {
                    validity(f[flen]); // Add validity object to field
                }
            }
        }

    };
    validity = function(el) {
        var elem = el,
            missing = valueMissing(elem),
            attrs = {
                type: elem.getAttribute("type"),
                pattern: elem.getAttribute("pattern"),
                placeholder: elem.getAttribute("placeholder")
            },
            isType = /^(email|url)$/i,
            evt = /^(input|keyup)$/i,
            fType = ((isType.test(attrs.type)) ? attrs.type : ((attrs.pattern) ? attrs.pattern : false)),
            patt = pattern(elem,fType),
            step = range(elem,"step"),
            min = range(elem,"min"),
            max = range(elem,"max"),
            customError = !( elem.validationMessage === "" || elem.validationMessage === undefined );

        elem.checkValidity = function() { return checkValidity.call(this,elem); };
        elem.setCustomValidity = function(msg) { setCustomValidity.call(elem,msg); };

        elem.validity = {
            valueMissing: missing,
            patternMismatch: patt,
            rangeUnderflow: min,
            rangeOverflow: max,
            stepMismatch: step,
            customError: customError,
            valid: (!missing && !patt && !step && !min && !max && !customError)
        };

        if(attrs.placeholder && !evt.test(curEvt)) { placeholder(elem); }
    };
    checkField = function(e) {
        var el = getTarget(e) || e, // checkValidity method passes element not event
            events = /^(input|keyup|focusin|focus|change)$/i,
            ignoredTypes = /^(submit|image|button|reset)$/i,
            specialTypes = /^(checkbox|radio)$/i,
            checkForm = true;

        if(nodes.test(el.nodeName) && !(ignoredTypes.test(el.type) || ignoredTypes.test(el.nodeName))) {
            curEvt = e.type;

            if(!support()) {
                validity(el);
            }

            if(el.validity.valid && (el.value !== "" || specialTypes.test(el.type)) || (el.value !== el.getAttribute("placeholder") && el.validity.valid)) {
                removeClass(el,[args.invalidClass,args.requiredClass]);
                addClass(el,args.validClass);
            } else if(!events.test(curEvt)) {
                if(el.validity.valueMissing) {
                    removeClass(el,[args.invalidClass,args.validClass]);
                    addClass(el,args.requiredClass);
                } else if(!el.validity.valid) {
                    removeClass(el,[args.validClass,args.requiredClass]);
                    addClass(el,args.invalidClass);
                }
            } else if(el.validity.valueMissing) {
                removeClass(el,[args.requiredClass,args.invalidClass,args.validClass]);
            }
            if(curEvt === "input" && checkForm) {
                // If input is triggered remove the keyup event
                unlisten(el.form,"keyup",checkField,true);
                checkForm = false;
            }
        }
    };
    checkValidity = function(el) {
        var f, ff, isDisabled, isRequired, hasPattern, invalid = false;

        if(el.nodeName.toLowerCase() === "form") {
            f = el.elements;

            for(var i = 0,len = f.length;i < len;i++) {
                ff = f[i];

                isDisabled = !!(ff.attributes["disabled"]);
                isRequired = !!(ff.attributes["required"]);
                hasPattern = !!(ff.attributes["pattern"]);

                if(ff.nodeName.toLowerCase() !== "fieldset" && !isDisabled && (isRequired || hasPattern && isRequired)) {
                    checkField(ff);
                    if(!ff.validity.valid && !invalid) {
                        if(isSubmit) { // If it's not a submit event the field shouldn't be focused
                            ff.focus();
                        }
                        invalid = true;
                        args.onInvalid.call(el, ff);
                    }
                }
            }
            return !invalid;
        } else {
            checkField(el);
            return el.validity.valid;
        }
    };
    setCustomValidity = function(msg) {
        var el = this;

        el.validationMessage = msg;
    };

    bypassChecks = function(e) {
        // handle formnovalidate attribute
        var el = getTarget(e);

        if(el.attributes["formnovalidate"] && el.type === "submit") {
            bypassSubmit = true;
        }
    };

    support = function() {
        return (isHostMethod(field,"validity") && isHostMethod(field,"checkValidity"));
    };

    // Create helper methods to emulate attributes in older browsers
    pattern = function(el, type) {
        if(type === "email") {
            return !emailPatt.test(el.value);
        } else if(type === "url") {
            return !urlPatt.test(el.value);
        } else if(!type) {
            return false;
        } else {
            var placeholder = el.getAttribute("placeholder"),
                val = el.value;

            usrPatt = new RegExp('^(?:' + type + ')$');

            if(val === placeholder) {
                return false;
            } else if(val === "") {
                return false;
            } else {
                return !usrPatt.test(el.value);
            }
        }
    };
    placeholder = function(el) {
        var attrs = { placeholder: el.getAttribute("placeholder") },
            focus = /^(focus|focusin|submit)$/i,
            node = /^(input|textarea)$/i,
            ignoredType = /^password$/i,
            isNative = !!("placeholder" in field);

        if(!isNative && node.test(el.nodeName) && !ignoredType.test(el.type)) {
            if(el.value === "" && !focus.test(curEvt)) {
                el.value = attrs.placeholder;
                listen(el.form,'submit', function () {
                  curEvt = 'submit';
                  placeholder(el);
                }, true);
                addClass(el,args.placeholderClass);
            } else if(el.value === attrs.placeholder && focus.test(curEvt)) {
                el.value = "";
                removeClass(el,args.placeholderClass);
            }
        }
    };
    range = function(el, type) {
        // Emulate min, max and step
        var min = parseInt(el.getAttribute("min"),10) || 0,
            max = parseInt(el.getAttribute("max"),10) || false,
            step = parseInt(el.getAttribute("step"),10) || 1,
            val = parseInt(el.value,10),
            mismatch = (val-min)%step;

        if(!valueMissing(el) && !isNaN(val)) {
            if(type === "step") {
                return (el.getAttribute("step")) ? (mismatch !== 0) : false;
            } else if(type === "min") {
                return (el.getAttribute("min")) ? (val < min) : false;
            } else if(type === "max") {
                return (el.getAttribute("max")) ? (val > max) : false;
            }
        } else if(el.getAttribute("type") === "number") {
            return true;
        } else {
            return false;
        }
    };
    required = function(el) {
        var required = !!(el.attributes["required"]);

        return (required) ? valueMissing(el) : false;
    };
    valueMissing = function(el) {
        var placeholder = el.getAttribute("placeholder"),
            specialTypes = /^(checkbox|radio)$/i,
            isRequired = !!(el.attributes["required"]);
        return !!(isRequired && (el.value === "" || el.value === placeholder || (specialTypes.test(el.type) && !isSiblingChecked(el))));
    };

    /* Util methods */
    listen = function (node,type,fn,capture) {
        if(isHostMethod(window,"addEventListener")) {
            /* FF & Other Browsers */
            node.addEventListener( type, fn, capture );
        } else if(isHostMethod(window,"attachEvent") && typeof window.event !== "undefined") {
            /* Internet Explorer way */
            if(type === "blur") {
                type = "focusout";
            } else if(type === "focus") {
                type = "focusin";
            }
            node.attachEvent( "on" + type, fn );
        }
    };
    unlisten = function (node,type,fn,capture) {
        if(isHostMethod(window,"removeEventListener")) {
            /* FF & Other Browsers */
            node.removeEventListener( type, fn, capture );
        } else if(isHostMethod(window,"detachEvent") && typeof window.event !== "undefined") {
            /* Internet Explorer way */
            node.detachEvent( "on" + type, fn );
        }
    };
    preventActions = function (evt) {
        evt = evt || window.event;

        if(evt.stopImmediatePropagation && evt.preventDefault) {
            evt.stopImmediatePropagation();
            evt.preventDefault();
        } else {
            evt.cancelBubble = true;
            evt.returnValue = false;
        }
    };
    getTarget = function (evt) {
        evt = evt || window.event;
        return evt.target || evt.srcElement;
    };
    addClass = function (e,c) {
        var re;
        if (!e.className) {
            e.className = c;
        }
        else {
            re = new RegExp('(^|\\s)' + c + '(\\s|$)');
            if (!re.test(e.className)) { e.className += ' ' + c; }
        }
    };
    removeClass = function (e,c) {
        var re, m, arr = (typeof c === "object") ? c.length : 1, len = arr;
        if (e.className) {
            if (e.className === c) {
                e.className = '';
            } else {
                while(arr--) {
                    re = new RegExp('(^|\\s)' + ((len > 1) ? c[arr] : c) + '(\\s|$)');
                    m = e.className.match(re);
                    if (m && m.length === 3) { e.className = e.className.replace(re, (m[1] && m[2])?' ':''); }
                }
            }
        }
    };
    isHostMethod = function(o, m) {
        var t = typeof o[m], reFeaturedMethod = new RegExp('^function|object$', 'i');
        return !!((reFeaturedMethod.test(t) && o[m]) || t === 'unknown');
    };
    /* Checking if one of the radio siblings is checked */
    isSiblingChecked = function(el) {
        var siblings = document.getElementsByName(el.name);
        for(var i=0; i<siblings.length; i++){
            if(siblings[i].checked){
                return true;
            }
        }
        return false;
    };

    // Since all methods are only used internally no need to expose globally
    return {
        setup: setup
    };

}));
<|endoftext|>


<commit_before>/**
 * Provides requestAnimationFrame in a cross browser way.
 * @author greggman / http://greggman.com/
 */

if ( !window.requestAnimationFrame ) {

	window.requestAnimationFrame = ( function() {

		return window.requestAnimationFrame ||
		window.webkitRequestAnimationFrame ||
		window.mozRequestAnimationFrame ||
		window.oRequestAnimationFrame ||
		window.msRequestAnimationFrame ||
		function( /* function FrameRequestCallback */ callback, /* DOMElement Element */ element ) {

			window.setTimeout( callback, 1000 / 60 );

		};

	} )();

}
<commit_msg>Simpler RequestAnimationFrame.js<commit_after>/**
 * Provides requestAnimationFrame in a cross browser way.
 * @author greggman / http://greggman.com/
 */

if ( !window.requestAnimationFrame ) {

	window.requestAnimationFrame = ( function() {

		return window.webkitRequestAnimationFrame ||
		window.mozRequestAnimationFrame ||
		window.oRequestAnimationFrame ||
		window.msRequestAnimationFrame ||
		function( /* function FrameRequestCallback */ callback, /* DOMElement Element */ element ) {

			window.setTimeout( callback, 1000 / 60 );

		};

	} )();

}
<|endoftext|>


<commit_before>import { <%= name.toUpperCase() %>_PATH as path } from 'constants'

export default store => ({
  path,
  /*  Async getComponent is only invoked when route matches   */
  getComponent(nextState, cb) {
    /*  Webpack - use 'require.ensure' to create a split point
        and embed an async module loader (jsonp) when bundling   */
    require.ensure(
      [],
      require => {
        /*  Webpack - use require callback to define
          dependencies for bundling   */
        const <%= name %> = require('./components/<%= name %>Page').default

        /*  Return getComponent   */
        cb(null, <%= name %>)

        /* Webpack named bundle   */
      },
      '<%= name %>'
    )
  }
})
<commit_msg>Router matches <%= name %> instead <%= name %>page<commit_after>import { <%= name.toUpperCase() %>_PATH as path } from 'constants'

export default store => ({
  path,
  /*  Async getComponent is only invoked when route matches   */
  getComponent(nextState, cb) {
    /*  Webpack - use 'require.ensure' to create a split point
        and embed an async module loader (jsonp) when bundling   */
    require.ensure(
      [],
      require => {
        /*  Webpack - use require callback to define
          dependencies for bundling   */
        const <%= name %> = require('./components/<%= name %>').default

        /*  Return getComponent   */
        cb(null, <%= name %>)

        /* Webpack named bundle   */
      },
      '<%= name %>'
    )
  }
})
<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * HSTS is HTTPS Strict Transport Security: a way for sites to elect to always
 * use HTTPS. See http://dev.chromium.org/sts
 *
 * This UI allows a user to query and update the browser's list of HSTS domains.

 *  @constructor
 */
function HSTSView() {
  const mainBoxId = 'hsts-view-tab-content';
  const queryInputId = 'hsts-view-query-input';
  const formId = 'hsts-view-query-form';
  const queryOutputDivId = 'hsts-view-query-output';
  const addInputId = 'hsts-view-add-input';
  const addFormId = 'hsts-view-add-form';
  const addCheckId = 'hsts-view-check-input';
  const addPinsId = 'hsts-view-add-pins';
  const deleteInputId = 'hsts-view-delete-input';
  const deleteFormId = 'hsts-view-delete-form';

  DivView.call(this, mainBoxId);

  this.queryInput_ = $(queryInputId);
  this.addCheck_ = $(addCheckId);
  this.addInput_ = $(addInputId);
  this.addPins_ = $(addPinsId);
  this.deleteInput_ = $(deleteInputId);
  this.queryOutputDiv_ = $(queryOutputDivId);

  var form = $(formId);
  form.addEventListener('submit', this.onSubmitQuery_.bind(this), false);
  form = $(addFormId);
  form.addEventListener('submit', this.onSubmitAdd_.bind(this), false);
  form = $(deleteFormId);
  form.addEventListener('submit', this.onSubmitDelete_.bind(this), false);

  g_browser.addHSTSObserver(this);
}

inherits(HSTSView, DivView);

HSTSView.prototype.onSubmitQuery_ = function(event) {
  g_browser.sendHSTSQuery(this.queryInput_.value);
  event.preventDefault();
};

HSTSView.prototype.onSubmitAdd_ = function(event) {
  g_browser.sendHSTSAdd(this.addInput_.value,
                        this.addCheck_.checked,
                        this.addPins_.value);
  g_browser.sendHSTSQuery(this.addInput_.value);
  this.queryInput_.value = this.addInput_.value;
  this.addCheck_.checked = false;
  this.addInput_.value = '';
  this.addPins_.value = '';
  event.preventDefault();
};

HSTSView.prototype.onSubmitDelete_ = function(event) {
  g_browser.sendHSTSDelete(this.deleteInput_.value);
  this.deleteInput_.value = '';
  event.preventDefault();
};

function hstsModeToString(m) {
  if (m == 0) {
    return 'STRICT';
  } else if (m == 1) {
    return 'OPPORTUNISTIC';
  } else if (m == 2) {
    return 'SPDY';
  } else if (m == 3) {
    return 'NONE';
  } else {
    return 'UNKNOWN';
  }
}

function yellowFade(element) {
  element.style.webkitTransitionProperty = 'background-color';
  element.style.webkitTransitionDuration = '0';
  element.style.backgroundColor = '#fffccf';
  setTimeout(function() {
    element.style.webkitTransitionDuration = '1000ms';
    element.style.backgroundColor = '#fff';
  }, 0);
}

HSTSView.prototype.onHSTSQueryResult = function(result) {
  if (result.error != undefined) {
    this.queryOutputDiv_.innerHTML = '';
    s = addNode(this.queryOutputDiv_, 'span');
    s.textContent = result.error;
    s.style.color = 'red';
    yellowFade(this.queryOutputDiv_);
    return;
  }

  if (result.result == false) {
    this.queryOutputDiv_.innerHTML = 'Not found';
    yellowFade(this.queryOutputDiv_);
    return;
  }

  this.queryOutputDiv_.innerHTML = '';

  s = addNode(this.queryOutputDiv_, 'span');
  s.innerHTML = 'Found: mode: ';

  t = addNode(this.queryOutputDiv_, 'tt');
  t.textContent = hstsModeToString(result.mode);

  addTextNode(this.queryOutputDiv_, ' include_subdomains:');

  t = addNode(this.queryOutputDiv_, 'tt');
  t.textContent = result.subdomains;

  addTextNode(this.queryOutputDiv_, ' domain:');

  t = addNode(this.queryOutputDiv_, 'tt');
  t.textContent = result.domain;

  addTextNode(this.queryOutputDiv_, ' is_preloaded:');

  t = addNode(this.queryOutputDiv_, 'tt');
  t.textContent = result.preloaded;

  addTextNode(this.queryOutputDiv_, ' pubkey_hashes:');

  t = addNode(this.queryOutputDiv_, 'tt');
  t.textContent = result.public_key_hashes;

  yellowFade(this.queryOutputDiv_);
}
<commit_msg>Refactor HSTSView to be defined inside an anonymous namespace. <commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * HSTS is HTTPS Strict Transport Security: a way for sites to elect to always
 * use HTTPS. See http://dev.chromium.org/sts
 *
 * This UI allows a user to query and update the browser's list of HSTS domains.
 */

var HSTSView = (function() {
  // IDs for special HTML elements in hsts_view.html
  const MAIN_BOX_ID = 'hsts-view-tab-content';
  const QUERY_INPUT_ID = 'hsts-view-query-input';
  const FORM_ID = 'hsts-view-query-form';
  const QUERY_OUTPUT_DIV_ID = 'hsts-view-query-output';
  const ADD_INPUT_ID = 'hsts-view-add-input';
  const ADD_FORM_ID = 'hsts-view-add-form';
  const ADD_CHECK_ID = 'hsts-view-check-input';
  const ADD_PINS_ID = 'hsts-view-add-pins';
  const DELETE_INPUT_ID = 'hsts-view-delete-input';
  const DELETE_FORM_ID = 'hsts-view-delete-form';

  // We inherit from DivView.
  var superClass = DivView;

  /**
   * @constructor
   */
  function HSTSView() {
    // Call superclass's constructor.
    superClass.call(this, MAIN_BOX_ID);

    this.queryInput_ = $(QUERY_INPUT_ID);
    this.addCheck_ = $(ADD_CHECK_ID);
    this.addInput_ = $(ADD_INPUT_ID);
    this.addPins_ = $(ADD_PINS_ID);
    this.deleteInput_ = $(DELETE_INPUT_ID);
    this.queryOutputDiv_ = $(QUERY_OUTPUT_DIV_ID);

    var form = $(FORM_ID);
    form.addEventListener('submit', this.onSubmitQuery_.bind(this), false);
    form = $(ADD_FORM_ID);
    form.addEventListener('submit', this.onSubmitAdd_.bind(this), false);
    form = $(DELETE_FORM_ID);
    form.addEventListener('submit', this.onSubmitDelete_.bind(this), false);

    g_browser.addHSTSObserver(this);
  }

  cr.addSingletonGetter(HSTSView);

  HSTSView.prototype = {
    // Inherit the superclass's methods.
    __proto__: superClass.prototype,

    onSubmitQuery_: function(event) {
      g_browser.sendHSTSQuery(this.queryInput_.value);
      event.preventDefault();
    },

    onSubmitAdd_: function(event) {
      g_browser.sendHSTSAdd(this.addInput_.value,
                            this.addCheck_.checked,
                            this.addPins_.value);
      g_browser.sendHSTSQuery(this.addInput_.value);
      this.queryInput_.value = this.addInput_.value;
      this.addCheck_.checked = false;
      this.addInput_.value = '';
      this.addPins_.value = '';
      event.preventDefault();
    },

    onSubmitDelete_: function(event) {
      g_browser.sendHSTSDelete(this.deleteInput_.value);
      this.deleteInput_.value = '';
      event.preventDefault();
    },

    onHSTSQueryResult: function(result) {
      if (result.error != undefined) {
        this.queryOutputDiv_.innerHTML = '';
        s = addNode(this.queryOutputDiv_, 'span');
        s.textContent = result.error;
        s.style.color = 'red';
        yellowFade(this.queryOutputDiv_);
        return;
      }

      if (result.result == false) {
        this.queryOutputDiv_.innerHTML = 'Not found';
        yellowFade(this.queryOutputDiv_);
        return;
      }

      this.queryOutputDiv_.innerHTML = '';

      s = addNode(this.queryOutputDiv_, 'span');
      s.innerHTML = 'Found: mode: ';

      t = addNode(this.queryOutputDiv_, 'tt');
      t.textContent = modeToString(result.mode);

      addTextNode(this.queryOutputDiv_, ' include_subdomains:');

      t = addNode(this.queryOutputDiv_, 'tt');
      t.textContent = result.subdomains;

      addTextNode(this.queryOutputDiv_, ' domain:');

      t = addNode(this.queryOutputDiv_, 'tt');
      t.textContent = result.domain;

      addTextNode(this.queryOutputDiv_, ' is_preloaded:');

      t = addNode(this.queryOutputDiv_, 'tt');
      t.textContent = result.preloaded;

      addTextNode(this.queryOutputDiv_, ' pubkey_hashes:');

      t = addNode(this.queryOutputDiv_, 'tt');
      t.textContent = result.public_key_hashes;

      yellowFade(this.queryOutputDiv_);
    }
  };

  function modeToString(m) {
    if (m == 0) {
      return 'STRICT';
    } else if (m == 1) {
      return 'OPPORTUNISTIC';
    } else if (m == 2) {
      return 'SPDY';
    } else if (m == 3) {
      return 'NONE';
    } else {
      return 'UNKNOWN';
    }
  }

  function yellowFade(element) {
    element.style.webkitTransitionProperty = 'background-color';
    element.style.webkitTransitionDuration = '0';
    element.style.backgroundColor = '#fffccf';
    setTimeout(function() {
      element.style.webkitTransitionDuration = '1000ms';
      element.style.backgroundColor = '#fff';
    }, 0);
  }

  return HSTSView;
})();
<|endoftext|>


<commit_before>import NativePromise from 'native-promise-only';
import Formio from './Formio';
import Webform from './Webform';
import { fastCloneDeep, eachComponent } from './utils/utils';

export default class PDF extends Webform {
  constructor(element, options) {
    super(element, options);
    this.components = [];
  }

  init() {
    super.init();

    // Handle an iframe submission.
    this.on('iframe-submission', (submission) => this.setValue(submission, {
      fromIframe: true
    }), true);

    this.on('iframe-change', (submission) => this.setValue(submission, {
      fromIframe: true
    }), true);

    this.on('iframe-getIframePositions', () => {
      const iframeBoundingClientRect = document.querySelector('iframe').getBoundingClientRect();
      this.postMessage({
        name: 'iframePositions',
        data: {
          iframe: {
            top: iframeBoundingClientRect.top
          },
          scrollY: window.scrollY || window.pageYOffset
        }
      });
    });

    // Trigger when this form is ready.
    this.on('iframe-ready', () => this.iframeReadyResolve(), true);
  }

  render() {
    this.submitButton = this.addComponent({
      input: true,
      type: 'button',
      action: 'submit',
      internal: true,
      label: 'Submit',
      key: 'submit',
      ref: 'button',
      hidden: this.checkSubmitButtonHiddenness()
    });

    return this.renderTemplate('pdf', {
      submitButton: this.submitButton.render(),
      classes: 'formio-form-pdf',
      children: this.renderComponents()
    });
  }

  redraw() {
    this.postMessage({ name: 'redraw' });
    return this.builderMode ? NativePromise.resolve() : super.redraw();
  }

  rebuild() {
    if (this.builderMode && this.component.components) {
      this.destroyComponents();
      this.addComponents();
      return NativePromise.resolve();
    }
    this.postMessage({ name: 'redraw' });
    return super.rebuild();
  }

  attach(element) {
    return super.attach(element).then(() => {
      this.loadRefs(element, {
        button: 'single',
        buttonMessageContainer: 'single',
        buttonMessage: 'single',
        zoomIn: 'single',
        zoomOut: 'single',
        iframeContainer: 'single'
      });
      this.submitButton.refs = { ...this.refs };
      this.submitButton.attachButton();

      // Reset the iframeReady promise.
      this.iframeReady = new NativePromise((resolve, reject) => {
        this.iframeReadyResolve = resolve;
        this.iframeReadyReject = reject;
      });

      // iframes cannot be in the template so manually create it
      this.iframeElement = this.ce('iframe', {
        src: this.getSrc(),
        id: `iframe-${this.id}`,
        seamless: true,
        class: 'formio-iframe'
      });

      this.iframeElement.formioContainer = this.component.components;
      this.iframeElement.formioComponent = this;

      // Append the iframe to the iframeContainer in the template
      this.empty(this.refs.iframeContainer);
      this.appendChild(this.refs.iframeContainer, this.iframeElement);

      // Post the form to the iframe
      this.postMessage({ name: 'form', data: this.form });

      // Hide the submit button if the associated component is hidden
      const submitButton = this.components.find(c => c.element === this.refs.button);
      if (submitButton) {
        this.refs.button.classList.toggle('hidden', !submitButton.visible);
      }

      this.addEventListener(this.refs.zoomIn, 'click', (event) => {
        event.preventDefault();
        this.postMessage({ name: 'zoomIn' });
      });

      this.addEventListener(this.refs.zoomOut, 'click', (event) => {
        event.preventDefault();
        this.postMessage({ name: 'zoomOut' });
      });

      const form = fastCloneDeep(this.form);
      if (this.formio) {
        form.projectUrl = this.formio.projectUrl;
        form.url = this.formio.formUrl;
        form.base = this.formio.base;
        this.postMessage({ name: 'token', data: this.formio.getToken() });
      }

      this.emit('attach');
    });
  }

  /**
   * Get the submission from the iframe.
   *
   * @return {Promise<any>}
   */
  getSubmission() {
    return new NativePromise((resolve) => {
      this.once('iframe-submission', resolve);
      this.postMessage({ name: 'getSubmission' });
    });
  }

  /**
   * Ensure we have the submission from the iframe before we submit the form.
   *
   * @param options
   * @return {*}
   */
  submitForm(options = {}) {
    this.postMessage({ name: 'getErrors' });
    return this.getSubmission().then(() => super.submitForm(options));
  }

  getSrc() {
    if (!this._form || !this._form.settings || !this._form.settings.pdf) {
      return '';
    }

    let iframeSrc = `${this._form.settings.pdf.src}.html`;
    const params = [`id=${this.id}`];

    if (this.options.readOnly) {
      params.push('readonly=1');
    }

    if (this.options.zoom) {
      params.push(`zoom=${this.options.zoom}`);
    }

    if (this.builderMode) {
      params.push('builder=1');
    }

    if (params.length) {
      iframeSrc += `?${params.join('&')}`;
    }

    return iframeSrc;
  }

  setForm(form) {
    if (this.builderMode && this.form.components) {
      this.postMessage({ name: 'form', data: this.form });
      return NativePromise.resolve();
    }
    return super.setForm(form).then(() => {
      if (this.formio) {
        form.projectUrl = this.formio.projectUrl;
        form.url = this.formio.formUrl;
        form.base = this.formio.base;
        this.postMessage({ name: 'token', data: this.formio.getToken() });
      }
      this.postMessage({ name: 'form', data: form });
    });
  }

  /**
   * Set's the value of this form component.
   *
   * @param submission
   * @param flags
   */
  setValue(submission, flags = {}) {
    const changed = super.setValue(submission, flags);
    if (!flags || !flags.fromIframe) {
      this.once('iframe-ready', () => {
        this.postMessage({ name: 'submission', data: submission });
      });
    }
    return changed;
  }

  setSubmission(submission) {
    submission.readOnly = !!this.options.readOnly;
    return super.setSubmission(submission).then(() => {
      if (this.formio) {
        this.formio.getDownloadUrl().then((url) => {
          // Add a download button if it has a download url.
          if (!url) {
            return;
          }
          if (!this.downloadButton) {
            if (this.options.primaryProject) {
              url += `&project=${this.options.primaryProject}`;
            }
            this.downloadButton = this.ce('a', {
              href: url,
              target: '_blank',
              style: 'position:absolute;right:10px;top:110px;cursor:pointer;'
            }, this.ce('img', {
              src: require('./pdf.image'),
              style: 'width:3em;'
            }));
            this.element.insertBefore(this.downloadButton, this.iframe);
          }
        });
      }
    });
  }

  postMessage(message) {
    // If we get here before the iframeReady promise is set up, it's via the superclass constructor
    if (!this.iframeReady) {
      return;
    }

    if (!message.type) {
      message.type = 'iframe-data';
    }

    this.iframeReady.then(() => {
      if (this.iframeElement && this.iframeElement.contentWindow) {
        this.iframeElement.contentWindow.postMessage(JSON.stringify(message), '*');
      }
    });
  }

  focusOnComponent(key) {
    this.postMessage({
      name: 'focusErroredField',
      data: key,
    });
  }

  // Do not clear the iframe.
  clear() {}

  showErrors(error, triggerEvent) {
    const helpBlock = document.getElementById('submit-error');

    if (!helpBlock && this.errors.length) {
      const p = this.ce('p', { class: 'help-block' });

      this.setContent(p, this.t('submitError'));
      p.addEventListener('click', () => {
        window.scrollTo(0, 0);
      });

      const div = this.ce('div', { id: 'submit-error', class: 'has-error' });

      this.appendTo(p, div);
      this.appendTo(div, this.element);
    }

    if (!this.errors.length && helpBlock) {
      helpBlock.remove();
    }

    super.showErrors(error, triggerEvent);
  }

  checkSubmitButtonHiddenness() {
    let hidden = false;
    eachComponent(this.component.components, (component) => {
      if (
        (component.type === 'button') &&
        ((component.action === 'submit') || !component.action)
      ) {
        hidden = component.hidden || false;
      }
    });

    return hidden;
  }
}

/**
 * Listen for window messages.
 */
window.addEventListener('message', (event) => {
  let eventData = null;
  try {
    eventData = JSON.parse(event.data);
  }
  catch (err) {
    eventData = null;
  }

  // If this form exists, then emit the event within this form.
  if (
    eventData &&
    eventData.name &&
    eventData.formId &&
    Formio.forms.hasOwnProperty(eventData.formId)
  ) {
    Formio.forms[eventData.formId].emit(`iframe-${eventData.name}`, eventData.data);
  }
});
<commit_msg>Fixed redirection after hitting the pdf submit button<commit_after>import NativePromise from 'native-promise-only';
import Formio from './Formio';
import Webform from './Webform';
import { fastCloneDeep, eachComponent } from './utils/utils';

export default class PDF extends Webform {
  constructor(element, options) {
    super(element, options);
    this.components = [];
  }

  init() {
    super.init();

    // Handle an iframe submission.
    this.on('iframe-submission', (submission) => this.setValue(submission, {
      fromIframe: true
    }), true);

    this.on('iframe-change', (submission) => this.setValue(submission, {
      fromIframe: true
    }), true);

    this.on('iframe-getIframePositions', () => {
      const iframeBoundingClientRect = document.querySelector('iframe').getBoundingClientRect();
      this.postMessage({
        name: 'iframePositions',
        data: {
          iframe: {
            top: iframeBoundingClientRect.top
          },
          scrollY: window.scrollY || window.pageYOffset
        }
      });
    });

    // Trigger when this form is ready.
    this.on('iframe-ready', () => this.iframeReadyResolve(), true);
  }

  render() {
    this.submitButton = this.addComponent({
      input: true,
      type: 'button',
      action: 'submit',
      internal: true,
      label: 'Submit',
      key: 'submit',
      ref: 'button',
      hidden: this.checkSubmitButtonHiddenness()
    });

    return this.renderTemplate('pdf', {
      submitButton: this.submitButton.render(),
      classes: 'formio-form-pdf',
      children: this.renderComponents()
    });
  }

  redraw() {
    this.postMessage({ name: 'redraw' });
    return this.builderMode ? NativePromise.resolve() : super.redraw();
  }

  rebuild() {
    if (this.builderMode && this.component.components) {
      this.destroyComponents();
      this.addComponents();
      return NativePromise.resolve();
    }
    this.postMessage({ name: 'redraw' });
    return super.rebuild();
  }

  attach(element) {
    return super.attach(element).then(() => {
      this.loadRefs(element, {
        button: 'single',
        buttonMessageContainer: 'single',
        buttonMessage: 'single',
        zoomIn: 'single',
        zoomOut: 'single',
        iframeContainer: 'single'
      });
      this.submitButton.refs = { ...this.refs };
      this.submitButton.attachButton();

      // Reset the iframeReady promise.
      this.iframeReady = new NativePromise((resolve, reject) => {
        this.iframeReadyResolve = resolve;
        this.iframeReadyReject = reject;
      });

      // iframes cannot be in the template so manually create it
      this.iframeElement = this.ce('iframe', {
        src: this.getSrc(),
        id: `iframe-${this.id}`,
        seamless: true,
        class: 'formio-iframe'
      });

      this.iframeElement.formioContainer = this.component.components;
      this.iframeElement.formioComponent = this;

      // Append the iframe to the iframeContainer in the template
      this.empty(this.refs.iframeContainer);
      this.appendChild(this.refs.iframeContainer, this.iframeElement);

      // Post the form to the iframe
      this.postMessage({ name: 'form', data: this.form });

      // Hide the submit button if the associated component is hidden
      const submitButton = this.components.find(c => c.element === this.refs.button);
      if (submitButton) {
        this.refs.button.classList.toggle('hidden', !submitButton.visible);
      }

      this.addEventListener(this.refs.zoomIn, 'click', (event) => {
        event.preventDefault();
        this.postMessage({ name: 'zoomIn' });
      });

      this.addEventListener(this.refs.zoomOut, 'click', (event) => {
        event.preventDefault();
        this.postMessage({ name: 'zoomOut' });
      });

      const form = fastCloneDeep(this.form);
      if (this.formio) {
        form.projectUrl = this.formio.projectUrl;
        form.url = this.formio.formUrl;
        form.base = this.formio.base;
        this.postMessage({ name: 'token', data: this.formio.getToken() });
      }

      this.emit('attach');
    });
  }

  /**
   * Get the submission from the iframe.
   *
   * @return {Promise<any>}
   */
  getSubmission() {
    return new NativePromise((resolve) => {
      this.once('iframe-submission', resolve);
      this.postMessage({ name: 'getSubmission' });
    });
  }

  /**
   * Ensure we have the submission from the iframe before we submit the form.
   *
   * @param options
   * @return {*}
   */
  submitForm(options = {}) {
    this.postMessage({ name: 'getErrors' });
    return this.getSubmission().then(() => super.submitForm(options));
  }

  getSrc() {
    if (!this._form || !this._form.settings || !this._form.settings.pdf) {
      return '';
    }

    let iframeSrc = `${this._form.settings.pdf.src}.html`;
    const params = [`id=${this.id}`];

    if (this.options.readOnly) {
      params.push('readonly=1');
    }

    if (this.options.zoom) {
      params.push(`zoom=${this.options.zoom}`);
    }

    if (this.builderMode) {
      params.push('builder=1');
    }

    if (params.length) {
      iframeSrc += `?${params.join('&')}`;
    }

    return iframeSrc;
  }

  setForm(form) {
    if (this.builderMode && this.form.components) {
      this.postMessage({ name: 'form', data: this.form });
      return NativePromise.resolve();
    }
    return super.setForm(form).then(() => {
      if (this.formio) {
        form.projectUrl = this.formio.projectUrl;
        form.url = this.formio.formUrl;
        form.base = this.formio.base;
        this.postMessage({ name: 'token', data: this.formio.getToken() });
      }
      this.postMessage({ name: 'form', data: form });
    });
  }

  /**
   * Set's the value of this form component.
   *
   * @param submission
   * @param flags
   */
  setValue(submission, flags = {}) {
    const changed = super.setValue(submission, flags);
    if (!flags || !flags.fromIframe) {
      this.once('iframe-ready', () => {
        this.postMessage({ name: 'submission', data: submission });
      });
    }
    return changed;
  }

  setSubmission(submission) {
    submission.readOnly = !!this.options.readOnly;
    return super.setSubmission(submission).then(() => {
      if (this.formio) {
        this.formio.getDownloadUrl().then((url) => {
          // Add a download button if it has a download url.
          if (!url) {
            return;
          }
          if (!this.downloadButton) {
            if (this.options.primaryProject) {
              url += `&project=${this.options.primaryProject}`;
            }
            this.downloadButton = this.ce('a', {
              href: url,
              target: '_blank',
              style: 'position:absolute;right:10px;top:110px;cursor:pointer;'
            }, this.ce('img', {
              src: require('./pdf.image'),
              style: 'width:3em;'
            }));
            this.element.insertBefore(this.downloadButton, this.iframe);
          }
        });
      }
    });
  }

  setAlert(type, message, classes) {
    super.setAlert(type, message, classes);

    const buttonTop = this.refs.button.offsetTop;
    window.scrollTo(0, buttonTop);
  }

  postMessage(message) {
    // If we get here before the iframeReady promise is set up, it's via the superclass constructor
    if (!this.iframeReady) {
      return;
    }

    if (!message.type) {
      message.type = 'iframe-data';
    }

    this.iframeReady.then(() => {
      if (this.iframeElement && this.iframeElement.contentWindow) {
        this.iframeElement.contentWindow.postMessage(JSON.stringify(message), '*');
      }
    });
  }

  focusOnComponent(key) {
    this.postMessage({
      name: 'focusErroredField',
      data: key,
    });
  }

  // Do not clear the iframe.
  clear() {}

  showErrors(error, triggerEvent) {
    const helpBlock = document.getElementById('submit-error');

    if (!helpBlock && this.errors.length) {
      const p = this.ce('p', { class: 'help-block' });

      this.setContent(p, this.t('submitError'));
      p.addEventListener('click', () => {
        window.scrollTo(0, 0);
      });

      const div = this.ce('div', { id: 'submit-error', class: 'has-error' });

      this.appendTo(p, div);
      this.appendTo(div, this.element);
    }

    if (!this.errors.length && helpBlock) {
      helpBlock.remove();
    }

    super.showErrors(error, triggerEvent);
  }

  checkSubmitButtonHiddenness() {
    let hidden = false;
    eachComponent(this.component.components, (component) => {
      if (
        (component.type === 'button') &&
        ((component.action === 'submit') || !component.action)
      ) {
        hidden = component.hidden || false;
      }
    });

    return hidden;
  }
}

/**
 * Listen for window messages.
 */
window.addEventListener('message', (event) => {
  let eventData = null;
  try {
    eventData = JSON.parse(event.data);
  }
  catch (err) {
    eventData = null;
  }

  // If this form exists, then emit the event within this form.
  if (
    eventData &&
    eventData.name &&
    eventData.formId &&
    Formio.forms.hasOwnProperty(eventData.formId)
  ) {
    Formio.forms[eventData.formId].emit(`iframe-${eventData.name}`, eventData.data);
  }
});
<|endoftext|>


<commit_before>import {FunctionInstance} from './command.js';
import {If, Condition} from './conditionals.js';
import {Loop} from './loops.js';
import store from '../store.jsx';
import {MoveXLeft, MoveXRight, MoveYUp, MoveYDown, Speak, CollectStar} from './konvaUtils.js';

export function storeCmd (func, command, parent = null) {
  let commandInstance;
  if (command.commandId === 0) commandInstance = new MoveYUp(); //MoveUp
  else if (command.commandId === 1) commandInstance = new MoveYDown(); //Move Down
  else if (command.commandId === 2) commandInstance = new MoveXLeft(); //MoveLeft
  else if (command.commandId === 3) commandInstance = new MoveXRight(); //MoveRight
  else if (command.commandId === 4) commandInstance = new CollectStar(); //Speak
  else if (command.commandId === 5) commandInstance = new If(new Condition(command.condition)); //If
  else if (command.commandId === 6) commandInstance = new Loop(); //Loop
  else if (command.commandId === 7) commandInstance = new CollectStar(); //CollectStar

  if (parent) parent.then(commandInstance)
  else func.storeCommand(commandInstance)
  return commandInstance;
}

export function mapStateToCmdObj(func = new FunctionInstance(), program = store.getState().commands.procedure, parent = null) {
  if (parent || program.length){
    program.forEach(command => {
      let parentCmd = storeCmd(func, command, parent)
      let nested = command.children;
      if (nested) return mapStateToCmdObj(func, nested, parentCmd);
      else return mapStateToCmdObj(func, program.slice(1));
    });
  }
  return func;
}
<commit_msg>Update mapStateToCmdObj.js<commit_after>import {FunctionInstance} from './command.js';
import {If, Condition} from './conditionals.js';
import {Loop} from './loops.js';
import store from '../store.jsx';
import {MoveXLeft, MoveXRight, MoveYUp, MoveYDown, Speak, CollectStar} from './konvaUtils.js';

export function storeCmd (func, command, parent = null) {
  let commandInstance;
  if (command.commandId === 0) commandInstance = new MoveYUp(); //MoveUp
  else if (command.commandId === 1) commandInstance = new MoveYDown(); //Move Down
  else if (command.commandId === 2) commandInstance = new MoveXLeft(); //MoveLeft
  else if (command.commandId === 3) commandInstance = new MoveXRight(); //MoveRight
  else if (command.commandId === 4) commandInstance = new Speak('pig'); //Speak
  else if (command.commandId === 5) commandInstance = new If(new Condition(command.condition)); //If
  else if (command.commandId === 6) commandInstance = new Loop(); //Loop
  else if (command.commandId === 7) commandInstance = new CollectStar(); //CollectStar

  if (parent) parent.then(commandInstance)
  else func.storeCommand(commandInstance)
  return commandInstance;
}

export function mapStateToCmdObj(func = new FunctionInstance(), program = store.getState().commands.procedure, parent = null) {
  if (parent || program.length){
    program.forEach(command => {
      let parentCmd = storeCmd(func, command, parent)
      let nested = command.children;
      if (nested) return mapStateToCmdObj(func, nested, parentCmd);
      else return mapStateToCmdObj(func, program.slice(1));
    });
  }
  return func;
}
<|endoftext|>


<commit_before>/**
*
* ToolsComponents
*
*/

import React from 'react';
import styled from 'styled-components';
import { ThemeProvider } from 'styled-components';
import { Link } from 'react-router';
import { FormattedMessage } from 'react-intl';

import ContentBlock from 'components/ContentBlock';
import Isvg from 'react-inlinesvg';

import messages from './messages';

import { TYPE_STORIES, TYPE_TACTICS, TYPE_PRINCIPLES,
          TYPE_THEORIES, TYPE_METHODOLOGIES } from './constants';

import RealWorldIconImage from 'assets/images/icons/real-world.svg';

function ToolsComponents() {
  return (

      <FormattedMessage {...messages.header} />

  );
}

ToolsComponents.propTypes = {

};

export const getToolTypeColor = (type) => {
  switch(type) {
    case TYPE_STORIES:
      return "#08eb8c";
    case TYPE_TACTICS:
      return "#ff9200";
    case TYPE_PRINCIPLES:
      return "#166ce3";
    case TYPE_THEORIES:
      return "#f93732";
    case TYPE_METHODOLOGIES:
      return "#b700c2";
  }
}

/*** START OF TOOLS ICONS ***/
export const RealWorldIcon = styled(Isvg)`
  svg {
    fill: ${props=>props.type ? getToolTypeColor(props.type) : 'red'};

    .circle {
      fill: black;
    }
  }
`;

export const PotentialRiskIcon = styled(Isvg)`
  svg {
    fill: ${props=>props.type ? getToolTypeColor(props.type) : 'red'};
  }
`;
/*** END OF TOOLS ICONS ***/

export const ToolsButton = styled.button`
  outline: none;
  cursor: pointer;
  ${p => p.color ? `color: ${p.color};` : ''}
  font-weight: bold;
  padding: 0;
  img { margin-right: 10px;}
  display: inline-block;
  ${
    props=> {
      if (props.lang&&props.lang==='ar') {
        return `transform: ${props.toShow&&props.rotate ? 'rotate(0)' : 'rotate(180deg)'};`
      } else {
        return `transform: ${props.toShow&&props.rotate ? 'rotate(180deg)' : 'rotate(0)'};`
      }
    }
  }

  transition:  transform 0.4s ease;

  text-transform: uppercase;

  svg, svg * {
    fill: ${props=>props.color ? props.color : (props.toShow ? 'black' : '#828486')};
    width: ${props=>props.width || 'auto'};
    transition:  fill 0.4s ease;
  }
`;
export const ToolsListMenu = styled.ul`
    padding: 0;
    padding: 10px 0 10px;
    border-bottom: 2px solid black;
    margin: 0;
    display: ${props=>props.show?'block':'none'};

    & > li:first-child {
      ${props=>props.lang==='ar' ? 'border-left' : 'border-right'}: 2px solid;
    }
`;
export const ToolsListMenuItem = styled.li`
  list-style: none;
  display: inline-block;
  width: 49%;
  text-align: center;
`;

export const ToolType = styled.h3`
  margin: 0;
  font-size: ${p=>p.ar?'35px':'20px'};
  letter-spacing: ${p=>p.ar?'3px':'0'};
  padding-top: 20px;
  font-family: 'Paint Hand', 'Massira Spray', serif;
  color: ${props => getToolTypeColor(props.type) };
`;

export const ToolTitle = styled.h1`
  font-size: 32px;
  letter-spacing: 1px;
  font-weight: normal;
  margin: 0;
  font-size: ${p=>p.ar?'30px':'30px'};
  line-height: ${p=>p.ar?'40px':'1'};
  > a {
    color: ${props=>props.color || 'black'};
  }
  color: ${props=>props.color || 'black'};
`;
export const ToolsList = styled.ul`
padding: 0 0 0 5px;
margin: 0;
`;
export const ToolsListItem = styled.li`
  list-style: none;
  margin: 10px;
  border-top: 2px solid;

  &:first-child {
    border: none;
  }
`;

export const ToolsMenu = styled.ul`
  width: 73px;
  float: ${props=>props.theme.lang === 'ar' ? 'right' : 'left'};
  height: 100%;
  margin: 0;
  padding: 20px 0;
  border: solid black;
  border-width: ${props=>props.theme.lang === 'ar' ? '0 0 0 2px' : '0 2px 0 0'};
`;
export const ToolsMenuItem = styled.li`
  list-style: none;
  margin: 10px 0 20px;
  .isvg {
    &::after {
      content: ' ';
      display: block;
      clear: both;
    }
  }
`;

export const ToolsListContainer = styled.div``;
export const ToolsViewport = styled.div`
    ${(props) => props.showTools ? '350px' : '75px' };
height: 100%;`;

export const ToolsContainer = styled.div`
  position: fixed;

  width: ${(props) => props.showTools ? '350px' : '75px' };
  height: calc(100vh - 170px);
  border: 2px solid black;
  top: 93px;

  ${props=>props.theme.lang == 'ar' ? 'left: 50%' : 'right: 50%;'}
  transform: translateX(${(props) => props.showTools ?
      (props=>props.theme.lang == 'ar' ? '-685px' : '685px') :
      (props=>props.theme.lang == 'ar' ? '-640px' : '640px') });
  transition: transform 0.3s ease, width 0.3s ease;
  overflow-x: hidden;
  overflow-y: hidden;
  `;

export const ToolContainer = styled.div`
  ${props=>props.lang==='ar' ? 'float: right' : 'float: left'};
  margin-right: 10px;
  margin-bottom: 10px;
  text-align: left;
`;
export const ToolViewport = styled.div`
  margin: 0;
  padding: 0;
`
// Block View
export const BlockContainer = styled(ToolContainer)`
  background-image: ${props => props.background};
  background-size: cover;
  background-position: center;
  width: 250px;
  height: 250px;
  margin: 10px;
  margin-${p=>p.lang==='ar'?'right':'left'}: 17px;
  margin-${p=>p.lang==='ar'?'left':'right'}: 2px;
  margin-bottom: 10px;
  margin-top: 10px;
`;
export const BlockViewport = styled(ToolViewport)`
  background-color: rgba(0,0,0,0.5);
  padding: 10px;
  width: 100%;
  height: 100%;
  position: relative;
`;
export const BlockSpiel = styled(ContentBlock)`
  color: ${props=>getToolTypeColor(props.type)};
  position: absolute;
  top: 0;
  left: 0;
  padding: 10px;
  font-weight: 800;
  opacity: ${props=>props.show?(props.forceShow?'0':'1'):'0'};
  transition: opacity 0.2s;
`;

export const BlockViewTitleArea = styled.div`
  position: absolute;
  left: 10px;
  padding-right: 10px;
  z-index: 100;
  width: calc(100% - 10px);
  opacity: ${props=>props.show ? '1': (props.forceShow?'1':'0')};
  transition: opacity 0.2s;
`;
export const BlockAddRem = styled.div`
`;

//List View
export const ListContainer = styled(ToolContainer)`
  width: 48%;
  height: 190px;
  text-align: left;

`;

export const ListViewport = styled(ToolViewport)`
  background-color: none;
  padding: 0 10px 0 50px;
  position: relative;

  &::before{
    content: ' ';
    width: 53px;
    height: 1px;
    border-bottom: 2px solid;
    position: absolute;
    top: 0px;
    left: 50px;
  }

  h3 {
    padding-top: 5px;
  }
`;
export const ListSpiel = styled.p`
  margin: 0;
  font-size: 12px;
`;
export const ListDivider = styled.h3`
  color: black;
  border-color: black;
  border-width: 2px;
  margin-top: 0px;
  width: 60px;
`;
export default ToolsComponents;
<commit_msg>Tool list view fix<commit_after>/**
*
* ToolsComponents
*
*/

import React from 'react';
import styled from 'styled-components';
import { ThemeProvider } from 'styled-components';
import { Link } from 'react-router';
import { FormattedMessage } from 'react-intl';

import ContentBlock from 'components/ContentBlock';
import Isvg from 'react-inlinesvg';

import messages from './messages';

import { TYPE_STORIES, TYPE_TACTICS, TYPE_PRINCIPLES,
          TYPE_THEORIES, TYPE_METHODOLOGIES } from './constants';

import RealWorldIconImage from 'assets/images/icons/real-world.svg';

function ToolsComponents() {
  return (

      <FormattedMessage {...messages.header} />

  );
}

ToolsComponents.propTypes = {

};

export const getToolTypeColor = (type) => {
  switch(type) {
    case TYPE_STORIES:
      return "#08eb8c";
    case TYPE_TACTICS:
      return "#ff9200";
    case TYPE_PRINCIPLES:
      return "#166ce3";
    case TYPE_THEORIES:
      return "#f93732";
    case TYPE_METHODOLOGIES:
      return "#b700c2";
  }
}

/*** START OF TOOLS ICONS ***/
export const RealWorldIcon = styled(Isvg)`
  svg {
    fill: ${props=>props.type ? getToolTypeColor(props.type) : 'red'};

    .circle {
      fill: black;
    }
  }
`;

export const PotentialRiskIcon = styled(Isvg)`
  svg {
    fill: ${props=>props.type ? getToolTypeColor(props.type) : 'red'};
  }
`;
/*** END OF TOOLS ICONS ***/

export const ToolsButton = styled.button`
  outline: none;
  cursor: pointer;
  ${p => p.color ? `color: ${p.color};` : ''}
  font-weight: bold;
  padding: 0;
  img { margin-right: 10px;}
  display: inline-block;
  ${
    props=> {
      if (props.lang&&props.lang==='ar') {
        return `transform: ${props.toShow&&props.rotate ? 'rotate(0)' : 'rotate(180deg)'};`
      } else {
        return `transform: ${props.toShow&&props.rotate ? 'rotate(180deg)' : 'rotate(0)'};`
      }
    }
  }

  transition:  transform 0.4s ease;

  text-transform: uppercase;

  svg, svg * {
    fill: ${props=>props.color ? props.color : (props.toShow ? 'black' : '#828486')};
    width: ${props=>props.width || 'auto'};
    transition:  fill 0.4s ease;
  }
`;
export const ToolsListMenu = styled.ul`
    padding: 0;
    padding: 10px 0 10px;
    border-bottom: 2px solid black;
    margin: 0;
    display: ${props=>props.show?'block':'none'};

    & > li:first-child {
      ${props=>props.lang==='ar' ? 'border-left' : 'border-right'}: 2px solid;
    }
`;
export const ToolsListMenuItem = styled.li`
  list-style: none;
  display: inline-block;
  width: 49%;
  text-align: center;
`;

export const ToolType = styled.h3`
  margin: 0;
  font-size: ${p=>p.ar?'35px':'20px'};
  letter-spacing: ${p=>p.ar?'3px':'0'};
  padding-top: 20px;
  font-family: 'Paint Hand', 'Massira Spray', serif;
  color: ${props => getToolTypeColor(props.type) };
`;

export const ToolTitle = styled.h1`
  font-size: 32px;
  letter-spacing: 1px;
  font-weight: normal;
  margin: 0;
  font-size: ${p=>p.ar?'30px':'30px'};
  line-height: ${p=>p.ar?'40px':'1'};
  > a {
    color: ${props=>props.color || 'black'};
  }
  color: ${props=>props.color || 'black'};
`;
export const ToolsList = styled.ul`
padding: 0 0 0 5px;
margin: 0;
`;
export const ToolsListItem = styled.li`
  list-style: none;
  margin: 10px;
  border-top: 2px solid;

  &:first-child {
    border: none;
  }
`;

export const ToolsMenu = styled.ul`
  width: 73px;
  float: ${props=>props.theme.lang === 'ar' ? 'right' : 'left'};
  height: 100%;
  margin: 0;
  padding: 20px 0;
  border: solid black;
  border-width: ${props=>props.theme.lang === 'ar' ? '0 0 0 2px' : '0 2px 0 0'};
`;
export const ToolsMenuItem = styled.li`
  list-style: none;
  margin: 10px 0 20px;
  .isvg {
    &::after {
      content: ' ';
      display: block;
      clear: both;
    }
  }
`;

export const ToolsListContainer = styled.div``;
export const ToolsViewport = styled.div`
    ${(props) => props.showTools ? '350px' : '75px' };
height: 100%;`;

export const ToolsContainer = styled.div`
  position: fixed;

  width: ${(props) => props.showTools ? '350px' : '75px' };
  height: calc(100vh - 170px);
  border: 2px solid black;
  top: 93px;

  ${props=>props.theme.lang == 'ar' ? 'left: 50%' : 'right: 50%;'}
  transform: translateX(${(props) => props.showTools ?
      (props=>props.theme.lang == 'ar' ? '-685px' : '685px') :
      (props=>props.theme.lang == 'ar' ? '-640px' : '640px') });
  transition: transform 0.3s ease, width 0.3s ease;
  overflow-x: hidden;
  overflow-y: hidden;
  `;

export const ToolContainer = styled.div`
  ${props=>props.lang==='ar' ? 'float: right' : 'float: left'};
  margin-right: 10px;
  margin-bottom: 10px;
  text-align: left;
`;
export const ToolViewport = styled.div`
  margin: 0;
  padding: 0;
`
// Block View
export const BlockContainer = styled(ToolContainer)`
  background-image: ${props => props.background};
  background-size: cover;
  background-position: center;
  width: 250px;
  height: 250px;
  margin: 10px;
  margin-${p=>p.lang==='ar'?'right':'left'}: 17px;
  margin-${p=>p.lang==='ar'?'left':'right'}: 2px;
  margin-bottom: 10px;
  margin-top: 10px;
`;
export const BlockViewport = styled(ToolViewport)`
  background-color: rgba(0,0,0,0.5);
  padding: 10px;
  width: 100%;
  height: 100%;
  position: relative;
`;
export const BlockSpiel = styled(ContentBlock)`
  color: ${props=>getToolTypeColor(props.type)};
  position: absolute;
  top: 0;
  left: 0;
  padding: 10px;
  font-weight: 800;
  opacity: ${props=>props.show?(props.forceShow?'0':'1'):'0'};
  transition: opacity 0.2s;
`;

export const BlockViewTitleArea = styled.div`
  position: absolute;
  left: 10px;
  padding-right: 10px;
  z-index: 100;
  width: calc(100% - 10px);
  opacity: ${props=>props.show ? '1': (props.forceShow?'1':'0')};
  transition: opacity 0.2s;
`;
export const BlockAddRem = styled.div`
`;

//List View
export const ListContainer = styled(ToolContainer)`
  width: 48%;
  height: 190px;
  text-align: left;

`;

export const ListViewport = styled(ToolViewport)`
  background-color: none;
  padding: 0 10px 0 50px;
  position: relative;

  &::before{
    content: ' ';
    width: 53px;
    height: 1px;
    border-bottom: 2px solid;
    position: absolute;
    top: 0px;
    ${p=>p.theme.isArabic?'right: 9px;':'left: 50px;'};
  }

  h3 {
    padding-top: 5px;
  }
`;
export const ListSpiel = styled.p`
  margin: 0;
  font-size: 12px;
`;
export const ListDivider = styled.h3`
  color: black;
  border-color: black;
  border-width: 2px;
  margin-top: 0px;
  width: 60px;
`;
export default ToolsComponents;
<|endoftext|>


<commit_before>/* global Buildkite */

import React from 'react';
import PropTypes from 'prop-types';
import CreateReactClass from 'create-react-class';

import Emojify from '../../shared/Emojify';
import Icon from '../../shared/Icon';

import jobCommandOneliner from '../../../lib/jobCommandOneliner';

const { BuildHeaderPipelineManualStepComponent, BuildHeaderPipelineTriggerStepComponent } = Buildkite;

const BuildHeaderPipelineComponent = CreateReactClass({
  mixins: [Buildkite.BootstrapTooltipMixin],

  getInitialState() {
    return { showBroken: false };
  },

  propTypes: {
    build: PropTypes.object.isRequired
  },

  render() {
    const brokenJobs = this.brokenJobCount();
    const action = this.state.showBroken ? "Hide" : "Show";
    const icon = this.state.showBroken ? "eye-strikethrough" : "eye";
    const suffix = brokenJobs > 1 ? "jobs" : "job";

    const toggleBrokenNode = brokenJobs > 0
      ? (
        <button
          className="btn dark-gray hover-black regular mt0 ml0 pt0 pl0"
          onClick={this.handleToggleBrokenStepsClick}
        >
          <div
            title={`${action} ${brokenJobs} skipped ${suffix}`}
            data-toggle="tooltip"
            data-animation="false"
          >
            <Icon icon={icon} className="relative" style={{ top: -3 }} />

        </button>
      )
      : null;

    return (

          {this.stepNodes()}

          {toggleBrokenNode}

    );
  },

  brokenJobCount() {
    return this.props.build.jobs
      .filter((job) => (
        (job.state === 'broken') && (job.type !== 'waiter')
      )).length;
  },

  stepNodes() {
    if (this.props.build.jobs.length === 0) {
      return (

          There are no build steps for this pipeline. To add a step, go to your Pipeline Settings.

      );
    }

    const jobs = this.state.showBroken
      ? this.props.build.jobs
      : this.props.build.jobs.filter(({ state }) => state !== "broken");

    return jobs.map((job) => this.pipelineStep(job));
  },

  pipelineStep(job) {
    const stepClassName = this.stepClassName(job);

    if (job.type === "script") {
      if (job.state === "broken") {
        return (

            {this.jobName(job)}

        );
      }

      const href = `${this.props.build.path}#${job.id}`;

      return (

          {this.jobName(job)}

      );
    } else if (job.type === "waiter") {
      if (job.continueOnFailure) {
        return (
          <div
            key={job.id}
            className={`${stepClassName} dark-gray relative`}
            title="Wait for all previous steps to finish including failures"
          >

            <Icon icon="chevron-right" style={{ height: 15, width: 15 }} />

        );
      }

      return (
        <div
          key={job.id}
          className={`${stepClassName} dark-gray`}
          title="Wait for all previous steps to pass"
        >
          <Icon icon="chevron-right" style={{ height: 15, width: 15 }} />

      );
    } else if (job.type === "manual") {
      return (
        <BuildHeaderPipelineManualStepComponent
          key={job.id}
          build={this.props.build}
          job={job}
          stepClassName={stepClassName}
        />
      );
    } else if (job.type === "trigger") {
      return (
        <BuildHeaderPipelineTriggerStepComponent
          key={job.id}
          build={this.props.build}
          job={job}
          stepClassName={stepClassName}
        />
      );
    }

    return (

        {job.type}

    );
  },

  stepClassName(job) {
    const state = job.state === 'finished' && (job.type === 'script' || job.type === 'trigger')
      ? (
        job.passed
          ? 'passed'
          : 'failed'
      )
      : job.state;

    return [
      'build-pipeline-job',
      `build-pipeline-job-${job.type.replace(/_/g, '-')}`,
      `build-pipeline-state-${state}`,
      'truncate',
      'align-middle'
    ].join(' ');
  },

  handleScriptJobClick(job) {
    return function(evt) {
      // return if the user did a middle-click, right-click, or used a modifier
      // key (like ctrl-click, meta-click, shift-click, etc.)
      if ((evt.button !== 0) || evt.altKey || evt.ctrlKey || evt.metaKey || evt.shiftKey) {
        return;
      }

      evt.preventDefault();
      return Buildkite.NewDispatcher.handleViewAction({ actionType: "JOB_TOGGLE", job, source: "BUILD_HEADER" });
    };
  },

  jobName(job) {
    if (job.name) {
      return <Emojify text={job.name} />;
    }

    return (

        {jobCommandOneliner(job.command)}

    );
  },

  handleToggleBrokenStepsClick(evt) {
    evt.preventDefault();
    evt.target.blur();
    return this.setState({ showBroken: !this.state.showBroken });
  }
});

export default BuildHeaderPipelineComponent;<commit_msg>No this really does need to be at render time<commit_after>/* global Buildkite */

import React from 'react';
import PropTypes from 'prop-types';
import CreateReactClass from 'create-react-class';

import Emojify from '../../shared/Emojify';
import Icon from '../../shared/Icon';

import jobCommandOneliner from '../../../lib/jobCommandOneliner';

const BuildHeaderPipelineComponent = CreateReactClass({
  displayName: 'BuildHeaderPipelineComponent',

  mixins: [Buildkite.BootstrapTooltipMixin],

  getInitialState() {
    return { showBroken: false };
  },

  propTypes: {
    build: PropTypes.object.isRequired
  },

  render() {
    const brokenJobs = this.brokenJobCount();
    const action = this.state.showBroken ? "Hide" : "Show";
    const icon = this.state.showBroken ? "eye-strikethrough" : "eye";
    const suffix = brokenJobs > 1 ? "jobs" : "job";

    const toggleBrokenNode = brokenJobs > 0
      ? (
        <button
          className="btn dark-gray hover-black regular mt0 ml0 pt0 pl0"
          onClick={this.handleToggleBrokenStepsClick}
        >
          <div
            title={`${action} ${brokenJobs} skipped ${suffix}`}
            data-toggle="tooltip"
            data-animation="false"
          >
            <Icon icon={icon} className="relative" style={{ top: -3 }} />

        </button>
      )
      : null;

    return (

          {this.stepNodes()}

          {toggleBrokenNode}

    );
  },

  brokenJobCount() {
    return this.props.build.jobs
      .filter((job) => (
        (job.state === 'broken') && (job.type !== 'waiter')
      )).length;
  },

  stepNodes() {
    if (this.props.build.jobs.length === 0) {
      return (

          There are no build steps for this pipeline. To add a step, go to your Pipeline Settings.

      );
    }

    const jobs = this.state.showBroken
      ? this.props.build.jobs
      : this.props.build.jobs.filter(({ state }) => state !== "broken");

    return jobs.map((job) => this.pipelineStep(job));
  },

  pipelineStep(job) {
    const stepClassName = this.stepClassName(job);

    const { BuildHeaderPipelineManualStepComponent, BuildHeaderPipelineTriggerStepComponent } = Buildkite;

    if (job.type === "script") {
      if (job.state === "broken") {
        return (

            {this.jobName(job)}

        );
      }

      const href = `${this.props.build.path}#${job.id}`;

      return (

          {this.jobName(job)}

      );
    } else if (job.type === "waiter") {
      if (job.continueOnFailure) {
        return (
          <div
            key={job.id}
            className={`${stepClassName} dark-gray relative`}
            title="Wait for all previous steps to finish including failures"
          >

            <Icon icon="chevron-right" style={{ height: 15, width: 15 }} />

        );
      }

      return (
        <div
          key={job.id}
          className={`${stepClassName} dark-gray`}
          title="Wait for all previous steps to pass"
        >
          <Icon icon="chevron-right" style={{ height: 15, width: 15 }} />

      );
    } else if (job.type === "manual") {
      return (
        <BuildHeaderPipelineManualStepComponent
          key={job.id}
          build={this.props.build}
          job={job}
          stepClassName={stepClassName}
        />
      );
    } else if (job.type === "trigger") {
      return (
        <BuildHeaderPipelineTriggerStepComponent
          key={job.id}
          build={this.props.build}
          job={job}
          stepClassName={stepClassName}
        />
      );
    }

    return (

        {job.type}

    );
  },

  stepClassName(job) {
    const state = job.state === 'finished' && (job.type === 'script' || job.type === 'trigger')
      ? (
        job.passed
          ? 'passed'
          : 'failed'
      )
      : job.state;

    return [
      'build-pipeline-job',
      `build-pipeline-job-${job.type.replace(/_/g, '-')}`,
      `build-pipeline-state-${state}`,
      'truncate',
      'align-middle'
    ].join(' ');
  },

  handleScriptJobClick(job) {
    return function(evt) {
      // return if the user did a middle-click, right-click, or used a modifier
      // key (like ctrl-click, meta-click, shift-click, etc.)
      if ((evt.button !== 0) || evt.altKey || evt.ctrlKey || evt.metaKey || evt.shiftKey) {
        return;
      }

      evt.preventDefault();
      return Buildkite.NewDispatcher.handleViewAction({ actionType: "JOB_TOGGLE", job, source: "BUILD_HEADER" });
    };
  },

  jobName(job) {
    if (job.name) {
      return <Emojify text={job.name} />;
    }

    return (

        {jobCommandOneliner(job.command)}

    );
  },

  handleToggleBrokenStepsClick(evt) {
    evt.preventDefault();
    evt.target.blur();
    return this.setState({ showBroken: !this.state.showBroken });
  }
});

export default BuildHeaderPipelineComponent;
<|endoftext|>


<commit_before>/*
 *
 * ToolPage
 *
 */

import React, { PropTypes } from 'react';
import Markdown from 'react-markdown';
import { Link } from 'react-router';
import { connect } from 'react-redux';
import { FormattedMessage } from 'react-intl';
import { createStructuredSelector } from 'reselect';
import { RouterLink } from 'utils/markdown';
import ToolSnapshotArea from 'components/ToolSnapshotArea';
import LanguageThemeProvider from 'components/LanguageThemeProvider';
import AdderRemover from 'containers/Tools/AdderRemover';
import { BorderedButton } from 'components/CommonComponents';
import { ToolMainArea,
         ToolMainContent,
         ToolReadShortContent,
         ToolReadFullContent } from 'components/ToolsPageComponents';

import ToolHowToUse from 'components/ToolHowToUse';
import ToolWhyItWorked from 'components/ToolWhyItWorked';
import ToolWhyItFailed from 'components/ToolWhyItFailed';
import ToolKeyItems from 'components/ToolKeyItems';
import ToolEpigraph from 'components/ToolEpigraph';
import ToolWithPullQuote from 'components/ToolWithPullQuote';
// import { makeSelectToolById } from 'containers/Tool/selectors';
import ToolLearnMore from './ToolLearnMore';
import ToolRealWorld from './ToolRealWorld';
import ToolUntranslated from './ToolUntranslated';
import { PROP_FULL_WRITE_UP, PROP_SHORT_WRITE_UP } from './constants';

import messages from './messages';

export class ToolPageMain extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function

  constructor(props) {
    super(props);
    this.state = {
      showFull: false
    }
  }

  componentWillReceiveProps(nextProps) {
    //Refresh if label is different
    if (nextProps.params.label !== this.props.params.label) {
      this.setState({ showFull: false });
    }
  }

  handleShowClick() {
    this.setState({ showFull : !this.state.showFull })
  }
  generateShortContent() {
    if (!this.props[PROP_SHORT_WRITE_UP] ) return null;
    return(
      <ToolReadShortContent>
        <Markdown
          source={this.props[PROP_SHORT_WRITE_UP].replace(/\(([^()]*?)\.jpg\)/g,"(https://www.beautifulrising.org/$1.jpg)") }
          renderers={{Link: RouterLink}}
        />
      </ToolReadShortContent>
    );
  }

  renderWithPullQuote(content) {
    const split = content.split('\n').filter(item => item !== "");
    return (<ToolWithPullQuote content={split} pullQuote={this.props['pull-quote']} />)
  }

  generateFullContent() {

    if (!this.props['full-write-up']) return null;

    const imageReplaced = this.props['full-write-up'].replace(/\(([^()]*?)\.jpg\)/g,"(https://www.beautifulrising.org/$1.jpg)");

    return(
      <ToolReadFullContent>
        <ToolEpigraph {...this.props}/>
        { this.props['pull-quote'] !== ''
            ? this.renderWithPullQuote(imageReplaced)
            : <Markdown
                source={imageReplaced}
                renderers={{Link: RouterLink}}
              />
        }
      </ToolReadFullContent>
    );
  }

  generateContent(){
    if (this.state.showFull) {
      return this.generateFullContent();
    } else {
      return this.generateShortContent();
    }
  }

  checkContentLength() {
    if( this.props.lang[PROP_FULL_WRITE_UP] ) {

      //Check translation status for Full Writeup
      if (
        !this.props.showIfUntranslated(PROP_FULL_WRITE_UP)
      ) return null;

      return (
        <ToolMainContent>
          {this.generateContent()}
          <BorderedButton onClick={this.handleShowClick.bind(this)}>
            {this.state.showFull
                ? (<FormattedMessage {...messages.showLess}/>)
                : (<FormattedMessage {...messages.showMore}/>) }
          </BorderedButton>
        </ToolMainContent>
      );
    } else {
      if (
        !this.props.showIfUntranslated(PROP_SHORT_WRITE_UP)
      ) return null;

      return (
        <ToolMainContent>
          {this.generateShortContent()}
        </ToolMainContent>
      )
    }
  }

  renderRealWorldExample() {
    if (this.props.type === 'story')
      return null;

    return (<ToolRealWorld {...this.props} />);
  }

  renderSnapshot() {

    return (
      <ToolSnapshotArea  {...this.props} />
    );
  }
  render() {
    // If snapshot, render the snapshot area...
    const snapshotArea = this.props['module-type'] === 'snapshot'
                          ? this.renderSnapshot() : null;

    return (
      <LanguageThemeProvider>
        <ToolMainArea>
            <ToolUntranslated {...this.props} />
            { this.checkContentLength()}
            <ToolHowToUse show={this.props.showIfUntranslated('how-to-use')} text={this.props['how-to-use']} />
            <ToolWhyItWorked show={this.props.showIfUntranslated('why-it-worked')} text={this.props['why-it-worked']} />
            <ToolWhyItFailed show={this.props.showIfUntranslated('why-it-failed')} text={this.props['why-it-failed']} />
            <ToolKeyItems
              keyTactics={this.props['key-modules'] ? this.props['key-modules']['key-tactics'] : []}
              keyPrinciples={this.props['key-modules'] ? this.props['key-modules']['key-principles']  : []}
              keyTheories={this.props['key-modules'] ? this.props['key-modules']['key-theories'] : [] }
              keyMethodologies={this.props['key-modules'] ? this.props['key-modules']['key-methodologies'] : [] }

              showTactics = { this.props.showIfUntranslated('key-tactics')}
              showPrinciples = { this.props.showIfUntranslated('key-principles')}
              showTheories = { this.props.showIfUntranslated('key-theories')}
              showMethodologies = { this.props.showIfUntranslated('key-methodologies')}
            />
            <ToolLearnMore {...this.props} />

            {snapshotArea}

            { this.renderRealWorldExample() }
        </ToolMainArea>
      </LanguageThemeProvider>
    );
  }
}

ToolPageMain.propTypes = {
  dispatch: PropTypes.func.isRequired,
};

function mapDispatchToProps(dispatch) {
  return {
    dispatch
  };
}

export default connect(null, mapDispatchToProps)(ToolPageMain);
<commit_msg>Fix for read more<commit_after>/*
 *
 * ToolPage
 *
 */

import React, { PropTypes } from 'react';
import Markdown from 'react-markdown';
import { Link } from 'react-router';
import { connect } from 'react-redux';
import { FormattedMessage } from 'react-intl';
import { createStructuredSelector } from 'reselect';
import { RouterLink } from 'utils/markdown';
import ToolSnapshotArea from 'components/ToolSnapshotArea';
import LanguageThemeProvider from 'components/LanguageThemeProvider';
import AdderRemover from 'containers/Tools/AdderRemover';
import { BorderedButton } from 'components/CommonComponents';
import { ToolMainArea,
         ToolMainContent,
         ToolReadShortContent,
         ToolReadFullContent } from 'components/ToolsPageComponents';

import ToolHowToUse from 'components/ToolHowToUse';
import ToolWhyItWorked from 'components/ToolWhyItWorked';
import ToolWhyItFailed from 'components/ToolWhyItFailed';
import ToolKeyItems from 'components/ToolKeyItems';
import ToolEpigraph from 'components/ToolEpigraph';
import ToolWithPullQuote from 'components/ToolWithPullQuote';
// import { makeSelectToolById } from 'containers/Tool/selectors';
import ToolLearnMore from './ToolLearnMore';
import ToolRealWorld from './ToolRealWorld';
import ToolUntranslated from './ToolUntranslated';
import { PROP_FULL_WRITE_UP, PROP_SHORT_WRITE_UP } from './constants';

import messages from './messages';

export class ToolPageMain extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function

  constructor(props) {
    super(props);
    this.state = {
      showFull: false
    }
  }

  componentWillReceiveProps(nextProps) {
    //Refresh if label is different
    if (nextProps.params.label !== this.props.params.label) {
      this.setState({ showFull: false });
    }
  }

  handleShowClick() {
    this.setState({ showFull : !this.state.showFull })
  }
  generateShortContent() {
    if (!this.props[PROP_SHORT_WRITE_UP] ) return null;
    return(
      <ToolReadShortContent>
        <Markdown
          source={this.props[PROP_SHORT_WRITE_UP].replace(/\(([^()]*?)\.jpg\)/g,"(https://www.beautifulrising.org/$1.jpg)") }
          renderers={{Link: RouterLink}}
        />
      </ToolReadShortContent>
    );
  }

  renderWithPullQuote(content) {
    const split = content.split('\n').filter(item => item !== "");
    return (<ToolWithPullQuote content={split} pullQuote={this.props['pull-quote']} />)
  }

  generateFullContent() {

    if (!this.props['full-write-up']) return null;

    const imageReplaced = this.props['full-write-up'].replace(/\(([^()]*?)\.jpg\)/g,"(https://www.beautifulrising.org/$1.jpg)");

    return(
      <ToolReadFullContent>
        <ToolEpigraph {...this.props}/>
        { this.props['pull-quote'] !== ''
            ? this.renderWithPullQuote(imageReplaced)
            : <Markdown
                source={imageReplaced}
                renderers={{Link: RouterLink}}
              />
        }
      </ToolReadFullContent>
    );
  }

  generateContent(){
    if (this.state.showFull) {
      return this.generateFullContent();
    } else {
      return this.generateShortContent();
    }
  }

  checkContentLength() {

    if( this.props.showIfUntranslated(PROP_FULL_WRITE_UP) && this.props['full-write-up'] ) {
      return (
        <ToolMainContent>
          {this.generateContent()}
          <BorderedButton onClick={this.handleShowClick.bind(this)}>
            {this.state.showFull
                ? (<FormattedMessage {...messages.showLess}/>)
                : (<FormattedMessage {...messages.showMore}/>) }
          </BorderedButton>
        </ToolMainContent>
      );
    } else {
      if (
        !this.props.showIfUntranslated(PROP_SHORT_WRITE_UP)
      ) return null;

      return (
        <ToolMainContent>
          {this.generateShortContent()}
        </ToolMainContent>
      )
    }
  }

  renderRealWorldExample() {
    if (this.props.type === 'story')
      return null;

    return (<ToolRealWorld {...this.props} />);
  }

  renderSnapshot() {

    return (
      <ToolSnapshotArea  {...this.props} />
    );
  }
  render() {
    // If snapshot, render the snapshot area...
    const snapshotArea = this.props['module-type'] === 'snapshot'
                          ? this.renderSnapshot() : null;

    return (
      <LanguageThemeProvider>
        <ToolMainArea>
            <ToolUntranslated {...this.props} />
            { this.checkContentLength()}
            <ToolHowToUse show={this.props.showIfUntranslated('how-to-use')} text={this.props['how-to-use']} />
            <ToolWhyItWorked show={this.props.showIfUntranslated('why-it-worked')} text={this.props['why-it-worked']} />
            <ToolWhyItFailed show={this.props.showIfUntranslated('why-it-failed')} text={this.props['why-it-failed']} />
            <ToolKeyItems
              keyTactics={this.props['key-modules'] ? this.props['key-modules']['key-tactics'] : []}
              keyPrinciples={this.props['key-modules'] ? this.props['key-modules']['key-principles']  : []}
              keyTheories={this.props['key-modules'] ? this.props['key-modules']['key-theories'] : [] }
              keyMethodologies={this.props['key-modules'] ? this.props['key-modules']['key-methodologies'] : [] }

              showTactics = { this.props.showIfUntranslated('key-tactics')}
              showPrinciples = { this.props.showIfUntranslated('key-principles')}
              showTheories = { this.props.showIfUntranslated('key-theories')}
              showMethodologies = { this.props.showIfUntranslated('key-methodologies')}
            />
            <ToolLearnMore {...this.props} />

            {snapshotArea}

            { this.renderRealWorldExample() }
        </ToolMainArea>
      </LanguageThemeProvider>
    );
  }
}

ToolPageMain.propTypes = {
  dispatch: PropTypes.func.isRequired,
};

function mapDispatchToProps(dispatch) {
  return {
    dispatch
  };
}

export default connect(null, mapDispatchToProps)(ToolPageMain);
<|endoftext|>


<commit_before>// @flow
import React, { Component } from 'react';
import AppBar from 'material-ui/AppBar';
import { observer } from 'mobx-react';
import WalletSendForm from '../../components/wallet/WalletSendForm';
import WalletNavigation from '../../components/wallet/navigation/WalletNavigation';
import wallet from '../../stores/walletStore';
import styles from './WalletSendPage.scss';

export default observer(class WalletSendPage extends Component {
  render() {
    return (

        <AppBar
          title="Daedalus"
          className={styles.appBar}
        />

        <WalletNavigation wallet={wallet} />

        <WalletSendForm />

    );
  }
});
<commit_msg>dont show the menu icon in the app bar for the mvp<commit_after>// @flow
import React, { Component } from 'react';
import AppBar from 'material-ui/AppBar';
import { observer } from 'mobx-react';
import WalletSendForm from '../../components/wallet/WalletSendForm';
import WalletNavigation from '../../components/wallet/navigation/WalletNavigation';
import wallet from '../../stores/walletStore';
import styles from './WalletSendPage.scss';

export default observer(class WalletSendPage extends Component {
  render() {
    return (

        <AppBar
          title="Daedalus"
          className={styles.appBar}
          showMenuIconButton={false}
        />

        <WalletNavigation wallet={wallet} />

        <WalletSendForm />

    );
  }
});
<|endoftext|>