<commit_before>// 中文编码 utf8
var _slider = createElement(div);
css(_slider, "position:absolute;top:0px;left:0px;right:0px;bottom:0px;width:100%;height:100%;");
var container = createElement(div);
var windowInnerWidth = window.innerWidth || screen.availWidth;
css(container, "overflow:hidden;position:relative;width:100%;height:120px;font-size:60px;");
onresize(window, function (event) { });
var floor = Math.floor;
var ceil = Math.ceil;
var round = Math.round;
var abs = Math.abs;
var sign = Math.sign;
var body = document.body;
var is_touch_enabled = "ontouchstart" in window;
var extendTouch = function (e) {
    var touch = e.touches[0];
    for (var k in touch) {
        e[k] = touch[k];
    }
    return e;
};
var has_moving_instance;
/**
 *
 * @param {Boolean,Array,Function} autoplay
 */
function slider(autoplay) {
    var outter = createElement(container);
    var _imageMain = createElement(_slider);
    var _imageHelp = createElement(_slider);
    var play_autostart = autoplay === true;
    outter.src = function (index) {
        var block = createElement(_slider);
        text(block, index);
        return block;
    };
    if (isFunction(autoplay) || isArray(autoplay)) {
        outter.src = autoplay;
    }
    var generator = function (index, ratio) {
        var src = outter.src;
        if (isArray(src)) {
            src = src[index];
        }
        if (isFunction(src)) {
            src = src(index, 1 - abs(ratio));
        }
        if (src) {
            if (src.parentNode !== outter) {
                appendChild(outter, src);
            }
        }
        return src;
    };
    var negative_index = 0,
        current_index = 0,
        delta_negative_index = 0,
        timer_animate = 0,
        timer_playyer = 0,
        saved_x = 0,
        saved_y = 0,
        moving = 0,
        direction,
        _speed = speed(1);
    var reshape = function (index, ising) {
        current_index = index;
        var width = outter.offsetWidth || windowInnerWidth;
        var indexLeft = floor(index);
        var indexRight = indexLeft + 1;
        if (ising === false) {
            //预载
            generator(indexLeft - 1, 1);
            generator(indexLeft - 2, 1);
            generator(indexLeft - 3, 1);
            generator(indexLeft - 4, 1);
            generator(indexLeft + 2, 1);
            generator(indexLeft + 3, 1);
            generator(indexLeft + 4, 1);
        }
        _imageMain = generator(indexLeft, indexLeft - index);
        _imageHelp = generator(indexRight, indexRight - index);
        var childNodes = outter.childNodes;
        for (var dx = childNodes.length - 1; dx >= 0; dx--) {
            var childNode = childNodes[dx];
            if (childNode !== _imageMain && childNode !== _imageHelp) {
                remove(childNode);
            }
        }
        if (!width) return;
        css(_imageMain, {
            position: "absolute",
            width: width + "px",
            height: "100%",
            left: round((indexLeft - index) * width) + "px"
        });
        css(_imageHelp, {
            position: "absolute",
            width: "100%",
            height: "100%",
            left: round((indexRight - index) * width) + "px"
        });
        outter.hasLeft = _imageMain;
        outter.hasRight = _imageHelp;
    };
    var animate = function () {
        clearTimeout(timer_animate);
        var width = outter.offsetWidth;
        if (abs(current_index + negative_index) < 1.25 / width)
            return reshape(-negative_index, false);
        timer_animate = setTimeout(animate, 20);
        reshape((current_index * 3 - negative_index) / 4);
    };
    var park = function () {
        direction = 0;
        if (delta_negative_index > 0) {
            if (negative_index - floor(negative_index) > 0.3 / (1 + abs(_speed())))
                negative_index = ceil(negative_index);
            else
                negative_index = floor(negative_index);
        } else if (delta_negative_index < 0) {
            if (ceil(negative_index) - negative_index > 0.3 / (1 + abs(_speed())))
                negative_index = floor(negative_index);
            else
                negative_index = ceil(negative_index);
        } else {
            negative_index = round(negative_index);
        }
        if (play.ing) {
            negative_index++;
            play();
        } else {
            animate();
        }
    };
    var play = function () {
        play.ing = true;
        clearTimeout(timer_playyer);
        timer_playyer = setTimeout(play, 5);
        negative_index--;
        animate();
    };
    var stop = function () {
        clearTimeout(timer_playyer);
        play.ing = false;
    };
    var moveDeltaX = function (deltax, event) {
        var width = outter.offsetWidth;
        if (!outter.hasLeft && deltax > 0) {
            var current_Left = parseInt(_imageHelp.style.left);
            var avail_deltaWidth = round(width >> 2);
            if (current_Left + deltax >= avail_deltaWidth) {
                deltax = avail_deltaWidth - current_Left;
                saved_x += deltax;
            } else {
                saved_x = event.clientX;
            }
            _speed(0);
        } else if (!outter.hasRight && deltax < 0) {
            var current_Left = parseInt(_imageMain.style.left);
            var avail_deltaWidth = -round(width >> 2);
            if (current_Left + deltax <= avail_deltaWidth) {
                deltax = avail_deltaWidth - current_Left;
                saved_x += deltax;
            } else {
                saved_x = event.clientX;
            }
            _speed(0);
        } else {
            saved_x = event.clientX;
            _speed(deltax);
        }
        delta_negative_index = deltax / width;
        negative_index += delta_negative_index;
        reshape(-negative_index);

    }
    var mousemove = function (event) {
        if (event.defaultPrevented) return;
        if (event.type !== "touchmove" && event.which === 0) return mouseup();
        var deltax = event.clientX - saved_x;
        var deltay = event.clientY - saved_y;
        if (!direction) {
            if (abs(deltax) < 3 && abs(deltay) < 3) return;
            if (abs(deltay) - abs(deltax) > 0) { //垂直方向
                direction = -1;
            } else { //水平方向
                direction = 1;
            }
        }
        if (direction < 0) {
            return;
        }
        if (!moving) {
            return;
        }
        event.preventDefault();
        // event.stopPropagation && event.stopPropagation();
        moveDeltaX(deltax, event);
    };
    var mouseup = function () {
        mousemove_remove();
        mouseup_remove();
        moving = has_moving_instance = false;
        park();
    };
    var stop_wheel_timer = 0;
    onmousewheel(outter, function (event) {
        if (!event.deltaX) return;
        if (event._target && event._target !== this) return;
        event._target = outter;
        clearTimeout(stop_wheel_timer);
        stop_wheel_timer = setTimeout(park, 30);
        var deltax = -event.deltaX;
        moveDeltaX(deltax, event);
    });
    var mousemove_remove, mouseup_remove;
    onmousedown(outter, function (event) {
        clearTimeout(timer_animate);
        clearTimeout(timer_playyer);
        if (has_moving_instance) {
            return;
        }
        has_moving_instance = true;
        moving = true;
        direction = 0;
        _speed(0);
        mousemove_remove = onmousemove(body, mousemove);
        mouseup_remove = onmouseup(body, mouseup);
        saved_x = event.clientX;
        saved_y = event.clientY;
    });

    if (is_touch_enabled) {
        var addEventListener = function (target, eventname, handle) {
            target.addEventListener(eventname, handle);
        };
        var removeEventListener = function (target, eventname, handle) {
            target.removeEventListener(eventname, handle);
        };
        addEventListener(outter, "touchstart", function (e) {
            clearTimeout(timer_animate);
            clearTimeout(timer_playyer);
            if (has_moving_instance) {
                return;
            }
            has_moving_instance = true;
            moving = e.target;
            direction = 0;
            _speed(0);
            addEventListener(moving, "touchmove", ontouchmove);
            addEventListener(moving, "touchcancel", ontouchend);
            addEventListener(moving, "touchend", ontouchend);
            extendTouch(e);
            saved_x = e.clientX;
            saved_y = e.clientY;
        });
        var ontouchmove = function (e) {
            extendTouch(e);
            mousemove(e);
        };
        var ontouchend = function (e) {
            removeEventListener(moving, "touchmove", ontouchmove);
            removeEventListener(moving, "touchcancel", ontouchend);
            removeEventListener(moving, "touchend", ontouchend);
            moving = has_moving_instance = false;
            park();
        };
    }
    outter.go = function (index) {
        negative_index = -index;
        reshape(index, false);
    };
    return outter;
}<commit_msg>兼容edge浏览器<commit_after>// 中文编码 utf8
var _slider = createElement(div);
css(_slider, "position:absolute;top:0px;left:0px;right:0px;bottom:0px;width:100%;height:100%;");
var container = createElement(div);
var windowInnerWidth = window.innerWidth || screen.availWidth;
css(container, "overflow:hidden;position:relative;width:100%;height:120px;font-size:60px;");
onresize(window, function (event) { });
var floor = Math.floor;
var ceil = Math.ceil;
var round = Math.round;
var abs = Math.abs;
var sign = Math.sign;
var body = document.body;
var is_touch_enabled = "ontouchstart" in window;
var extendTouch = function (e) {
    var touch = e.touches[0];
    for (var k in touch) {
        e[k] = touch[k];
    }
    return e;
};
var has_moving_instance;
/**
 *
 * @param {Boolean,Array,Function} autoplay
 */
function slider(autoplay) {
    var outter = createElement(container);
    var _imageMain = createElement(_slider);
    var _imageHelp = createElement(_slider);
    var play_autostart = autoplay === true;
    outter.src = function (index) {
        var block = createElement(_slider);
        text(block, index);
        return block;
    };
    if (isFunction(autoplay) || isArray(autoplay)) {
        outter.src = autoplay;
    }
    var generator = function (index, ratio) {
        var src = outter.src;
        if (isArray(src)) {
            src = src[index];
        }
        if (isFunction(src)) {
            src = src(index, 1 - abs(ratio));
        }
        if (src) {
            if (src.parentNode !== outter) {
                appendChild(outter, src);
            }
        }
        return src;
    };
    var negative_index = 0,
        current_index = 0,
        delta_negative_index = 0,
        timer_animate = 0,
        timer_playyer = 0,
        saved_x = 0,
        saved_y = 0,
        moving = 0,
        direction,
        _speed = speed(1);
    var reshape = function (index, ising) {
        current_index = index;
        var width = outter.offsetWidth || windowInnerWidth;
        var indexLeft = floor(index);
        var indexRight = indexLeft + 1;
        if (ising === false) {
            //预载
            generator(indexLeft - 1, 1);
            generator(indexLeft - 2, 1);
            generator(indexLeft - 3, 1);
            generator(indexLeft - 4, 1);
            generator(indexLeft + 2, 1);
            generator(indexLeft + 3, 1);
            generator(indexLeft + 4, 1);
        }
        _imageMain = generator(indexLeft, indexLeft - index);
        _imageHelp = generator(indexRight, indexRight - index);
        var childNodes = outter.childNodes;
        for (var dx = childNodes.length - 1; dx >= 0; dx--) {
            var childNode = childNodes[dx];
            if (childNode !== _imageMain && childNode !== _imageHelp) {
                remove(childNode);
            }
        }
        if (!width) return;
        css(_imageMain, {
            position: "absolute",
            width: width + "px",
            height: "100%",
            left: round((indexLeft - index) * width) + "px"
        });
        css(_imageHelp, {
            position: "absolute",
            width: "100%",
            height: "100%",
            left: round((indexRight - index) * width) + "px"
        });
        outter.hasLeft = _imageMain;
        outter.hasRight = _imageHelp;
    };
    var animate = function () {
        clearTimeout(timer_animate);
        var width = outter.offsetWidth;
        if (abs(current_index + negative_index) < 1.25 / width)
            return reshape(-negative_index, false);
        timer_animate = setTimeout(animate, 20);
        reshape((current_index * 3 - negative_index) / 4);
    };
    var park = function () {
        direction = 0;
        if (delta_negative_index > 0) {
            if (negative_index - floor(negative_index) > 0.3 / (1 + abs(_speed())))
                negative_index = ceil(negative_index);
            else
                negative_index = floor(negative_index);
        } else if (delta_negative_index < 0) {
            if (ceil(negative_index) - negative_index > 0.3 / (1 + abs(_speed())))
                negative_index = floor(negative_index);
            else
                negative_index = ceil(negative_index);
        } else {
            negative_index = round(negative_index);
        }
        if (play.ing) {
            negative_index++;
            play();
        } else {
            animate();
        }
    };
    var play = function () {
        play.ing = true;
        clearTimeout(timer_playyer);
        timer_playyer = setTimeout(play, 5);
        negative_index--;
        animate();
    };
    var stop = function () {
        clearTimeout(timer_playyer);
        play.ing = false;
    };
    var moveDeltaX = function (deltax, event) {
        var width = outter.offsetWidth;
        if (!outter.hasLeft && deltax > 0) {
            var current_Left = parseInt(_imageHelp.style.left);
            var avail_deltaWidth = round(width >> 2);
            if (current_Left + deltax >= avail_deltaWidth) {
                deltax = avail_deltaWidth - current_Left;
                saved_x += deltax;
            } else {
                saved_x = event.clientX;
            }
            _speed(0);
        } else if (!outter.hasRight && deltax < 0) {
            var current_Left = parseInt(_imageMain.style.left);
            var avail_deltaWidth = -round(width >> 2);
            if (current_Left + deltax <= avail_deltaWidth) {
                deltax = avail_deltaWidth - current_Left;
                saved_x += deltax;
            } else {
                saved_x = event.clientX;
            }
            _speed(0);
        } else {
            saved_x = event.clientX;
            _speed(deltax);
        }
        delta_negative_index = deltax / width;
        negative_index += delta_negative_index;
        reshape(-negative_index);
    };
    var mousemove = function (event) {
        if (event.defaultPrevented) return;
        if (event.type !== "touchmove" && event.which === 0) return mouseup();
        var deltax = event.clientX - saved_x;
        var deltay = event.clientY - saved_y;
        if (!direction) {
            if (abs(deltax) < 3 && abs(deltay) < 3) return;
            if (abs(deltay) - abs(deltax) > 0) { //垂直方向
                direction = -1;
            } else { //水平方向
                direction = 1;
            }
        }
        if (direction < 0) {
            return;
        }
        if (!moving) {
            return;
        }
        event.preventDefault();
        // event.stopPropagation && event.stopPropagation();
        moveDeltaX(deltax, event);
    };
    var mouseup = function () {
        mousemove_remove();
        mouseup_remove();
        moving = has_moving_instance = false;
        park();
    };
    var stop_wheel_timer = 0;
    onmousewheel(outter, function (event) {
        if (!event.deltaX) return;
        if (event._target && event._target !== this) return;
        event._target = outter;
        clearTimeout(stop_wheel_timer);
        stop_wheel_timer = setTimeout(park, 60);
        var deltax = -event.deltaX;
        moveDeltaX(deltax, event);
    });
    var mousemove_remove, mouseup_remove;
    onmousedown(outter, function (event) {
        clearTimeout(timer_animate);
        clearTimeout(timer_playyer);
        if (has_moving_instance) {
            return;
        }
        has_moving_instance = true;
        moving = true;
        direction = 0;
        _speed(0);
        mousemove_remove = onmousemove(body, mousemove);
        mouseup_remove = onmouseup(body, mouseup);
        saved_x = event.clientX;
        saved_y = event.clientY;
    });

    if (is_touch_enabled) {
        var addEventListener = function (target, eventname, handle) {
            target.addEventListener(eventname, handle);
        };
        var removeEventListener = function (target, eventname, handle) {
            target.removeEventListener(eventname, handle);
        };
        addEventListener(outter, "touchstart", function (e) {
            clearTimeout(timer_animate);
            clearTimeout(timer_playyer);
            if (has_moving_instance) {
                return;
            }
            has_moving_instance = true;
            moving = e.target;
            direction = 0;
            _speed(0);
            addEventListener(moving, "touchmove", ontouchmove);
            addEventListener(moving, "touchcancel", ontouchend);
            addEventListener(moving, "touchend", ontouchend);
            extendTouch(e);
            saved_x = e.clientX;
            saved_y = e.clientY;
        });
        var ontouchmove = function (e) {
            extendTouch(e);
            mousemove(e);
        };
        var ontouchend = function (e) {
            removeEventListener(moving, "touchmove", ontouchmove);
            removeEventListener(moving, "touchcancel", ontouchend);
            removeEventListener(moving, "touchend", ontouchend);
            moving = has_moving_instance = false;
            park();
        };
    }
    outter.go = function (index) {
        negative_index = -index;
        reshape(index, false);
    };
    return outter;
}<|endoftext|>


<commit_before>'use strict';

/*
* The following copyright, license, and long comment were part of the original implementation available as part of [FreeBSD]{@link https://svnweb.freebsd.org/base/release/9.3.0/lib/msun/src/e_exp.c?view=markup}.
*
* The implementation follows the original, but has been modified for JavaScript.
*/

/*
* ====================================================
* Copyright (C) 2004 by Sun Microsystems, Inc. All rights reserved.
*
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/

// MODULES //

var isnan = require( '@stdlib/math/base/utils/is-nan' );
var trunc = require( '@stdlib/math/base/special/truncate' );
var NINF = require( '@stdlib/math/constants/float64-ninf' );
var PINF = require( '@stdlib/math/constants/float64-pinf' );
var expmulti = require( './expmulti.js' );

// CONSTANTS //

var LN2_HI = 6.93147180369123816490e-01;
var LN2_LO = 1.90821492927058770002e-10;
var LOG2_E = 1.44269504088896338700e+00;
var OVERFLOW  = 7.09782712893383973096e+02;
var UNDERFLOW = -7.45133219101941108420e+02;
var NEARZERO  = 1.0 / (1 << 28); // 2^-28;
var NEG_NEARZERO = -NEARZERO;

// EXP //

/**
* Evaluates the natural exponential function.
*
* #### Method
*
* 1. We reduce \\( x \\) to an \\( r \\) so that \\( |r| \leq 0.5 \; \ln(2) \approx 0.34658 \\). Given \\( x \\), we find an \\( r \\) and integer \\( k \\) such that
*
*   ``` tex
*   x = k \cdot \ln(2) + r,  |r| \leq 0.5 \cdot \ln(2).
*   ```
*
*   <!-- <note> -->
*   \\( r \\) can be represented as \\( r = \mathrm{hi} - \mathrm{lo} \\) for better accuracy.
*   <!-- </note> -->
*
* 2. We approximate of \\( e^{r} \\) by a special rational function on the interval \\([0,0.34658]\\):
*
*   ``` tex
*   \begin{align*}
*   R\left(r^2\right) &= r \cdot \frac{ e^{r}+1 }{ e^{r}-1 } \\
*   &= 2 + frac{r^2}{6} - \frac{r^4}{360} + \ldots
*   \end{align*}
*   ```
*
*   We use a special Remes algorithm on \\([0,0.34658]\\) to generate a polynomial of degree \\(5\\) to approximate \\(R\\). The maximum error of this polynomial approximation is bounded by \\(2^{-59}. In other words,
*
*   ``` tex
*   R(z) \sim 2 + P_1 z + P_2 z^2 + P_3 z^3 + P_4 z^4 + P_5 z^5
*   ```
*
*   where \\( z = r^2 \\) and
*
*   ``` tex
*   \left|  2 + P_1 z + \ldots + P_5 z^5  - R(z) \right| \leq 2^{-59}
*   ```
*
*   <!-- <note> -->
*   The values of \\( P_1 \\) to \\( P_5 \\) are listed in the source code.
*   <!-- </note> -->
*   The computation of \\( e^{r} \\) thus becomes
*
*   ``` tex
*   \begin{align*}
*   e^{r} &= 1 + \frac{2r}{R-r} \\
*           &= 1 + r + \frac{r \cdot R_1(r)}{2 - R_1(r)}\ \text{for better accuracy},
*   \end{align*}
*   ```
*
*   where
*
*   ``` tex
*   R_1(r) = r - ( P_1\ r^2 + P_2\ r^4 + \ldots + P_5\ r^{10}
*   ```
*
* 3. We scale back to obtain \\( e^{x} \\). From step 1, we have
*
*   ``` tex
*   e^{x} = 2^k e^{r}
*   ```
*
*
* #### Special Cases
*
* ``` tex
* \begin{align*}
* e^\infty &= \infty \\
* e^{-\infty} &= 0 \\
* e^{\mathrm{NaN}} &= \mathrm{NaN} \\
* e^0 &= 1\ \mathrm{is\ exact\ for\ finite\ argument\ only\}
* \end{align*}
* ```
*
* #### Notes
*
* - According to an error analysis, the error is always less than \\(1\\) ulp (unit in the last place).
* - For IEEE double,
*   * if \\(x > 7.09782712893383973096\mbox{e+}02\\) then \\(e^{x}\\) overflows
*   * if \\(x < -7.45133219101941108420\mbox{e+}02\\) then \\(e^{x}\\) underflows
* - The hexadecimal values included in the source code are the intended ones for the used constants. Decimal values may be used, provided that the compiler will convert from decimal to binary accurately enough to produce the intended hexadecimal values.
*
*
* @param {number} x - input value
* @returns {number} function value
*
* @example
* var v = exp( 4.0 );
* // returns ~54.5982
* @example
* var v = exp( -9.0 );
* // returns ~1.234e-4
* @example
* var v = exp( 0.0 );
* // returns 1.0
* @example
* var v = exp( NaN );
* // returns NaN
*/
function exp( x ) {
	var hi;
	var lo;
	var k;

	if ( isnan( x ) || x === PINF ) {
		return x;
	}
	if ( x === NINF ) {
		return 0.0;
	}
	if ( x > OVERFLOW ) {
		return PINF;
	}
	if ( x < UNDERFLOW ) {
		return 0.0;
	}
	if (
		x > NEG_NEARZERO &&
		x < NEARZERO
	) {
		return 1.0 + x;
	}
	// Reduce and compute `r = hi - lo` for extra precision.
	if ( x < 0.0 ) {
		k = trunc( LOG2_E*x - 0.5 );
	} else {
		k = trunc( LOG2_E*x + 0.5 );
	}
	hi = x - k*LN2_HI;
	lo = k * LN2_LO;

	return expmulti( hi, lo, k );
} // end FUNCTION exp()

// EXPORTS //

module.exports = exp;
<commit_msg>Fix TeX markup<commit_after>'use strict';

/*
* The following copyright, license, and long comment were part of the original implementation available as part of [FreeBSD]{@link https://svnweb.freebsd.org/base/release/9.3.0/lib/msun/src/e_exp.c?view=markup}.
*
* The implementation follows the original, but has been modified for JavaScript.
*/

/*
* ====================================================
* Copyright (C) 2004 by Sun Microsystems, Inc. All rights reserved.
*
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/

// MODULES //

var isnan = require( '@stdlib/math/base/utils/is-nan' );
var trunc = require( '@stdlib/math/base/special/truncate' );
var NINF = require( '@stdlib/math/constants/float64-ninf' );
var PINF = require( '@stdlib/math/constants/float64-pinf' );
var expmulti = require( './expmulti.js' );

// CONSTANTS //

var LN2_HI = 6.93147180369123816490e-01;
var LN2_LO = 1.90821492927058770002e-10;
var LOG2_E = 1.44269504088896338700e+00;
var OVERFLOW  = 7.09782712893383973096e+02;
var UNDERFLOW = -7.45133219101941108420e+02;
var NEARZERO  = 1.0 / (1 << 28); // 2^-28;
var NEG_NEARZERO = -NEARZERO;

// EXP //

/**
* Evaluates the natural exponential function.
*
* #### Method
*
* 1. We reduce \\( x \\) to an \\( r \\) so that \\( |r| \leq 0.5 \cdot \ln(2) \approx 0.34658 \\). Given \\( x \\), we find an \\( r \\) and integer \\( k \\) such that
*
*   ``` tex
*   \begin{align*}
*   x &= k \cdot \ln(2) + r \\
*   |r| &\leq 0.5 \cdot \ln(2)
*   \end{align*}
*   ```
*
*   <!-- <note> -->
*   \\( r \\) can be represented as \\( r = \mathrm{hi} - \mathrm{lo} \\) for better accuracy.
*   <!-- </note> -->
*
* 2. We approximate of \\( e^{r} \\) by a special rational function on the interval \\([0,0.34658]\\):
*
*   ``` tex
*   \begin{align*}
*   R\left(r^2\right) &= r \cdot \frac{ e^{r}+1 }{ e^{r}-1 } \\
*   &= 2 + \frac{r^2}{6} - \frac{r^4}{360} + \ldots
*   \end{align*}
*   ```
*
*   We use a special Remes algorithm on \\([0,0.34658]\\) to generate a polynomial of degree \\(5\\) to approximate \\(R\\). The maximum error of this polynomial approximation is bounded by \\(2^{-59}\\). In other words,
*
*   ``` tex
*   R(z) \sim 2 + P_1 z + P_2 z^2 + P_3 z^3 + P_4 z^4 + P_5 z^5
*   ```
*
*   where \\( z = r^2 \\) and
*
*   ``` tex
*   \left|  2 + P_1 z + \ldots + P_5 z^5  - R(z) \right| \leq 2^{-59}
*   ```
*
*   <!-- <note> -->
*   The values of \\( P_1 \\) to \\( P_5 \\) are listed in the source code.
*   <!-- </note> -->
*   The computation of \\( e^{r} \\) thus becomes
*
*   ``` tex
*   \begin{align*}
*   e^{r} &= 1 + \frac{2r}{R-r} \\
*           &= 1 + r + \frac{r \cdot R_1(r)}{2 - R_1(r)}\ \text{for better accuracy}
*   \end{align*}
*   ```
*
*   where
*
*   ``` tex
*   R_1(r) = r - P_1\ r^2 + P_2\ r^4 + \ldots + P_5\ r^{10}
*   ```
*
* 3. We scale back to obtain \\( e^{x} \\). From step 1, we have
*
*   ``` tex
*   e^{x} = 2^k e^{r}
*   ```
*
*
* #### Special Cases
*
* ``` tex
* \begin{align*}
* e^\infty &= \infty \\
* e^{-\infty} &= 0 \\
* e^{\mathrm{NaN}} &= \mathrm{NaN} \\
* e^0 &= 1\ \mathrm{is\ exact\ for\ finite\ argument\ only}
* \end{align*}
* ```
*
* #### Notes
*
* - According to an error analysis, the error is always less than \\(1\\) ulp (unit in the last place).
* - For IEEE double,
*   * if \\(x > 7.09782712893383973096\mbox{e+}02\\), then \\(e^{x}\\) overflows
*   * if \\(x < -7.45133219101941108420\mbox{e+}02\\), then \\(e^{x}\\) underflows
* - The hexadecimal values included in the source code are the intended ones for the used constants. Decimal values may be used, provided that the compiler will convert from decimal to binary accurately enough to produce the intended hexadecimal values.
*
*
* @param {number} x - input value
* @returns {number} function value
*
* @example
* var v = exp( 4.0 );
* // returns ~54.5982
* @example
* var v = exp( -9.0 );
* // returns ~1.234e-4
* @example
* var v = exp( 0.0 );
* // returns 1.0
* @example
* var v = exp( NaN );
* // returns NaN
*/
function exp( x ) {
	var hi;
	var lo;
	var k;

	if ( isnan( x ) || x === PINF ) {
		return x;
	}
	if ( x === NINF ) {
		return 0.0;
	}
	if ( x > OVERFLOW ) {
		return PINF;
	}
	if ( x < UNDERFLOW ) {
		return 0.0;
	}
	if (
		x > NEG_NEARZERO &&
		x < NEARZERO
	) {
		return 1.0 + x;
	}
	// Reduce and compute `r = hi - lo` for extra precision.
	if ( x < 0.0 ) {
		k = trunc( LOG2_E*x - 0.5 );
	} else {
		k = trunc( LOG2_E*x + 0.5 );
	}
	hi = x - k*LN2_HI;
	lo = k * LN2_LO;

	return expmulti( hi, lo, k );
} // end FUNCTION exp()

// EXPORTS //

module.exports = exp;
<|endoftext|>


<commit_before>var $ = require('jquery');

var ToolbarUpdater = function($changelist) {
    this.$changelist = $changelist;
};

ToolbarUpdater.prototype = {
    getToolbar: function($changelist) {
        var $toolbar = $changelist.find('#toolbar');

        if ($toolbar.length == 0) {
            $toolbar = $('<div>').attr('id', 'toolbar');
            $('#changelist').prepend($toolbar);
        }

        return $toolbar;
    },
    updateToolbar: function($toolbar) {
        var placeholder = $toolbar.find('input[type="submit"]').val();
        $toolbar.find('#searchbar').attr('placeholder', placeholder);
    },
    moveFilters: function($changelist, $toolbar) {
        var filterName;
        var $search = $toolbar.find('#searchbar');

        $changelist.find('#changelist-filter').children().each(function() {
            var $element = $(this);

            if ($element.prop('tagName') == 'H3') {
                filterName = $element.text();
            } else if ($element.prop('tagName') == 'UL') {
                var $select = $('<select>').addClass('changelist-filter-select');
                var $items = $element.find('li');

                $.each($element.prop('attributes'), function() {
                    $select.attr(this.name, this.value);
                });

                if ($items.filter('.selected').length > 1) {
                    $select.attr('multiple', true);
                }

                $items.each(function(i) {
                    var $item = $(this);
                    var $link = $item.find('a');
                    var $option = $('<option>')
                        .text($link.text())
                        .attr('data-url', $link.attr('href'))
                        .attr('selected', $item.hasClass('selected'));

                    if (i == 0 ) {
                        if (filterName != null) {
                            $option.text(filterName)
                        }

                        var $separator = $('<option>')
                            .attr('disabled', true)
                            .text('---');

                        $option = $option.add($separator);
                    }

                    $select.append($option);
                });

                var $wrapper = $('<span>')
                    .addClass('changelist-filter-select-wrapper')
                    .append($select);

                if ($search.length) {
                    $wrapper.insertAfter($search);
                } else {
                    $toolbar.append($wrapper);
                }

                filterName = null;
            } else if ($element.hasClass('changelist-filter-popup')) {
                var $toggle = $element.find('.changelist-filter-popup-toggle');
                var $content = $element.find('.changelist-filter-popup-content');
                var $wrapper = $('<span>')
                    .addClass('changelist-filter-select-wrapper')
                    .append($element);

                if ($search.length) {
                    $wrapper.insertAfter($search);
                } else {
                    $toolbar.append($wrapper);
                }

                $toggle.on('click', function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    $content.toggleClass('visible');
                });

                $content.on('click', function(e) {
                    e.stopPropagation();
                });

                $(document.body).on('click', function() {
                    $content.removeClass('visible');
                });
            }
        });

        $changelist.find('#changelist-filter').remove();
    },
    fixFloatLineBreak: function() {
        $('#content-main').each(function() {
            var $content = $(this);

            $.each(['#toolbar', '.object-tools', 'changeform-navigation'], function(i, selector) {
                var $element = $content.find(selector).first();

                if ($element.length == 0) {
                    return;
                }

                $('<div>')
                    .addClass('clear')
                    .insertAfter($element);

                return false;
            });
        });
    },
    run: function() {
        var $toolbar = this.getToolbar(this.$changelist);

        try {
            this.updateToolbar($toolbar);
            this.moveFilters(this.$changelist, $toolbar);
        } catch (e) {
            console.error(e, e.stack);
        }

        try {
            this.fixFloatLineBreak();
        } catch (e) {
            console.error(e, e.stack);
        }

        $toolbar.addClass('initialized');
    }
};

$(document).ready(function() {
    $('#changelist').each(function() {
        new ToolbarUpdater($(this)).run();
    });
});
<commit_msg>Fix select class name override<commit_after>var $ = require('jquery');

var ToolbarUpdater = function($changelist) {
    this.$changelist = $changelist;
};

ToolbarUpdater.prototype = {
    getToolbar: function($changelist) {
        var $toolbar = $changelist.find('#toolbar');

        if ($toolbar.length == 0) {
            $toolbar = $('<div>').attr('id', 'toolbar');
            $('#changelist').prepend($toolbar);
        }

        return $toolbar;
    },
    updateToolbar: function($toolbar) {
        var placeholder = $toolbar.find('input[type="submit"]').val();
        $toolbar.find('#searchbar').attr('placeholder', placeholder);
    },
    moveFilters: function($changelist, $toolbar) {
        var filterName;
        var $search = $toolbar.find('#searchbar');

        $changelist.find('#changelist-filter').children().each(function() {
            var $element = $(this);

            if ($element.prop('tagName') == 'H3') {
                filterName = $element.text();
            } else if ($element.prop('tagName') == 'UL') {
                var $select = $('<select>');
                var $items = $element.find('li');

                $.each($element.prop('attributes'), function() {
                    $select.attr(this.name, this.value);
                });

                $select.addClass('changelist-filter-select');

                if ($items.filter('.selected').length > 1) {
                    $select.attr('multiple', true);
                }

                $items.each(function(i) {
                    var $item = $(this);
                    var $link = $item.find('a');
                    var $option = $('<option>')
                        .text($link.text())
                        .attr('data-url', $link.attr('href'))
                        .attr('selected', $item.hasClass('selected'));

                    if (i == 0 ) {
                        if (filterName != null) {
                            $option.text(filterName)
                        }

                        var $separator = $('<option>')
                            .attr('disabled', true)
                            .text('---');

                        $option = $option.add($separator);
                    }

                    $select.append($option);
                });

                var $wrapper = $('<span>')
                    .addClass('changelist-filter-select-wrapper')
                    .append($select);

                if ($search.length) {
                    $wrapper.insertAfter($search);
                } else {
                    $toolbar.append($wrapper);
                }

                filterName = null;
            } else if ($element.hasClass('changelist-filter-popup')) {
                var $toggle = $element.find('.changelist-filter-popup-toggle');
                var $content = $element.find('.changelist-filter-popup-content');
                var $wrapper = $('<span>')
                    .addClass('changelist-filter-select-wrapper')
                    .append($element);

                if ($search.length) {
                    $wrapper.insertAfter($search);
                } else {
                    $toolbar.append($wrapper);
                }

                $toggle.on('click', function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    $content.toggleClass('visible');
                });

                $content.on('click', function(e) {
                    e.stopPropagation();
                });

                $(document.body).on('click', function() {
                    $content.removeClass('visible');
                });
            }
        });

        $changelist.find('#changelist-filter').remove();
    },
    fixFloatLineBreak: function() {
        $('#content-main').each(function() {
            var $content = $(this);

            $.each(['#toolbar', '.object-tools', 'changeform-navigation'], function(i, selector) {
                var $element = $content.find(selector).first();

                if ($element.length == 0) {
                    return;
                }

                $('<div>')
                    .addClass('clear')
                    .insertAfter($element);

                return false;
            });
        });
    },
    run: function() {
        var $toolbar = this.getToolbar(this.$changelist);

        try {
            this.updateToolbar($toolbar);
            this.moveFilters(this.$changelist, $toolbar);
        } catch (e) {
            console.error(e, e.stack);
        }

        try {
            this.fixFloatLineBreak();
        } catch (e) {
            console.error(e, e.stack);
        }

        $toolbar.addClass('initialized');
    }
};

$(document).ready(function() {
    $('#changelist').each(function() {
        new ToolbarUpdater($(this)).run();
    });
});
<|endoftext|>


<commit_before>// @vue/component
export default {
  name: 'BVCarbonAd',
  props: {
    id: {
      type: String,
      default: '_carbonads_js'
    },
    url: {
      type: String,
      default: '//cdn.carbonads.com/carbon.js'
    },
    serve: {
      type: String,
      default: 'CE7ITK77'
    },
    placement: {
      type: String,
      default: 'bootstrap-vuejsorg'
    }
  },
  data() {
    return {
      mounted: false
    }
  },
  computed: {
    src() {
      return `${this.url}?serve=${this.serve}&placement=${this.placement}`
    }
  },
  mounted() {
    this.$nextTick(() => {
      requestAnimationFrame(() => {
        this.mounted = true
      })
    })
  },
  beforeDestroy() {
    this.mounted = false
  },
  render(h) {
    let $script = h()
    if (this.mounted) {
      $script = h('script', {
        attrs: {
          id: this.id,
          async: 'async',
          type: 'text/javascript',
          src: this.src
        }
      })
    }
    return h('aside', { staticClass: 'bv-carbon-ad' }, [$script])
  }
}
<commit_msg>chore(docs): remove any old Carbonads scripts from `<head>` (#5422)<commit_after>// @vue/component
export default {
  name: 'BVCarbonAd',
  props: {
    id: {
      type: String,
      default: '_carbonads_js'
    },
    url: {
      type: String,
      default: '//cdn.carbonads.com/carbon.js'
    },
    serve: {
      type: String,
      default: 'CE7ITK77'
    },
    placement: {
      type: String,
      default: 'bootstrap-vuejsorg'
    }
  },
  data() {
    return {
      mounted: false
    }
  },
  computed: {
    src() {
      return `${this.url}?serve=${this.serve}&placement=${this.placement}`
    }
  },
  mounted() {
    // Remove any leftover Carbonads scripts from the `<head>`
    const $nodes = document.querySelectorAll('head > script[id="_carbonads_projs"]')
    for (const $node of $nodes) {
      try {
        $node.parentNode.removeChild($node)
      } catch {}
    }

    // Show the new ad
    this.$nextTick(() => {
      requestAnimationFrame(() => {
        this.mounted = true
      })
    })
  },
  beforeDestroy() {
    this.mounted = false
  },
  render(h) {
    let $script = h()
    if (this.mounted) {
      $script = h('script', {
        attrs: {
          id: this.id,
          async: 'async',
          type: 'text/javascript',
          src: this.src
        }
      })
    }
    return h('aside', { staticClass: 'bv-carbon-ad' }, [$script])
  }
}
<|endoftext|>


<commit_before>
//
// Copyright © 2016-present Kary Foundation, Inc. All Rights Reserved
//   Author: Pouya Kary <k@karyfoundation.org>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//

//
// ─── TOGGLE CONSOLE ─────────────────────────────────────────────────────────────
//

    function onToggleSideConsole ( ) {
        let sideConsole = document.getElementById( editorContainerId )

        if ( sideConsole.className === "" )
            sideConsole.className = hideShowSideConsoleClassName
        else
            sideConsole.className = ""

        let resizer = setInterval( ( ) => { Blockly.svgResize( workspace ) }, 30 )
        setTimeout( ( ) => { clearInterval( resizer ) }, 400 )
    }

// ────────────────────────────────────────────────────────────────────────────────
<commit_msg>going for 60fps<commit_after>
//
// Copyright © 2016-present Kary Foundation, Inc. All Rights Reserved
//   Author: Pouya Kary <k@karyfoundation.org>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//

//
// ─── TOGGLE CONSOLE ─────────────────────────────────────────────────────────────
//

    function onToggleSideConsole ( ) {
        let sideConsole = document.getElementById( editorContainerId )

        if ( sideConsole.className === "" )
            sideConsole.className = hideShowSideConsoleClassName
        else
            sideConsole.className = ""

        let resizer = setInterval( ( ) => { Blockly.svgResize( workspace ) }, 15 )
        setTimeout( ( ) => { clearInterval( resizer ) }, 400 )
    }

// ────────────────────────────────────────────────────────────────────────────────
<|endoftext|>


<commit_before>"use strict";

class gsuiPatterns {
	constructor( opt ) {
		const root = gsuiPatterns.template.cloneNode( true ),
			elNewDrums = root.querySelector( "[data-action='newDrums']" ),
			elNewSynth = root.querySelector( "[data-action='newSynth']" ),
			elBufferList = root.querySelector( ".gsuiPatterns-panelBuffers .gsuiPatterns-panel-list" ),
			elDrumsList = root.querySelector( ".gsuiPatterns-panelDrums .gsuiPatterns-panel-list" ),
			elSynthList = root.querySelector( ".gsuiPatterns-panelKeys .gsuiPatterns-panel-list" ),
			nlKeysLists = root.getElementsByClassName( "gsuiPatterns-synth-patterns" ),
			fnsPattern = Object.freeze( {
				clone: id => this.onchange( "clonePattern", id ),
				remove: id => this.onchange( "removePattern", id ),
				undefined: id => this.onchange( "openPattern", id ),
				redirect: ( id, e ) => this._openChannelsPopup( "pattern", id, e ),
			} ),
			fnsSynth = Object.freeze( {
				expand: id => this.expandSynth( id ),
				undefined: id => this.onchange( "openSynth", id ),
				redirect: ( id, e ) => this._openChannelsPopup( "synth", id, e ),
				newPattern: id => {
					this.onchange( "addPatternKeys", id );
					this.expandSynth( id, true );
				},
				delete: id => {
					elSynthList.children.length > 1
						? this.onchange( "removeSynth", id )
						: gsuiPopup.alert( "Error", "You have to keep at least one synthesizer" );
				},
			} );

		this.rootElement = root;
		this.onchange = opt.onchange;
		this._elBufferList = elBufferList;
		this._elDrumsList = elDrumsList;
		this._elSynthList = elSynthList;
		this._nlKeysLists = nlKeysLists;
		this._fnsSynth = fnsSynth;
		this._fnsPattern = fnsPattern;
		Object.freeze( this );

		new gsuiReorder( {
			rootElement: elBufferList,
			direction: "column",
			dataTransfer: opt.patternDataTransfer,
			dataTransferType: "pattern-buffer",
			itemSelector: ".gsuiPatterns-pattern",
			handleSelector: ".gsuiPatterns-pattern-grip",
			parentSelector: ".gsuiPatterns-panel-list",
			onchange: this._onreorderPatterns.bind( this, elBufferList ),
		} );
		new gsuiReorder( {
			rootElement: elDrumsList,
			direction: "column",
			dataTransfer: opt.patternDataTransfer,
			dataTransferType: "pattern-drums",
			itemSelector: ".gsuiPatterns-pattern",
			handleSelector: ".gsuiPatterns-pattern-grip",
			parentSelector: ".gsuiPatterns-panel-list",
			onchange: this._onreorderPatterns.bind( this, elDrumsList ),
		} );
		new gsuiReorder( {
			rootElement: elSynthList,
			direction: "column",
			dataTransfer: opt.patternDataTransfer,
			dataTransferType: "pattern-keys",
			itemSelector: ".gsuiPatterns-pattern",
			handleSelector: ".gsuiPatterns-pattern-grip",
			parentSelector: ".gsuiPatterns-synth-patterns",
			onchange: this._onreorderPatternsKeys.bind( this ),
		} );
		elSynthList.ondragover = e => {
			const syn = e.target.closest( ".gsuiPatterns-synth" );

			if ( syn ) {
				this.expandSynth( syn.dataset.id, true );
			}
		};
		elSynthList.ondblclick = e => {
			if ( e.target.classList.contains( "gsuiPatterns-synth-info" ) ) {
				this.expandSynth( e.target.closest( ".gsuiPatterns-synth" ).dataset.id );
			}
		};
		elBufferList.onclick =
		elDrumsList.onclick = this._onclickListPatterns.bind( this );
		elSynthList.onclick = this._onclickSynths.bind( this );
		elNewDrums.onclick = () => this.onchange( "addPatternDrums" );
		elNewSynth.onclick = () => this.onchange( "addSynth" );
	}

	// .........................................................................
	attached() {
		const panels = new gsuiPanels( this.rootElement );

		panels.attached();
	}
	expandSynth( id, b ) {
		const root = this._getSynth( id ),
			show = root.classList.toggle( "gsuiPatterns-synth-expanded", b );

		root.querySelector( ".gsuiPatterns-synth-expand" ).dataset.icon = `caret-${ show ? "down" : "right" }`;
	}
	reorderPatterns( patterns ) {
		gsuiReorder.listReorder( this._elBufferList, patterns );
		gsuiReorder.listReorder( this._elDrumsList, patterns );
		Array.prototype.forEach.call( this._nlKeysLists, list => {
			gsuiReorder.listReorder( list, patterns );
		} );
	}
	_openChannelsPopup( objFamily, objId, e ) {
		const currChanId = e.target.dataset.id;

		gsuiPatterns.selectChanPopupSelect.value = currChanId;
		gsuiPopup.custom( {
			title: "Channels",
			element: gsuiPatterns.selectChanPopupContent,
			submit: data => {
				if ( data.channel !== currChanId ) {
					this.onchange( "redirectToChannel", objFamily, objId, data.channel );
				}
			}
		} );
	}

	// .........................................................................
	addChannel( id, name ) {
		const elOpt = document.createElement( "option" );

		elOpt.value = id;
		elOpt.textContent = name;
		gsuiPatterns.selectChanPopupSelect.append( elOpt );
	}
	updateChannel( id, name ) {
		gsuiPatterns.selectChanPopupSelect.querySelector( `option[value="${ id }"]` ).textContent = name;
		this.rootElement.querySelectorAll( `.gsuiPatterns-btnSolid[data-id="${ id }"] .gsuiPatterns-btnText` )
			.forEach( el => el.textContent = name );
	}
	deleteChannel( id ) {
		gsuiPatterns.selectChanPopupSelect.querySelector( `option[value="${ id }"]` ).remove();
	}

	// .........................................................................
	addSynth( id ) {
		const elSyn = gsuiPatterns.synthTemplate.cloneNode( true );

		elSyn.dataset.id = id;
		this._elSynthList.prepend( elSyn );
	}
	changeSynth( id, prop, val ) {
		const elSyn = this._getSynth( id );

		switch ( prop ) {
			case "name": elSyn.querySelector( ".gsuiPatterns-synth-name" ).textContent = val; break;
			case "dest": elSyn.querySelector( ".gsuiPatterns-synth-dest" ).dataset.id = val; break;
			case "destName": elSyn.querySelector( ".gsuiPatterns-synth-dest .gsuiPatterns-btnText" ).textContent = val; break;
		}
	}
	deleteSynth( id ) {
		this._getSynth( id ).remove();
	}

	// .........................................................................
	addPattern( id, { type, synth } ) {
		const elPat = gsuiPatterns.patternTemplate.cloneNode( true );

		elPat.dataset.id = id;
		if ( type !== "buffer" ) {
			elPat.querySelector( ".gsuiPatterns-destArrow" ).remove();
			elPat.querySelector( ".gsuiPatterns-pattern-dest" ).remove();
		} else {
			elPat.querySelector( "[data-action='clone']" ).remove(); // 1.
		}
		this._getPatternParent( type, synth ).append( elPat );
	}
	changePattern( id, prop, val ) {
		const elPat = this._getPattern( id );

		switch ( prop ) {
			case "order": elPat.dataset.order = val; break;
			case "name": elPat.querySelector( ".gsuiPatterns-pattern-name" ).textContent = val; break;
			case "dest": elPat.querySelector( ".gsuiPatterns-pattern-dest" ).dataset.id = val; break;
			case "destName": elPat.querySelector( ".gsuiPatterns-pattern-dest .gsuiPatterns-btnText" ).textContent = val; break;
			case "synth": this._getPatternParent( "keys", val ).append( elPat ); break;
		}
	}
	appendPatternSVG( id, svg ) {
		svg.classList.add( "gsuiPatterns-pattern-svg" );
		this._getPattern( id ).querySelector( ".gsuiPatterns-pattern-content" ).append( svg );
	}
	deletePattern( id ) {
		const elPat = this._getPattern( id );

		if ( elPat ) { // 2.
			elPat.remove();
		}
	}

	// .........................................................................
	selectPattern( type, id ) {
		const elList = type === "drums"
				? this._elDrumsList
				: this._elSynthList;

		elList.querySelector( ".gsuiPatterns-pattern-selected" )?.classList?.remove( "gsuiPatterns-pattern-selected" );
		this._getPattern( id )?.classList?.add( "gsuiPatterns-pattern-selected" );
	}
	selectSynth( id ) {
		this._elSynthList.querySelector( ".gsuiPatterns-synth-selected" )?.classList?.remove( "gsuiPatterns-synth-selected" );
		this._getSynth( id ).classList.add( "gsuiPatterns-synth-selected" );
	}

	// .........................................................................
	_getSynth( id ) {
		return this._elSynthList.querySelector( `.gsuiPatterns-synth[data-id="${ id }"]` );
	}
	_getPattern( id ) {
		return this.rootElement.querySelector( `.gsuiPatterns-pattern[data-id="${ id }"]` );
	}
	_getPatternParent( type, synthId ) {
		switch ( type ) {
			case "buffer": return this._elBufferList;
			case "drums": return this._elDrumsList;
			case "keys": return this._elSynthList.querySelector( `.gsuiPatterns-synth[data-id="${ synthId }"] .gsuiPatterns-synth-patterns` );
		}
	}

	// .........................................................................
	_onreorderPatterns( list, elPat ) {
		this.onchange( "reorderPattern", elPat.dataset.id,
			gsuiReorder.listComputeOrderChange( list, {} ) );
	}
	_onreorderPatternsKeys( elPat, indA, indB, parA, parB ) {
		if ( parA === parB ) {
			this._onreorderPatterns( parA, elPat );
		} else {
			const patId = elPat.dataset.id,
				synth = parB.parentNode.dataset.id,
				patterns = { [ patId ]: { synth } };

			gsuiReorder.listComputeOrderChange( parA, patterns );
			gsuiReorder.listComputeOrderChange( parB, patterns );
			this.onchange( "redirectPatternKeys", patId, synth, patterns );
		}
	}
	_onclickListPatterns( e ) {
		const pat = e.target.closest( ".gsuiPatterns-pattern" );

		if ( pat ) {
			this._fnsPattern[ e.target.dataset.action ]( pat.dataset.id, e );
			return false;
		}
	}
	_onclickSynths( e ) {
		if ( this._onclickListPatterns( e ) !== false ) {
			const syn = e.target.closest( ".gsuiPatterns-synth" );

			if ( syn ) {
				this._fnsSynth[ e.target.dataset.action ]( syn.dataset.id, e );
			}
		}
	}
}

gsuiPatterns.selectChanPopupContent = document.querySelector( "#gsuiPatterns-selectChanPopupContent" );
gsuiPatterns.selectChanPopupSelect = document.querySelector( "#gsuiPatterns-selectChanPopupSelect" );
gsuiPatterns.selectChanPopupContent.remove();

gsuiPatterns.template = document.querySelector( "#gsuiPatterns-template" );
gsuiPatterns.template.remove();
gsuiPatterns.template.removeAttribute( "id" );

gsuiPatterns.synthTemplate = document.querySelector( "#gsuiPatterns-synth-template" );
gsuiPatterns.synthTemplate.remove();
gsuiPatterns.synthTemplate.removeAttribute( "id" );

gsuiPatterns.patternTemplate = document.querySelector( "#gsuiPatterns-pattern-template" );
gsuiPatterns.patternTemplate.remove();
gsuiPatterns.patternTemplate.removeAttribute( "id" );

Object.freeze( gsuiPatterns );

/*
1. The cloning feature for the patterns of type buffer is removed because it's for the moment useless.
2. We are checking if the pattern exists because the entire synth could have been removed before.
*/
<commit_msg>gsuiPatterns: update the redirect actions' name<commit_after>"use strict";

class gsuiPatterns {
	constructor( opt ) {
		const root = gsuiPatterns.template.cloneNode( true ),
			elNewDrums = root.querySelector( "[data-action='newDrums']" ),
			elNewSynth = root.querySelector( "[data-action='newSynth']" ),
			elBufferList = root.querySelector( ".gsuiPatterns-panelBuffers .gsuiPatterns-panel-list" ),
			elDrumsList = root.querySelector( ".gsuiPatterns-panelDrums .gsuiPatterns-panel-list" ),
			elSynthList = root.querySelector( ".gsuiPatterns-panelKeys .gsuiPatterns-panel-list" ),
			nlKeysLists = root.getElementsByClassName( "gsuiPatterns-synth-patterns" ),
			fnsPattern = Object.freeze( {
				clone: id => this.onchange( "clonePattern", id ),
				remove: id => this.onchange( "removePattern", id ),
				undefined: id => this.onchange( "openPattern", id ),
				redirect: ( id, e ) => this._openChannelsPopup( "redirectPatternBuffer", id, e ),
			} ),
			fnsSynth = Object.freeze( {
				expand: id => this.expandSynth( id ),
				undefined: id => this.onchange( "openSynth", id ),
				redirect: ( id, e ) => this._openChannelsPopup( "redirectSynth", id, e ),
				newPattern: id => {
					this.onchange( "addPatternKeys", id );
					this.expandSynth( id, true );
				},
				delete: id => {
					elSynthList.children.length > 1
						? this.onchange( "removeSynth", id )
						: gsuiPopup.alert( "Error", "You have to keep at least one synthesizer" );
				},
			} );

		this.rootElement = root;
		this.onchange = opt.onchange;
		this._elBufferList = elBufferList;
		this._elDrumsList = elDrumsList;
		this._elSynthList = elSynthList;
		this._nlKeysLists = nlKeysLists;
		this._fnsSynth = fnsSynth;
		this._fnsPattern = fnsPattern;
		Object.freeze( this );

		new gsuiReorder( {
			rootElement: elBufferList,
			direction: "column",
			dataTransfer: opt.patternDataTransfer,
			dataTransferType: "pattern-buffer",
			itemSelector: ".gsuiPatterns-pattern",
			handleSelector: ".gsuiPatterns-pattern-grip",
			parentSelector: ".gsuiPatterns-panel-list",
			onchange: this._onreorderPatterns.bind( this, elBufferList ),
		} );
		new gsuiReorder( {
			rootElement: elDrumsList,
			direction: "column",
			dataTransfer: opt.patternDataTransfer,
			dataTransferType: "pattern-drums",
			itemSelector: ".gsuiPatterns-pattern",
			handleSelector: ".gsuiPatterns-pattern-grip",
			parentSelector: ".gsuiPatterns-panel-list",
			onchange: this._onreorderPatterns.bind( this, elDrumsList ),
		} );
		new gsuiReorder( {
			rootElement: elSynthList,
			direction: "column",
			dataTransfer: opt.patternDataTransfer,
			dataTransferType: "pattern-keys",
			itemSelector: ".gsuiPatterns-pattern",
			handleSelector: ".gsuiPatterns-pattern-grip",
			parentSelector: ".gsuiPatterns-synth-patterns",
			onchange: this._onreorderPatternsKeys.bind( this ),
		} );
		elSynthList.ondragover = e => {
			const syn = e.target.closest( ".gsuiPatterns-synth" );

			if ( syn ) {
				this.expandSynth( syn.dataset.id, true );
			}
		};
		elSynthList.ondblclick = e => {
			if ( e.target.classList.contains( "gsuiPatterns-synth-info" ) ) {
				this.expandSynth( e.target.closest( ".gsuiPatterns-synth" ).dataset.id );
			}
		};
		elBufferList.onclick =
		elDrumsList.onclick = this._onclickListPatterns.bind( this );
		elSynthList.onclick = this._onclickSynths.bind( this );
		elNewDrums.onclick = () => this.onchange( "addPatternDrums" );
		elNewSynth.onclick = () => this.onchange( "addSynth" );
	}

	// .........................................................................
	attached() {
		const panels = new gsuiPanels( this.rootElement );

		panels.attached();
	}
	expandSynth( id, b ) {
		const root = this._getSynth( id ),
			show = root.classList.toggle( "gsuiPatterns-synth-expanded", b );

		root.querySelector( ".gsuiPatterns-synth-expand" ).dataset.icon = `caret-${ show ? "down" : "right" }`;
	}
	reorderPatterns( patterns ) {
		gsuiReorder.listReorder( this._elBufferList, patterns );
		gsuiReorder.listReorder( this._elDrumsList, patterns );
		Array.prototype.forEach.call( this._nlKeysLists, list => {
			gsuiReorder.listReorder( list, patterns );
		} );
	}
	_openChannelsPopup( action, objId, e ) {
		const currChanId = e.target.dataset.id;

		gsuiPatterns.selectChanPopupSelect.value = currChanId;
		gsuiPopup.custom( {
			title: "Channels",
			element: gsuiPatterns.selectChanPopupContent,
			submit: data => {
				if ( data.channel !== currChanId ) {
					this.onchange( action, objId, data.channel );
				}
			}
		} );
	}

	// .........................................................................
	addChannel( id, name ) {
		const elOpt = document.createElement( "option" );

		elOpt.value = id;
		elOpt.textContent = name;
		gsuiPatterns.selectChanPopupSelect.append( elOpt );
	}
	updateChannel( id, name ) {
		gsuiPatterns.selectChanPopupSelect.querySelector( `option[value="${ id }"]` ).textContent = name;
		this.rootElement.querySelectorAll( `.gsuiPatterns-btnSolid[data-id="${ id }"] .gsuiPatterns-btnText` )
			.forEach( el => el.textContent = name );
	}
	deleteChannel( id ) {
		gsuiPatterns.selectChanPopupSelect.querySelector( `option[value="${ id }"]` ).remove();
	}

	// .........................................................................
	addSynth( id ) {
		const elSyn = gsuiPatterns.synthTemplate.cloneNode( true );

		elSyn.dataset.id = id;
		this._elSynthList.prepend( elSyn );
	}
	changeSynth( id, prop, val ) {
		const elSyn = this._getSynth( id );

		switch ( prop ) {
			case "name": elSyn.querySelector( ".gsuiPatterns-synth-name" ).textContent = val; break;
			case "dest": elSyn.querySelector( ".gsuiPatterns-synth-dest" ).dataset.id = val; break;
			case "destName": elSyn.querySelector( ".gsuiPatterns-synth-dest .gsuiPatterns-btnText" ).textContent = val; break;
		}
	}
	deleteSynth( id ) {
		this._getSynth( id ).remove();
	}

	// .........................................................................
	addPattern( id, { type, synth } ) {
		const elPat = gsuiPatterns.patternTemplate.cloneNode( true );

		elPat.dataset.id = id;
		if ( type !== "buffer" ) {
			elPat.querySelector( ".gsuiPatterns-destArrow" ).remove();
			elPat.querySelector( ".gsuiPatterns-pattern-dest" ).remove();
		} else {
			elPat.querySelector( "[data-action='clone']" ).remove(); // 1.
		}
		this._getPatternParent( type, synth ).append( elPat );
	}
	changePattern( id, prop, val ) {
		const elPat = this._getPattern( id );

		switch ( prop ) {
			case "order": elPat.dataset.order = val; break;
			case "name": elPat.querySelector( ".gsuiPatterns-pattern-name" ).textContent = val; break;
			case "dest": elPat.querySelector( ".gsuiPatterns-pattern-dest" ).dataset.id = val; break;
			case "destName": elPat.querySelector( ".gsuiPatterns-pattern-dest .gsuiPatterns-btnText" ).textContent = val; break;
			case "synth": this._getPatternParent( "keys", val ).append( elPat ); break;
		}
	}
	appendPatternSVG( id, svg ) {
		svg.classList.add( "gsuiPatterns-pattern-svg" );
		this._getPattern( id ).querySelector( ".gsuiPatterns-pattern-content" ).append( svg );
	}
	deletePattern( id ) {
		const elPat = this._getPattern( id );

		if ( elPat ) { // 2.
			elPat.remove();
		}
	}

	// .........................................................................
	selectPattern( type, id ) {
		const elList = type === "drums"
				? this._elDrumsList
				: this._elSynthList;

		elList.querySelector( ".gsuiPatterns-pattern-selected" )?.classList?.remove( "gsuiPatterns-pattern-selected" );
		this._getPattern( id )?.classList?.add( "gsuiPatterns-pattern-selected" );
	}
	selectSynth( id ) {
		this._elSynthList.querySelector( ".gsuiPatterns-synth-selected" )?.classList?.remove( "gsuiPatterns-synth-selected" );
		this._getSynth( id ).classList.add( "gsuiPatterns-synth-selected" );
	}

	// .........................................................................
	_getSynth( id ) {
		return this._elSynthList.querySelector( `.gsuiPatterns-synth[data-id="${ id }"]` );
	}
	_getPattern( id ) {
		return this.rootElement.querySelector( `.gsuiPatterns-pattern[data-id="${ id }"]` );
	}
	_getPatternParent( type, synthId ) {
		switch ( type ) {
			case "buffer": return this._elBufferList;
			case "drums": return this._elDrumsList;
			case "keys": return this._elSynthList.querySelector( `.gsuiPatterns-synth[data-id="${ synthId }"] .gsuiPatterns-synth-patterns` );
		}
	}

	// .........................................................................
	_onreorderPatterns( list, elPat ) {
		this.onchange( "reorderPattern", elPat.dataset.id,
			gsuiReorder.listComputeOrderChange( list, {} ) );
	}
	_onreorderPatternsKeys( elPat, indA, indB, parA, parB ) {
		if ( parA === parB ) {
			this._onreorderPatterns( parA, elPat );
		} else {
			const patId = elPat.dataset.id,
				synth = parB.parentNode.dataset.id,
				patterns = { [ patId ]: { synth } };

			gsuiReorder.listComputeOrderChange( parA, patterns );
			gsuiReorder.listComputeOrderChange( parB, patterns );
			this.onchange( "redirectPatternKeys", patId, synth, patterns );
		}
	}
	_onclickListPatterns( e ) {
		const pat = e.target.closest( ".gsuiPatterns-pattern" );

		if ( pat ) {
			this._fnsPattern[ e.target.dataset.action ]( pat.dataset.id, e );
			return false;
		}
	}
	_onclickSynths( e ) {
		if ( this._onclickListPatterns( e ) !== false ) {
			const syn = e.target.closest( ".gsuiPatterns-synth" );

			if ( syn ) {
				this._fnsSynth[ e.target.dataset.action ]( syn.dataset.id, e );
			}
		}
	}
}

gsuiPatterns.selectChanPopupContent = document.querySelector( "#gsuiPatterns-selectChanPopupContent" );
gsuiPatterns.selectChanPopupSelect = document.querySelector( "#gsuiPatterns-selectChanPopupSelect" );
gsuiPatterns.selectChanPopupContent.remove();

gsuiPatterns.template = document.querySelector( "#gsuiPatterns-template" );
gsuiPatterns.template.remove();
gsuiPatterns.template.removeAttribute( "id" );

gsuiPatterns.synthTemplate = document.querySelector( "#gsuiPatterns-synth-template" );
gsuiPatterns.synthTemplate.remove();
gsuiPatterns.synthTemplate.removeAttribute( "id" );

gsuiPatterns.patternTemplate = document.querySelector( "#gsuiPatterns-pattern-template" );
gsuiPatterns.patternTemplate.remove();
gsuiPatterns.patternTemplate.removeAttribute( "id" );

Object.freeze( gsuiPatterns );

/*
1. The cloning feature for the patterns of type buffer is removed because it's for the moment useless.
2. We are checking if the pattern exists because the entire synth could have been removed before.
*/
<|endoftext|>


<commit_before>define(function (require, exports, module) {

function getComputedStyle($el){
    return window.getComputedStyle($el[0], null);
}

function getTransformMatrix($el){
    var computed = getComputedStyle($el);
    var transform = computed.getPropertyValue("-webkit-transform") ||
                    computed.getPropertyValue("-moz-transform") ||
                    computed.getPropertyValue("-ms-transform") ||
                    computed.getPropertyValue("-o-transform") ||
                    computed.getPropertyValue("transform");

    var values = transform.split('(')[1];
        values = values.split(')')[0];
        values = values.split(',');

    return _.map(values, function(each){
        return parseInt(each, 10);
    });
}

function getZIndex($el){
    var computed = getComputedStyle($el);
    return parseInt(computed.getPropertyValue('z-index'), 10);
}

function getSize($el){
    var computed = getComputedStyle($el);
    var width = computed.getPropertyValue('width');
    var height = computed.getPropertyValue('height');

    return [parseInt(width, 10), parseInt(height, 10)];
}

http://stackoverflow.com/questions/1740700/how-to-get-hex-color-value-rather-than-rgb-value
function rgb2hex(rgb) {
    rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    function hex(x) {
        return ("0" + parseInt(x).toString(16)).slice(-2);
    }
    return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}

exports.getComputedStyle = getComputedStyle;
exports.getTransformMatrix = getTransformMatrix;
exports.getZIndex = getZIndex;
exports.getSize = getSize;
exports.rgb2hex = rgb2hex;

});
<commit_msg>fixes uncommented url<commit_after>define(function (require, exports, module) {

function getComputedStyle($el){
    return window.getComputedStyle($el[0], null);
}

function getTransformMatrix($el){
    var computed = getComputedStyle($el);
    var transform = computed.getPropertyValue("-webkit-transform") ||
                    computed.getPropertyValue("-moz-transform") ||
                    computed.getPropertyValue("-ms-transform") ||
                    computed.getPropertyValue("-o-transform") ||
                    computed.getPropertyValue("transform");

    var values = transform.split('(')[1];
        values = values.split(')')[0];
        values = values.split(',');

    return _.map(values, function(each){
        return parseInt(each, 10);
    });
}

function getZIndex($el){
    var computed = getComputedStyle($el);
    return parseInt(computed.getPropertyValue('z-index'), 10);
}

function getSize($el){
    var computed = getComputedStyle($el);
    var width = computed.getPropertyValue('width');
    var height = computed.getPropertyValue('height');

    return [parseInt(width, 10), parseInt(height, 10)];
}

// http://stackoverflow.com/questions/1740700/how-to-get-hex-color-value-rather-than-rgb-value
function rgb2hex(rgb) {
    rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    function hex(x) {
        return ("0" + parseInt(x).toString(16)).slice(-2);
    }
    return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}

exports.getComputedStyle = getComputedStyle;
exports.getTransformMatrix = getTransformMatrix;
exports.getZIndex = getZIndex;
exports.getSize = getSize;
exports.rgb2hex = rgb2hex;

});
<|endoftext|>


<commit_before>// Unit test for a.form (plugin)

module('plugin/form.js');

/*
---------------------------------
  GET TEST
---------------------------------
*/
// Test default behavior
test('a.form.get-default-test', function() {
    var id = 'a.form.get-default-test';

    // Main element
    var f = document.createElement('form');
    f.id = id;
    f.style.display = 'none';
    f.onsubmit=function(){return false;}

    // We create some basic element: input, selectbox and submit button
    var input = document.createElement('input');
    input.name = id + '-input';
    input.value = 'input-ok';
    f.appendChild(input);

    // Select box
    var select = document.createElement('select');
    select.name = id + '-select';
    // Sub child
    var o1 = document.createElement('option');
    o1.value = 'select-choice1';
    select.appendChild(o1);
    var o2 = document.createElement('option');
    o2.value = 'select-choice2';
    select.appendChild(o2);
    f.appendChild(select);

    // Submit
    var submit = document.createElement('submit');
    submit.name = id + '-submit';
    submit.value = 'send';
    f.appendChild(submit);

    // Register element on dom
    document.body.appendChild(f);

    var test = a.form.get(document.getElementById(id));

    strictEqual(test[id + '-input'], 'input-ok', 'Test input');
    strictEqual(test[id + '-select'], 'select-choice1', 'Test select');
});

// Test checkbox
test('a.form.get-checkbox-test', function() {
    var id = 'a.form.get-checkbox-test';

    // Main element
    var f = document.createElement('form');
    f.id = id;
    f.style.display = 'none';
    f.onsubmit=function(){return false;}

    // First checkbox button
    var c1 = document.createElement('input');
    c1.type = 'checkbox';
    c1.name = id + '-c1';
    c1.checked = true;
    f.appendChild(c1);

    // Second checkbox button
    var c2 = document.createElement('input');
    c2.type = 'checkbox';
    c2.name = id + '-c2';
    c2.checked = false;
    f.appendChild(c2);

    // Register element on dom
    document.body.appendChild(f);

    // Get elements
    var test = a.form.get(document.getElementById(id));

    strictEqual(test[id + '-c1'], true, 'Test first checkbox');
    strictEqual(test[id + '-c2'], false, 'Test second checkbox');
});

// Test radio button group
test('a.form.get-radio-test', function() {
    var id = 'a.form.get-radio-test';

    // Main element
    var f = document.createElement('form');
    f.id = id;
    f.style.display = 'none';
    f.onsubmit=function(){return false;}

    // First radio button
    var r1 = document.createElement('input');
    r1.type = 'radio';
    r1.name = id + '-content';
    r1.value = 'r1';
    f.appendChild(r1);

    // Second radio button
    var r2 = document.createElement('input');
    r2.type = 'radio';
    r2.name = id + '-content';
    r2.value = 'r2';
    f.appendChild(r2);

    // Register element on dom
    document.body.appendChild(f);

    // Get first radio button check
    r1.checked = true;
    r2.checked = false;
    var test1 = a.form.get(document.getElementById(id));
    strictEqual(test1[id + '-content'], 'r1',
                        'Test first radio is found as checked');

    r1.checked = false;
    r2.checked = true;
    var test2 = a.form.get(document.getElementById(id));
    strictEqual(test2[id + '-content'], 'r2',
                        'Test second radio is found as checked');
});

// Test select, with or without option inside
test('a.form.select-empty', function() {
    var id = 'a.form.select-empty';

    // Main element
    var f = document.createElement('form');
    f.id = id;
    f.style.display = 'none';
    f.onsubmit=function(){return false;}

    // Select element
    var sel = document.createElement('select');
    sel.name = id + '-content';
    f.appendChild(sel);

    // Register element on dom
    document.body.appendChild(f);

    var test = a.form.get(document.getElementById(id));

    // Test the system is not hang by not existing options
    strictEqual(test[id + '-content'], null, 'Test empty select');
});

test('a.form.select-single', function() {
    var id = 'a.form.select-single';

    // Main element
    var f = document.createElement('form');
    f.id = id;
    f.style.display = 'none';
    f.onsubmit=function(){return false;}

    // Select element
    var sel = document.createElement('select');
    sel.name = id + '-content';
    f.appendChild(sel);

    var opt = document.createElement('option');
    opt.value = 'yatta';
    sel.appendChild(opt);

    // Register element on dom
    document.body.appendChild(f);

    var test = a.form.get(document.getElementById(id));

    // Test the system is not hang by not existing options
    strictEqual(test[id + '-content'], 'yatta', 'Test empty select');
});

test('a.form.select-full', function() {
    var id = 'a.form.select-full';

    // Main element
    var f = document.createElement('form');
    f.id = id;
    f.style.display = 'none';
    f.onsubmit=function(){return false;}

    // Select element
    var sel = document.createElement('select');
    sel.name = id + '-content';
    f.appendChild(sel);

    var opt1 = document.createElement('option');
    opt1.value = 'yatta';
    sel.appendChild(opt1);

    var opt2 = document.createElement('option');
    opt2.value = 'ok';
    sel.appendChild(opt2);
    opt2.selectedIndex = 1;

    // Register element on dom
    document.body.appendChild(f);

    var test = a.form.get(document.getElementById(id));

    // Test the system is not hang by not existing options
    strictEqual(test[id + '-content'], 'yatta', 'Test empty select');
});

// Test a simple blank input
test('a.form.get-blank', function() {
    var id = 'a.form.get-blank';

    // Main element
    var f = document.createElement('form');
    f.id = id;
    f.style.display = 'none';
    f.onsubmit=function(){return false;}

    // input element
    var i = document.createElement('input');
    i.name = id + '-content';
    i.type = 'text';
    f.appendChild(i);

    // Register element on dom
    document.body.appendChild(f);

    var test = a.form.get(document.getElementById(id));

    strictEqual(test[id + '-content'], null, 'Test empty content gives blank');
});

// Testing that input with a name using [] is treated as an array not
// a single value
test('a.form.get-input-array', function() {
    var id = 'a.form.get-input-array';

    // Main element
    var f = document.createElement('form');
    f.id = id;
    f.style.display = 'none';
    f.onsubmit=function(){return false;}

    // input element
    var first = document.createElement('input');
    first.name = id + '-content[]';
    first.type = 'text';
    first.value = 'first';
    f.appendChild(first);

    // input element
    var second = document.createElement('input');
    second.name = id + '-content[]';
    second.type = 'text';
    second.value = 'second';
    f.appendChild(second);

    // Register element on dom
    document.body.appendChild(f);

    var test = a.form.get(document.getElementById(id));

    strictEqual(a.isArray(test[id + '-content[]']), true);
    strictEqual(test[id + '-content[]'][0], 'first');
    strictEqual(test[id + '-content[]'][1], 'second');
});

/*
---------------------------------
  VALIDATE TEST
---------------------------------
*/
// Test a basic validate is working as expected
test('a.form.validate-default-test', function() {
    var id = 'a.form.validate-default-test';

    // Main element
    var f = document.createElement('form');
    f.id = id;
    f.style.display = 'none';
    f.onsubmit=function(){return false;}

    // Create few elements with validate needed
    var i1 = document.createElement('input');
    i1.id = id + '-i1';
    i1.type = 'email';
    f.appendChild(i1);

    var i2 = document.createElement('input');
    i2.id = id + '-i2';
    i2.pattern = '^[a-zA-Z]+$';
    f.appendChild(i2);

    // Register element on dom
    document.body.appendChild(f);

    var test = a.form.validate(document.getElementById(id));

    if(test[0].id == id + '-i1') {
        strictEqual(test[0].id, id + '-i1',
                            'Test second id has been setted as not valid');
        strictEqual(test[1].id, id + '-i2',
                            'Test second id has been setted as not valid');
    } else {
        strictEqual(test[1].id, id + '-i1',
                            'Test second id has been setted as not valid');
        strictEqual(test[0].id, id + '-i2',
                            'Test second id has been setted as not valid');
    }
});<commit_msg>unit test for new data-name attribute.<commit_after>// Unit test for a.form (plugin)

module('plugin/form.js');

/*
---------------------------------
  GET TEST
---------------------------------
*/
// Test default behavior
test('a.form.get-default-test', function() {
    var id = 'a.form.get-default-test';

    // Main element
    var f = document.createElement('form');
    f.id = id;
    f.style.display = 'none';
    f.onsubmit=function(){return false;}

    // We create some basic element: input, selectbox and submit button
    var input = document.createElement('input');
    input.name = id + '-input';
    input.value = 'input-ok';
    f.appendChild(input);

    // Select box
    var select = document.createElement('select');
    select.name = id + '-select';
    // Sub child
    var o1 = document.createElement('option');
    o1.value = 'select-choice1';
    select.appendChild(o1);
    var o2 = document.createElement('option');
    o2.value = 'select-choice2';
    select.appendChild(o2);
    f.appendChild(select);

    // Submit
    var submit = document.createElement('submit');
    submit.name = id + '-submit';
    submit.value = 'send';
    f.appendChild(submit);

    // Register element on dom
    document.body.appendChild(f);

    var test = a.form.get(document.getElementById(id));

    strictEqual(test[id + '-input'], 'input-ok', 'Test input');
    strictEqual(test[id + '-select'], 'select-choice1', 'Test select');
});

// Test checkbox
test('a.form.get-checkbox-test', function() {
    var id = 'a.form.get-checkbox-test';

    // Main element
    var f = document.createElement('form');
    f.id = id;
    f.style.display = 'none';
    f.onsubmit=function(){return false;}

    // First checkbox button
    var c1 = document.createElement('input');
    c1.type = 'checkbox';
    c1.name = id + '-c1';
    c1.checked = true;
    f.appendChild(c1);

    // Second checkbox button
    var c2 = document.createElement('input');
    c2.type = 'checkbox';
    c2.name = id + '-c2';
    c2.checked = false;
    f.appendChild(c2);

    // Register element on dom
    document.body.appendChild(f);

    // Get elements
    var test = a.form.get(document.getElementById(id));

    strictEqual(test[id + '-c1'], true, 'Test first checkbox');
    strictEqual(test[id + '-c2'], false, 'Test second checkbox');
});

// Test radio button group
test('a.form.get-radio-test', function() {
    var id = 'a.form.get-radio-test';

    // Main element
    var f = document.createElement('form');
    f.id = id;
    f.style.display = 'none';
    f.onsubmit=function(){return false;}

    // First radio button
    var r1 = document.createElement('input');
    r1.type = 'radio';
    r1.name = id + '-content';
    r1.value = 'r1';
    f.appendChild(r1);

    // Second radio button
    var r2 = document.createElement('input');
    r2.type = 'radio';
    r2.name = id + '-content';
    r2.value = 'r2';
    f.appendChild(r2);

    // Register element on dom
    document.body.appendChild(f);

    // Get first radio button check
    r1.checked = true;
    r2.checked = false;
    var test1 = a.form.get(document.getElementById(id));
    strictEqual(test1[id + '-content'], 'r1',
                        'Test first radio is found as checked');

    r1.checked = false;
    r2.checked = true;
    var test2 = a.form.get(document.getElementById(id));
    strictEqual(test2[id + '-content'], 'r2',
                        'Test second radio is found as checked');
});

// Test select, with or without option inside
test('a.form.select-empty', function() {
    var id = 'a.form.select-empty';

    // Main element
    var f = document.createElement('form');
    f.id = id;
    f.style.display = 'none';
    f.onsubmit=function(){return false;}

    // Select element
    var sel = document.createElement('select');
    sel.name = id + '-content';
    f.appendChild(sel);

    // Register element on dom
    document.body.appendChild(f);

    var test = a.form.get(document.getElementById(id));

    // Test the system is not hang by not existing options
    strictEqual(test[id + '-content'], null, 'Test empty select');
});

test('a.form.select-single', function() {
    var id = 'a.form.select-single';

    // Main element
    var f = document.createElement('form');
    f.id = id;
    f.style.display = 'none';
    f.onsubmit=function(){return false;}

    // Select element
    var sel = document.createElement('select');
    sel.name = id + '-content';
    f.appendChild(sel);

    var opt = document.createElement('option');
    opt.value = 'yatta';
    sel.appendChild(opt);

    // Register element on dom
    document.body.appendChild(f);

    var test = a.form.get(document.getElementById(id));

    // Test the system is not hang by not existing options
    strictEqual(test[id + '-content'], 'yatta', 'Test empty select');
});

test('a.form.select-full', function() {
    var id = 'a.form.select-full';

    // Main element
    var f = document.createElement('form');
    f.id = id;
    f.style.display = 'none';
    f.onsubmit=function(){return false;}

    // Select element
    var sel = document.createElement('select');
    sel.name = id + '-content';
    f.appendChild(sel);

    var opt1 = document.createElement('option');
    opt1.value = 'yatta';
    sel.appendChild(opt1);

    var opt2 = document.createElement('option');
    opt2.value = 'ok';
    sel.appendChild(opt2);
    opt2.selectedIndex = 1;

    // Register element on dom
    document.body.appendChild(f);

    var test = a.form.get(document.getElementById(id));

    // Test the system is not hang by not existing options
    strictEqual(test[id + '-content'], 'yatta', 'Test empty select');
});

// Test a simple blank input
test('a.form.get-blank', function() {
    var id = 'a.form.get-blank';

    // Main element
    var f = document.createElement('form');
    f.id = id;
    f.style.display = 'none';
    f.onsubmit=function(){return false;}

    // input element
    var i = document.createElement('input');
    i.name = id + '-content';
    i.type = 'text';
    f.appendChild(i);

    // Register element on dom
    document.body.appendChild(f);

    var test = a.form.get(document.getElementById(id));

    strictEqual(test[id + '-content'], null, 'Test empty content gives blank');
});

// Testing that input with a name using [] is treated as an array not
// a single value
test('a.form.get-input-array', function() {
    var id = 'a.form.get-input-array';

    // Main element
    var f = document.createElement('form');
    f.id = id;
    f.style.display = 'none';
    f.onsubmit=function(){return false;}

    // input element
    var first = document.createElement('input');
    first.name = id + '-content[]';
    first.type = 'text';
    first.value = 'first';
    f.appendChild(first);

    // input element
    var second = document.createElement('input');
    second.name = id + '-content[]';
    second.type = 'text';
    second.value = 'second';
    f.appendChild(second);

    // Register element on dom
    document.body.appendChild(f);

    var test = a.form.get(document.getElementById(id));

    strictEqual(a.isArray(test[id + '-content[]']), true);
    strictEqual(test[id + '-content[]'][0], 'first');
    strictEqual(test[id + '-content[]'][1], 'second');
});

// Testing the custom tag attribute data-name to override the a.form way of
// finding field name
test('a.form.custom-attribute', function() {
    var id = 'a.form.custom-attribute';

    // Main element
    var f = document.createElement('form');
    f.id = id;
    f.style.display = 'none';
    f.onsubmit=function(){return false;}

    // input element
    var i = document.createElement('input');
    i.name = id + '-content';
    i.type = 'text';
    i.value = 'something';
    i.setAttribute('data-name', id + '-custom-data');
    f.appendChild(i);

    // Register element on dom
    document.body.appendChild(f);

    var test = a.form.get(document.getElementById(id));

    strictEqual(test[id + '-custom-data'], 'something', 'Test custom tag');
});

/*
---------------------------------
  VALIDATE TEST
---------------------------------
*/
// Test a basic validate is working as expected
test('a.form.validate-default-test', function() {
    var id = 'a.form.validate-default-test';

    // Main element
    var f = document.createElement('form');
    f.id = id;
    f.style.display = 'none';
    f.onsubmit=function(){return false;}

    // Create few elements with validate needed
    var i1 = document.createElement('input');
    i1.id = id + '-i1';
    i1.type = 'email';
    f.appendChild(i1);

    var i2 = document.createElement('input');
    i2.id = id + '-i2';
    i2.pattern = '^[a-zA-Z]+$';
    f.appendChild(i2);

    // Register element on dom
    document.body.appendChild(f);

    var test = a.form.validate(document.getElementById(id));

    if(test[0].id == id + '-i1') {
        strictEqual(test[0].id, id + '-i1',
                            'Test second id has been setted as not valid');
        strictEqual(test[1].id, id + '-i2',
                            'Test second id has been setted as not valid');
    } else {
        strictEqual(test[1].id, id + '-i1',
                            'Test second id has been setted as not valid');
        strictEqual(test[0].id, id + '-i2',
                            'Test second id has been setted as not valid');
    }
});<|endoftext|>


<commit_before>$(document).ready(function() {
  // the file extension regex matching on supported image and pdf types
  var extensionRegexImage = /\.(png|jpe?g|gif|bmp)$/i;
  var extensionRegexAll = /\.(png|jpe?g|gif|bmp|pdf)$/i;

  // modify thumbnail links in wiki content -> add filename from ./img/@alt to url to support fancybox preview
  $("div.wiki a.thumbnail").attr('href', function(i, v){
    return v.replace(/\/attachments\/(\d+)/g,'/attachments/download/$1') + '/' + $(this).children('img').attr('alt').replace(/(.*\.(png|jpe?g|gif|bmp))(\s\(.*\))?/gi,'$1');
  });

  // modify filename links in journal details -> add filename to url to support fancybox preview
  $("div.journal ul.details li a:not([title])").attr('href', function(i, v){
    if($(this).html().match(extensionRegexAll)) {
      return v.replace(/\/attachments\/(\d+)/g,'/attachments/download/$1') + '/' + $(this).html();
    } else {
      return v;
    }
  });

  // modify thumbnail links after journal details -> add filename to url to support fancybox preview
  $("div.journal div.thumbnails a[title]").attr('href', function(i, v){
    if($(this).attr('title').match(extensionRegexAll)) {
      return v.replace(/\/attachments\/(\d+)/g,'/attachments/download/$1') + '/' + $(this).attr('title');
    } else {
      return v;
    }
  });

  // add a magnifier icon before download icon for images and pdf
  $("div.journal ul.details li a.icon-download").each(function(i, obj) {
    if($(this).attr('href').match(extensionRegexAll)) {
      var icon = $(this).clone().attr('class', function(i, v){
        return v.replace(/-download/g,'-magnifier');
      }).removeAttr('title');
      icon.insertBefore($(this));
    }
  });

  // add rel attribute to thumbnails of the same journal entry
  $("div.journal div.thumbnails a").each(function(i, obj) {
    var relgroup = 'thumbnails-' + $(this).closest('div.journal').attr('id')
    $(this)
      .attr('rel', relgroup)
      .attr('data-fancybox', relgroup)
  });

  // DMSF support
  var dmsf_link_selector = "a[data-downloadurl][href^='/dmsf/files/'][href$='/view']";

  // #40 ... add class="thumbnail" to DMSF macro thumbnails on wiki pages
  $("div.wiki " + dmsf_link_selector).each(function(i, obj) {
    var filename = $(this).attr('data-downloadurl').split(':')[1];
    // Also support PDF preview in lightbox
    var isPdf = filename.match(/\.pdf$/i);
    // only apply thumbnail class to image and pdf links
    if(filename.match(extensionRegexAll)) {
      $(this)
        .addClass('thumbnail')
        .attr('data-type', isPdf ? 'iframe' : 'image')
        .attr('title', filename)
        .attr('data-caption', filename)
        .removeAttr('target')
        .removeAttr('data-downloadurl');
    }
  });

  // #63 ... add class="lightbox" to DMSF image links in DMS browser
  $(".controller-dmsf #browser .dmsf_title " + dmsf_link_selector).each(function(i, obj) {
    var filename = $(this).attr('data-downloadurl').split(':')[1];
    // only apply thumbnail class to image and pdf links
    if(filename.match(extensionRegexImage)) {
      $(this)
        .addClass('lightbox')
        .attr('data-type', 'image')
        .attr('title', filename)
        .attr('data-caption', filename)
        .attr('rel', 'dmsf-browser')
        .attr('data-fancybox', 'dmsf-browser')
        .removeAttr('target')
        .removeAttr('data-downloadurl');
    }
  });

  // #53 DMSF support in issues: add class="lightbox" to DMSF thumbnails and preview links
  $("div.attachments.dmsf_parent_container a[href^='/dmsf/files/'][href$='/view']").each(function(i, obj) {
    // extract filename from attribute 'data-downloadurl' from closest element with the same 'href'
    var href = $(this).attr('href');
    var filename = $("div.attachments.dmsf_parent_container > p > a[href='" + href + "'].dmsf-icon-file").first().attr('data-downloadurl').split(':')[1];
    // create 3 fancybox 'rel' groups to avoid image duplicates in slideshow
    var relgroup = '';
    if($(this).closest('div.thumbnails').length) {
      relgroup = 'thumbnails';
    } else if($(this).hasClass('icon-only')) {
      relgroup = 'icon';
    } else if($(this).hasClass('thumbnail')) {
      relgroup = 'imagelink';
    }
    // Also support PDF preview in lightbox
    var isPdf = filename.match(/\.pdf$/i);
    // only apply thumbnail class to image and pdf links
    if(filename.match(extensionRegexAll)) {
      $(this)
        .addClass('lightbox')
        .attr('data-type', isPdf ? 'iframe' : 'image')
        .attr('title', filename)
        .attr('data-caption', filename)
        .attr('data-fancybox', 'dmsf-' + relgroup);
        // do not remove 'data-downloadurl' here otherwise the filename extraction crashes for following dmsf thumbnails
    }
  });

  // Add Fancybox to image links
  $("div.attachments a.lightbox")
  .add("div.attachments a.lightbox_preview")
  .add("div.journal ul.details a:not(.icon-download)").filter(function(index,elem) { $(elem).attr('href').match(extensionRegexImage) })
  .add("div.journal div.thumbnails a")
  .add("div.wiki a.thumbnail")
  .add(".controller-dmsf #browser a.lightbox")
  .add(".avatar a")
  .fancybox({
    animationEffect    : 'zoom',
    animationDuration  : 200,
    transitionEffect   : 'fade',
    transitionDuration : 200,
    buttons: [
      'zoom',
      'fullScreen',
      'download',
      'thumbs',
      'close'
    ]
  });

  // Add Fancybox to PDF links
  $("div.attachments a.pdf")
  .add("div.journal ul.details a:not(.icon-download)").filter(function(index,elem) { $(elem).attr('href').match(/\.pdf$/i) })
  .add("div.journal div.thumbnails a").filter(function(index,elem) { $(elem).attr('href').match(/\.pdf$/i) })
  .fancybox({
    animationEffect    : 'zoom',
    animationDuration  : 200,
    transitionEffect   : 'fade',
    transitionDuration : 200,
    type               : 'iframe',
    iframe : {
      preload: true
    },
    buttons: [
      'fullScreen',
      'download',
      'close'
    ]
  });
});
<commit_msg>bugfix for javascript bugfix for IE11 // refs #66<commit_after>$(document).ready(function() {
  // the file extension regex matching on supported image and pdf types
  var extensionRegexImage = /\.(png|jpe?g|gif|bmp)$/i;
  var extensionRegexAll = /\.(png|jpe?g|gif|bmp|pdf)$/i;

  // modify thumbnail links in wiki content -> add filename from ./img/@alt to url to support fancybox preview
  $("div.wiki a.thumbnail").attr('href', function(i, v){
    return v.replace(/\/attachments\/(\d+)/g,'/attachments/download/$1') + '/' + $(this).children('img').attr('alt').replace(/(.*\.(png|jpe?g|gif|bmp))(\s\(.*\))?/gi,'$1');
  });

  // modify filename links in journal details -> add filename to url to support fancybox preview
  $("div.journal ul.details li a:not([title])").attr('href', function(i, v){
    if($(this).html().match(extensionRegexAll)) {
      return v.replace(/\/attachments\/(\d+)/g,'/attachments/download/$1') + '/' + $(this).html();
    } else {
      return v;
    }
  });

  // modify thumbnail links after journal details -> add filename to url to support fancybox preview
  $("div.journal div.thumbnails a[title]").attr('href', function(i, v){
    if($(this).attr('title').match(extensionRegexAll)) {
      return v.replace(/\/attachments\/(\d+)/g,'/attachments/download/$1') + '/' + $(this).attr('title');
    } else {
      return v;
    }
  });

  // add a magnifier icon before download icon for images and pdf
  $("div.journal ul.details li a.icon-download").each(function(i, obj) {
    if($(this).attr('href').match(extensionRegexAll)) {
      var icon = $(this).clone().attr('class', function(i, v){
        return v.replace(/-download/g,'-magnifier');
      }).removeAttr('title');
      icon.insertBefore($(this));
    }
  });

  // add rel attribute to thumbnails of the same journal entry
  $("div.journal div.thumbnails a").each(function(i, obj) {
    var relgroup = 'thumbnails-' + $(this).closest('div.journal').attr('id')
    $(this)
      .attr('rel', relgroup)
      .attr('data-fancybox', relgroup)
  });

  // DMSF support
  var dmsf_link_selector = "a[data-downloadurl][href^='/dmsf/files/'][href$='/view']";

  // #40 ... add class="thumbnail" to DMSF macro thumbnails on wiki pages
  $("div.wiki " + dmsf_link_selector).each(function(i, obj) {
    var filename = $(this).attr('data-downloadurl').split(':')[1];
    // Also support PDF preview in lightbox
    var isPdf = filename.match(/\.pdf$/i);
    // only apply thumbnail class to image and pdf links
    if(filename.match(extensionRegexAll)) {
      $(this)
        .addClass('thumbnail')
        .attr('data-type', isPdf ? 'iframe' : 'image')
        .attr('title', filename)
        .attr('data-caption', filename)
        .removeAttr('target')
        .removeAttr('data-downloadurl');
    }
  });

  // #63 ... add class="lightbox" to DMSF image links in DMS browser
  $(".controller-dmsf #browser .dmsf_title " + dmsf_link_selector).each(function(i, obj) {
    var filename = $(this).attr('data-downloadurl').split(':')[1];
    // only apply thumbnail class to image and pdf links
    if(filename.match(extensionRegexImage)) {
      $(this)
        .addClass('lightbox')
        .attr('data-type', 'image')
        .attr('title', filename)
        .attr('data-caption', filename)
        .attr('rel', 'dmsf-browser')
        .attr('data-fancybox', 'dmsf-browser')
        .removeAttr('target')
        .removeAttr('data-downloadurl');
    }
  });

  // #53 DMSF support in issues: add class="lightbox" to DMSF thumbnails and preview links
  $("div.attachments.dmsf_parent_container a[href^='/dmsf/files/'][href$='/view']").each(function(i, obj) {
    // extract filename from attribute 'data-downloadurl' from closest element with the same 'href'
    var href = $(this).attr('href');
    var filename = $("div.attachments.dmsf_parent_container > p > a[href='" + href + "'].dmsf-icon-file").first().attr('data-downloadurl').split(':')[1];
    // create 3 fancybox 'rel' groups to avoid image duplicates in slideshow
    var relgroup = '';
    if($(this).closest('div.thumbnails').length) {
      relgroup = 'thumbnails';
    } else if($(this).hasClass('icon-only')) {
      relgroup = 'icon';
    } else if($(this).hasClass('thumbnail')) {
      relgroup = 'imagelink';
    }
    // Also support PDF preview in lightbox
    var isPdf = filename.match(/\.pdf$/i);
    // only apply thumbnail class to image and pdf links
    if(filename.match(extensionRegexAll)) {
      $(this)
        .addClass('lightbox')
        .attr('data-type', isPdf ? 'iframe' : 'image')
        .attr('title', filename)
        .attr('data-caption', filename)
        .attr('data-fancybox', 'dmsf-' + relgroup);
        // do not remove 'data-downloadurl' here otherwise the filename extraction crashes for following dmsf thumbnails
    }
  });

  // Add Fancybox to image links
  $("div.attachments a.lightbox")
  .add("div.attachments a.lightbox_preview")
  .add("div.journal ul.details a:not(.icon-download)").filter(function(index,elem) { return $(elem).attr('href').match(extensionRegexImage) })
  .add("div.journal div.thumbnails a")
  .add("div.wiki a.thumbnail")
  .add(".controller-dmsf #browser a.lightbox")
  .add(".avatar a")
  .fancybox({
    animationEffect    : 'zoom',
    animationDuration  : 200,
    transitionEffect   : 'fade',
    transitionDuration : 200,
    buttons: [
      'zoom',
      'fullScreen',
      'download',
      'thumbs',
      'close'
    ]
  });

  // Add Fancybox to PDF links
  $("div.attachments a.pdf")
  .add("div.journal ul.details a:not(.icon-download)").filter(function(index,elem) { return $(elem).attr('href').match(/\.pdf$/i) })
  .add("div.journal div.thumbnails a").filter(function(index,elem) { return $(elem).attr('href').match(/\.pdf$/i) })
  .fancybox({
    animationEffect    : 'zoom',
    animationDuration  : 200,
    transitionEffect   : 'fade',
    transitionDuration : 200,
    type               : 'iframe',
    iframe : {
      preload: true
    },
    buttons: [
      'fullScreen',
      'download',
      'close'
    ]
  });
});
<|endoftext|>