<commit_before>/**
 * Created by clstrfvck on 13/06/2017.
 */
import React from "react"
import { connect } from 'react-redux'
import axios from "axios"
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import Redirect from 'react-router-dom'
import CreateClient from '../CreateClient'

class NewClient extends React.Component {
    constructor(props){
        super(props)
    }

    render(){

        return(
            <CreateClient{...this.props}/>
        )
    }
}

const mapDispatchToProps = (dispatch) => {
    return {
        changePersonType(personType){
            dispatch({type: 'CREATION_CHANGE_PERSON_TYPE', payload: personType});
            console.log('dispatched person type change')
        },

    onFieldValueChange(source, value) {
            dispatch({
                type: 'CREATION_CHANGE_FIELD_VALUE',
                payload: {
                    key: source,
                    value: value
                }
            })
        },
        onSubmit(details){
            let errors = {}
            let emailValidation = /\S+@\S+\.\S+/
            let nameValidation = /^[A-Za-z ]{3,20}$/
            let addressValidation = /^[A-Za-z0-9 ]{3,20}$/
            let contactValidation = /^[0-9]{5,20}$/
            let documentIdValidation = /^[0-9 ]{3,20}$/
            let personalIdValidation = /^[0-9 ]{8,8}$/
            let companyRegistrationValidation = /^[0-9 ]{8,8}$/
            let vatDutyNumberValidation = /^[0-9 ]{14,14}$/

            dispatch({type: 'CREATION_ATTEMPT'})

            if(details.type==='privatePerson')  {

                if(!nameValidation.test(details.name))  {
                    errors.name = 'Sisesta korrektne nimi';
                }else {errors.name = '';}

                if(!personalIdValidation.test(details.personalId))  {
                      errors.personalId = 'Sisesta korrektne isikukood';
                }else {errors.personalId = '';}

                if(!documentIdValidation.test(details.documentId))  {
                    errors.documentId = 'Sisesta korrektne dokumendi number';
                }else {errors.documentId = '';}

                if(!emailValidation.test(details.email))  {
                    errors.email = 'Sisesta korrektne email';
                }else {errors.email = '';}

                if(!contactValidation.test(details.contact))  {
                    errors.contact = 'Sisesta korrektne telefoninumber';
                }else {errors.contact = '';}

                if(!addressValidation.test(details.address))  {
                    errors.address = 'Sisesta korrektne aadress';
                }else {errors.address = '';}
            }

            if(details.type==='juridicalPerson') {
                if(!nameValidation.test(details.name))  {
                    errors.name = 'Sisesta korrektne nimi';
                }else {errors.name = '';}

                if (!companyRegistrationValidation.test(details.name)) {
                 errors.companyRegistration = 'Sisesta korrektne registrinumber';
                }else {errors.companyRegistration = '';}

                if (!vatDutyNumberValidation.test(details.name)) {
                 errors.vatDutyNumber = 'Sisesta korrektne käibemaksukohustuslase number';
                }else {errors.vatDutyNumber = '';}

                if(!emailValidation.test(details.email))  {
                    errors.email = 'Sisesta korrektne email';
                }else {errors.email = '';}

                if(!contactValidation.test(details.contact))  {
                 errors.contact = 'Sisesta korrektne telefoninumber';
                }else {errors.contact = '';}

                if(!addressValidation.test(details.address))  {
                 errors.address = 'Sisesta korrektne aadress';
                }else {errors.address = '';}
            }
            if(Object.keys(errors).length<1){
                axios.post('/api/user/create', {
                    email: details.email,
                    personal_data: {
                        nimi: details.name,
                        tel_nr: details.contact,
                        aadress: details.address,
                        isikukood: details.personalId,
                        dok_nr: details.documentId,
                        eraisik: (details.type==='privatePerson'),
                        juriidiline_isik: (details.type==='juridicalPerson'),
                        reg_nr: details.companyRegistration,
                        kmk_nr: details.vatDutyNumber
                    }
                })
                    .then(({data})=>{
                        if(data.status === 'accept') {
                            dispatch({type: 'CREATION_SUCCESS', payload: data.msg})
                        } else {
                            dispatch({type: 'CREATION_FAILURE', payload: data.msg})
                        }
                    })
                    .catch(error => {
                        console.log(error);
                        dispatch({type: 'CREATION_FAILURE', payload: error})
                    })
            } else {
                console.log('dispatching')
                dispatch({
                    type: "CREATION_FIELD_ERROR",
                    payload: errors
                })
            }
        }
    }
};

const mapStateToProps = (state) => {
    return {
        activeTab: state.clientManagement.creation.activeTab,
        loading: state.clientManagement.creation.loading,
        submitted: state.clientManagement.creation.submitted,
        errors: state.clientManagement.creation.errors,
        details: state.clientManagement.creation.details
    };
};

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(NewClient);<commit_msg>fetch now working, currently no check for duplicate email<commit_after>/**
 * Created by clstrfvck on 13/06/2017.
 */
import React from "react"
import { connect } from 'react-redux'
import axios from "axios"
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import Redirect from 'react-router-dom'
import CreateClient from '../CreateClient'

class NewClient extends React.Component {
    constructor(props){
        super(props)
    }

    render(){

        return(
            <CreateClient{...this.props}/>
        )
    }
}

const mapDispatchToProps = (dispatch) => {
    return {
        changePersonType(personType){
            dispatch({type: 'CREATION_CHANGE_PERSON_TYPE', payload: personType});
            console.log('dispatched person type change')
        },

    onFieldValueChange(source, value) {
            dispatch({
                type: 'CREATION_CHANGE_FIELD_VALUE',
                payload: {
                    key: source,
                    value: value
                }
            })
        },
        onSubmit(details){
            let errors = {}
            let emailValidation = /\S+@\S+\.\S+/
            let nameValidation = /^[A-Za-z ]{3,20}$/
            let addressValidation = /^[A-Za-z0-9 ]{3,20}$/
            let contactValidation = /^[0-9]{5,20}$/
            let documentIdValidation = /^[0-9 ]{3,20}$/
            let personalIdValidation = /^[0-9 ]{11,11}$/
            let companyRegistrationValidation = /^[0-9 ]{8,8}$/
            let vatDutyNumberValidation = /^[0-9 ]{14,14}$/

            dispatch({type: 'CREATION_ATTEMPT'})

            if(details.type==='privatePerson')  {

                if(!nameValidation.test(details.name))  {
                    errors.name = 'Sisesta korrektne nimi';
                }else {errors.name}

                if(!personalIdValidation.test(details.personalId))  {
                      errors.personalId = 'Sisesta korrektne isikukood';
                }else {errors.personalId}

                if(!documentIdValidation.test(details.documentId))  {
                    errors.documentId = 'Sisesta korrektne dokumendi number';
                }else {errors.documentId}

                if(!emailValidation.test(details.email))  {
                    errors.email = 'Sisesta korrektne email';
                }else {delete errors.email}

                if(!contactValidation.test(details.contact))  {
                    errors.contact = 'Sisesta korrektne telefoninumber';
                }else {delete errors.contact}

                if(!addressValidation.test(details.address))  {
                    errors.address = 'Sisesta korrektne aadress';
                }else {delete errors.address}
            }

            if(details.type==='juridicalPerson') {
                if(!nameValidation.test(details.name))  {
                    errors.name = 'Sisesta korrektne nimi';
                }else {delete errors.name}

                if (!companyRegistrationValidation.test(details.name)) {
                 errors.companyRegistration = 'Sisesta korrektne registrinumber';
                }else {delete errors.companyRegistration}

                if (!vatDutyNumberValidation.test(details.name)) {
                 errors.vatDutyNumber = 'Sisesta korrektne käibemaksukohustuslase number';
                }else {delete errors.vatDutyNumber}

                if(!emailValidation.test(details.email))  {
                    errors.email = 'Sisesta korrektne email';
                }else {delete errors.email}

                if(!contactValidation.test(details.contact))  {
                 errors.contact = 'Sisesta korrektne telefoninumber';
                }else {delete errors.contact}

                if(!addressValidation.test(details.address))  {
                 errors.address = 'Sisesta korrektne aadress';
                }else {delete errors.address}
            }
            console.log("errorid",errors)
            if(Object.keys(errors).length<1){
                axios.post('/api/user/create', {
                    email: details.email,
                    personal_data: {
                        nimi: details.name,
                        tel_nr: details.contact,
                        aadress: details.address,
                        isikukood: details.personalId,
                        dok_nr: details.documentId,
                        eraisik: (details.type==='privatePerson'),
                        juriidiline_isik: (details.type==='juridicalPerson'),
                        reg_nr: details.companyRegistration,
                        kmk_nr: details.vatDutyNumber
                    }
                })
                    .then(({data})=>{
                    console.log(data)
                        if(data.status === 'accept') {
                            dispatch({type: 'CREATION_SUCCESS', payload: data.msg})
                        } else {
                            dispatch({type: 'CREATION_FAILURE', payload: data.msg})
                        }
                    })
                    .catch(error => {
                        console.log(error);
                        dispatch({type: 'CREATION_FAILURE', payload: error})
                    })
            } else {
                console.log('dispatching')
                dispatch({
                    type: "CREATION_FIELD_ERROR",
                    payload: errors
                })
            }
        }
    }
};

const mapStateToProps = (state) => {
    return {
        activeTab: state.clientManagement.creation.activeTab,
        loading: state.clientManagement.creation.loading,
        submitted: state.clientManagement.creation.submitted,
        errors: state.clientManagement.creation.errors,
        details: state.clientManagement.creation.details
    };
};

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(NewClient);<|endoftext|>


<commit_before>// 中文编码 utf8
var _slider = document.createElement("div");
addClass(_slider, "slider-item");
var container = document.createElement("div");
var floor = Math.floor;
var ceil = Math.ceil;
var round = Math.round;
var abs = Math.abs;
/**
 *
 * @param {Boolean|Array|Function} autoplay
 */
function slider(autoplay, circle = true) {
    var outter = container.cloneNode();
    {
        for (let cx = 0, dx = arguments.length; cx < dx; cx++) {
            let arg = arguments[cx];
            if (arg === true || arg === false) {
                circle = arg;
            } else if (isNode(arg)) {
                outter = arg;
            } else {
                autoplay = arg;
            }
        }
    }
    var _imageMain = _slider.cloneNode();
    var _imageHelp = _slider.cloneNode();
    outter.src = function (index) {
        var block = _slider.cloneNode();
        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)) {
            if (circle) {
                index = index % src.length;
                if (index < 0) index += src.length;
            }
            src = src[index];
        }
        if (isFunction(src)) {
            src = src(index, 1 - abs(ratio), ratio);
        }
        if (src) {
            if (src.parentNode !== outter) {
                remove(src);
                appendChild(outter, src);
            }
            src.index = index;
        }
        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, emit) {
        outter.index = current_index = index;
        var width = outter.clientWidth || +innerWidth;
        var indexLeft = floor(index);
        var indexRight = indexLeft + 1;
        _imageMain = generator(indexLeft, indexLeft - index);
        _imageHelp = generator(indexRight, indexRight - index);
        if (_imageHelp === _imageMain) {
            if (index - indexLeft < .5) {
                _imageHelp = null;
            } else {
                _imageMain = null;
            }
        };
        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);
            if (emit !== false) dispatch(outter, 'changed');
        }
        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 (indexLeft === index) remove(_imageHelp);
        if (!width) return;
        css(_imageMain, {
            position: "absolute",
            width: "100%",
            height: "100%",
            left: round((indexLeft - index) * width) + "px"
        });
        css(_imageHelp, {
            position: "absolute",
            width: "100%",
            height: "100%",
            left: round((indexRight - index) * width) + "px"
        });
    };
    var animate = function () {
        cancelAnimationFrame(timer_animate);
        var width = outter.clientWidth;
        if (abs(current_index + negative_index) < 1.25 / width)
            return reshape(-negative_index, false);
        timer_animate = requestAnimationFrame(animate);
        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);
        }
        animate();
        var event = createEvent("park");
        event.index = -negative_index;
        dispatch(outter, event);
        if (player.ing) play();
    };
    var play = function () {
        if (!player.ing) {
            player.ing = true;
        }
        clearTimeout(timer_playyer);
        timer_playyer = setTimeout(player, player.schedule);
    };
    var player = function () {
        if (!player.direction) {
            player.direction = 1;
        }
        if (!switchBy(player.direction)) {
            player.direction = -player.direction;
        }
    };
    player.schedule = 5000;
    var isMiss = false;
    var switchBy = function (count) {
        clearTimeout(timer_playyer);
        if (player.ing) {
            timer_playyer = setTimeout(player, player.schedule);
        }
        var enabled = generator(count - negative_index, 1);
        enabled = enabled && enabled !== _imageMain;
        if (isMiss) {
            if (enabled) outter.go(outter.index + count);
        } else {
            if (enabled) negative_index -= count;
            animate();
        }
        return enabled;
    };
    var moveDeltaX = function (deltax, event) {
        var width = outter.clientWidth;
        var singleTarget = (!_imageMain || !_imageHelp) && (_imageMain || _imageHelp);
        if (singleTarget) {
            var current_Left = singleTarget.offsetLeft;
            var avail_deltaWidth = round(width >> 2);
            if (current_Left + deltax > avail_deltaWidth) {
                deltax = avail_deltaWidth - current_Left;
                saved_x += deltax;
            } else 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.moveLocked) return;
        var deltax = event.clientX - saved_x;
        var deltay = event.clientY - saved_y;
        if (!direction) {
            if (abs(deltax) < MOVELOCK_DELTA && abs(deltay) < MOVELOCK_DELTA) return;
            if (abs(deltay) - abs(deltax) > 0) { //垂直方向
                direction = -1;
            } else { //水平方向
                direction = 1;
            }
        }
        if (direction < 0) {
            return;
        }
        if (!moving) {
            return;
        }
        event.moveLocked = true;
        // event.stopPropagation && event.stopPropagation();
        moveDeltaX(deltax, event);
    };
    var stop_wheel_timer = 0;
    onmousewheel(outter, function (event) {
        if (event.defaultPrevented) return;
        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);
    });
    moveupon(outter, {
        start(event) {
            cancelAnimationFrame(timer_animate);
            clearTimeout(timer_playyer);
            moving = true;
            direction = 0;
            _speed(0);
            saved_x = event.clientX;
            saved_y = event.clientY;
        },
        move: mousemove,
        end() {
            moving = false;
            park();
        }
    })

    outter.go = function (index, cache) {
        if (outter.index === index && cache !== false) return;
        negative_index = -index;
        var _removingMain = _imageMain;
        reshape(index, false, cache);
        css(_removingMain, "transition:.1s opacity ease-out,.1s transform;z-index:1;left:0;");
        appendChild(outter, _removingMain);
        setTimeout(function () {
            css(_removingMain, "transform:scale(.97);opacity:0;");
        });
        setTimeout(function () {
            remove(_removingMain);
            css(_removingMain, "transform:;opacity:;transition:");
            css(_imageMain, "transform:;opacity:;transition:");
        }, 300);
        css(_imageMain, "z-index:0;transform:scale(.92);opacity:0;transition:none");
        setTimeout(() => css(_imageMain, "transform:scale(1);opacity:1;transition:.2s transform ease-out,.4s opacity"), 0);
        if (player.ing) play();
        return outter;
    };
    outter.play = function (schedule = player.schedule, _isMiss) {
        if (isDefined(_isMiss)) {
            isMiss = _isMiss;
        }
        if (schedule !== player.schedule) {
            player.schedule = schedule;
            play();
        } else if (!player.ing) {
            play();
        }
        return outter;
    };
    outter.stop = function () {
        player.ing = false;
        return outter;
    };
    outter.miss = function (scadule) {
        outter.play(scadule, true);
    };
    outter.next = function (count = 1) {
        current_index += .1;
        switchBy(count);
        return outter;
    };
    outter.prev = function (count = 1) {
        current_index -= .1;
        switchBy(-count);
        return outter;
    };
    var cancel_resize;
    onappend(outter, function () {
        cancel_resize && cancel_resize();
        cancel_resize = onresize(window, function () {
            switchBy(0);
        });
        if (isFinite(outter.index)) switchBy(0);
    });
    onremove(outter, function () {
        cancel_resize && cancel_resize();
        cancel_resize = null;
    });
    css(outter, "overflow:hidden;-webkit-overflow-scrolling:auto;over-flow:auto;");
    return outter;
}<commit_msg>解决连续点击上一张可能无法切换的问题<commit_after>// 中文编码 utf8
var _slider = document.createElement("div");
addClass(_slider, "slider-item");
var container = document.createElement("div");
var floor = Math.floor;
var ceil = Math.ceil;
var round = Math.round;
var abs = Math.abs;
/**
 *
 * @param {Boolean|Array|Function} autoplay
 */
function slider(autoplay, circle = true) {
    var outter = container.cloneNode();
    {
        for (let cx = 0, dx = arguments.length; cx < dx; cx++) {
            let arg = arguments[cx];
            if (arg === true || arg === false) {
                circle = arg;
            } else if (isNode(arg)) {
                outter = arg;
            } else {
                autoplay = arg;
            }
        }
    }
    var _imageMain = _slider.cloneNode();
    var _imageHelp = _slider.cloneNode();
    outter.src = function (index) {
        var block = _slider.cloneNode();
        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)) {
            if (circle) {
                index = index % src.length;
                if (index < 0) index += src.length;
            }
            src = src[index];
        }
        if (isFunction(src)) {
            src = src(index, 1 - abs(ratio), ratio);
        }
        if (src) {
            if (src.parentNode !== outter) {
                remove(src);
                appendChild(outter, src);
            }
            src.index = index;
        }
        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, emit) {
        outter.index = current_index = index;
        var width = outter.clientWidth || +innerWidth;
        var indexLeft = floor(index);
        var indexRight = indexLeft + 1;
        _imageMain = generator(indexLeft, indexLeft - index);
        _imageHelp = generator(indexRight, indexRight - index);
        if (_imageHelp === _imageMain) {
            if (index - indexLeft < .5) {
                _imageHelp = null;
            } else {
                _imageMain = null;
            }
        };
        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);
            if (emit !== false) dispatch(outter, 'changed');
        }
        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 (indexLeft === index) remove(_imageHelp);
        if (!width) return;
        css(_imageMain, {
            position: "absolute",
            width: "100%",
            height: "100%",
            left: round((indexLeft - index) * width) + "px"
        });
        css(_imageHelp, {
            position: "absolute",
            width: "100%",
            height: "100%",
            left: round((indexRight - index) * width) + "px"
        });
    };
    var animate = function () {
        cancelAnimationFrame(timer_animate);
        var width = outter.clientWidth;
        if (abs(current_index + negative_index) < 1.25 / width)
            return reshape(-negative_index, false);
        timer_animate = requestAnimationFrame(animate);
        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);
        }
        animate();
        var event = createEvent("park");
        event.index = -negative_index;
        dispatch(outter, event);
        if (player.ing) play();
    };
    var play = function () {
        if (!player.ing) {
            player.ing = true;
        }
        clearTimeout(timer_playyer);
        timer_playyer = setTimeout(player, player.schedule);
    };
    var player = function () {
        if (!player.direction) {
            player.direction = 1;
        }
        if (!switchBy(player.direction)) {
            player.direction = -player.direction;
        }
    };
    player.schedule = 5000;
    var isMiss = false;
    var switchBy = function (count) {
        clearTimeout(timer_playyer);
        if (player.ing) {
            timer_playyer = setTimeout(player, player.schedule);
        }
        var enabled = generator(count - negative_index, 1);
        if (isMiss) {
            if (enabled) outter.go(outter.index + count);
        } else {
            if (enabled) negative_index -= count;
            animate();
        }
        return enabled;
    };
    var moveDeltaX = function (deltax, event) {
        var width = outter.clientWidth;
        var singleTarget = (!_imageMain || !_imageHelp) && (_imageMain || _imageHelp);
        if (singleTarget) {
            var current_Left = singleTarget.offsetLeft;
            var avail_deltaWidth = round(width >> 2);
            if (current_Left + deltax > avail_deltaWidth) {
                deltax = avail_deltaWidth - current_Left;
                saved_x += deltax;
            } else 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.moveLocked) return;
        var deltax = event.clientX - saved_x;
        var deltay = event.clientY - saved_y;
        if (!direction) {
            if (abs(deltax) < MOVELOCK_DELTA && abs(deltay) < MOVELOCK_DELTA) return;
            if (abs(deltay) - abs(deltax) > 0) { //垂直方向
                direction = -1;
            } else { //水平方向
                direction = 1;
            }
        }
        if (direction < 0) {
            return;
        }
        if (!moving) {
            return;
        }
        event.moveLocked = true;
        // event.stopPropagation && event.stopPropagation();
        moveDeltaX(deltax, event);
    };
    var stop_wheel_timer = 0;
    onmousewheel(outter, function (event) {
        if (event.defaultPrevented) return;
        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);
    });
    moveupon(outter, {
        start(event) {
            cancelAnimationFrame(timer_animate);
            clearTimeout(timer_playyer);
            moving = true;
            direction = 0;
            _speed(0);
            saved_x = event.clientX;
            saved_y = event.clientY;
        },
        move: mousemove,
        end() {
            moving = false;
            park();
        }
    })

    outter.go = function (index, cache) {
        if (outter.index === index && cache !== false) return;
        negative_index = -index;
        var _removingMain = _imageMain;
        reshape(index, false, cache);
        css(_removingMain, "transition:.1s opacity ease-out,.1s transform;z-index:1;left:0;");
        appendChild(outter, _removingMain);
        setTimeout(function () {
            css(_removingMain, "transform:scale(.97);opacity:0;");
        });
        setTimeout(function () {
            remove(_removingMain);
            css(_removingMain, "transform:;opacity:;transition:");
            css(_imageMain, "transform:;opacity:;transition:");
        }, 300);
        css(_imageMain, "z-index:0;transform:scale(.92);opacity:0;transition:none");
        setTimeout(() => css(_imageMain, "transform:scale(1);opacity:1;transition:.2s transform ease-out,.4s opacity"), 0);
        if (player.ing) play();
        return outter;
    };
    outter.play = function (schedule = player.schedule, _isMiss) {
        if (isDefined(_isMiss)) {
            isMiss = _isMiss;
        }
        if (schedule !== player.schedule) {
            player.schedule = schedule;
            play();
        } else if (!player.ing) {
            play();
        }
        return outter;
    };
    outter.stop = function () {
        player.ing = false;
        return outter;
    };
    outter.miss = function (scadule) {
        outter.play(scadule, true);
    };
    outter.next = function (count = 1) {
        current_index += .1;
        switchBy(count);
        return outter;
    };
    outter.prev = function (count = 1) {
        current_index -= .1;
        switchBy(-count);
        return outter;
    };
    var cancel_resize;
    onappend(outter, function () {
        cancel_resize && cancel_resize();
        cancel_resize = onresize(window, function () {
            switchBy(0);
        });
        if (isFinite(outter.index)) switchBy(0);
    });
    onremove(outter, function () {
        cancel_resize && cancel_resize();
        cancel_resize = null;
    });
    css(outter, "overflow:hidden;-webkit-overflow-scrolling:auto;over-flow:auto;");
    return outter;
}<|endoftext|>


<commit_before>(function() {
  'use strict';

  angular.module('civic.common')
    .directive('userBlock', userBlockDirective)
    .controller('UserBlockController', UserBlockController);

  // @ngInject
  function userBlockDirective() {
    return /* @ngInject */ {
      restrict: 'E',
      scope: {
        user: '='
      },
      templateUrl: 'components/directives/userBlock.tpl.html'
    };
  }
})();
<commit_msg>removed extraneous userBlock controller call<commit_after>(function() {
  'use strict';

  angular.module('civic.common')
    .directive('userBlock', userBlockDirective);

  // @ngInject
  function userBlockDirective() {
    return /* @ngInject */ {
      restrict: 'E',
      scope: {
        user: '='
      },
      templateUrl: 'components/directives/userBlock.tpl.html'
    };
  }
})();
<|endoftext|>


<commit_before>var Arrow = require('arrow'),
	_ = require('lodash');

/**
 * Creates models from your schema (see "fetchSchema" for more information on the schema).
 */
exports.createModelsFromSchema = function () {
	var self = this,
		models = {};

	Object.keys(self.schema.objects).forEach(function (modelName) {
		var object = self.schema.objects[modelName],
			fields = {};
		Object.keys(object).forEach(function (fieldName) {
			if (fieldName !== 'id') {
				fields[fieldName] = {
					type: self.convertDataTypeToJSType(object[fieldName].DATA_TYPE),
					required: object.IS_NULLABLE === 'NO'
				};
			}
		});

		models[self.name + '/' + modelName] = Arrow.Model.extend(self.name + '/' + modelName, {
			name: self.name + '/' + modelName,
			autogen: !!self.config.modelAutogen,
			fields: fields,
			connector: self,
			generated: true
		});
	});

	self.models = _.defaults(self.models || {}, models);
};
<commit_msg>[ARRCONN-238] Use primaryKey column with different name than 'id' in models<commit_after>var Arrow = require('arrow'),
	_ = require('lodash');

/**
 * Creates models from your schema (see "fetchSchema" for more information on the schema).
 */
exports.createModelsFromSchema = function () {
	var self = this,
		models = {},
		exposePrimaryKeyAsId = _.has(Arrow.getGlobal(), 'config.serialization.exposePrimaryKeyAsId') ? _.get(Arrow.getGlobal(), 'config.serialization.exposePrimaryKeyAsId') : false;

	/**
	 * Returns model's primary key column's name
	 * @param {string} modelName
	 * @returns {string}
	 */
	function getPrimaryKeyFromSchema(modelName) {
		return self.schema.primary_keys[modelName];
	}

	/**
	 * Get model fields except the primaryKey field
	 * @param {string} modelName
	 * @param {Object} modelSchema
	 * @returns {Object}
	 */
	function getFieldsExceptPrimaryKey(modelName, modelSchema) {
		return Object.keys(modelSchema)
			.filter(function (fieldName) {
				var primaryKeyColumnName = getPrimaryKeyFromSchema(modelName);
				return exposePrimaryKeyAsId && typeof primaryKeyColumnName !== 'undefined' && fieldName === primaryKeyColumnName ? false : (fieldName === 'id' ? false : true);
			})
			.reduce(function (fields, fieldName) {
				fields[fieldName] = {
					type: self.convertDataTypeToJSType(modelSchema[fieldName].DATA_TYPE),
					required: modelSchema.IS_NULLABLE === 'NO'
				};

				return fields;
			}, {});
	}

	/**
	 * Generate Arrow Model base on model name and fields
	 * @param {string} modelName
	 * @param {Object} fields
	 * @returns {Object}
	 */
	function genModel (modelName, fields) {
		var primaryKeyColumnName = getPrimaryKeyFromSchema(modelName);

		var modelInfo = {
			name: self.name + '/' + modelName,
			autogen: !!self.config.modelAutogen,
			fields: fields,
			connector: self,
			generated: true
		};

		if (typeof primaryKeyColumnName !== undefined) {
			modelInfo.metadata = {
				primarykey: primaryKeyColumnName
			};
		}

		return Arrow.Model.extend(self.name + '/' + modelName, modelInfo);
	}

	// Generate models based on schema objects
	Object.keys(self.schema.objects).forEach(function (modelName) {
		var object = self.schema.objects[modelName];

		var fields = getFieldsExceptPrimaryKey(modelName, object);
		models[self.name + '/' + modelName] = genModel(modelName, fields);
	});

	self.models = _.defaults(self.models || {}, models);
};

<|endoftext|>


<commit_before>"use strict";

var value = require("value");

var env = require("../environment.js"),
    RemoteService = require("../../client/RemoteService.js");

/**
 * process the response and modify the model-instance
 * @param {!Model} modelInstance
 * @param {!Object} response
 * @return {Error} err
 */
function processResponse (modelInstance, response) {

    var err = null,
        model = {};

    if (typeof response !== "object" || response === null) {
        return new Error("(alamid) Invalid Response: Object expected.");
    }

    if (response.status === "error") {
        err = new Error(response.message || "An error occurred.");
    }

    if (response.data !== undefined && response.status === "success") {
        model = response.data;
    }

    if (!err) {

        //set parent ids
        if (model.ids !== undefined) {
            modelInstance.setIds(model.ids);
        }
        //set id
        if (model.id !== undefined) {
            modelInstance.setId(model.id);
        }

        if (model && value(model).notTypeOf(modelInstance.constructor)) {
            modelInstance.set(model);    // this may throw an exception
        }
    }

    return err;
}

/**
 * call the actual service
 * function acts like a proxy and strips unneeded params
 * it also handles sync / async service-responses
 *
 * @param {!Function} serviceFunction
 * @param {Boolean} remote
 * @param {Object} ids
 * @param {Object} data
 * @param {Function} callback
 */
function callService (serviceFunction, remote, ids, data, callback) {

    var args = Array.prototype.slice.call(arguments, 0);
    //the last param is callback dude!
    callback = args[args.length-1];

    //remove the first two elements, because it's the function itself
    args.splice(0, 1);

    //remove "remote" attribute on the server
    if (env.isServer()) {
        args.splice(0, 1);
    }

    //async
    if (serviceFunction.length === args.length) {
        serviceFunction.apply(this, args);
    }
    //sync
    else if (serviceFunction.length === args.length - 1) {
        //remove the final callback
        args.splice(args.length-1, 1);
        callback(serviceFunction.apply(this, args));
    }
    //invalid function passed
    else {
        throw new Error("(alamid) Function '" +
            serviceFunction.toString().replace(/\s\{.*/, "") + "' accepts unexpected number of arguments");
    }
}

/**
 * handle the service call and model-modification
 * returns an error and the service-call response
 *
 * @param {!Model} modelInstance
 * @param {!String} method
 * @param {!Boolean} remote
 * @param {!Function} callback
 */
function serviceAdapter (modelInstance, method, remote, callback) {

    var service = modelInstance.getService(),
        ids = modelInstance.getIds(),
        url = modelInstance.getUrl();

    function onServiceResponse (response) {
        var err;

        try {
            err = processResponse (modelInstance, response);

        } catch (err) {
            err.message = "(alamid) Service-Error [" + method + "] " + err.message;
        }

        if (!err) {
            modelInstance.emit(method);
        }

        callback(err, response);
    }

    //remote-services work only on the client
    if (env.isClient() && remote === true) {
        //load remote-service-adapter
        remote = new RemoteService(url);
    }

    //No client service defined
    //append remote-service as main service and set remote to false
    if(!service && remote === true) {
        service = remote;
        remote = false;
    }

    if (!service || !service[method]) {
        callback(new Error("(alamid) " + modelInstance.getUrl() + "[" + method + "] : There is no service available."));
        return;
    }

    //METHOD DEPENDENT CALLS
    switch (method) {

        case "create" :
            callService(service[method].bind(service), remote, ids, modelInstance, onServiceResponse);
            break;
        case "read" :
            callService(service[method].bind(service),  remote, ids, onServiceResponse);
            break;

        case "update" :
            callService(service[method].bind(service), remote, ids, modelInstance, onServiceResponse);
            break;
        case "destroy" :
            callService(service[method].bind(service), remote, ids, onServiceResponse);
            break;
        default :
            onServiceResponse(new Error("(alamid) Service-Adapter - invalid method '" + method + "'"));
    }
}

module.exports = serviceAdapter;<commit_msg>- manual merges<commit_after>"use strict";

var value = require("value");

var env = require("../env.js"),
    RemoteService = require("../../client/RemoteService.class.js");

/**
 * process the response and modify the model-instance
 * @param {!Model} modelInstance
 * @param {!Object} response
 * @return {Error} err
 */
function processResponse (modelInstance, response) {

    var err = null,
        model = {};

    if (typeof response !== "object" || response === null) {
        return new Error("(alamid) Invalid Response: Object expected.");
    }

    if (response.status === "error") {
        err = new Error(response.message || "An error occurred.");
    }

    if (response.data !== undefined && response.status === "success") {
        model = response.data;
    }

    if (!err) {

        //set parent ids
        if (model.ids !== undefined) {
            modelInstance.setIds(model.ids);
        }
        //set id
        if (model.id !== undefined) {
            modelInstance.setId(model.id);
        }

        if (model && value(model).notTypeOf(modelInstance.constructor)) {
            modelInstance.set(model);    // this may throw an exception
        }
    }

    return err;
}

/**
 * call the actual service
 * function acts like a proxy and strips unneeded params
 * it also handles sync / async service-responses
 *
 * @param {!Function} serviceFunction
 * @param {Boolean} remote
 * @param {Object} ids
 * @param {Object} data
 * @param {Function} callback
 */
function callService (serviceFunction, remote, ids, data, callback) {

    var args = Array.prototype.slice.call(arguments, 0);
    //the last param is callback dude!
    callback = args[args.length-1];

    //remove the first two elements, because it's the function itself
    args.splice(0, 1);

    //remove "remote" attribute on the server
    if (env.isServer()) {
        args.splice(0, 1);
    }

    //async
    if (serviceFunction.length === args.length) {
        serviceFunction.apply(this, args);
    }
    //sync
    else if (serviceFunction.length === args.length - 1) {
        //remove the final callback
        args.splice(args.length-1, 1);
        callback(serviceFunction.apply(this, args));
    }
    //invalid function passed
    else {
        throw new Error("(alamid) Function '" +
            serviceFunction.toString().replace(/\s\{.*/, "") + "' accepts unexpected number of arguments");
    }
}

/**
 * handle the service call and model-modification
 * returns an error and the service-call response
 *
 * @param {!Model} modelInstance
 * @param {!String} method
 * @param {!Boolean} remote
 * @param {!Function} callback
 */
function serviceAdapter (modelInstance, method, remote, callback) {

    var service = modelInstance.getService(),
        ids = modelInstance.getIds(),
        url = modelInstance.getUrl();

    function onServiceResponse (response) {
        var err;

        try {
            err = processResponse (modelInstance, response);

        } catch (err) {
            err.message = "(alamid) Service-Error [" + method + "] " + err.message;
        }

        if (!err) {
            modelInstance.emit(method);
        }

        callback(err, response);
    }

    //remote-services work only on the client
    if (env.isClient() && remote === true) {
        //load remote-service-adapter
        remote = new RemoteService(url);
    }

    //No client service defined
    //append remote-service as main service and set remote to false
    if(!service && remote === true) {
        service = remote;
        remote = false;
    }

    if (!service || !service[method]) {
        callback(new Error("(alamid) " + modelInstance.getUrl() + "[" + method + "] : There is no service available."));
        return;
    }

    //METHOD DEPENDENT CALLS
    switch (method) {

        case "create" :
            callService(service[method].bind(service), remote, ids, modelInstance, onServiceResponse);
            break;
        case "read" :
            callService(service[method].bind(service),  remote, ids, onServiceResponse);
            break;

        case "update" :
            callService(service[method].bind(service), remote, ids, modelInstance, onServiceResponse);
            break;
        case "destroy" :
            callService(service[method].bind(service), remote, ids, onServiceResponse);
            break;
        default :
            onServiceResponse(new Error("(alamid) Service-Adapter - invalid method '" + method + "'"));
    }
}

module.exports = serviceAdapter;<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

'use strict';

var chalk = require('chalk');
var execSync = require('child_process').execSync;
var spawn = require('cross-spawn');
var opn = require('opn');

// https://github.com/sindresorhus/opn#app
var OSX_CHROME = 'google chrome';

const Actions = Object.freeze({
  NONE: 0,
  BROWSER: 1,
  SCRIPT: 2,
});

function getBrowserEnv() {
  // Attempt to honor this environment variable.
  // It is specific to the operating system.
  // See https://github.com/sindresorhus/opn#app for documentation.
  const value = process.env.BROWSER;
  let action;
  if (!value) {
    // Default.
    action = Actions.BROWSER;
  } else if (value.toLowerCase().endsWith('.js')) {
    action = Actions.SCRIPT;
  } else if (value.toLowerCase() === 'none') {
    action = Actions.NONE;
  } else {
    action = Actions.BROWSER;
  }
  return { action, value };
}

function executeNodeScript(scriptPath, url) {
  const extraArgs = process.argv.slice(2);
  const child = spawn('node', [scriptPath, ...extraArgs, url], {
    stdio: 'inherit',
  });
  child.on('close', code => {
    if (code !== 0) {
      console.log();
      console.log(
        chalk.red(
          'The script specified as BROWSER environment variable failed.'
        )
      );
      console.log(chalk.cyan(scriptPath) + ' exited with code ' + code + '.');
      console.log();
      return;
    }
  });
  return true;
}

function startBrowserProcess(browser, url) {
  // If we're on OS X, the user hasn't specifically
  // requested a different browser, we can try opening
  // Chrome with AppleScript. This lets us reuse an
  // existing tab when possible instead of creating a new one.
  const shouldTryOpenChromeWithAppleScript = process.platform === 'darwin' &&
    (typeof browser !== 'string' || browser === OSX_CHROME);

  if (shouldTryOpenChromeWithAppleScript) {
    try {
      // Try our best to reuse existing tab
      // on OS X Google Chrome with AppleScript
      execSync('ps cax | grep "Google Chrome"');
      execSync('osascript openChrome.applescript ' + url, {
        cwd: __dirname,
        stdio: 'ignore',
      });
      return true;
    } catch (err) {
      // Ignore errors.
    }
  }

  // Another special case: on OS X, check if BROWSER has been set to "open".
  // In this case, instead of passing `open` to `opn` (which won't work),
  // just ignore it (thus ensuring the intended behavior, i.e. opening the system browser):
  // https://github.com/facebookincubator/create-react-app/pull/1690#issuecomment-283518768
  if (process.platform === 'darwin' && browser === 'open') {
    browser = undefined;
  }

  // Fallback to opn
  // (It will always open new tab)
  try {
    var options = { app: browser };
    opn(url, options).catch(() => {}); // Prevent `unhandledRejection` error.
    return true;
  } catch (err) {
    return false;
  }
}

/**
 * Reads the BROWSER evironment variable and decides what to do with it. Returns
 * true if it opened a browser or ran a node.js script, otherwise false.
 */
function openBrowser(url) {
  const { action, value } = getBrowserEnv();
  switch (action) {
    case Actions.NONE:
      // Special case: BROWSER="none" will prevent opening completely.
      return false;
    case Actions.SCRIPT:
      return executeNodeScript(value, url);
    case Actions.BROWSER:
      return startBrowserProcess(value, url);
    default:
      throw new Error('Not implemented.');
  }
}

module.exports = openBrowser;
<commit_msg>react-dev-utils/openBrowser now supports urls with 2+ params (#2076)<commit_after>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

'use strict';

var chalk = require('chalk');
var execSync = require('child_process').execSync;
var spawn = require('cross-spawn');
var opn = require('opn');

// https://github.com/sindresorhus/opn#app
var OSX_CHROME = 'google chrome';

const Actions = Object.freeze({
  NONE: 0,
  BROWSER: 1,
  SCRIPT: 2,
});

function getBrowserEnv() {
  // Attempt to honor this environment variable.
  // It is specific to the operating system.
  // See https://github.com/sindresorhus/opn#app for documentation.
  const value = process.env.BROWSER;
  let action;
  if (!value) {
    // Default.
    action = Actions.BROWSER;
  } else if (value.toLowerCase().endsWith('.js')) {
    action = Actions.SCRIPT;
  } else if (value.toLowerCase() === 'none') {
    action = Actions.NONE;
  } else {
    action = Actions.BROWSER;
  }
  return { action, value };
}

function executeNodeScript(scriptPath, url) {
  const extraArgs = process.argv.slice(2);
  const child = spawn('node', [scriptPath, ...extraArgs, url], {
    stdio: 'inherit',
  });
  child.on('close', code => {
    if (code !== 0) {
      console.log();
      console.log(
        chalk.red(
          'The script specified as BROWSER environment variable failed.'
        )
      );
      console.log(chalk.cyan(scriptPath) + ' exited with code ' + code + '.');
      console.log();
      return;
    }
  });
  return true;
}

function startBrowserProcess(browser, url) {
  // If we're on OS X, the user hasn't specifically
  // requested a different browser, we can try opening
  // Chrome with AppleScript. This lets us reuse an
  // existing tab when possible instead of creating a new one.
  const shouldTryOpenChromeWithAppleScript = process.platform === 'darwin' &&
    (typeof browser !== 'string' || browser === OSX_CHROME);

  if (shouldTryOpenChromeWithAppleScript) {
    try {
      // Try our best to reuse existing tab
      // on OS X Google Chrome with AppleScript
      execSync('ps cax | grep "Google Chrome"');
      execSync('osascript openChrome.applescript "' + encodeURI(url) + '"', {
        cwd: __dirname,
        stdio: 'ignore',
      });
      return true;
    } catch (err) {
      // Ignore errors.
    }
  }

  // Another special case: on OS X, check if BROWSER has been set to "open".
  // In this case, instead of passing `open` to `opn` (which won't work),
  // just ignore it (thus ensuring the intended behavior, i.e. opening the system browser):
  // https://github.com/facebookincubator/create-react-app/pull/1690#issuecomment-283518768
  if (process.platform === 'darwin' && browser === 'open') {
    browser = undefined;
  }

  // Fallback to opn
  // (It will always open new tab)
  try {
    var options = { app: browser };
    opn(url, options).catch(() => {}); // Prevent `unhandledRejection` error.
    return true;
  } catch (err) {
    return false;
  }
}

/**
 * Reads the BROWSER evironment variable and decides what to do with it. Returns
 * true if it opened a browser or ran a node.js script, otherwise false.
 */
function openBrowser(url) {
  const { action, value } = getBrowserEnv();
  switch (action) {
    case Actions.NONE:
      // Special case: BROWSER="none" will prevent opening completely.
      return false;
    case Actions.SCRIPT:
      return executeNodeScript(value, url);
    case Actions.BROWSER:
      return startBrowserProcess(value, url);
    default:
      throw new Error('Not implemented.');
  }
}

module.exports = openBrowser;
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react'
import warning from 'warning'
import matchPath from './matchPath'

/**
 * The public API for rendering the first <Route> that matches.
 */
class Switch extends React.Component {
  static contextTypes = {
    router: PropTypes.shape({
      listen: PropTypes.func.isRequired
    }).isRequired
  }

  static propTypes = {
    children: PropTypes.node,
    location: PropTypes.object
  }

  state = {
    location: this.props.location || this.context.router.location
  }

  componentWillMount() {
    if (!this.props.location) {
      const { router } = this.context

      // Start listening here so we can <Redirect> on the initial render.
      this.unlisten = router.listen(() => {
        this.setState({
          location: router.location
        })
      })
    }
  }

  componentWillReceiveProps(nextProps) {
    warning(
      !(nextProps.location && !this.props.location),
      'You cannot change from an uncontrolled to controlled Switch. You passed in a `location` prop on a re-render when initially there was none.'
    )
    warning(
      !(!nextProps.location && this.props.location),
      'You cannot change from a controlled to an uncontrolled Switch. You passed in a `location` prop initially but on a re-render there was none.'
    )
  }

  componentWillUnmount() {
    if (this.unlisten)
      this.unlisten()
  }

  render() {
    const { children:routes } = this.props
    const { location } = this.state

    let route, match
    for (let i = 0, length = routes.length; match == null && i < length; ++i) {
      route = routes[i]
      match = matchPath(location.pathname, route.props)
    }

    return match ? React.cloneElement(route, { computedMatch: match }) : null
  }
}

export default Switch
<commit_msg>Use the safer React.Children functions<commit_after>import React, { PropTypes } from 'react'
import warning from 'warning'
import matchPath from './matchPath'

/**
 * The public API for rendering the first <Route> that matches.
 */
class Switch extends React.Component {
  static contextTypes = {
    router: PropTypes.shape({
      listen: PropTypes.func.isRequired
    }).isRequired
  }

  static propTypes = {
    children: PropTypes.node,
    location: PropTypes.object
  }

  state = {
    location: this.props.location || this.context.router.location
  }

  componentWillMount() {
    if (!this.props.location) {
      const { router } = this.context

      // Start listening here so we can <Redirect> on the initial render.
      this.unlisten = router.listen(() => {
        this.setState({
          location: router.location
        })
      })
    }
  }

  componentWillReceiveProps(nextProps) {
    warning(
      !(nextProps.location && !this.props.location),
      'You cannot change from an uncontrolled to controlled Switch. You passed in a `location` prop on a re-render when initially there was none.'
    )
    warning(
      !(!nextProps.location && this.props.location),
      'You cannot change from a controlled to an uncontrolled Switch. You passed in a `location` prop initially but on a re-render there was none.'
    )
  }

  componentWillUnmount() {
    if (this.unlisten)
      this.unlisten()
  }

  render() {
    const { children } = this.props
    const { location } = this.state

    let match, matchedRoute
    React.Children.forEach(children, route => {
      if (match == null) {
        matchedRoute = route
        match = matchPath(location.pathname, route.props)
      }
    })

    return match ? React.cloneElement(matchedRoute, { computedMatch: match }) : null
  }
}

export default Switch
<|endoftext|>


<commit_before>Package.describe({
	name: 'rocketchat:external',
	version: '0.0.1',
	summary: 'External for Rocket.Chat'
});

Package.registerBuildPlugin({
	name: "builExternal",
	use: [],
	sources: [
		'plugin/build-external.js'
	],
	npmDependencies: {
		"shelljs": "0.5.1"
	}
});

Package.onUse(function(api) {
	api.versionsFrom('1.0');

	api.use(['coffeescript', 'webapp', 'autoupdate'], 'server');

	api.addFiles('external.coffee', 'server');
	api.addFiles('methods.coffee', 'server');
	api.addFiles('publications.coffee', 'server');

	api.addFiles('rocket-external.js', 'client', {isAsset: true});
	api.addFiles('public/external.css', 'client', {isAsset: true});
	api.addFiles('public/external.js', 'client', {isAsset: true});
	api.addFiles('public/head.html', 'server', {isAsset: true});
});
<commit_msg>Retirado ", { isAsset: true }"<commit_after>Package.describe({
	name: 'rocketchat:external',
	version: '0.0.1',
	summary: 'External for Rocket.Chat'
});

Package.registerBuildPlugin({
	name: "builExternal",
	use: [],
	sources: [
		'plugin/build-external.js'
	],
	npmDependencies: {
		"shelljs": "0.5.1"
	}
});

Package.onUse(function(api) {
	api.versionsFrom('1.0');

	api.use(['coffeescript', 'webapp', 'autoupdate'], 'server');

	api.addFiles('external.coffee', 'server');
	api.addFiles('methods.coffee', 'server');
	api.addFiles('publications.coffee', 'server');

	api.addFiles('rocket-external.js', 'client');
	api.addFiles('public/external.css', 'client');
	api.addFiles('public/external.js', 'client');
	api.addFiles('public/head.html', 'server');
});
<|endoftext|>


<commit_before>import React from 'react';
import {searchUser} from '../api/requester';
import {
  View,
  Alert,
  Text,
  TextInput,
  StyleSheet,
  TouchableHighlight,
  AsyncStorage,
  DeviceEventEmitter,
  ListView,
  TouchableOpacity,
} from 'react-native';
import Hr from 'react-native-hr';

import {
  Container,
  Button
} from 'native-base';
import {
	Actions,
} from 'react-native-router-flux';

import { getTagId } from 'nfc-react-native';
const Sound = require('react-native-sound');

// const requireAudio = require('./button_beep_tone.mp3');

// import { Sound } from 'react-native-sound';

import globalStyles from '../../themes/styles'
import styles from './styles';
import { SwipeListView,SwipeRow } from 'react-native-swipe-list-view';
class ScanningView extends React.Component {
  constructor(){
    super();
    this.ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state = {
      counter : 0,
      listViewData: []//Array(10).fill('').map((_,i)=>`item #${i}`)
    };

    AsyncStorage.getItem("text").then((value) => {
      this.setState({text: value});
    }).done();

  }
  deleteRow(secId, rowId, rowMap) {
		rowMap[`${secId}${rowId}`].closeRow();
		let newData = [...this.state.listViewData];
		newData.splice(rowId, 1);
		this.setState({
      counter: this.state.counter-1,
      listViewData: newData
    });
}

  playSoundBundle () {
    const s = new Sound('button_beep_tone.mp3', Sound.MAIN_BUNDLE, (e) => {
      if (e) {
        console.log('error', e);
      } else {
        s.setSpeed(1);
        console.log('duration', s.getDuration());
        s.play(() => s.release()); // Release when it's done so we're not using up resources
      }
    });
  };

  componentDidMount() {

      this._mounted = true;
      // this.startNFCloop();

      DeviceEventEmitter.addListener('onTagError', function (e) {
          console.log('error', e)
          // alert(JSON.stringify(e))
      });

      DeviceEventEmitter.addListener('onTagDetected', (e) => {
          let stringifiedId = JSON.stringify(e);
          this.playSoundBundle();
          Alert.alert("Isaula: " + stringifiedId);
          // this.state.user_details.name = stringifiedId;
      });
  }

  addPassenger(passanger){
    let newData = this.state.listViewData;
    newData.unshift(passanger)
    this.setState({
      counter: this.state.counter+1,
      listViewData: newData
    });
  }

  HandleButton(){
    //Actions.pop({popNum: 4});
  }

  searchUserByCarnet(carnet){
      if(carnet != ''){
       searchUser(carnet)
        .then(response => {
          if(response.length<=0){
            alert("Carnet numero: "+ carnet+" no se ha encontrado");
          }else{
            this.addPassenger(response)
          }
        })
        .catch((error) => {
          throw error;
        });
      }
  }

  render(){
    return (
        <View style={styles.container}>
          <Text style={globalStyles.title}>Ingreso de pasajeros</Text>
          <Text style={styles.text}>Bus de {this.props.routeName} en dirección {this.props.routeDirection} {this.props.routeDirection=="entrada"?'al':'del'} templo</Text>
          <Text style={styles.text}>
            Num. Pasajeros: {this.state.counter}
          </Text>
          <Text style={styles.text}>
            Carnet:
          </Text>
          <TextInput
            ref="textId"
            style={styles.formInput}
            placeholder="Ingrese número de carnet"
            onChangeText={(text) => {
                this._textInput = text
              }
            }
            />
          <Button style={styles.btn} onPress={this.searchUserByCarnet.bind(this, this._textInput)}>
            Ingresar
          </Button>

          <View style={styles.informationUser}>
    					<SwipeListView
                swipeRowStyle={{flex: 1}}
                enableEmptySections={true}
    						dataSource={this.ds.cloneWithRows(this.state.listViewData)}
    						renderRow={ data => (
    							<TouchableHighlight
    								style={styles.rowFront}
    							>
    								<View>
    									<Text>{data}</Text>
    								</View>
    							</TouchableHighlight>
    						)}
    						renderHiddenRow={ (data, secId, rowId, rowMap) => (
    							<View style={styles.rowBack}>
    								<TouchableOpacity style={[styles.backRightBtn, styles.backRightBtnRight]} onPress={ _ => this.deleteRow(secId, rowId, rowMap) }>
    									<Text style={styles.backTextWhite}>Delete</Text>
    								</TouchableOpacity>
    							</View>
    						)}
    						rightOpenValue={-75}
    					/>
          </View>
          <TouchableHighlight style={styles.touchable} onPress={this.playSoundBundle}>
            <Text style={styles.touchableText}>Terminar</Text>
          </TouchableHighlight>
        </View>
    );
  }
}
// this.HandleButton.bind(this)
export default ScanningView;
<commit_msg>cleaning view<commit_after>import React from 'react';
import {searchUser} from '../api/requester';
import {
  View,
  Alert,
  Text,
  TextInput,
  StyleSheet,
  TouchableHighlight,
  AsyncStorage,
  DeviceEventEmitter,
  ListView,
  TouchableOpacity,
} from 'react-native';
import Hr from 'react-native-hr';

import {
  Container,
  Button
} from 'native-base';
import {
	Actions,
} from 'react-native-router-flux';

import { getTagId } from 'nfc-react-native';
const Sound = require('react-native-sound');

// const requireAudio = require('./button_beep_tone.mp3');

// import { Sound } from 'react-native-sound';

import globalStyles from '../../themes/styles'
import styles from './styles';
import { SwipeListView,SwipeRow } from 'react-native-swipe-list-view';
class ScanningView extends React.Component {
  constructor(){
    super();
    this.ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state = {
      counter : 0,
      listViewData: []//Array(10).fill('').map((_,i)=>`item #${i}`)
    };

    AsyncStorage.getItem("text").then((value) => {
      this.setState({text: value});
    }).done();

  }
  deleteRow(secId, rowId, rowMap) {
		rowMap[`${secId}${rowId}`].closeRow();
		let newData = [...this.state.listViewData];
		newData.splice(rowId, 1);
		this.setState({
      counter: this.state.counter-1,
      listViewData: newData
    });
}

  playSoundBundle () {
    const s = new Sound('button_beep_tone.mp3', Sound.MAIN_BUNDLE, (e) => {
      if (e) {
        console.log('error', e);
      } else {
        s.setSpeed(1);
        console.log('duration', s.getDuration());
        s.play(() => s.release()); // Release when it's done so we're not using up resources
      }
    });
  };

  componentDidMount() {

      this._mounted = true;
      // this.startNFCloop();

      DeviceEventEmitter.addListener('onTagError', function (e) {
          console.log('error', e)
          // alert(JSON.stringify(e))
      });

      DeviceEventEmitter.addListener('onTagDetected', (e) => {
          let stringifiedId = JSON.stringify(e);
          this.playSoundBundle();
          Alert.alert("Isaula: " + stringifiedId);
          // this.state.user_details.name = stringifiedId;
      });
  }

  addPassenger(passanger){
    let newData = this.state.listViewData;
    newData.unshift(passanger)
    this.setState({
      counter: this.state.counter+1,
      listViewData: newData
    });
  }

  HandleButton(){
    //Actions.pop({popNum: 4});
  }

  searchUserByCarnet(carnet){
      if(carnet != ''){
       searchUser(carnet)
        .then(response => {
          if(response.length<=0){
            alert("Carnet numero: "+ carnet+" no se ha encontrado");
          }else{
            this.addPassenger(response)
          }
        })
        .catch((error) => {
          throw error;
        });
      }
  }

  render(){
    return (
        <View style={styles.container}>
          <Text style={globalStyles.title}>Ingreso de pasajeros</Text>
          <Text style={styles.text}>Bus de {this.props.routeName} en dirección {this.props.routeDirection} {this.props.routeDirection=="entrada"?'al':'del'} templo</Text>
          <Text style={styles.text}>
            Num. Pasajeros: {this.state.counter}
          </Text>

          <View style={styles.informationUser}>
    					<SwipeListView
                swipeRowStyle={{flex: 1}}
                enableEmptySections={true}
    						dataSource={this.ds.cloneWithRows(this.state.listViewData)}
    						renderRow={ data => (
    							<TouchableHighlight
    								style={styles.rowFront}
    							>
    								<View>
    									<Text>{data}</Text>
    								</View>
    							</TouchableHighlight>
    						)}
    						renderHiddenRow={ (data, secId, rowId, rowMap) => (
    							<View style={styles.rowBack}>
    								<TouchableOpacity style={[styles.backRightBtn, styles.backRightBtnRight]} onPress={ _ => this.deleteRow(secId, rowId, rowMap) }>
    									<Text style={styles.backTextWhite}>Delete</Text>
    								</TouchableOpacity>
    							</View>
    						)}
    						rightOpenValue={-75}
    					/>
          </View>
          <TouchableHighlight style={styles.touchable} onPress={this.playSoundBundle}>
            <Text style={styles.touchableText}>Terminar</Text>
          </TouchableHighlight>
        </View>
    );
  }
}
// this.HandleButton.bind(this)
export default ScanningView;
<|endoftext|>


<commit_before>import Block from '../models/block'
import Change from '../models/change'
import Decoration from '../models/decoration'
import Document from '../models/document'
import History from '../models/history'
import Inline from '../models/inline'
import Leaf from '../models/leaf'
import Mark from '../models/mark'
import Node from '../models/node'
import Operation from '../models/operation'
import Point from '../models/point'
import Range from '../models/range'
import Schema from '../models/schema'
import Selection from '../models/selection'
import Stack from '../models/stack'
import Text from '../models/text'
import Value from '../models/value'
import isObject, { TYPES } from '../utils/is-object'
import mixin from '../utils/mixin'

/**
 * A factory for the interface that all Slate objects implement.
 *
 * @type {Function}
 */

function create(type) {
  const TYPE = TYPES[type]
  const camel = `${type.charAt(0).toUpperCase()}${type.slice(1)}`
  const is = `is${camel}`

  class ObjectInterface {
    /**
     * Return the type of the object.
     *
     * @return {String}
     */

    get object() {
      return type
    }
  }

  ObjectInterface[is] = isObject.bind(null, type)
  ObjectInterface.prototype[TYPE] = true
  return ObjectInterface
}

/**
 * Mix in the object interfaces.
 */

debugger

mixin(create('block'), [Block])
mixin(create('change'), [Change])
mixin(create('decoration'), [Decoration])
mixin(create('document'), [Document])
mixin(create('history'), [History])
mixin(create('inline'), [Inline])
mixin(create('leaf'), [Leaf])
mixin(create('mark'), [Mark])
mixin(create('node'), [Node])
mixin(create('operation'), [Operation])
mixin(create('point'), [Point])
mixin(create('range'), [Range])
mixin(create('schema'), [Schema])
mixin(create('selection'), [Selection])
mixin(create('stack'), [Stack])
mixin(create('text'), [Text])
mixin(create('value'), [Value])
<commit_msg>remove debugger<commit_after>import Block from '../models/block'
import Change from '../models/change'
import Decoration from '../models/decoration'
import Document from '../models/document'
import History from '../models/history'
import Inline from '../models/inline'
import Leaf from '../models/leaf'
import Mark from '../models/mark'
import Node from '../models/node'
import Operation from '../models/operation'
import Point from '../models/point'
import Range from '../models/range'
import Schema from '../models/schema'
import Selection from '../models/selection'
import Stack from '../models/stack'
import Text from '../models/text'
import Value from '../models/value'
import isObject, { TYPES } from '../utils/is-object'
import mixin from '../utils/mixin'

/**
 * A factory for the interface that all Slate objects implement.
 *
 * @type {Function}
 */

function create(type) {
  const TYPE = TYPES[type]
  const camel = `${type.charAt(0).toUpperCase()}${type.slice(1)}`
  const is = `is${camel}`

  class ObjectInterface {
    /**
     * Return the type of the object.
     *
     * @return {String}
     */

    get object() {
      return type
    }
  }

  ObjectInterface[is] = isObject.bind(null, type)
  ObjectInterface.prototype[TYPE] = true
  return ObjectInterface
}

/**
 * Mix in the object interfaces.
 */

mixin(create('block'), [Block])
mixin(create('change'), [Change])
mixin(create('decoration'), [Decoration])
mixin(create('document'), [Document])
mixin(create('history'), [History])
mixin(create('inline'), [Inline])
mixin(create('leaf'), [Leaf])
mixin(create('mark'), [Mark])
mixin(create('node'), [Node])
mixin(create('operation'), [Operation])
mixin(create('point'), [Point])
mixin(create('range'), [Range])
mixin(create('schema'), [Schema])
mixin(create('selection'), [Selection])
mixin(create('stack'), [Stack])
mixin(create('text'), [Text])
mixin(create('value'), [Value])
<|endoftext|>


<commit_before>describe('mdSidenav', function() {
  beforeEach(module('material.components.sidenav', 'ngAnimateMock', function($provide) {
    $provide.value('$$rAF', function(cb) { cb(); });
  }));

  function setup(attrs) {
    var el;
    inject(function($compile, $rootScope) {
      var parent = angular.element('<div>');
      el = angular.element('<md-sidenav ' + (attrs||'') + '>');
      parent.append(el);
      $compile(parent)($rootScope);
      $rootScope.$apply();
    });
    return el;
  }

  describe('directive', function() {

    it('should bind isOpen attribute', inject(function($rootScope, $animate) {
      var el = setup('md-is-open="show"');
      $rootScope.$apply('show = true');

      $animate.triggerCallbacks();
      expect(el.hasClass('md-closed')).toBe(false);
      expect(el.parent().find('md-backdrop').length).toBe(1);

      $rootScope.$apply('show = false');
      $animate.triggerCallbacks();
      expect(el.hasClass('md-closed')).toBe(true);
      expect(el.parent().find('md-backdrop').length).toBe(0);
    }));

    it('should close on escape', inject(function($rootScope, $animate, $mdConstant, $timeout) {
      var el = setup('md-is-open="show"');
      $rootScope.$apply('show = true');

      $animate.triggerCallbacks();
      el.parent().triggerHandler({
        type: 'keydown',
        keyCode: $mdConstant.KEY_CODE.ESCAPE
      });
      $timeout.flush();
      expect($rootScope.show).toBe(false);
    }));

    it('should close on backdrop click', inject(function($rootScope, $animate, $timeout) {
      var el = setup('md-is-open="show"');
      $rootScope.$apply('show = true');

      $animate.triggerCallbacks();
      el.parent().find('md-backdrop').triggerHandler('click');
      $timeout.flush();
      expect($rootScope.show).toBe(false);
    }));

    it('should focus sidenav on open', inject(function($rootScope, $animate, $document) {
      TestUtil.mockElementFocus(this);
      var el = setup('md-is-open="show"');
      $rootScope.$apply('show = true');

      $animate.triggerCallbacks();
      expect($document.activeElement).toBe(el[0]);
    }));

    it('should lock open when is-locked-open is true', inject(function($rootScope, $animate, $document) {
      var el = setup('md-is-open="show" md-is-locked-open="lock"');
      expect(el.hasClass('md-locked-open')).toBe(false);
      $rootScope.$apply('lock = true');
      expect(el.hasClass('md-locked-open')).toBe(true);
      $rootScope.$apply('show = true');
      $animate.triggerCallbacks();
      expect(el.parent().find('md-backdrop').hasClass('md-locked-open')).toBe(true);
    }));

    it('should expose $mdMedia service as $media local in is-locked-open attribute', function() {
      var mdMediaSpy = jasmine.createSpy('$mdMedia');
      module(function($provide) {
        $provide.value('$mdMedia', mdMediaSpy);
      });
      inject(function($rootScope, $animate, $document, $mdMedia) {
        var el = setup('md-is-locked-open="$media(123)"');
        expect($mdMedia).toHaveBeenCalledWith(123);
      });
    });

  });

  describe('controller', function() {
    it('should create controller', function() {
      var el = setup('');
      var controller = el.controller('mdSidenav');
      expect(controller).not.toBe(undefined);
    });

    it('should open and close and toggle', inject(function($timeout) {
      var el = setup('');
      var scope = el.isolateScope();
      var controller = el.controller('mdSidenav');

      // Should start closed
      expect(el.hasClass('md-closed')).toBe(true);

      controller.open();
      scope.$apply();

      expect(el.hasClass('md-closed')).toBe(false);

      controller.close();
      scope.$apply();

      expect(el.hasClass('md-closed')).toBe(true);

      controller.toggle();
      scope.$apply();

      expect(el.hasClass('md-closed')).toBe(false);
    }));

  });

  describe("controller Promise API", function() {
    var $animate, $rootScope;

      function flush() {
        if ( !$rootScope.$$phase) {
          $rootScope.$apply();
        }
        $animate.triggerCallbacks();
      }

    beforeEach( inject(function(_$animate_,_$rootScope_,_$timeout_) {
        $animate = _$animate_;
        $rootScope = _$rootScope_;
        $timeout = _$timeout_;
    }));

    it('should open(), close(), and toggle() with promises', function () {
      var el = setup('');
      var scope = el.isolateScope();
      var controller = el.controller('mdSidenav');

      var openDone = 0, closeDone = 0, toggleDone = 0;
      var onOpen = function() { openDone++; };
      var onClose = function() { closeDone++; };
      var onToggle = function() { toggleDone++; };

      controller
        .open()
        .then(onOpen)
        .then(controller.close)
        .then(onClose);

      flush();
      expect(openDone).toBe(1);
      flush();
      expect(closeDone).toBe(1);

      controller
        .close()
        .then(onClose);

      flush();
      expect(closeDone).toBe(2);
      expect(scope.isOpen).toBe(false);

      controller
        .toggle()
        .then(onToggle);

      flush();
      expect(toggleDone).toBe(1);
      expect(scope.isOpen).toBe(true);
    });

    it('should open() to work multiple times before close()', function () {
      var el = setup('');
      var controller = el.controller('mdSidenav');

      var openDone = 0, closeDone = 0;
      var onOpen = function() { openDone++; };
      var onClose = function() { closeDone++; };

      controller
        .open()
        .then(onOpen)
        .then(controller.open)
        .then(onOpen);

      flush();
      expect(openDone).toBe(2);
      expect(closeDone).toBe(0);
      expect(el.hasClass('md-closed')).toBe(false);

      controller
        .close()
        .then(onClose);

      flush();
      expect(openDone).toBe(2);
      expect(closeDone).toBe(1);
      expect(el.hasClass('md-closed')).toBe(true);
    });

  });

  describe('$mdSidenav Service', function() {
    it('should grab instance', inject(function($mdSidenav) {
      var el = setup('md-component-id="left"');
      var scope = el.isolateScope();

      var instance = $mdSidenav('left');
      expect(instance).toBeTruthy();

      instance.open();
      scope.$apply();

      expect(el.hasClass('md-closed')).toBe(false);

      instance.close();
      scope.$apply();

      expect(el.hasClass('md-closed')).toBe(true);

      instance.toggle();
      scope.$apply();

      expect(el.hasClass('md-closed')).toBe(false);

      instance.toggle();
      scope.$apply();

      expect(el.hasClass('md-closed')).toBe(true);
    }));

    it('exposes state', inject(function($mdSidenav) {
      var el = setup('md-component-id="stateTest" md-is-open="shouldOpen" md-is-locked-open="shouldLockOpen"');
      var scope = el.scope();

      var instance = $mdSidenav('stateTest');
      expect(instance.isOpen()).toBe(false);
      expect(instance.isLockedOpen()).toBe(false);

      scope.shouldOpen = true;
      scope.shouldLockOpen = true;
      scope.$digest();
      expect(instance.isOpen()).toBe(true);
      expect(instance.isLockedOpen()).toBe(true);
    }));
  });

});
<commit_msg>test(mdSidenav): test for state of isOpen and isLockedOpen<commit_after>describe('mdSidenav', function() {
  beforeEach(module('material.components.sidenav', 'ngAnimateMock', function($provide) {
    $provide.value('$$rAF', function(cb) { cb(); });
  }));

  function setup(attrs) {
    var el;
    inject(function($compile, $rootScope) {
      var parent = angular.element('<div>');
      el = angular.element('<md-sidenav ' + (attrs||'') + '>');
      parent.append(el);
      $compile(parent)($rootScope);
      $rootScope.$apply();
    });
    return el;
  }

  describe('directive', function() {

    it('should bind isOpen attribute', inject(function($rootScope, $animate) {
      var el = setup('md-is-open="show"');
      $rootScope.$apply('show = true');

      $animate.triggerCallbacks();
      expect(el.hasClass('md-closed')).toBe(false);
      expect(el.parent().find('md-backdrop').length).toBe(1);

      $rootScope.$apply('show = false');
      $animate.triggerCallbacks();
      expect(el.hasClass('md-closed')).toBe(true);
      expect(el.parent().find('md-backdrop').length).toBe(0);
    }));

    it('should close on escape', inject(function($rootScope, $animate, $mdConstant, $timeout) {
      var el = setup('md-is-open="show"');
      $rootScope.$apply('show = true');

      $animate.triggerCallbacks();
      el.parent().triggerHandler({
        type: 'keydown',
        keyCode: $mdConstant.KEY_CODE.ESCAPE
      });
      $timeout.flush();
      expect($rootScope.show).toBe(false);
    }));

    it('should close on backdrop click', inject(function($rootScope, $animate, $timeout) {
      var el = setup('md-is-open="show"');
      $rootScope.$apply('show = true');

      $animate.triggerCallbacks();
      el.parent().find('md-backdrop').triggerHandler('click');
      $timeout.flush();
      expect($rootScope.show).toBe(false);
    }));

    it('should focus sidenav on open', inject(function($rootScope, $animate, $document) {
      TestUtil.mockElementFocus(this);
      var el = setup('md-is-open="show"');
      $rootScope.$apply('show = true');

      $animate.triggerCallbacks();
      expect($document.activeElement).toBe(el[0]);
    }));

    it('should lock open when is-locked-open is true', inject(function($rootScope, $animate, $document) {
      var el = setup('md-is-open="show" md-is-locked-open="lock"');
      expect(el.hasClass('md-locked-open')).toBe(false);
      $rootScope.$apply('lock = true');
      expect(el.hasClass('md-locked-open')).toBe(true);
      $rootScope.$apply('show = true');
      $animate.triggerCallbacks();
      expect(el.parent().find('md-backdrop').hasClass('md-locked-open')).toBe(true);
    }));

    it('should expose $mdMedia service as $media local in is-locked-open attribute', function() {
      var mdMediaSpy = jasmine.createSpy('$mdMedia');
      module(function($provide) {
        $provide.value('$mdMedia', mdMediaSpy);
      });
      inject(function($rootScope, $animate, $document, $mdMedia) {
        var el = setup('md-is-locked-open="$media(123)"');
        expect($mdMedia).toHaveBeenCalledWith(123);
      });
    });

  });

  describe('controller', function() {
    it('should create controller', function() {
      var el = setup('');
      var controller = el.controller('mdSidenav');
      expect(controller).not.toBe(undefined);
    });

    it('should open and close and toggle', inject(function($timeout) {
      var el = setup('');
      var scope = el.isolateScope();
      var controller = el.controller('mdSidenav');

      // Should start closed
      expect(el.hasClass('md-closed')).toBe(true);

      controller.open();
      scope.$apply();

      expect(el.hasClass('md-closed')).toBe(false);

      controller.close();
      scope.$apply();

      expect(el.hasClass('md-closed')).toBe(true);

      controller.toggle();
      scope.$apply();

      expect(el.hasClass('md-closed')).toBe(false);
    }));

  });

  describe("controller Promise API", function() {
    var $animate, $rootScope;

      function flush() {
        if ( !$rootScope.$$phase) {
          $rootScope.$apply();
        }
        $animate.triggerCallbacks();
      }

    beforeEach( inject(function(_$animate_,_$rootScope_,_$timeout_) {
        $animate = _$animate_;
        $rootScope = _$rootScope_;
        $timeout = _$timeout_;
    }));

    it('should open(), close(), and toggle() with promises', function () {
      var el = setup('');
      var scope = el.isolateScope();
      var controller = el.controller('mdSidenav');

      var openDone = 0, closeDone = 0, toggleDone = 0;
      var onOpen = function() { openDone++; };
      var onClose = function() { closeDone++; };
      var onToggle = function() { toggleDone++; };

      controller
        .open()
        .then(onOpen)
        .then(controller.close)
        .then(onClose);

      flush();
      expect(openDone).toBe(1);
      flush();
      expect(closeDone).toBe(1);

      controller
        .close()
        .then(onClose);

      flush();
      expect(closeDone).toBe(2);
      expect(scope.isOpen).toBe(false);

      controller
        .toggle()
        .then(onToggle);

      flush();
      expect(toggleDone).toBe(1);
      expect(scope.isOpen).toBe(true);
    });

    it('should open() to work multiple times before close()', function () {
      var el = setup('');
      var controller = el.controller('mdSidenav');

      var openDone = 0, closeDone = 0;
      var onOpen = function() { openDone++; };
      var onClose = function() { closeDone++; };

      controller
        .open()
        .then(onOpen)
        .then(controller.open)
        .then(onOpen);

      flush();
      expect(openDone).toBe(2);
      expect(closeDone).toBe(0);
      expect(el.hasClass('md-closed')).toBe(false);

      controller
        .close()
        .then(onClose);

      flush();
      expect(openDone).toBe(2);
      expect(closeDone).toBe(1);
      expect(el.hasClass('md-closed')).toBe(true);
    });

  });

  describe('$mdSidenav Service', function() {
    it('should grab instance', inject(function($mdSidenav) {
      var el = setup('md-component-id="left"');
      var scope = el.isolateScope();

      var instance = $mdSidenav('left');
      expect(instance).toBeTruthy();

      instance.open();
      scope.$apply();

      expect(el.hasClass('md-closed')).toBe(false);

      instance.close();
      scope.$apply();

      expect(el.hasClass('md-closed')).toBe(true);

      instance.toggle();
      scope.$apply();

      expect(el.hasClass('md-closed')).toBe(false);

      instance.toggle();
      scope.$apply();

      expect(el.hasClass('md-closed')).toBe(true);
    }));

    it('exposes state', inject(function($mdSidenav) {
      var el = setup('md-component-id="stateTest" md-is-open="shouldOpen" md-is-locked-open="shouldLockOpen"');
      var scope = el.scope();

      var instance = $mdSidenav('stateTest');
      expect(instance.isOpen()).toBe(false);
      expect(instance.isLockedOpen()).toBe(false);

      scope.shouldOpen = true;
      scope.shouldLockOpen = true;
      scope.$digest();
      expect(instance.isOpen()).toBe(true);
      expect(instance.isLockedOpen()).toBe(true);

      scope.shouldOpen = false;
      scope.shouldLockOpen = true;
      scope.$digest();
      expect(instance.isOpen()).toBe(false);
      expect(instance.isLockedOpen()).toBe(true);
    }));
  });

});
<|endoftext|>