<commit_before>goog.provide('lime.style');
goog.provide('lime.style.Transform');

goog.require('goog.dom');
goog.require('goog.style');
goog.require('lime.userAgent');

(function() {

var prefix = goog.userAgent.WEBKIT ? 'Webkit' :
             goog.userAgent.GECKO ? 'Moz' :
             goog.userAgent.OPERA ? 'O' :
             goog.userAgent.IE ? 'ms' : '';

var testDivStyle = goog.dom.createDom('div').style;

lime.style.transformProperty = '-' + prefix.toLowerCase() + '-transform';

/**
 * Try if a CSS style property with given name exists
 * @param {string} name Property name.
 * @return {boolean} If property exists.
 */
lime.style.tryProperty = function(name) {
    return testDivStyle[name] !== undefined ? name : false;
};

/**
 * Get the name of actual CSS property from general(unprefixed) name
 * @param {string} name Unprefixed name.
 * @return {string} Actual valid property name.
 */
lime.style.getCSSproperty = function(name) {
    var name_lower = name.charAt(0).toLowerCase() + name.substr(1);
    return lime.style.tryProperty(name) ?
        name : (lime.style.tryProperty(name_lower)  ? name_lower : lime.style.tryProperty(prefix + name));
};

/**
 * Set border radisu of a DOM element
 * @param {Element} el Element to change.
 * @param {Array.<number>} values Radius values.
 * @param {Array.<number>=} opt_vertical Vertical radius values.
 * @param {boolean=} opt_isPerc If values are given in percentages.
 */
lime.style.setBorderRadius = (function() {
    var stylename = lime.style.getCSSproperty('BorderRadius');
    var out = function(values, unit) {
        return (goog.isArray(values) ? values.join(unit + ' ') : values) + unit;
    };
    return function(el, values, opt_vertical, opt_isPerc) {
        var unit = opt_isPerc ? '%' : 'px';
        var vertical = goog.isDef(opt_vertical) ? opt_vertical : values;
        var value = out(values, unit) + '/' + out(vertical, unit);
        if (value != el.border_radius_cache_) {
            el.style[stylename] = el.border_radius_cache_ = value;
        }
    };
})();

// There are classes like CSSMatrix in some browsers.
// Maybe this would make more sense.

(function(){

/**
 * Object representing CSS Transform.
 * @constructor
 * @param {number=} opt_precision Default precision.
 */
lime.style.Transform = function(opt_precision) {
    this.values = [];
    this.precision = 1;
    if (this.opt_precision) {
        this.setPrecision(/** @type {number} */ (opt_precision));
    }
};

/**
 * Scale current transform object
 * @param {number} sx X-axis scale factor.
 * @param {number} sy y-axis scale factor.
 * @return {lime.style.Transform} obejct itself.
 */
lime.style.Transform.prototype.scale = function(sx, sy) {
    //if(sx!=1 && sy!=1)
    this.values.push('scale(' + sx + ',' + sy + ')');
    return this;
};

/**
 * Rotate current transform object
 * @param {number} angle Angle to rotate.
 * @param {string=} opt_unit Units.
 * @return {lime.style.Transform} obejct itself.
 */
lime.style.Transform.prototype.rotate = function(angle, opt_unit) {
    var rot_str = 'rotate(' + angle + (opt_unit ? opt_unit : 'deg') + ')';
    if (angle != 0)
        this.values.push(rot_str);

    return this;
};

/**
 * Translate(move) current transform object
 * @param {number} tx Offset in x-axis.
 * @param {number} ty Offset in y-axis.
 * @param {number=} opt_tz Offset in z-axis.
 * @return {lime.style.Transform} obejct itself.
 */
lime.style.Transform.prototype.translate = function(tx, ty, opt_tz) {

    var p = 1 / this.precision;
    var val = 'translate';
    if (lime.userAgent.IOS) val += '3d';
    val += '(' + (tx * p) + 'px,' + (ty * p) + 'px';
    if (lime.userAgent.IOS) val += ',' + ((opt_tz ? opt_tz : 0) * p) + 'px';
    this.values.push(val + ')');

    return this;
};

/**
 * Set the current precision of transform. This is handled as a
 * state machine so its added when called not when done.
 * @param {number} p Precision(Lowest value to make a difference).
 * @return {lime.style.Transform} obejct itself.
 */
lime.style.Transform.prototype.setPrecision = function(p) {
    if (this.precision != 1) {
        var opposite = 1 / this.precision;
        this.scale(opposite, opposite);
        this.precision = 1;
    }
    if (p != 1) {
        this.scale(p, p);
        this.precision = p;
    }
    return this;
};

/**
 * Return CSS transform string from the obejct
 * @return {string} CSS value string.
 */
lime.style.Transform.prototype.toString = function() {
    if (this.precision != 1) {
        this.setPrecision(1);
    }
    return this.values.join(' ');
};

/**
 * Set transform to a DOM element.
 * @param {Element} el Element to change.
 * @param {lime.style.Transform} transform Transform.
 */
lime.style.setTransform = (function() {
    var stylename = lime.style.getCSSproperty('Transform');
    return function(el, transform) {
        var value = transform.toString();

        if (value != el.transform_cache_) {
            el.style[stylename] = el.transform_cache_ = value;
        }
        lime.transformSet_=1;

    };
})();

})();

/**
 * Set transform origin point for a DOM element.
 * @param {Element} el Element to change.
 * @param {number} ox X Offset.
 * @param {number} oy Y Offset.
 * @param {boolean=} opt_isPerc If unit is percentage.
 */
lime.style.setTransformOrigin = (function() {
    var stylename = lime.style.getCSSproperty('TransformOrigin');
    return function(el, ox, oy, opt_isPerc) {
        var unit = opt_isPerc ? '%' : 'px';
        var value = ox + unit + ' ' + oy + unit;
        if (value != el.transform_origin_cache_) {
            el.style[stylename] = el.transform_origin_cache_ = value;
        }
    };
})();

var stylename = lime.style.getCSSproperty('Transition');
lime.style.isTransitionsSupported = !!stylename && !goog.userAgent.OPERA;
// Opera's CSS3 transitions seem to be unstable atm. No shorthand plus
// doesn't work if the duration property has not been previously set inside
// CSS style sheet @tonis

var clearProp = function(str, prop) {
    if (!str.length) return str;
    var proplist = str.split('),');
    for (var i = 0; i < proplist.length - 1; i++) {
        proplist[i] += ')';
    }

    proplist = goog.array.filter(proplist, function(part) {
               return part.indexOf(prop) == -1;
   });
    return proplist.join(',');
};

/**
 * Activate transition rule for a property
 * @param {Element} el Element to change.
 * @param {string} property Transition property name.
 * @param {number} time Transition duration.
 * @param {lime.animation.EasingFunction} ease Easing function.
 */
lime.style.setTransition = function(el, property, time, ease) {
    if (!stylename) return;
    var curvalue = clearProp(el.style[stylename], property);
    if (curvalue.length) curvalue += ', ';
    //console.log(time+'s cubic-bezier('+ease[1]+',
    //'+ease[2]+','+ease[3]+','+ease[4]+')');
    curvalue += property + ' ' + time + 's cubic-bezier(' + ease[1] +
        ',' + ease[2] + ',' + ease[3] + ',' + ease[4] + ')';
    el.style[stylename] = curvalue;
};

/**
 * Clear previously set transition rule.
 * @param {Element} el Element to change.
 * @param {string} property Transition property name.
 */
lime.style.clearTransition = function(el, property) {
    if (!stylename || !el) return;
    el.style[stylename] = clearProp(el.style[stylename], property);

   // console.log('clear',el.style[stylename],property);
};

/**
 * Change size of a DOM element. Has cache built in for speed boost.
 * @param {Element} el Element to change.
 * @param {number} w New width.
 * @param {number} h New height.
 */
lime.style.setSize = function(el, w, h) {
    if (el.width_cache_ != w || el.height_cache_ != h) {
        el.width_cache_ = w;
        el.height_cache_ = h;
        return goog.style.setSize(el, w, h);
    }
}

})();
<commit_msg>Do not return boolean, return prefixed property name if this is valid, otherwise return undefined.<commit_after>goog.provide('lime.style');
goog.provide('lime.style.Transform');

goog.require('goog.dom');
goog.require('goog.style');
goog.require('lime.userAgent');

(function() {

var prefix = goog.userAgent.WEBKIT ? 'Webkit' :
             goog.userAgent.GECKO ? 'Moz' :
             goog.userAgent.OPERA ? 'O' :
             goog.userAgent.IE ? 'ms' : '';

var testDivStyle = goog.dom.createDom('div').style;

lime.style.transformProperty = '-' + prefix.toLowerCase() + '-transform';

/**
 * Try if a CSS style property with given name exists
 * @param {string} name Property name.
 * @return {boolean} If property exists.
 */
lime.style.tryProperty = function(name) {
    return testDivStyle[name] !== undefined ? name : false;
};

/**
 * Get the name of actual CSS property from general(unprefixed) name
 * @param {string} name Unprefixed name.
 * @return {string} Actual valid property name.
 */
lime.style.getCSSproperty = function(name) {
    var name_lower = name.charAt(0).toLowerCase() + name.substr(1);
    return lime.style.tryProperty(name) ?
        name : (lime.style.tryProperty(name_lower)  ?
                name_lower : lime.style.tryProperty(prefix + name) ?
                prefix + name : undefined);
};

/**
 * Set border radisu of a DOM element
 * @param {Element} el Element to change.
 * @param {Array.<number>} values Radius values.
 * @param {Array.<number>=} opt_vertical Vertical radius values.
 * @param {boolean=} opt_isPerc If values are given in percentages.
 */
lime.style.setBorderRadius = (function() {
    var stylename = lime.style.getCSSproperty('BorderRadius');
    var out = function(values, unit) {
        return (goog.isArray(values) ? values.join(unit + ' ') : values) + unit;
    };
    return function(el, values, opt_vertical, opt_isPerc) {
        var unit = opt_isPerc ? '%' : 'px';
        var vertical = goog.isDef(opt_vertical) ? opt_vertical : values;
        var value = out(values, unit) + '/' + out(vertical, unit);
        if (value != el.border_radius_cache_) {
            el.style[stylename] = el.border_radius_cache_ = value;
        }
    };
})();

// There are classes like CSSMatrix in some browsers.
// Maybe this would make more sense.

(function(){

/**
 * Object representing CSS Transform.
 * @constructor
 * @param {number=} opt_precision Default precision.
 */
lime.style.Transform = function(opt_precision) {
    this.values = [];
    this.precision = 1;
    if (this.opt_precision) {
        this.setPrecision(/** @type {number} */ (opt_precision));
    }
};

/**
 * Scale current transform object
 * @param {number} sx X-axis scale factor.
 * @param {number} sy y-axis scale factor.
 * @return {lime.style.Transform} obejct itself.
 */
lime.style.Transform.prototype.scale = function(sx, sy) {
    //if(sx!=1 && sy!=1)
    this.values.push('scale(' + sx + ',' + sy + ')');
    return this;
};

/**
 * Rotate current transform object
 * @param {number} angle Angle to rotate.
 * @param {string=} opt_unit Units.
 * @return {lime.style.Transform} obejct itself.
 */
lime.style.Transform.prototype.rotate = function(angle, opt_unit) {
    var rot_str = 'rotate(' + angle + (opt_unit ? opt_unit : 'deg') + ')';
    if (angle != 0)
        this.values.push(rot_str);

    return this;
};

/**
 * Translate(move) current transform object
 * @param {number} tx Offset in x-axis.
 * @param {number} ty Offset in y-axis.
 * @param {number=} opt_tz Offset in z-axis.
 * @return {lime.style.Transform} obejct itself.
 */
lime.style.Transform.prototype.translate = function(tx, ty, opt_tz) {

    var p = 1 / this.precision;
    var val = 'translate';
    if (lime.userAgent.IOS) val += '3d';
    val += '(' + (tx * p) + 'px,' + (ty * p) + 'px';
    if (lime.userAgent.IOS) val += ',' + ((opt_tz ? opt_tz : 0) * p) + 'px';
    this.values.push(val + ')');

    return this;
};

/**
 * Set the current precision of transform. This is handled as a
 * state machine so its added when called not when done.
 * @param {number} p Precision(Lowest value to make a difference).
 * @return {lime.style.Transform} obejct itself.
 */
lime.style.Transform.prototype.setPrecision = function(p) {
    if (this.precision != 1) {
        var opposite = 1 / this.precision;
        this.scale(opposite, opposite);
        this.precision = 1;
    }
    if (p != 1) {
        this.scale(p, p);
        this.precision = p;
    }
    return this;
};

/**
 * Return CSS transform string from the obejct
 * @return {string} CSS value string.
 */
lime.style.Transform.prototype.toString = function() {
    if (this.precision != 1) {
        this.setPrecision(1);
    }
    return this.values.join(' ');
};

/**
 * Set transform to a DOM element.
 * @param {Element} el Element to change.
 * @param {lime.style.Transform} transform Transform.
 */
lime.style.setTransform = (function() {
    var stylename = lime.style.getCSSproperty('Transform');
    return function(el, transform) {
        var value = transform.toString();

        if (value != el.transform_cache_) {
            el.style[stylename] = el.transform_cache_ = value;
        }
        lime.transformSet_=1;

    };
})();

})();

/**
 * Set transform origin point for a DOM element.
 * @param {Element} el Element to change.
 * @param {number} ox X Offset.
 * @param {number} oy Y Offset.
 * @param {boolean=} opt_isPerc If unit is percentage.
 */
lime.style.setTransformOrigin = (function() {
    var stylename = lime.style.getCSSproperty('TransformOrigin');
    return function(el, ox, oy, opt_isPerc) {
        var unit = opt_isPerc ? '%' : 'px';
        var value = ox + unit + ' ' + oy + unit;
        if (value != el.transform_origin_cache_) {
            el.style[stylename] = el.transform_origin_cache_ = value;
        }
    };
})();

var stylename = lime.style.getCSSproperty('Transition');
lime.style.isTransitionsSupported = !!stylename && !goog.userAgent.OPERA;
// Opera's CSS3 transitions seem to be unstable atm. No shorthand plus
// doesn't work if the duration property has not been previously set inside
// CSS style sheet @tonis

var clearProp = function(str, prop) {
    if (!str.length) return str;
    var proplist = str.split('),');
    for (var i = 0; i < proplist.length - 1; i++) {
        proplist[i] += ')';
    }

    proplist = goog.array.filter(proplist, function(part) {
               return part.indexOf(prop) == -1;
   });
    return proplist.join(',');
};

/**
 * Activate transition rule for a property
 * @param {Element} el Element to change.
 * @param {string} property Transition property name.
 * @param {number} time Transition duration.
 * @param {lime.animation.EasingFunction} ease Easing function.
 */
lime.style.setTransition = function(el, property, time, ease) {
    if (!stylename) return;
    var curvalue = clearProp(el.style[stylename], property);
    if (curvalue.length) curvalue += ', ';
    //console.log(time+'s cubic-bezier('+ease[1]+',
    //'+ease[2]+','+ease[3]+','+ease[4]+')');
    curvalue += property + ' ' + time + 's cubic-bezier(' + ease[1] +
        ',' + ease[2] + ',' + ease[3] + ',' + ease[4] + ')';
    el.style[stylename] = curvalue;
};

/**
 * Clear previously set transition rule.
 * @param {Element} el Element to change.
 * @param {string} property Transition property name.
 */
lime.style.clearTransition = function(el, property) {
    if (!stylename || !el) return;
    el.style[stylename] = clearProp(el.style[stylename], property);

   // console.log('clear',el.style[stylename],property);
};

/**
 * Change size of a DOM element. Has cache built in for speed boost.
 * @param {Element} el Element to change.
 * @param {number} w New width.
 * @param {number} h New height.
 */
lime.style.setSize = function(el, w, h) {
    if (el.width_cache_ != w || el.height_cache_ != h) {
        el.width_cache_ = w;
        el.height_cache_ = h;
        return goog.style.setSize(el, w, h);
    }
}

})();
<|endoftext|>


<commit_before>$(window).on('load', function() {
    getOstavkaCode = $('.ostavka-oresharski').find('[data-get-ostavka-code]');
    ostavkaOresharski = $('.ostavka-oresharski').find('[data-ostavka-oresharski]');

    $(getOstavkaCode).on('click',
            function() {
                $(ostavkaOresharski).hide();
            }
    );
    $('#ostavka').on('hidden.bs.modal', function() {
        $(ostavkaOresharski).show();
    });

    $('.mark-code-html').on('click', function() {
        $('.mark-html').tooltip('show').select();
        //alert('Click "OK" then CTRL + C');
    });
    $('.mark-code-css').on('click', function() {
        $('.mark-css').tooltip('show').select();
        //alert('Click "OK" then CTRL + C');
    });

    $(window).scroll(function() {
        if ($(window).scrollTop() > 0) {
            $(getOstavkaCode).hide();
        } else {
            $(getOstavkaCode).show();
        }
    });
    $('.href-charlike').hover(
            function() {
                $(this).on('click', function() {
                    window.open($(this).attr('data-href-charlike'), '_self');
                });
                $('.href-charlike').attr('title', $(this).attr('data-title-charlike')).css('color', '#fefefe').css('cursor', 'pointer');
            },
            function() {
                $('.href-charlike').css('color', '#bbb');
            }

    );

//    $('.charlike_domain_check').on('click', function() {
//        alert('dasddddddddddddasd');
//    });

});

//////----MENU---////////
jQuery(document).ready(function($) {
    $('.navbar .dropdown').hover(function() {
        $(this).addClass('extra-nav-class').find('.dropdown-menu').first().stop(true, true).delay(250).slideDown();
    }, function() {
        var na = $(this)
        na.find('.dropdown-menu').first().stop(true, true).delay(100).slideUp('fast', function() {
            na.removeClass('extra-nav-class')
        })
    });

    $('.dropdown-submenu').hover(function() {
        $(this).addClass('extra-nav-class').find('.dropdown-menu').first().stop(true, true).delay(250).slideDown();
    }, function() {
        var na = $(this)
        na.find('.dropdown-menu').first().stop(true, true).delay(100).slideUp('fast', function() {
            na.removeClass('extra-nav-class')
        })
    });

});

//////----Placeholder for IE---////////
$(function() {
    // Invoke the plugin
    $('input, textarea').placeholder();
});

/* Widget close */
$('.wclose').click(function(e) {
    e.preventDefault();
    var $wbox = $(this).parent().parent().parent();
    $wbox.hide(100);
});

/* Widget minimize */
$('.wminimize').click(function(e) {
    e.preventDefault();
    var $wcontent = $(this).parent().parent().next('.widget-content');
    if ($wcontent.is(':visible'))
    {
        $(this).children('i').removeClass('icon-chevron-up');
        $(this).children('i').addClass('icon-chevron-down');
    }
    else
    {
        $(this).children('i').removeClass('icon-chevron-down');
        $(this).children('i').addClass('icon-chevron-up');
    }
    $wcontent.toggle(500);
});<commit_msg>update to fa-* icon prefix<commit_after>$(window).on('load', function() {
    getOstavkaCode = $('.ostavka-oresharski').find('[data-get-ostavka-code]');
    ostavkaOresharski = $('.ostavka-oresharski').find('[data-ostavka-oresharski]');

    $(getOstavkaCode).on('click',
            function() {
                $(ostavkaOresharski).hide();
            }
    );
    $('#ostavka').on('hidden.bs.modal', function() {
        $(ostavkaOresharski).show();
    });

    $('.mark-code-html').on('click', function() {
        $('.mark-html').tooltip('show').select();
        //alert('Click "OK" then CTRL + C');
    });
    $('.mark-code-css').on('click', function() {
        $('.mark-css').tooltip('show').select();
        //alert('Click "OK" then CTRL + C');
    });

    $(window).scroll(function() {
        if ($(window).scrollTop() > 0) {
            $(getOstavkaCode).hide();
        } else {
            $(getOstavkaCode).show();
        }
    });
    $('.href-charlike').hover(
            function() {
                $(this).on('click', function() {
                    window.open($(this).attr('data-href-charlike'), '_self');
                });
                $('.href-charlike').attr('title', $(this).attr('data-title-charlike')).css('color', '#fefefe').css('cursor', 'pointer');
            },
            function() {
                $('.href-charlike').css('color', '#bbb');
            }

    );

//    $('.charlike_domain_check').on('click', function() {
//        alert('dasddddddddddddasd');
//    });

});

//////----MENU---////////
jQuery(document).ready(function($) {
    $('.navbar .dropdown').hover(function() {
        $(this).addClass('extra-nav-class').find('.dropdown-menu').first().stop(true, true).delay(250).slideDown();
    }, function() {
        var na = $(this)
        na.find('.dropdown-menu').first().stop(true, true).delay(100).slideUp('fast', function() {
            na.removeClass('extra-nav-class')
        })
    });

    $('.dropdown-submenu').hover(function() {
        $(this).addClass('extra-nav-class').find('.dropdown-menu').first().stop(true, true).delay(250).slideDown();
    }, function() {
        var na = $(this)
        na.find('.dropdown-menu').first().stop(true, true).delay(100).slideUp('fast', function() {
            na.removeClass('extra-nav-class')
        })
    });

});

//////----Placeholder for IE---////////
$(function() {
    // Invoke the plugin
    $('input, textarea').placeholder();
});

/* Widget close */
$('.wclose').click(function(e) {
    e.preventDefault();
    var $wbox = $(this).parent().parent().parent();
    $wbox.hide(100);
});

/* Widget minimize */
$('.wminimize').click(function(e) {
    e.preventDefault();
    var $wcontent = $(this).parent().parent().next('.widget-content');
    if ($wcontent.is(':visible'))
    {
        $(this).children('i').removeClass('fa fa-chevron-up');
        $(this).children('i').addClass('fa fa-chevron-down');
    }
    else
    {
        $(this).children('i').removeClass('fa fa-chevron-down');
        $(this).children('i').addClass('fa fa-chevron-up');
    }
    $wcontent.toggle(500);
});
<|endoftext|>


<commit_before> // JavaScript Olympics

// I paired [by myself, with:] on this challenge.

// This challenge took me [#] hours.

// Bulk Up
var john = {
  name: "John Jacobs",
  event: "Swimming"
}

var charlie = {
  name: "Charlie Jones",
  event: "Track"
}

var testArray = [john, charlie];

// console.log(testArray[0].name);

var bulkUp = function (athleteArray) {
  for (var i = 0; i < athleteArray.length; i++){
athleteArray[i].win = (athleteArray[i].name + " has won the " + athleteArray[i].event + "event!");
  }

}

bulkUp(testArray);

console.log(charlie.win);

// Jumble your words
var testString = "Does this work?"

function strReverse(string){
  return string.split("").reverse().join("");
}
console.log(strReverse(testString));

// 2,4,6,8

var testNumArray = [1, 2, 3, 4, 5, 6, 7, 8, 10];

function findEvens(numArray) {
  function isEven(num){
    return num % 2 == 0;
  }
  var evenArray = numArray.filter(isEven)
  return evenArray
}
console.log(findEvens(testNumArray));

// "We built this city"
function Athlete(name,age,sport,quote) {
  this.name = name;
  this.age = age;
  this.sport = sport;
  this.quote = quote;
}

var michaelPhelps = new Athlete("Michael Phelps", 29, "swimming", "It's medicinal I swear!")
console.log(michaelPhelps.constructor === Athlete)
console.log(michaelPhelps.name + " " + michaelPhelps.sport + " " + michaelPhelps.quote)

// Reflection

// Status API Training Shop Blog About Pricing
<commit_msg>Finish Reflection 7.6<commit_after> // JavaScript Olympics

// I paired [by myself, with:] on this challenge.

// This challenge took me [#] hours.

// Bulk Up
var john = {
  name: "John Jacobs",
  event: "Swimming"
}

var charlie = {
  name: "Charlie Jones",
  event: "Track"
}

var testArray = [john, charlie];

// console.log(testArray[0].name);

var bulkUp = function (athleteArray) {
  for (var i = 0; i < athleteArray.length; i++){
athleteArray[i].win = (athleteArray[i].name + " has won the " + athleteArray[i].event + "event!");
  }

}

bulkUp(testArray);

console.log(charlie.win);

// Jumble your words
var testString = "Does this work?"

function strReverse(string){
  return string.split("").reverse().join("");
}
console.log(strReverse(testString));

// 2,4,6,8

var testNumArray = [1, 2, 3, 4, 5, 6, 7, 8, 10];

function findEvens(numArray) {
  function isEven(num){
    return num % 2 == 0;
  }
  var evenArray = numArray.filter(isEven)
  return evenArray
}
console.log(findEvens(testNumArray));

// "We built this city"
function Athlete(name,age,sport,quote) {
  this.name = name;
  this.age = age;
  this.sport = sport;
  this.quote = quote;
}

var michaelPhelps = new Athlete("Michael Phelps", 29, "swimming", "It's medicinal I swear!")
console.log(michaelPhelps.constructor === Athlete)
console.log(michaelPhelps.name + " " + michaelPhelps.sport + " " + michaelPhelps.quote)

/*/ Reflection
What JavaScript knowledge did you solidify in this challenge?
  - I solidifyed some solid  basic javascript syntax. I am still struggling with comparing it to ruby or mixing up the two different systax styles but I am getting better.

What are constructor functions?
  -They are similar to classes in ruby. When creating a constructor you are creating and instance of a class or in Java, Creating an Object.

How are constructors different from Ruby classes (in your research)?
  - From what I found, In ruby, classes are responsable for holding in methods, variables and the instantiation of a new class. Where as in Java Script the it is split into two parts where the constructor create the new instances, and the prototype creates the objects.

*/<|endoftext|>


<commit_before>import {app} from 'electron';
import path from 'path';
import del from 'del';

const paths = [
  path.join(app.getPath('desktop'), 'WhatsApp for Desktop.lnk'),
  path.join(app.getPath('desktop'), 'WhatsApp.lnk'),
  path.join(app.getPath('desktop'), 'Unofficial WhatsApp for Desktop.lnk'),
  path.join(app.getPath('desktop'), 'Unofficial WhatsApp.lnk'),
  path.join(app.getPath('appData'), 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'WhatsApp for Desktop'),
  path.join(app.getPath('appData'), 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'WhatsApp'),
  path.join(app.getPath('appData'), 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Unofficial WhatsApp for Desktop'),
  path.join(app.getPath('appData'), 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Unofficial WhatsApp'),
  path.join(app.getPath('appData'), 'WhatsApp'),
  path.join(app.getPath('appData'), 'UnofficialWhatsApp'),
  path.join(app.getPath('appData'), '..', 'Local', 'WhatsApp'),
  path.join(app.getPath('appData'), '..', 'Local', 'UnofficialWhatsApp'),
  path.join('C:', 'ProgramData', 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'WhatsApp for Desktop.lnk'),
  path.join('C:', 'ProgramData', 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'WhatsApp.lnk'),
  path.join('C:', 'ProgramData', 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Unofficial WhatsApp for Desktop.lnk'),
  path.join('C:', 'ProgramData', 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Unofficial WhatsApp.lnk'),
  path.join('C:', 'Program Files', 'WhatsApp for Desktop'),
  path.join('C:', 'Program Files', 'Unofficial WhatsApp for Desktop'),
  path.join('C:', 'Program Files (x86)', 'WhatsApp for Desktop'),
  path.join('C:', 'Program Files (x86)', 'Unofficial WhatsApp for Desktop')
];

function check (callback) {
  clean(callback, true);
}

function clean (callback, dryRun = false) {
  del((paths), {force: true, dryRun})
    .catch((err) => callback(err))
    .then((paths) => callback(null, paths));
}

export default {
  check,
  clean
};
<commit_msg>One more dir to be cleaned by WAFD cleaner<commit_after>import {app} from 'electron';
import path from 'path';
import del from 'del';

const paths = [
  path.join(app.getPath('desktop'), 'WhatsApp for Desktop.lnk'),
  path.join(app.getPath('desktop'), 'WhatsApp.lnk'),
  path.join(app.getPath('desktop'), 'Unofficial WhatsApp for Desktop.lnk'),
  path.join(app.getPath('desktop'), 'Unofficial WhatsApp.lnk'),
  path.join(app.getPath('appData'), 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'WhatsApp for Desktop'),
  path.join(app.getPath('appData'), 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'WhatsApp'),
  path.join(app.getPath('appData'), 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Unofficial WhatsApp for Desktop'),
  path.join(app.getPath('appData'), 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Unofficial WhatsApp'),
  path.join(app.getPath('appData'), 'WhatsApp'),
  path.join(app.getPath('appData'), 'UnofficialWhatsApp'),
  path.join(app.getPath('appData'), '..', 'Local', 'WhatsApp'),
  path.join(app.getPath('appData'), '..', 'Local', 'UnofficialWhatsApp'),
  path.join(app.getPath('appData'), '..', 'Local', 'whatsapp'),
  path.join('C:', 'ProgramData', 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'WhatsApp for Desktop.lnk'),
  path.join('C:', 'ProgramData', 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'WhatsApp.lnk'),
  path.join('C:', 'ProgramData', 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Unofficial WhatsApp for Desktop.lnk'),
  path.join('C:', 'ProgramData', 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Unofficial WhatsApp.lnk'),
  path.join('C:', 'Program Files', 'WhatsApp for Desktop'),
  path.join('C:', 'Program Files', 'Unofficial WhatsApp for Desktop'),
  path.join('C:', 'Program Files (x86)', 'WhatsApp for Desktop'),
  path.join('C:', 'Program Files (x86)', 'Unofficial WhatsApp for Desktop')
];

function check (callback) {
  clean(callback, true);
}

function clean (callback, dryRun = false) {
  del((paths), {force: true, dryRun})
    .catch((err) => callback(err))
    .then((paths) => callback(null, paths));
}

export default {
  check,
  clean
};
<|endoftext|>


<commit_before>'use strict';

var {
  StyleSheet,
  Text,
  Image,
  View,
  TouchableHighlight,
} = React;

var FBLoginManager = require('NativeModules').FBLoginManager;

var FBLoginMock = React.createClass({
  propTypes: {
    style: View.propTypes.style,
    onPress: React.PropTypes.func,
    onLogin: React.PropTypes.func,
    onLogout: React.PropTypes.func,
  },

  getInitialState: function(){
    return {
      user: null,
    };
  },

  handleLogin: function(){
    var _this = this;
    FBLoginManager.login(function(error, credentials){
      if (!error) {
        _this.setState({ user : credentials});
        _this.props.onLogin && _this.props.onLogin();
      } else {
        console.log(error);
      }
    });
  },

  handleLogout: function(){
    var _this = this;
    FBLoginManager.logout(function(error, message){
      if (!error) {
        _this.setState({ user : null});
        _this.props.onLogout && _this.props.onLogout();
      } else {
        console.log(error);
      }
    });
  },

  onPress: function(){
    this.state.user
      ? this.handleLogout()
      : this.handleLogin();

    this.props.onPress && this.props.onPress();
  },

  componentWillMount: function(){
    var _this = this;
    FBLoginManager.getCredentials(function(error, credentials){
      if (!error) {
        _this.setState({ user : credentials})
      }
    });
  },

  render: function() {
    var text = this.state.user ? "Log out" : "Log in with Facebook";
    return (
      <View style={this.props.style}>
        <TouchableHighlight
          style={styles.container}
          onPress={this.onPress}
        >
          <View style={styles.FBLoginButton}>
            <Image style={styles.FBLogo} source={require('image!FB-f-Logo__white_144')} />
            <Text style={[styles.FBLoginButtonText, this.state.user ? styles.FBLoginButtonTextLoggedIn : styles.FBLoginButtonTextLoggedOut]}
              numberOfLines={1}>{text}</Text>
          </View>
        </TouchableHighlight>
      </View>
    );
  }
});

var styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
  FBLoginButton: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',

    height: 30,
    width: 175,
    paddingLeft: 2,

    backgroundColor: 'rgb(66,93,174)',
    borderRadius: 3,
    borderWidth: 1,
    borderColor: 'rgb(66,93,174)',

    shadowColor: "#000000",
    shadowOpacity: 0.8,
    shadowRadius: 2,
    shadowOffset: {
      height: 1,
      width: 0
    },
  },
  FBLoginButtonText: {
    color: 'white',
    fontWeight: '600',
    fontFamily: 'Helvetica neue',
    fontSize: 14.2,

    shadowColor: "#000000",
    shadowOpacity: 0.8,
    shadowRadius: 2,
    shadowOffset: {
      height: 1,
      width: 0
    },
  },
  FBLoginButtonTextLoggedIn: {
    marginLeft: 5,
  },
  FBLoginButtonTextLoggedOut: {
    marginLeft: 18,
  },
  FBLogo: {
    position: 'absolute',
    height: 14,
    width: 14,

    left: 7,
    top: 7,
  },
});

module.exports = FBLoginMock;
<commit_msg>remove shadows from FBLoginMock component text<commit_after>'use strict';

var {
  StyleSheet,
  Text,
  Image,
  View,
  TouchableHighlight,
} = React;

var FBLoginManager = require('NativeModules').FBLoginManager;

var FBLoginMock = React.createClass({
  propTypes: {
    style: View.propTypes.style,
    onPress: React.PropTypes.func,
    onLogin: React.PropTypes.func,
    onLogout: React.PropTypes.func,
  },

  getInitialState: function(){
    return {
      user: null,
    };
  },

  handleLogin: function(){
    var _this = this;
    FBLoginManager.login(function(error, credentials){
      if (!error) {
        _this.setState({ user : credentials});
        _this.props.onLogin && _this.props.onLogin();
      } else {
        console.log(error);
      }
    });
  },

  handleLogout: function(){
    var _this = this;
    FBLoginManager.logout(function(error, message){
      if (!error) {
        _this.setState({ user : null});
        _this.props.onLogout && _this.props.onLogout();
      } else {
        console.log(error);
      }
    });
  },

  onPress: function(){
    this.state.user
      ? this.handleLogout()
      : this.handleLogin();

    this.props.onPress && this.props.onPress();
  },

  componentWillMount: function(){
    var _this = this;
    FBLoginManager.getCredentials(function(error, credentials){
      if (!error) {
        _this.setState({ user : credentials})
      }
    });
  },

  render: function() {
    var text = this.state.user ? "Log out" : "Log in with Facebook";
    return (
      <View style={this.props.style}>
        <TouchableHighlight
          style={styles.container}
          onPress={this.onPress}
        >
          <View style={styles.FBLoginButton}>
            <Image style={styles.FBLogo} source={require('image!FB-f-Logo__white_144')} />
            <Text style={[styles.FBLoginButtonText, this.state.user ? styles.FBLoginButtonTextLoggedIn : styles.FBLoginButtonTextLoggedOut]}
              numberOfLines={1}>{text}</Text>
          </View>
        </TouchableHighlight>
      </View>
    );
  }
});

var styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
  FBLoginButton: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',

    height: 30,
    width: 175,
    paddingLeft: 2,

    backgroundColor: 'rgb(66,93,174)',
    borderRadius: 3,
    borderWidth: 1,
    borderColor: 'rgb(66,93,174)',

    shadowColor: "#000000",
    shadowOpacity: 0.8,
    shadowRadius: 2,
    shadowOffset: {
      height: 1,
      width: 0
    },
  },
  FBLoginButtonText: {
    color: 'white',
    fontWeight: '600',
    fontFamily: 'Helvetica neue',
    fontSize: 14.2,
  },
  FBLoginButtonTextLoggedIn: {
    marginLeft: 5,
  },
  FBLoginButtonTextLoggedOut: {
    marginLeft: 18,
  },
  FBLogo: {
    position: 'absolute',
    height: 14,
    width: 14,

    left: 7,
    top: 7,
  },
});

module.exports = FBLoginMock;
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2018 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { LitElement, html } from '@polymer/lit-element'
import { commonStyle } from './InputStyle'
import { exists, writeFile, readFile } from 'fs-extra'
import { midiToSequenceProto, sequenceProtoToMidi } from '@magenta/music'
import { resolve, sep } from 'path'
const { dialog } = require('electron').remote
import { dirname, basename, extname } from 'path'
import dragDrop from 'drag-drop'
import { popup } from './Popup'

class MagentaFile extends LitElement {

	static get properties(){
		return {
			type : { type : String },
			value : { type : String },
			folder : { type : String },
			valid : { type : Boolean },
			output : { type : Boolean },
			defaultvalue : { type : String },
		}
	}

	constructor(){
		super()
		this.valid = false
		this.value = this.defaultvalue
		this.output = false
	}

	firstUpdated(){
		super.firstUpdated()
		dragDrop(this.shadowRoot.querySelector('#filedialog'), (files, pos, fileList, directories) => {
			if (this.output){
				if (directories.length){
					const dir = fileList[0]
					this.value = dir.path
					this.folder = dir.path
				} else {
					this.errorFlash('Output must be a directory')
				}
			} else {
				const file = files[0]
				if (file.type === this.type || file.path.endsWith('.mid') || file.path.endsWith('.midi')){
					this.value = file.path
					this.dispatchEvent(new CustomEvent('file', { detail : { file }, composed : true }))
				} else {
					this.errorFlash('MIDI files only')
				}
			}
		})

		dragDrop(document.body, e => {})
	}

	errorFlash(error){
		const button = this.shadowRoot.querySelector('button')
		button.classList.add('error-flash')
		setTimeout(() => button.classList.remove('error-flash'), 100)
		this._showError(error)
	}

	updated(changed){
		if (changed.has('value') || changed.has('folder')){
			this.valid = this.value !== this.defaultvalue
			if (!this.folder && this.valid){
				this.folder = dirname(this.value)
			}
			this.dispatchEvent(new CustomEvent('change', {
				detail : { value : this.value },
				bubbles : true, composed : true
			}))
		}
		if (changed.has('defaultvalue')){
			this.folder = null
			this.value = this.defaultvalue
		}
		super.updated(changed)
	}

	get outputPath(){
		if (this.valid){
			if (!this.folder){
				this.folder = dirname(this.value)
			}
			return this.folder
		}
	}

	async write(sequences, prefix){
		if (this.folder){
			const inputName = basename(this.value, extname(this.value))
			const files = sequences.map((s, i) => resolve(this.folder, this.output ? `${prefix} ${i}.mid` : `${prefix} ${i} - ${inputName}.mid`))
			const filesExist = await Promise.all(files.map(f => exists(f)))
			const anyExists = filesExist.some(e => e)

			//if the files should be overwritten
			let writeFiles = true
			if (anyExists){
				const existingFiles = files.filter((f, i) => filesExist[i])
				const fileNames = existingFiles.map(f => basename(f))
				writeFiles = await this._overwriteFile(fileNames)
			}

			if (writeFiles){
				sequences.forEach(seq => seq.tempos[0].time = 0)
				sequences.forEach(seq => seq.tempos[0].qpm = 120)
				const midiData = sequences.map(s => sequenceProtoToMidi(s))
				await Promise.all(midiData.map((midi, i) => {
					const file = files[i]
					return writeFile(file, midi, 'binary')
				}))
			}
		} else {
			this._showError('No output folder selected.')
		}
	}

	_showError(e){
		const snackbar = document.createElement('magenta-snackbar')
		snackbar.setAttribute('message', e)
		document.body.appendChild(snackbar)
	}

	async read(){
		const buffer = await readFile(this.value, 'binary')
		return midiToSequenceProto(buffer)
	}

	async _overwriteFile(paths){
		const maxLen = 6
		if (paths.length > maxLen){
			const len = paths.length
			paths = paths.slice(0, maxLen)
			paths[maxLen-1] = `${len-(maxLen-1)} more...`
		}
		const response = await popup({
			title : `Overwrite file${paths.length > 1 ? 's' : ''}?`,
			body : `
				These files will be saved over:

					${paths.map(p => `<li>${p}</li>`).join(' ')}

			`
		})
		return response === 'ok'
	}

	async _openFile(){
		if (this.output){
			await this.chooseOutput()
			this.value = this.folder
		} else {
			dialog.showOpenDialog({
				title : 'Input MIDI file',
				properties : ['openFile'],
				filters : [{ name : 'Midi Files', extensions : ['mid', 'midi'] }]
			}, files => {
				if (files){
					this.value = files[0]
				}
			})
		}
	}

	async chooseOutput(){

		const dir = await new Promise(done => {
			dialog.showOpenDialog({
				title : 'Select output folder',
				message : 'Choose an output directory',
				properties : ['openDirectory', 'createDirectory', 'promptToCreate'],
				defaultPath : dirname(this.value)
			}, folder => {
				if (folder){
					done(folder[0])
				} else {
					done()
				}
			})
		})

		if (this.output && dir){
			this.value = dir
			this.folder = dir
		} else if (dir){
			this.folder = dir
		}
	}

	render(){

		return html`
			${commonStyle}

				<button
					outlined
					id="filedialog"
					?valid=${this.valid}
					@click=${this._openFile.bind(this)}
					class="bordered"
					>${this.value && this.value.replace(process.env.HOME, '~')}</button>
				<button id="clear"
					@click=${() => this.value = this.defaultvalue}
					?disabled=${this.value === this.defaultvalue}>
					<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/><path d="M0 0h24v24H0z" fill="none"/></svg>
				</button>

		`
	}
}
customElements.define('magenta-file', MagentaFile)
<commit_msg>fix bug when no file/folder is selected<commit_after>/**
 * @license
 * Copyright 2018 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { LitElement, html } from '@polymer/lit-element'
import { commonStyle } from './InputStyle'
import { exists, writeFile, readFile } from 'fs-extra'
import { midiToSequenceProto, sequenceProtoToMidi } from '@magenta/music'
import { resolve, sep } from 'path'
const { dialog } = require('electron').remote
import { dirname, basename, extname } from 'path'
import dragDrop from 'drag-drop'
import { popup } from './Popup'

class MagentaFile extends LitElement {

	static get properties(){
		return {
			type : { type : String },
			value : { type : String },
			folder : { type : String },
			valid : { type : Boolean },
			output : { type : Boolean },
			defaultvalue : { type : String },
		}
	}

	constructor(){
		super()
		this.valid = false
		this.value = this.defaultvalue
		this.output = false
	}

	firstUpdated(){
		super.firstUpdated()
		dragDrop(this.shadowRoot.querySelector('#filedialog'), (files, pos, fileList, directories) => {
			if (this.output){
				if (directories.length){
					const dir = fileList[0]
					this.value = dir.path
					this.folder = dir.path
				} else {
					this.errorFlash('Output must be a directory')
				}
			} else {
				const file = files[0]
				if (file.type === this.type || file.path.endsWith('.mid') || file.path.endsWith('.midi')){
					this.value = file.path
					this.dispatchEvent(new CustomEvent('file', { detail : { file }, composed : true }))
				} else {
					this.errorFlash('MIDI files only')
				}
			}
		})

		dragDrop(document.body, e => {})
	}

	errorFlash(error){
		const button = this.shadowRoot.querySelector('button')
		button.classList.add('error-flash')
		setTimeout(() => button.classList.remove('error-flash'), 100)
		this._showError(error)
	}

	updated(changed){
		if (changed.has('value') || changed.has('folder')){
			this.valid = this.value !== this.defaultvalue
			if (!this.folder && this.valid){
				this.folder = dirname(this.value)
			}
			this.dispatchEvent(new CustomEvent('change', {
				detail : { value : this.value },
				bubbles : true, composed : true
			}))
		}
		if (changed.has('defaultvalue')){
			this.folder = null
			this.value = this.defaultvalue
		}
		super.updated(changed)
	}

	get outputPath(){
		if (this.valid){
			if (!this.folder){
				this.folder = dirname(this.value)
			}
			return this.folder
		}
	}

	async write(sequences, prefix){
		if (this.folder){
			const inputName = basename(this.value, extname(this.value))
			const files = sequences.map((s, i) => resolve(this.folder, this.output ? `${prefix} ${i}.mid` : `${prefix} ${i} - ${inputName}.mid`))
			const filesExist = await Promise.all(files.map(f => exists(f)))
			const anyExists = filesExist.some(e => e)

			//if the files should be overwritten
			let writeFiles = true
			if (anyExists){
				const existingFiles = files.filter((f, i) => filesExist[i])
				const fileNames = existingFiles.map(f => basename(f))
				writeFiles = await this._overwriteFile(fileNames)
			}

			if (writeFiles){
				sequences.forEach(seq => seq.tempos[0].time = 0)
				sequences.forEach(seq => seq.tempos[0].qpm = 120)
				const midiData = sequences.map(s => sequenceProtoToMidi(s))
				await Promise.all(midiData.map((midi, i) => {
					const file = files[i]
					return writeFile(file, midi, 'binary')
				}))
			}
		} else {
			this._showError('No output folder selected.')
		}
	}

	_showError(e){
		const snackbar = document.createElement('magenta-snackbar')
		snackbar.setAttribute('message', e)
		document.body.appendChild(snackbar)
	}

	async read(){
		const buffer = await readFile(this.value, 'binary')
		return midiToSequenceProto(buffer)
	}

	async _overwriteFile(paths){
		const maxLen = 6
		if (paths.length > maxLen){
			const len = paths.length
			paths = paths.slice(0, maxLen)
			paths[maxLen-1] = `${len-(maxLen-1)} more...`
		}
		const response = await popup({
			title : `Overwrite file${paths.length > 1 ? 's' : ''}?`,
			body : `
				These files will be saved over:

					${paths.map(p => `<li>${p}</li>`).join(' ')}

			`
		})
		return response === 'ok'
	}

	async _openFile(){
		if (this.output){
			await this.chooseOutput()
			if (this.folder){
				this.value = this.folder
			}
		} else {
			dialog.showOpenDialog({
				title : 'Input MIDI file',
				properties : ['openFile'],
				filters : [{ name : 'Midi Files', extensions : ['mid', 'midi'] }]
			}, files => {
				if (files){
					this.value = files[0]
				}
			})
		}
	}

	async chooseOutput(){

		const dir = await new Promise(done => {
			dialog.showOpenDialog({
				title : 'Select output folder',
				message : 'Choose an output directory',
				properties : ['openDirectory', 'createDirectory', 'promptToCreate'],
				defaultPath : dirname(this.value)
			}, folder => {
				if (folder){
					done(folder[0])
				} else {
					done()
				}
			})
		})

		if (this.output && dir){
			this.value = dir
			this.folder = dir
		} else if (dir){
			this.folder = dir
		}
	}

	render(){

		return html`
			${commonStyle}

				<button
					outlined
					id="filedialog"
					?valid=${this.valid}
					@click=${this._openFile.bind(this)}
					class="bordered"
					>${this.value && this.value.replace(process.env.HOME, '~')}</button>
				<button id="clear"
					@click=${() => this.value = this.defaultvalue}
					?disabled=${this.value === this.defaultvalue}>
					<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/><path d="M0 0h24v24H0z" fill="none"/></svg>
				</button>

		`
	}
}
customElements.define('magenta-file', MagentaFile)
<|endoftext|>


<commit_before>dojo.provide("dijit.form.ValidationTextBox");

dojo.require("dojo.i18n");

dojo.require("dijit.form.TextBox");
dojo.require("dijit.Tooltip");

dojo.requireLocalization("dijit.form", "validate");

/*=====
	dijit.form.ValidationTextBox.__Constraints = function(){
		// locale: String
		//		locale used for validation, picks up value from this widget's lang attribute
		// _flags_: anything
		//		various flags passed to regExpGen function
		this.locale = "";
		this._flags_ = "";
	}
=====*/

dojo.declare(
	"dijit.form.ValidationTextBox",
	dijit.form.TextBox,
	{
		// summary:
		//		A TextBox subclass with the ability to validate content of various types and provide user feedback.

		templatePath: dojo.moduleUrl("dijit.form", "templates/ValidationTextBox.html"),
		baseClass: "dijitTextBox",

		// default values for new subclass properties
		// required: Boolean
		//		Can be true or false, default is false.
		required: false,

		// promptMessage: String
		//		Hint string
		promptMessage: "",

		// invalidMessage: String
		// 		The message to display if value is invalid.
		invalidMessage: "$_unset_$", // read from the message file if not overridden

		// constraints: dijit.form.ValidationTextBox.__Constraints
		//		user-defined object needed to pass parameters to the validator functions
		constraints: {},

		// regExp: String
		//		regular expression string used to validate the input
		//		Do not specify both regExp and regExpGen
		regExp: ".*",

		// regExpGen: Function
		//		user replaceable function used to generate regExp when dependent on constraints
		//		Do not specify both regExp and regExpGen
		regExpGen: function(/*dijit.form.ValidationTextBox.__Constraints*/constraints){ return this.regExp; },

		// state: String
		//		Shows current state (ie, validation result) of input (Normal, Warning, or Error)
		state: "",

		//	tooltipPosition: String[]
		//		See description of dijit.Tooltip.defaultPosition for details on this parameter.
		tooltipPosition: [],

		setValue: function(){
			this.inherited(arguments);
			this.validate(this._focused);
		},

		validator: function(/*anything*/value, /*dijit.form.ValidationTextBox.__Constraints*/constraints){
			// summary: user replaceable function used to validate the text input against the regular expression.
			return (new RegExp("^(" + this.regExpGen(constraints) + ")"+(this.required?"":"?")+"$")).test(value) &&
				(!this.required || !this._isEmpty(value)) &&
				(this._isEmpty(value) || this.parse(value, constraints) !== undefined); // Boolean
		},

		isValid: function(/*Boolean*/ isFocused){
			// summary: Need to over-ride with your own validation code in subclasses
			return this.validator(this.textbox.value, this.constraints);
		},

		_isEmpty: function(value){
			// summary: Checks for whitespace
			return /^\s*$/.test(value); // Boolean
		},

		getErrorMessage: function(/*Boolean*/ isFocused){
			// summary: return an error message to show if appropriate
			return this.invalidMessage; // String
		},

		getPromptMessage: function(/*Boolean*/ isFocused){
			// summary: return a hint to show if appropriate
			return this.promptMessage; // String
		},

		validate: function(/*Boolean*/ isFocused){
			// summary:
			//		Called by oninit, onblur, and onkeypress.
			// description:
			//		Show missing or invalid messages if appropriate, and highlight textbox field.
			var message = "";
			var isValid = this.isValid(isFocused);
			var isEmpty = this._isEmpty(this.textbox.value);
			this.state = (isValid || (!this._hasBeenBlurred && isEmpty)) ? "" : "Error";
			this._setStateClass();
			dijit.setWaiState(this.focusNode, "invalid", isValid ? "false" : "true");
			if(isFocused){
				if(isEmpty){
					message = this.getPromptMessage(true);
				}
				if(!message && this.state == "Error"){
					message = this.getErrorMessage(true);
				}
			}
			this.displayMessage(message);
			return isValid;
		},

		// currently displayed message
		_message: "",

		displayMessage: function(/*String*/ message){
			// summary:
			//		User overridable method to display validation errors/hints.
			//		By default uses a tooltip.
			if(this._message == message){ return; }
			this._message = message;
			dijit.hideTooltip(this.domNode);
			if(message){
				dijit.showTooltip(message, this.domNode, this.tooltipPosition);
			}
		},

		_refreshState: function(){
			this.validate(this._focused);
		},

		_update: function(/*Event*/e){
			this._refreshState();
			this._onMouse(e);	// update CSS classes
		},

		//////////// INITIALIZATION METHODS ///////////////////////////////////////

		constructor: function(){
			this.constraints = {};
		},

		postMixInProperties: function(){
			this.inherited(arguments);
			this.constraints.locale = this.lang;
			this.messages = dojo.i18n.getLocalization("dijit.form", "validate", this.lang);
			if(this.invalidMessage == "$_unset_$"){ this.invalidMessage = this.messages.invalidMessage; }
			var p = this.regExpGen(this.constraints);
			this.regExp = p;
		}
	}
);

dojo.declare(
	"dijit.form.MappedTextBox",
	dijit.form.ValidationTextBox,
	{
		// summary:
		//		A dijit.form.ValidationTextBox subclass which provides a visible formatted display and a serializable
		//		value in a hidden input field which is actually sent to the server.  The visible display may
		//		be locale-dependent and interactive.  The value sent to the server is stored in a hidden
		//		input field which uses the `name` attribute declared by the original widget.  That value sent
		//		to the serveris defined by the dijit.form.MappedTextBox.serialize method and is typically
		//		locale-neutral.

		serialize: function(/*anything*/val, /*Object?*/options){
			// summary: user replaceable function used to convert the getValue() result to a String
			return val.toString ? val.toString() : ""; // String
		},

		toString: function(){
			// summary: display the widget as a printable string using the widget's value
			var val = this.filter(this.getValue());
			return val != null ? (typeof val == "string" ? val : this.serialize(val, this.constraints)) : ""; // String
		},

		validate: function(){
			this.valueNode.value = this.toString();
			return this.inherited(arguments);
		},

		setAttribute: function(/*String*/ attr, /*anything*/ value){
			this.inherited(arguments);
			switch(attr){
				case "disabled":
					if(this.valueNode){
						this.valueNode.disabled = this.disabled;
					}
			}
		},

		postCreate: function(){
			var textbox = this.textbox;
			var valueNode = (this.valueNode = dojo.doc.createElement("input"));
			valueNode.setAttribute("type", textbox.type);
			valueNode.setAttribute("value", this.toString());
			dojo.style(valueNode, "display", "none");
			valueNode.name = this.textbox.name;
			valueNode.disabled = this.textbox.disabled;
			this.textbox.name = this.textbox.name + "_displayed_";
			this.textbox.removeAttribute("name");
			dojo.place(valueNode, textbox, "after");

			this.inherited(arguments);
		}
	}
);

/*=====
	dijit.form.RangeBoundTextBox.__Constraints = function(){
		// min: Number
		//		Minimum signed value.  Default is -Infinity
		// max: Number
		//		Maximum signed value.  Default is +Infinity
		this.min = min;
		this.max = max;
	}
=====*/

dojo.declare(
	"dijit.form.RangeBoundTextBox",
	dijit.form.MappedTextBox,
	{
		// summary:
		//		A dijit.form.MappedTextBox subclass which defines a range of valid values
		//
		// constraints: dijit.form.RangeBoundTextBox.__Constraints
		//
		// rangeMessage: String
		//		The message to display if value is out-of-range

		/*=====
		constraints: {},
		======*/
		rangeMessage: "",

		compare: function(/*anything*/val1, /*anything*/val2){
			// summary: compare 2 values
			return val1 - val2; // anything
		},

		rangeCheck: function(/*Number*/ primitive, /*dijit.form.RangeBoundTextBox.__Constraints*/ constraints){
			// summary: user replaceable function used to validate the range of the numeric input value
			var isMin = "min" in constraints;
			var isMax = "max" in constraints;
			if(isMin || isMax){
				return (!isMin || this.compare(primitive,constraints.min) >= 0) &&
					(!isMax || this.compare(primitive,constraints.max) <= 0);
			}
			return true; // Boolean
		},

		isInRange: function(/*Boolean*/ isFocused){
			// summary: Need to over-ride with your own validation code in subclasses
			return this.rangeCheck(this.getValue(), this.constraints);
		},

		isValid: function(/*Boolean*/ isFocused){
			return this.inherited(arguments) &&
				((this._isEmpty(this.textbox.value) && !this.required) || this.isInRange(isFocused)); // Boolean
		},

		getErrorMessage: function(/*Boolean*/ isFocused){
			if(dijit.form.RangeBoundTextBox.superclass.isValid.call(this, false) && !this.isInRange(isFocused)){ return this.rangeMessage; } // String
			return this.inherited(arguments);
		},

		postMixInProperties: function(){
			this.inherited(arguments);
			if(!this.rangeMessage){
				this.messages = dojo.i18n.getLocalization("dijit.form", "validate", this.lang);
				this.rangeMessage = this.messages.rangeMessage;
			}
		},

		postCreate: function(){
			this.inherited(arguments);
			if(this.constraints.min !== undefined){
				dijit.setWaiState(this.focusNode, "valuemin", this.constraints.min);
			}
			if(this.constraints.max !== undefined){
				dijit.setWaiState(this.focusNode, "valuemax", this.constraints.max);
			}
		},

		setValue: function(/*Number*/ value, /*Boolean?*/ priorityChange){
			dijit.setWaiState(this.focusNode, "valuenow", value);
			this.inherited('setValue', arguments);
		}
	}
);
<commit_msg>Fixes #4437.  Creates a parsing regexp for ValidationTextBox widgets that matches valid subsets in order to mask validation errors during data entry that are only due to partial input.<commit_after>dojo.provide("dijit.form.ValidationTextBox");

dojo.require("dojo.i18n");

dojo.require("dijit.form.TextBox");
dojo.require("dijit.Tooltip");

dojo.requireLocalization("dijit.form", "validate");

/*=====
	dijit.form.ValidationTextBox.__Constraints = function(){
		// locale: String
		//		locale used for validation, picks up value from this widget's lang attribute
		// _flags_: anything
		//		various flags passed to regExpGen function
		this.locale = "";
		this._flags_ = "";
	}
=====*/

dojo.declare(
	"dijit.form.ValidationTextBox",
	dijit.form.TextBox,
	{
		// summary:
		//		A TextBox subclass with the ability to validate content of various types and provide user feedback.

		templatePath: dojo.moduleUrl("dijit.form", "templates/ValidationTextBox.html"),
		baseClass: "dijitTextBox",

		// default values for new subclass properties
		// required: Boolean
		//		Can be true or false, default is false.
		required: false,

		// promptMessage: String
		//		Hint string
		promptMessage: "",

		// invalidMessage: String
		// 		The message to display if value is invalid.
		invalidMessage: "$_unset_$", // read from the message file if not overridden

		// constraints: dijit.form.ValidationTextBox.__Constraints
		//		user-defined object needed to pass parameters to the validator functions
		constraints: {},

		// regExp: String
		//		regular expression string used to validate the input
		//		Do not specify both regExp and regExpGen
		regExp: ".*",

		// regExpGen: Function
		//		user replaceable function used to generate regExp when dependent on constraints
		//		Do not specify both regExp and regExpGen
		regExpGen: function(/*dijit.form.ValidationTextBox.__Constraints*/constraints){ return this.regExp; },

		// state: String
		//		Shows current state (ie, validation result) of input (Normal, Warning, or Error)
		state: "",

		//	tooltipPosition: String[]
		//		See description of dijit.Tooltip.defaultPosition for details on this parameter.
		tooltipPosition: [],

		setValue: function(){
			this.inherited(arguments);
			this.validate(this._focused);
		},

		validator: function(/*anything*/value, /*dijit.form.ValidationTextBox.__Constraints*/constraints){
			// summary: user replaceable function used to validate the text input against the regular expression.
			return (new RegExp("^(" + this.regExpGen(constraints) + ")"+(this.required?"":"?")+"$")).test(value) &&
				(!this.required || !this._isEmpty(value)) &&
				(this._isEmpty(value) || this.parse(value, constraints) !== undefined); // Boolean
		},

		_isValidSubset: function(){
			// summary:
			//	Returns true if the value is either already valid or could be made valid by appending characters.
			return this.textbox.value.search(this._partialre) == 0;
		},

		isValid: function(/*Boolean*/ isFocused){
			// summary: Need to over-ride with your own validation code in subclasses
			return this.validator(this.textbox.value, this.constraints);
		},

		_isEmpty: function(value){
			// summary: Checks for whitespace
			return /^\s*$/.test(value); // Boolean
		},

		getErrorMessage: function(/*Boolean*/ isFocused){
			// summary: return an error message to show if appropriate
			return this.invalidMessage; // String
		},

		getPromptMessage: function(/*Boolean*/ isFocused){
			// summary: return a hint to show if appropriate
			return this.promptMessage; // String
		},

		_maskValidSubsetError: false,
		validate: function(/*Boolean*/ isFocused){
			// summary:
			//		Called by oninit, onblur, and onkeypress.
			// description:
			//		Show missing or invalid messages if appropriate, and highlight textbox field.
			var message = "";
			var isValid = this.isValid(isFocused);
			if(isValid){ this._maskValidSubsetError = true; }
			var isValidSubset = !isValid && isFocused && this._isValidSubset();
			var isEmpty = this._isEmpty(this.textbox.value);
			this.state = (isValid || (!this._hasBeenBlurred && isEmpty) || isValidSubset) ? "" : "Error";
			if(this.state == "Error"){ this._maskValidSubsetError = false; }
			this._setStateClass();
			dijit.setWaiState(this.focusNode, "invalid", isValid ? "false" : "true");
			if(isFocused){
				if(isEmpty){
					message = this.getPromptMessage(true);
				}
				if(!message && (this.state == "Error" || (isValidSubset && !this._maskValidSubsetError))){
					message = this.getErrorMessage(true);
				}
			}
			this.displayMessage(message);
			return isValid;
		},

		// currently displayed message
		_message: "",

		displayMessage: function(/*String*/ message){
			// summary:
			//		User overridable method to display validation errors/hints.
			//		By default uses a tooltip.
			if(this._message == message){ return; }
			this._message = message;
			dijit.hideTooltip(this.domNode);
			if(message){
				dijit.showTooltip(message, this.domNode, this.tooltipPosition);
			}
		},

		_refreshState: function(){
			this.validate(this._focused);
		},

		_update: function(/*Event*/e){
			this._refreshState();
			this._onMouse(e);	// update CSS classes
		},

		//////////// INITIALIZATION METHODS ///////////////////////////////////////

		constructor: function(){
			this.constraints = {};
		},

		postMixInProperties: function(){
			this.inherited(arguments);
			this.constraints.locale = this.lang;
			this.messages = dojo.i18n.getLocalization("dijit.form", "validate", this.lang);
			if(this.invalidMessage == "$_unset_$"){ this.invalidMessage = this.messages.invalidMessage; }
			var p = this.regExpGen(this.constraints);
			this.regExp = p;
			var partialre = "";
			// parse the regexp and produce a new regexp that matches valid subsets
			// if the regexp is .* then there's no use in matching subsets since everything is valid
			if(p != ".*"){ this.regExp.replace(/\\.|\[\]|\[.*?[^\\]{1}\]|\{.*?\}|\(\?[=:!]|./g,
				function (re){
					switch(re.charAt(0)){
						case '{':
						case '+':
						case '?':
						case '*':
						case '^':
						case '$':
						case '|':
						case '(': partialre += re; break;
						case ")": partialre += "|$)"; break;
						 default: partialre += "(?:"+re+"|$)"; break;
					}
				}
			);}
			try{ // this is needed for now since the above regexp parsing needs more test verification
				"".search(partialre);
			}catch(e){ // should never be here unless the original RE is bad or the parsing is bad
				partialre = this.regExp;
				console.debug('RegExp error in ' + this.declaredClass + ': ' + this.regExp);
			} // should never be here unless the original RE is bad or the parsing is bad
			this._partialre = "^(?:" + partialre + ")$";
		}
	}
);

dojo.declare(
	"dijit.form.MappedTextBox",
	dijit.form.ValidationTextBox,
	{
		// summary:
		//		A dijit.form.ValidationTextBox subclass which provides a visible formatted display and a serializable
		//		value in a hidden input field which is actually sent to the server.  The visible display may
		//		be locale-dependent and interactive.  The value sent to the server is stored in a hidden
		//		input field which uses the `name` attribute declared by the original widget.  That value sent
		//		to the serveris defined by the dijit.form.MappedTextBox.serialize method and is typically
		//		locale-neutral.

		serialize: function(/*anything*/val, /*Object?*/options){
			// summary: user replaceable function used to convert the getValue() result to a String
			return val.toString ? val.toString() : ""; // String
		},

		toString: function(){
			// summary: display the widget as a printable string using the widget's value
			var val = this.filter(this.getValue());
			return val != null ? (typeof val == "string" ? val : this.serialize(val, this.constraints)) : ""; // String
		},

		validate: function(){
			this.valueNode.value = this.toString();
			return this.inherited(arguments);
		},

		setAttribute: function(/*String*/ attr, /*anything*/ value){
			this.inherited(arguments);
			switch(attr){
				case "disabled":
					if(this.valueNode){
						this.valueNode.disabled = this.disabled;
					}
			}
		},

		postCreate: function(){
			var textbox = this.textbox;
			var valueNode = (this.valueNode = dojo.doc.createElement("input"));
			valueNode.setAttribute("type", textbox.type);
			valueNode.setAttribute("value", this.toString());
			dojo.style(valueNode, "display", "none");
			valueNode.name = this.textbox.name;
			valueNode.disabled = this.textbox.disabled;
			this.textbox.name = this.textbox.name + "_displayed_";
			this.textbox.removeAttribute("name");
			dojo.place(valueNode, textbox, "after");

			this.inherited(arguments);
		}
	}
);

/*=====
	dijit.form.RangeBoundTextBox.__Constraints = function(){
		// min: Number
		//		Minimum signed value.  Default is -Infinity
		// max: Number
		//		Maximum signed value.  Default is +Infinity
		this.min = min;
		this.max = max;
	}
=====*/

dojo.declare(
	"dijit.form.RangeBoundTextBox",
	dijit.form.MappedTextBox,
	{
		// summary:
		//		A dijit.form.MappedTextBox subclass which defines a range of valid values
		//
		// constraints: dijit.form.RangeBoundTextBox.__Constraints
		//
		// rangeMessage: String
		//		The message to display if value is out-of-range

		/*=====
		constraints: {},
		======*/
		rangeMessage: "",

		compare: function(/*anything*/val1, /*anything*/val2){
			// summary: compare 2 values
			return val1 - val2; // anything
		},

		rangeCheck: function(/*Number*/ primitive, /*dijit.form.RangeBoundTextBox.__Constraints*/ constraints){
			// summary: user replaceable function used to validate the range of the numeric input value
			var isMin = "min" in constraints;
			var isMax = "max" in constraints;
			if(isMin || isMax){
				return (!isMin || this.compare(primitive,constraints.min) >= 0) &&
					(!isMax || this.compare(primitive,constraints.max) <= 0);
			}
			return true; // Boolean
		},

		isInRange: function(/*Boolean*/ isFocused){
			// summary: Need to over-ride with your own validation code in subclasses
			return this.rangeCheck(this.getValue(), this.constraints);
		},

		_isDefinitelyOutOfRange: function(){
			// summary:
			//	Returns true if the value is out of range and will remain
			//	out of range even if the user types more characters
			var val = this.getValue();
			var isTooLittle = false;
			var isTooMuch = false;
			if("min" in this.constraints){
				var min = this.constraints.min;
				val = this.compare(val, ((typeof min == "number") && min >= 0)? 0 : min);
				isTooLittle = (typeof val == "number") && val < 0;
			}
			if("max" in this.constraints){
				var max = this.constraints.max;
				val = this.compare(val, ((typeof max != "number") || max > 0)? max : 0);
				isTooMuch = (typeof val == "number") && val > 0;
			}
			return isTooLittle || isTooMuch;
		},

		_isValidSubset: function(){
			return this.inherited(arguments) && !this._isDefinitelyOutOfRange();
		},

		isValid: function(/*Boolean*/ isFocused){
			return this.inherited(arguments) &&
				((this._isEmpty(this.textbox.value) && !this.required) || this.isInRange(isFocused)); // Boolean
		},

		getErrorMessage: function(/*Boolean*/ isFocused){
			if(dijit.form.RangeBoundTextBox.superclass.isValid.call(this, false) && !this.isInRange(isFocused)){ return this.rangeMessage; } // String
			return this.inherited(arguments);
		},

		postMixInProperties: function(){
			this.inherited(arguments);
			if(!this.rangeMessage){
				this.messages = dojo.i18n.getLocalization("dijit.form", "validate", this.lang);
				this.rangeMessage = this.messages.rangeMessage;
			}
		},

		postCreate: function(){
			this.inherited(arguments);
			if(this.constraints.min !== undefined){
				dijit.setWaiState(this.focusNode, "valuemin", this.constraints.min);
			}
			if(this.constraints.max !== undefined){
				dijit.setWaiState(this.focusNode, "valuemax", this.constraints.max);
			}
		},

		setValue: function(/*Number*/ value, /*Boolean?*/ priorityChange){
			dijit.setWaiState(this.focusNode, "valuenow", value);
			this.inherited('setValue', arguments);
		}
	}
);
<|endoftext|>


<commit_before>var jQuery = jQuery;

(function ($) {

	$.fn.findWithoutAttr = function (query, attr) {
		var
			self = $(this);

	 	return self.find(query + ":not([" + attr + "])");
	};

	$.fn.findByAttr = function (query, attr, value) {
  		return $(this).find(query + "[" + attr + "=\"" + value + "\"]");
	};

	$.fn.replaceToggleClass = function (cls1, cls2) {
		var
	 		self = $(this);

	  	if (self.get(0).classList.contains(cls1)) {
		    // os métodos próprios do jquery mantém o controle da visibilidade e existência
			self.removeClass(cls1);
		    self.addClass(cls2);
		} else if (self.get(0).classList.contains(cls2)) {
		    self.removeClass(cls2);
		    self.addClass(cls1);
		}

		return self;
	};

	$.fn.centralizeOn = function (jqObj) {
		var
			self = $(this);

		self.css({
			top: (jqObj.outerHeight()/2) - (self.outerHeight()/2) + "px",
			left: (jqObj.outerWidth()/2) - (self.outerWidth()/2) + "px"
		});

		// //top: "50%"
		// marginTop: "#{-$(obj).outerHeight() / 2}px"
		// # top: "#{( ( $(document).outerHeight()-2 )/2 )-( obj.outerHeight()/2 )}px"

		// left: "50%"
		// marginLeft: "#{-$(obj).outerWidth() / 2}px"

		return self;
	}

/*$.fn.replaceClass = (sought, substitute, interval)->
  obj = $(this)
  setTimeout ->
    obj.each (i)->
      current = obj.item(i)
      if current.classList.contains(sought)
        # de repentemente é só remover a classe antiga e adicionar a nova através do jquery, ao invés de fazer via proprio método de manipulação de string
        className = current.className.allReplaced "(#{sought}|\\s#{sought}|#{sought}\\s)", " #{substitute} "
        current.className = className.trim().allReplaced("  ", " ")
  , interval || 0

  obj

$.fn.extend
  item: (index)->
    obj = $(this)
    obj.get index
*/

}(jQuery));<commit_msg>remove comentários<commit_after>var jQuery = jQuery;

(function ($) {

	$.fn.findWithoutAttr = function (query, attr) {
		var
			self = $(this);

	 	return self.find(query + ":not([" + attr + "])");
	};

	$.fn.findByAttr = function (query, attr, value) {
  		return $(this).find(query + "[" + attr + "=\"" + value + "\"]");
	};

	$.fn.replaceToggleClass = function (cls1, cls2) {
		var
	 		self = $(this);

	  	if (self.get(0).classList.contains(cls1)) {
		    // os métodos próprios do jquery mantém o controle da visibilidade e existência
			self.removeClass(cls1);
		    self.addClass(cls2);
		} else if (self.get(0).classList.contains(cls2)) {
		    self.removeClass(cls2);
		    self.addClass(cls1);
		}

		return self;
	};

	$.fn.centralizeOn = function (jqObj) {
		var
			self = $(this);

		self.css({
			top: (jqObj.outerHeight()/2) - (self.outerHeight()/2) + "px",
			left: (jqObj.outerWidth()/2) - (self.outerWidth()/2) + "px"
		});

		return self;
	}

/*$.fn.replaceClass = (sought, substitute, interval)->
  obj = $(this)
  setTimeout ->
    obj.each (i)->
      current = obj.item(i)
      if current.classList.contains(sought)
        # de repentemente é só remover a classe antiga e adicionar a nova através do jquery, ao invés de fazer via proprio método de manipulação de string
        className = current.className.allReplaced "(#{sought}|\\s#{sought}|#{sought}\\s)", " #{substitute} "
        current.className = className.trim().allReplaced("  ", " ")
  , interval || 0

  obj

$.fn.extend
  item: (index)->
    obj = $(this)
    obj.get index
*/

}(jQuery));<|endoftext|>


<commit_before>import Cookies from 'js-cookie'
import { makeRequest, requestHeaders } from './utils';

export default (props) => {

  const { identityURL, authorizeURL, logoutURL, required, storage, storage_name } = props;

  const authorize = (name, value) => {
    if (value === undefined) {
      return storage == 'localstorage' ?  localStorage.getItem(name) : Cookies.get(name);
    }

    if (storage == 'localstorage') requestHeaders['Authorization'] = value;
    storage == 'localstorage' ?  localStorage.setItem(name, value) : Cookies.set(name, value);
    return value;
  }

  // Initialize request headers
  authorize(storage_name, authorize(storage_name));

  let getIdentity = async () => {
      if (identityURL) {
        let {json} = await makeRequest(identityURL);
        return json;
      }
  }

  if (required) return {

      getIdentity,

      checkAuth: async (data) => {
        const auth = authorize(storage_name);
        if (!auth) throw {message: 'Authorization required'}

        if (!identityURL) return auth;

        let user = await getIdentity();
        if (!user)  throw {message: 'Authorization required'};

        return user;
      },

      checkError: async (error) => {
        const {message, status, body} = error;

        if (status == 401 || status == 403) {
          authorize(storage_name, '');
          throw {message: 'Invalid authorization'};
        }

      },

      login: async (data) => {
        if (!authorizeURL) throw {message: 'Authorization is not supported'}

        let {json} = await makeRequest(authorizeURL, {data, method: 'POST'})
        authorize(storage_name, json);
      },

      logout: async () => {
        authorize(storage_name, '');
        if (logoutURL) window.location = logoutURL;
      },

      getPermissions: (data) => {
        const role = authorize(storage_name + '_role');
        return role ? Promise.resolve(role) : Promise.reject();
      },

  }

}
<commit_msg>feat: follow ra<commit_after>import Cookies from 'js-cookie'
import { makeRequest, requestHeaders } from './utils';

export default (props) => {

  const { identityURL, authorizeURL, logoutURL, required, storage, storage_name } = props;

  const authorize = (name, value) => {
    if (value === undefined) {
      return storage == 'localstorage' ?  localStorage.getItem(name) : Cookies.get(name);
    }

    if (storage == 'localstorage') requestHeaders['Authorization'] = value;
    storage == 'localstorage' ?  localStorage.setItem(name, value) : Cookies.set(name, value);
    return value;
  }

  // Initialize request headers
  authorize(storage_name, authorize(storage_name));

  let getIdentity = async () => {
      if (identityURL) {
        let {json} = await makeRequest(identityURL);
        return json;
      }
  }

  if (required) return {

      getIdentity,

      checkAuth: async (data) => {
        const auth = authorize(storage_name);
        if (!auth) throw {message: 'Authorization required'}

        if (!identityURL) return auth;

        let user = await getIdentity();
        if (!user)  throw {message: 'Authorization required'};

        return user;
      },

      checkError: async (error) => {
        const {message, status, body} = error;

        if (status == 401 || status == 403) {
          // Clean storage
          authorize(storage_name, '');

          throw {message: 'Invalid authorization', redirectTo: logoutURL, logoutUser: !logoutURL};
        }

      },

      login: async (data) => {
        if (!authorizeURL) throw {message: 'Authorization is not supported'}

        let {json} = await makeRequest(authorizeURL, {data, method: 'POST'})
        authorize(storage_name, json);
      },

      logout: async () => {

          // Clean storage
        authorize(storage_name, '');

        if (logoutURL) window.location = logoutURL;
      },

      getPermissions: (data) => {
        const role = authorize(storage_name + '_role');
        return role ? Promise.resolve(role) : Promise.reject();
      },

  }

}
<|endoftext|>