<commit_before>/**
 * Created by Nightpaws on 04/03/2016.
 */
//General requirements
var q = require('q');
var deferred = q.defer();
var config = require('../../../config');

//Database logging components
var messageModel = require('../../models/message.model');
var mongoose = require('mongoose');

//External posting requirements
var Twit = require('twit');
var facebook = require('tiny-facebook-wrapper');

//Twitter accounts for Twit
var first = new Twit({
    consumer_key: config.twitter.first.consumer_key,
    consumer_secret: config.twitter.first.consumer_secret,
    access_token: config.twitter.first.access_token_key,
    access_token_secret: config.twitter.first.access_token_secret,
    timeout_ms: 60 * 1000  // optional HTTP request timeout to apply to all requests.
});

var second = new Twit({
    consumer_key: config.twitter.second.consumer_key,
    consumer_secret: config.twitter.second.consumer_secret,
    access_token: config.twitter.second.access_token_key,
    access_token_secret: config.twitter.second.access_token_secret,
    timeout_ms: 60 * 1000  // optional HTTP request timeout to apply to all requests.
});

var third = new Twit({
    consumer_key: config.twitter.third.consumer_key,
    consumer_secret: config.twitter.third.consumer_secret,
    access_token: config.twitter.third.access_token_key,
    access_token_secret: config.twitter.third.access_token_secret,
    timeout_ms: 60 * 1000  // optional HTTP request timeout to apply to all requests.
});

var fourth = new Twit({
    consumer_key: config.twitter.fourth.consumer_key,
    consumer_secret: config.twitter.fourth.consumer_secret,
    access_token: config.twitter.fourth.access_token_key,
    access_token_secret: config.twitter.fourth.access_token_secret,
    timeout_ms: 60 * 1000  // optional HTTP request timeout to apply to all requests.
});

var fifth = new Twit({
    consumer_key: config.twitter.fifth.consumer_key,
    consumer_secret: config.twitter.fifth.consumer_secret,
    access_token: config.twitter.fifth.access_token_key,
    access_token_secret: config.twitter.fifth.access_token_secret,
    timeout_ms: 60 * 1000  // optional HTTP request timeout to apply to all requests.
});

var phd = new Twit({
    consumer_key: config.twitter.phd.consumer_key,
    consumer_secret: config.twitter.phd.consumer_secret,
    access_token: config.twitter.phd.access_token_key,
    access_token_secret: config.twitter.phd.access_token_secret,
    timeout_ms: 60 * 1000  // optional HTTP request timeout to apply to all requests.
});

//Access Token for Facebook
var accessToken1 = config.facebook.accessToken1;
var accessToken2 = config.facebook.accessToken2;
var accessToken3 = config.facebook.accessToken3;
var accessToken4 = config.facebook.accessToken4;
var accessToken5 = config.facebook.accessToken5;
var accessTokenPhD = config.facebook.accessTokenPhD;

var accounts = {
    submit: function (subject, message, recipients, sender) {

        //Initialise variables needed for submissions
        var q = require('q');
        var deferred = q.defer();
        var one, two, three, four, five, six;
        var s1 = true, s2 = true, s3 = true, s4 = true, s5 = true, s6 = true;

        one = recipients[0];
        two = recipients[1];
        three = recipients[2];
        four = recipients[3];
        five = recipients[4];
        six = recipients[5];

        //Message posting attempted! Log to database
        var msg = new messageModel({
            uid: sender,
            subject: subject,
            message: message,
            year: {
                first: recipients[0],
                second: recipients[1],
                third: recipients[2],
                fourth: recipients[3],
                fifth: recipients[4],
                phd: recipients[5]
            }
        });

        msg.save(function (err) {

            if (err) {

                if (err.code === 11000)
                    deferred.reject('Post flooding detected');
                else
                    deferred.reject('Error posting message');

            } else {
                var wallpost;

                console.log("DEBUG CODE =========");
                console.log("===subject: "+subject);
                console.log("===message: "+message);

                //if message content isn't null
                if (message != null) {
                    var t = subject + "\n\n" + message;
                    wallpost = t;

                    //if subject is long
                    if (subject.length > 100)
                        subject = subject.substring(0, subject.length - 40);
                } else {
                    //if message content is null
                    wallpost = subject;
                }

                //Perform submissions to Social Media
                if (one) {

                    //Facebook Posting
                    facebook.post('/' + config.facebook.pageID_year1 + '/feed', accessToken1, {message: wallpost}, function (error, res) {
                        if (error) {
                            s1 = false;
                            console.log("error: " + error); //json response
                        }
                        console.log("response: " + res);
                        var fbout = JSON.parse(res);

                        if(message!=null) {
                            //If post with contents
                            first.post('statuses/update', {status: subject + "... https://facebook.com/" + fbout.id})
                                .catch(function (err) {
                                    s1 = false;
                                    console.log(err);
                                });
                        }
                        else{
                            //else if subject/tweet only
                            first.post('statuses/update', {status: subject })
                                .catch(function (err) {
                                    s1 = false;
                                    console.log(err);
                                });
                        }
                    });

                }
                if (two) {

                    //Facebook Posting
                    facebook.post('/' + config.facebook.pageID_year2 + '/feed', accessToken2, {message: wallpost}, function (error, res) {
                        if (error) {
                            s2 = false;
                            console.log("error: " + error); //json response
                        }
                        console.log("response: " + res);
                        var fbout = JSON.parse(res);

                        //Twitter Posting
                        second.post('statuses/update', {status: subject + "... https://facebook.com/" + fbout.id})
                            .catch(function (err) {
                                s2 = false;
                                console.log(err);
                            });
                    });

                }
                if (three) {

                    //Facebook Posting
                    facebook.post('/' + config.facebook.pageID_year3 + '/feed', accessToken3, {message: wallpost}, function (error, res) {
                        if (error) {
                            s3 = false;
                            console.log("error: " + error); //json response
                        }
                        console.log("response: " + res);
                        var fbout = JSON.parse(res);

                        //Twitter Posting
                        third.post('statuses/update', {status: subject + "... https://facebook.com/" + fbout.id})
                            .catch(function (err) {
                                s3 = false;
                                console.log(err);
                            });
                    });

                }
                if (four) {

                    //Facebook Posting
                    facebook.post('/' + config.facebook.pageID_year4 + '/feed', accessToken4, {message: wallpost}, function (error, res) {
                        if (error) {
                            s4 = false;
                            console.log("error: " + error); //json response
                        }
                        console.log("response: " + res);
                        var fbout = JSON.parse(res);

                        //Twitter Posting
                        fourth.post('statuses/update', {status: subject + "... https://facebook.com/" + fbout.id})
                            .catch(function (err) {
                                s4 = false;
                                console.log(err);
                            });
                    });

                }
                if (five) {

                    //Facebook Posting
                    facebook.post('/' + config.facebook.pageID_year5 + '/feed', accessToken5, {message: wallpost}, function (error, res) {
                        if (error) {
                            s5 = false;
                            console.log("error: " + error); //json response
                        }
                        console.log("response: " + res);
                        var fbout = JSON.parse(res);

                        //Twitter Posting
                        fifth.post('statuses/update', {status: subject + "... https://facebook.com/" + fbout.id})
                            .catch(function (err) {
                                s5 = false;
                                console.log(err);
                            });
                    });

                }
                if (six) {

                    //Facebook Posting
                    facebook.post('/' + config.facebook.pageID_yearPhD + '/feed', accessTokenPhD, {message: wallpost}, function (error, res) {
                        if (error) {
                            s6 = false;
                            console.log("error: " + error); //json response
                        }
                        console.log("response: " + res);
                        var fbout = JSON.parse(res);

                        //Twitter Posting
                        phd.post('statuses/update', {status: subject + "... https://facebook.com/" + fbout.id})
                            .catch(function (err) {
                                s6 = false;
                                console.log(err);
                            });
                    });

                }
            }
        });

        var successState = [s1, s2, s3, s4, s5, s6];
        deferred.resolve(successState);

        return deferred.promise;
    }

};
module.exports = accounts;<commit_msg>further logging for traceback<commit_after>/**
 * Created by Nightpaws on 04/03/2016.
 */
//General requirements
var q = require('q');
var deferred = q.defer();
var config = require('../../../config');

//Database logging components
var messageModel = require('../../models/message.model');
var mongoose = require('mongoose');

//External posting requirements
var Twit = require('twit');
var facebook = require('tiny-facebook-wrapper');

//Twitter accounts for Twit
var first = new Twit({
    consumer_key: config.twitter.first.consumer_key,
    consumer_secret: config.twitter.first.consumer_secret,
    access_token: config.twitter.first.access_token_key,
    access_token_secret: config.twitter.first.access_token_secret,
    timeout_ms: 60 * 1000  // optional HTTP request timeout to apply to all requests.
});

var second = new Twit({
    consumer_key: config.twitter.second.consumer_key,
    consumer_secret: config.twitter.second.consumer_secret,
    access_token: config.twitter.second.access_token_key,
    access_token_secret: config.twitter.second.access_token_secret,
    timeout_ms: 60 * 1000  // optional HTTP request timeout to apply to all requests.
});

var third = new Twit({
    consumer_key: config.twitter.third.consumer_key,
    consumer_secret: config.twitter.third.consumer_secret,
    access_token: config.twitter.third.access_token_key,
    access_token_secret: config.twitter.third.access_token_secret,
    timeout_ms: 60 * 1000  // optional HTTP request timeout to apply to all requests.
});

var fourth = new Twit({
    consumer_key: config.twitter.fourth.consumer_key,
    consumer_secret: config.twitter.fourth.consumer_secret,
    access_token: config.twitter.fourth.access_token_key,
    access_token_secret: config.twitter.fourth.access_token_secret,
    timeout_ms: 60 * 1000  // optional HTTP request timeout to apply to all requests.
});

var fifth = new Twit({
    consumer_key: config.twitter.fifth.consumer_key,
    consumer_secret: config.twitter.fifth.consumer_secret,
    access_token: config.twitter.fifth.access_token_key,
    access_token_secret: config.twitter.fifth.access_token_secret,
    timeout_ms: 60 * 1000  // optional HTTP request timeout to apply to all requests.
});

var phd = new Twit({
    consumer_key: config.twitter.phd.consumer_key,
    consumer_secret: config.twitter.phd.consumer_secret,
    access_token: config.twitter.phd.access_token_key,
    access_token_secret: config.twitter.phd.access_token_secret,
    timeout_ms: 60 * 1000  // optional HTTP request timeout to apply to all requests.
});

//Access Token for Facebook
var accessToken1 = config.facebook.accessToken1;
var accessToken2 = config.facebook.accessToken2;
var accessToken3 = config.facebook.accessToken3;
var accessToken4 = config.facebook.accessToken4;
var accessToken5 = config.facebook.accessToken5;
var accessTokenPhD = config.facebook.accessTokenPhD;

var accounts = {
    submit: function (subject, message, recipients, sender) {
        console.log("FUNCTIONCALL ACCOUNT.ACTION.JS");
        console.log("values input");
        console.log("subject: " + subject);
        console.log("message: " + message);
        console.log("recipients" + recipients);
        console.log("sender:" + sender);
        console.log("END============");
        //Initialise variables needed for submissions
        var q = require('q');
        var deferred = q.defer();
        var one, two, three, four, five, six;
        var s1 = true, s2 = true, s3 = true, s4 = true, s5 = true, s6 = true;

        one = recipients[0];
        two = recipients[1];
        three = recipients[2];
        four = recipients[3];
        five = recipients[4];
        six = recipients[5];

        //Message posting attempted! Log to database
        var msg = new messageModel({
            uid: sender,
            subject: subject,
            message: message,
            year: {
                first: recipients[0],
                second: recipients[1],
                third: recipients[2],
                fourth: recipients[3],
                fifth: recipients[4],
                phd: recipients[5]
            }
        });

        msg.save(function (err) {

            if (err) {

                if (err.code === 11000)
                    deferred.reject('Post flooding detected');
                else
                    deferred.reject('Error posting message');

            } else {
                var wallpost;

                console.log("DEBUG CODE =========");
                console.log("===subject: " + subject);
                console.log("===message: " + message);

                //if message content isn't null
                if (message != null) {
                    var t = subject + "\n\n" + message;
                    wallpost = t;

                    //if subject is long
                    if (subject.length > 100)
                        subject = subject.substring(0, subject.length - 40);
                } else {
                    //if message content is null
                    wallpost = subject;
                }

                //Perform submissions to Social Media
                if (one) {

                    //Facebook Posting
                    facebook.post('/' + config.facebook.pageID_year1 + '/feed', accessToken1, {message: wallpost}, function (error, res) {
                        if (error) {
                            s1 = false;
                            console.log("error: " + error); //json response
                        }
                        console.log("response: " + res);
                        var fbout = JSON.parse(res);

                        if (message != null) {
                            //If post with contents
                            first.post('statuses/update', {status: subject + "... https://facebook.com/" + fbout.id})
                                .catch(function (err) {
                                    s1 = false;
                                    console.log(err);
                                });
                        }
                        else {
                            //else if subject/tweet only
                            first.post('statuses/update', {status: subject})
                                .catch(function (err) {
                                    s1 = false;
                                    console.log(err);
                                });
                        }
                    });

                }
                if (two) {

                    //Facebook Posting
                    facebook.post('/' + config.facebook.pageID_year2 + '/feed', accessToken2, {message: wallpost}, function (error, res) {
                        if (error) {
                            s2 = false;
                            console.log("error: " + error); //json response
                        }
                        console.log("response: " + res);
                        var fbout = JSON.parse(res);

                        //Twitter Posting
                        second.post('statuses/update', {status: subject + "... https://facebook.com/" + fbout.id})
                            .catch(function (err) {
                                s2 = false;
                                console.log(err);
                            });
                    });

                }
                if (three) {

                    //Facebook Posting
                    facebook.post('/' + config.facebook.pageID_year3 + '/feed', accessToken3, {message: wallpost}, function (error, res) {
                        if (error) {
                            s3 = false;
                            console.log("error: " + error); //json response
                        }
                        console.log("response: " + res);
                        var fbout = JSON.parse(res);

                        //Twitter Posting
                        third.post('statuses/update', {status: subject + "... https://facebook.com/" + fbout.id})
                            .catch(function (err) {
                                s3 = false;
                                console.log(err);
                            });
                    });

                }
                if (four) {

                    //Facebook Posting
                    facebook.post('/' + config.facebook.pageID_year4 + '/feed', accessToken4, {message: wallpost}, function (error, res) {
                        if (error) {
                            s4 = false;
                            console.log("error: " + error); //json response
                        }
                        console.log("response: " + res);
                        var fbout = JSON.parse(res);

                        //Twitter Posting
                        fourth.post('statuses/update', {status: subject + "... https://facebook.com/" + fbout.id})
                            .catch(function (err) {
                                s4 = false;
                                console.log(err);
                            });
                    });

                }
                if (five) {

                    //Facebook Posting
                    facebook.post('/' + config.facebook.pageID_year5 + '/feed', accessToken5, {message: wallpost}, function (error, res) {
                        if (error) {
                            s5 = false;
                            console.log("error: " + error); //json response
                        }
                        console.log("response: " + res);
                        var fbout = JSON.parse(res);

                        //Twitter Posting
                        fifth.post('statuses/update', {status: subject + "... https://facebook.com/" + fbout.id})
                            .catch(function (err) {
                                s5 = false;
                                console.log(err);
                            });
                    });

                }
                if (six) {

                    //Facebook Posting
                    facebook.post('/' + config.facebook.pageID_yearPhD + '/feed', accessTokenPhD, {message: wallpost}, function (error, res) {
                        if (error) {
                            s6 = false;
                            console.log("error: " + error); //json response
                        }
                        console.log("response: " + res);
                        var fbout = JSON.parse(res);

                        //Twitter Posting
                        phd.post('statuses/update', {status: subject + "... https://facebook.com/" + fbout.id})
                            .catch(function (err) {
                                s6 = false;
                                console.log(err);
                            });
                    });

                }
            }
        });

        var successState = [s1, s2, s3, s4, s5, s6];
        deferred.resolve(successState);

        return deferred.promise;
    }

};
module.exports = accounts;<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
//reference: https://github.com/JedWatson/react-select
import Select from 'react-select';

// Be sure to include styles at some point, probably during your bootstrapping
import 'react-select/dist/react-select.css';
import { connect } from 'react-redux'
import PropTypes from 'prop-types';
import {
    Button,
    FormGroup,
    FormControl,
    ControlLabel
 } from 'react-bootstrap';
import * as ChatService from '../../Team4of5_Service/Chat.js';

const style = {
    display: 'flex',
    alignItems: 'center',
    marginBottom: 20,
    marginTop: 20,
    width: 470,
    height: 40,
};

const buttonStyle = {
    marginBottom: 20,
    marginTop: 20
};

class CreateProject extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            options: [],
            value: []
        }
        this.handleSelectChange = this.handleSelectChange.bind(this);
        this.handleConfirm = this.handleConfirm.bind(this);
        this.getData = this.getData.bind(this);
    }

    componentDidMount() {
        //
        let self = this;
        ChatService.getUserContacts().then(function (data) {
            self.getData(data);
        }).catch(function (err) {
            console.log("Error:" + err)
        })
    }

    getData(data) {
        let moreDivs = [];
        for (let index in data) {
            let element = data[index];
            console.log(index);
            console.log(element);
            //Only "indivdual" type can be added into a project
            if (element.type == "Individual") {
                moreDivs.push(
                    { value: element.name, label: element.name, extraData: element, Uuid: index }
                );
            }

        }
        //setTimeout(() => {
        this.setState({ options: this.state.options.concat(moreDivs) });
        //}, 500);
    }

    handleSelectChange(value) {
        console.log('You\'ve selected: ', value);
        this.setState({ value });
    }

    handleConfirm() {
        let self = this;
        let title = this.refs.message.value;
        if (title == "") {
            alert("Please input your project name!");
        } else if (this.state.value == "") {
            alert("Please choose your members!");
        } else {
            ChatService.checkProjectNameExist(title).then(function () {
                let memUids = [];
                let users = ""
                for (let i = 0; i < self.state.value.length; i++) {
                    users = users.concat(self.state.value[i].value + " ")
                    memUids.push(self.state.value[i].Uuid);
                }
                console.log(title)
                ChatService.createProject(memUids, title).then(function (data) {
                    alert("Project name: " + title + "\n Project Members: " + users
                        + "\n Successfully added!");
                }).catch(function (err) {
                    alert("Error: " + err);
                })

                self.refs.message.value = "";
                self.setState({ value: [] })
            }).catch(function (err) {
                alert(err);
            })

        }
    }

    render() {
        return (

Create A New Project

                <FormControl style={style} ref="message" placeholder="Project Name" className="message-input" />

                <Select multi={true}
                    disabled={false}
                    value={this.state.value}
                    placeholder="Select your members"
                    options={this.state.options}
                    onChange={this.handleSelectChange} />

                <Button bsStyle="primary"
                    style={buttonStyle}
                    onClick={this.handleConfirm}>Confirm</Button>

        )
    }
}

export default CreateProject;
<commit_msg>Fix chat create project bug<commit_after>import React from 'react';
import ReactDOM from 'react-dom';
//reference: https://github.com/JedWatson/react-select
import Select from 'react-select';

// Be sure to include styles at some point, probably during your bootstrapping
import 'react-select/dist/react-select.css';
import { connect } from 'react-redux'
import PropTypes from 'prop-types';
import {
    Button,
    FormGroup,
    FormControl,
    ControlLabel
 } from 'react-bootstrap';
import * as ChatService from '../../Team4of5_Service/Chat.js';

const style = {
    display: 'flex',
    alignItems: 'center',
    marginBottom: 20,
    marginTop: 20,
    width: 470,
    height: 40,
};

const buttonStyle = {
    marginBottom: 20,
    marginTop: 20
};

class CreateProject extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            options: [],
            value: [],
            inputTitle: ''
        }
        this.handleSelectChange = this.handleSelectChange.bind(this);
        this.handleConfirm = this.handleConfirm.bind(this);
        this.getData = this.getData.bind(this);
    }

    componentDidMount() {
        //
        let self = this;
        ChatService.getUserContacts().then(function (data) {
            self.getData(data);
        }).catch(function (err) {
            console.log("Error:" + err)
        })
    }

    getData(data) {
        let moreDivs = [];
        for (let index in data) {
            let element = data[index];
            console.log(index);
            console.log(element);
            //Only "indivdual" type can be added into a project
            if (element.type == "Individual") {
                moreDivs.push(
                    { value: element.name, label: element.name, extraData: element, Uuid: index }
                );
            }

        }
        //setTimeout(() => {
        this.setState({ options: this.state.options.concat(moreDivs) });
        //}, 500);
    }

    handleSelectChange(value) {
        console.log('You\'ve selected:  ', value);
        this.setState({ value });
    }

    handleConfirm() {
        let self = this;
        let title = this.state.inputTitle.value
        if (title == "") {
            alert("Please input your project name!");
        } else if (this.state.value == "") {
            alert("Please choose your members!");
        } else {
            ChatService.checkProjectNameExist(title).then(function () {
                let memUids = [];
                let users = ""
                for (let i = 0; i < self.state.value.length; i++) {
                    users = users.concat(self.state.value[i].value + " ")
                    memUids.push(self.state.value[i].Uuid);
                }
                console.log(title)
                ChatService.createProject(memUids, title).then(function (data) {
                    alert("Project name: " + title + "\n Project Members: " + users
                        + "\n Successfully added!");
                }).catch(function (err) {
                    alert("Error: " + err);
                })

                self.state.inputTitle.value = "";
                self.setState({ value: [] })
            }).catch(function (err) {
                alert(err);
            })

        }
    }

    render() {
        return (

Create A New Project

                <FormControl style={style}
                     inputRef={title => this.state.inputTitle = title}
                     placeholder="Project Name" className="message-input" />

                <Select multi={true}
                    disabled={false}
                    value={this.state.value}
                    placeholder="Select your members"
                    options={this.state.options}
                    onChange={this.handleSelectChange} />

                <Button bsStyle="primary"
                    style={buttonStyle}
                    onClick={this.handleConfirm}>Confirm</Button>

        )
    }
}

export default CreateProject;
<|endoftext|>


<commit_before>/* eslint-disable global-require */

'use strict'

module.exports = {
  api: require('./libs/api.js'),
  es: require('./libs/es.js'),
  ingestcsv: require('./libs/ingest-csv.js')
}
<commit_msg>export ingest module<commit_after>/* eslint-disable global-require */

'use strict'

module.exports = {
  api: require('./libs/api.js'),
  es: require('./libs/es.js'),
  ingest: require('./libs/ingest.js'),
  ingestcsv: require('./libs/ingest-csv.js')
}
<|endoftext|>


<commit_before>import styled, {keyframes} from 'styled-components'

import {
  declareFlatBaseColors,
  declareFlatPrimaryColors,
  declareInteractionColors,
  declareRaisedBaseColors,
  declareRaisedPrimaryColors,
  stylingInk,
  stylingLook
} from '../utilStyles'

const declareIconColor = props => {
  let declareColor
  const {ink, look} = props
  const {FLAT, RAISED} = stylingLook
  const {BASE, PRIMARY} = stylingInk
  if (look === FLAT && ink === BASE) {
    declareColor = declareFlatBaseColors
  } else if (look === FLAT && ink === PRIMARY) {
    declareColor = declareFlatPrimaryColors
  } else if (look === RAISED && ink === BASE) {
    declareColor = declareRaisedBaseColors
  } else if (look === RAISED && ink === PRIMARY) {
    declareColor = declareRaisedPrimaryColors
  }
  return declareInteractionColors(declareColor(props), 'svg')
}

const rotateClockwise = keyframes`
  from {transform: rotate(0deg);}
  to {transform: rotate(360deg);}
`

const stepClockwiseTopLeft = keyframes`
  0%, 100% {transform: translate(0, 0);}
  22%      {transform: translate(0, 0);}
  25%      {transform: translate(50px, 0);}
  47%      {transform: translate(50px, 0);}
  50%      {transform: translate(50px, 50px);}
  72%      {transform: translate(50px, 50px);}
  75%      {transform: translate(0, 50px);}
  97%      {transform: translate(0, 50px);}
`

const stepClockwiseTopRight = keyframes`
  0%, 100% {transform: translate(0, 0);}
  22%      {transform: translate(0, 0);}
  25%      {transform: translate(0, 50px);}
  47%      {transform: translate(0, 50px);}
  50%      {transform: translate(-50px, 50px);}
  72%      {transform: translate(-50px, 50px);}
  75%      {transform: translate(-50px, 0);}
  97%      {transform: translate(-50px, 0);}
`

const stepClockwiseBottomLeft = keyframes`
  0%, 100% {transform: translate(0, 0);}
  22%      {transform: translate(0, 0);}
  25%      {transform: translate(0, -50px);}
  47%      {transform: translate(0, -50px);}
  50%      {transform: translate(50px, -50px);}
  72%      {transform: translate(50px, -50px);}
  75%      {transform: translate(50px, 0);}
  97%      {transform: translate(50px, 0);}
`

const StyledIconToccoWrapper = styled.i`
  &&& {
    animation: ${rotateClockwise} 3s linear infinite;
    display: block;
    height: ${props => props.size ? props.size : ''};
    width: ${props => props.size ? props.size : '100%'};
    ${props => declareIconColor(props)}

    // if not Internet Explorer 11 or lower do sophisticated animation (https://bit.ly/2Okub3j)
    @supports not (old: ie) {
      animation: none;
      .tocco-icon-top-left {
        animation-name: ${stepClockwiseTopLeft};
      }

      .tocco-icon-top-right {
        animation-name: ${stepClockwiseTopRight};
      }

      .tocco-icon-bottom-left {
        animation-name: ${stepClockwiseBottomLeft};
      }
    }
  }
`

const animationDuration = 9
const StyledIconToccoSvg = styled.svg.attrs({
  preserveAspectRatio: 'xMidYMid meet',
  viewBox: '0 0 100 100'
})`
  &&& {
    fill: inherit;
    height: ${props => props.size ? props.size : ''};
    width: ${props => props.size ? props.size : '100%'};

    .tocco-icon-top-left,
    .tocco-icon-top-right,
    .tocco-icon-bottom-left {
      animation-duration: ${animationDuration}s;
      animation-iteration-count: infinite;
      fill: transparent;
      stroke-width: 14.4;
      stroke: inherit;
    }

    .tocco-icon-top-left {
      animation-delay: ${animationDuration / 12}s;
    }

    .tocco-icon-top-right {
      animation-delay: 0;
    }

    .tocco-icon-bottom-left {
      animation-delay: ${animationDuration / 6}s;
    }
  }
`

export {
  StyledIconToccoWrapper,
  StyledIconToccoSvg
}
<commit_msg>style(tocco-ui): animate IconTocco immediately<commit_after>import styled, {keyframes} from 'styled-components'

import {
  declareFlatBaseColors,
  declareFlatPrimaryColors,
  declareInteractionColors,
  declareRaisedBaseColors,
  declareRaisedPrimaryColors,
  stylingInk,
  stylingLook
} from '../utilStyles'

const declareIconColor = props => {
  let declareColor
  const {ink, look} = props
  const {FLAT, RAISED} = stylingLook
  const {BASE, PRIMARY} = stylingInk
  if (look === FLAT && ink === BASE) {
    declareColor = declareFlatBaseColors
  } else if (look === FLAT && ink === PRIMARY) {
    declareColor = declareFlatPrimaryColors
  } else if (look === RAISED && ink === BASE) {
    declareColor = declareRaisedBaseColors
  } else if (look === RAISED && ink === PRIMARY) {
    declareColor = declareRaisedPrimaryColors
  }
  return declareInteractionColors(declareColor(props), 'svg')
}

const rotateClockwise = keyframes`
  from {transform: rotate(0deg);}
  to {transform: rotate(360deg);}
`

const stepClockwiseTopLeft = keyframes`
  0%, 100% {transform: translate(0, 0);}
  3%      {transform: translate(50px, 0);}
  25%      {transform: translate(50px, 0);}
  28%      {transform: translate(50px, 50px);}
  50%      {transform: translate(50px, 50px);}
  53%      {transform: translate(0, 50px);}
  75%      {transform: translate(0, 50px);}
  78%      {transform: translate(0, 0);}
`

const stepClockwiseTopRight = keyframes`
  0%, 100% {transform: translate(0, 0);}
  3%      {transform: translate(0, 50px);}
  25%      {transform: translate(0, 50px);}
  28%      {transform: translate(-50px, 50px);}
  50%      {transform: translate(-50px, 50px);}
  53%      {transform: translate(-50px, 0);}
  75%      {transform: translate(-50px, 0);}
  78%      {transform: translate(0, 0);}
`

const stepClockwiseBottomLeft = keyframes`
  0%, 100% {transform: translate(0, 0);}
  3%      {transform: translate(0, -50px);}
  25%      {transform: translate(0, -50px);}
  28%      {transform: translate(50px, -50px);}
  50%      {transform: translate(50px, -50px);}
  53%      {transform: translate(50px, 0);}
  75%      {transform: translate(50px, 0);}
  78%      {transform: translate(0, 0);}
`

const StyledIconToccoWrapper = styled.i`
  &&& {
    animation: ${rotateClockwise} 3s linear infinite;
    display: block;
    height: ${props => props.size ? props.size : ''};
    width: ${props => props.size ? props.size : '100%'};
    ${props => declareIconColor(props)}

    // if not Internet Explorer 11 or lower do sophisticated animation (https://bit.ly/2Okub3j)
    @supports not (old: ie) {
      animation: none;
      .tocco-icon-top-left {
        animation-name: ${stepClockwiseTopLeft};
      }

      .tocco-icon-top-right {
        animation-name: ${stepClockwiseTopRight};
      }

      .tocco-icon-bottom-left {
        animation-name: ${stepClockwiseBottomLeft};
      }
    }
  }
`

const animationDuration = 9
const StyledIconToccoSvg = styled.svg.attrs({
  preserveAspectRatio: 'xMidYMid meet',
  viewBox: '0 0 100 100'
})`
  &&& {
    fill: inherit;
    height: ${props => props.size ? props.size : ''};
    width: ${props => props.size ? props.size : '100%'};

    .tocco-icon-top-left,
    .tocco-icon-top-right,
    .tocco-icon-bottom-left {
      animation-duration: ${animationDuration}s;
      animation-iteration-count: infinite;
      fill: transparent;
      stroke-width: 14.4;
      stroke: inherit;
    }

    .tocco-icon-top-left {
      animation-delay: ${animationDuration / 12}s;
    }

    .tocco-icon-top-right {
      animation-delay: 0;
    }

    .tocco-icon-bottom-left {
      animation-delay: ${animationDuration / 6}s;
    }
  }
`

export {
  StyledIconToccoWrapper,
  StyledIconToccoSvg
}
<|endoftext|>


<commit_before>/**
 * Pimcore
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.pimcore.org/license
 *
 * @copyright  Copyright (c) 2009-2010 elements.at New Media Solutions GmbH (http://www.elements.at)
 * @license    http://www.pimcore.org/license     New BSD License
 */

pimcore.registerNS("pimcore.settings.httpErrorLog");
pimcore.settings.httpErrorLog = Class.create({

    initialize: function(id) {
        this.getTabPanel();
    },

    activate: function () {
        var tabPanel = Ext.getCmp("pimcore_panel_tabs");
        tabPanel.activate("pimcore_http_error_log");
    },

    getTabPanel: function () {

        if (!this.panel) {
            this.panel = new Ext.Panel({
                id: "pimcore_http_error_log",
                title: t("http_errors"),
                iconCls: "pimcore_icon_httperrorlog",
                border: false,
                layout: "fit",
                closable:true,
                items: [this.getGrid()]
            });

            var tabPanel = Ext.getCmp("pimcore_panel_tabs");
            tabPanel.add(this.panel);
            tabPanel.activate("pimcore_http_error_log");

            this.panel.on("destroy", function () {
                pimcore.globalmanager.remove("http_error_log");
            }.bind(this));

            pimcore.layout.refresh();
        }

        return this.panel;
    },

    getGrid: function () {

        this.store = new Ext.data.JsonStore({
            url: '/admin/misc/http-error-log',
            restful: false,
            root: "items",
            remoteSort: true,
            fields: ["id","path", "code", "date","amount"],
            baseParams: {
                limit: 20,
                filter: ""
            }
        });
        this.store.load();

        var typesColumns = [
            {header: "ID", width: 50, sortable: true, hidden: true, dataIndex: 'id'},
            {header: "Code", width: 60, sortable: true, dataIndex: 'code'},
            {header: t("path"), id: "path", width: 400, sortable: true, dataIndex: 'path'},
            {header: t("amount"), width: 60, sortable: true, dataIndex: 'amount'},
            {header: t("date"), id: "extension_description", width: 200, sortable: true, dataIndex: 'date', renderer: function(d) {
                var date = new Date(d * 1000);
                return date.format("Y-m-d H:i:s");
            }}
        ];

        this.filterField = new Ext.form.TextField({
            xtype: "textfield",
            width: 200,
            style: "margin: 0 10px 0 0;",
            enableKeyEvents: true,
            listeners: {
                "keydown" : function (field, key) {
                    if (key.getKey() == key.ENTER) {
                        var input = field;
                        this.store.baseParams.filter = input.getValue();
                        this.store.load();
                    }
                }.bind(this)
            }
        });

        this.pagingtoolbar = new Ext.PagingToolbar({
            pageSize: 20,
            store: this.store,
            displayInfo: true,
            displayMsg: '{0} - {1} / {2}',
            emptyMsg: t("no_objects_found")
        });

        // add per-page selection
        this.pagingtoolbar.add("-");

        this.pagingtoolbar.add(new Ext.Toolbar.TextItem({
            text: t("items_per_page")
        }));
        this.pagingtoolbar.add(new Ext.form.ComboBox({
            store: [
                [20, "20"],
                [40, "40"],
                [60, "60"],
                [80, "80"],
                [100, "100"]
            ],
            mode: "local",
            width: 50,
            value: 20,
            triggerAction: "all",
            listeners: {
                select: function (box, rec, index) {
                    this.pagingtoolbar.pageSize = intval(rec.data.field1);
                    this.pagingtoolbar.moveFirst();
                }.bind(this)
            }
        }));

        this.grid = new Ext.grid.GridPanel({
            frame: false,
            autoScroll: true,
            store: this.store,
            columns : typesColumns,
            autoExpandColumn: "path",
            trackMouseOver: true,
            bbar: this.pagingtoolbar,
            columnLines: true,
            stripeRows: true,
            viewConfig: {
                forceFit: true
            },
            tbar: [{
                text: t("refresh"),
                iconCls: "pimcore_icon_reload",
                handler: this.reload.bind(this)
            }, "-",{
                text: t('flush'),
                handler: function () {
                    Ext.Ajax.request({
                        url: "/admin/misc/http-error-log-flush",
                        success: function () {
                            this.store.reload();
                            this.grid.getView().refresh();
                        }.bind(this)
                    });
                }.bind(this),
                iconCls: "pimcore_icon_flush_recyclebin"
            }, "-", {
                text: t("errors_from_the_last_14_days"),
                xtype: "tbtext"
            }, '-',"->",{
              text: t("filter") + "/" + t("search"),
              xtype: "tbtext",
              style: "margin: 0 10px 0 0;"
            },
            this.filterField]
        });

        return this.grid;
    },

    reload: function () {
        this.store.reload();
    }
});<commit_msg>added open link in new window in http error log<commit_after>/**
 * Pimcore
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.pimcore.org/license
 *
 * @copyright  Copyright (c) 2009-2010 elements.at New Media Solutions GmbH (http://www.elements.at)
 * @license    http://www.pimcore.org/license     New BSD License
 */

pimcore.registerNS("pimcore.settings.httpErrorLog");
pimcore.settings.httpErrorLog = Class.create({

    initialize: function(id) {
        this.getTabPanel();
    },

    activate: function () {
        var tabPanel = Ext.getCmp("pimcore_panel_tabs");
        tabPanel.activate("pimcore_http_error_log");
    },

    getTabPanel: function () {

        if (!this.panel) {
            this.panel = new Ext.Panel({
                id: "pimcore_http_error_log",
                title: t("http_errors"),
                iconCls: "pimcore_icon_httperrorlog",
                border: false,
                layout: "fit",
                closable:true,
                items: [this.getGrid()]
            });

            var tabPanel = Ext.getCmp("pimcore_panel_tabs");
            tabPanel.add(this.panel);
            tabPanel.activate("pimcore_http_error_log");

            this.panel.on("destroy", function () {
                pimcore.globalmanager.remove("http_error_log");
            }.bind(this));

            pimcore.layout.refresh();
        }

        return this.panel;
    },

    getGrid: function () {

        this.store = new Ext.data.JsonStore({
            url: '/admin/misc/http-error-log',
            restful: false,
            root: "items",
            remoteSort: true,
            fields: ["id","path", "code", "date","amount"],
            baseParams: {
                limit: 20,
                filter: ""
            }
        });
        this.store.load();

        var typesColumns = [
            {header: "ID", width: 50, sortable: true, hidden: true, dataIndex: 'id'},
            {header: "Code", width: 60, sortable: true, dataIndex: 'code'},
            {header: t("path"), id: "path", width: 400, sortable: true, dataIndex: 'path'},
            {header: t("amount"), width: 60, sortable: true, dataIndex: 'amount'},
            {header: t("date"), id: "extension_description", width: 200, sortable: true, dataIndex: 'date', renderer: function(d) {
                var date = new Date(d * 1000);
                return date.format("Y-m-d H:i:s");
            }},
            {
                xtype: 'actioncolumn',
                width: 30,
                items: [{
                    tooltip: t('open'),
                    icon: "/pimcore/static/img/icon/world_go.png",
                    handler: function (grid, rowIndex) {
                        var data = grid.getStore().getAt(rowIndex);
                        window.open(data.get("path"));
                    }.bind(this)
                }]
            }
        ];

        this.filterField = new Ext.form.TextField({
            xtype: "textfield",
            width: 200,
            style: "margin: 0 10px 0 0;",
            enableKeyEvents: true,
            listeners: {
                "keydown" : function (field, key) {
                    if (key.getKey() == key.ENTER) {
                        var input = field;
                        this.store.baseParams.filter = input.getValue();
                        this.store.load();
                    }
                }.bind(this)
            }
        });

        this.pagingtoolbar = new Ext.PagingToolbar({
            pageSize: 20,
            store: this.store,
            displayInfo: true,
            displayMsg: '{0} - {1} / {2}',
            emptyMsg: t("no_objects_found")
        });

        // add per-page selection
        this.pagingtoolbar.add("-");

        this.pagingtoolbar.add(new Ext.Toolbar.TextItem({
            text: t("items_per_page")
        }));
        this.pagingtoolbar.add(new Ext.form.ComboBox({
            store: [
                [20, "20"],
                [40, "40"],
                [60, "60"],
                [80, "80"],
                [100, "100"]
            ],
            mode: "local",
            width: 50,
            value: 20,
            triggerAction: "all",
            listeners: {
                select: function (box, rec, index) {
                    this.pagingtoolbar.pageSize = intval(rec.data.field1);
                    this.pagingtoolbar.moveFirst();
                }.bind(this)
            }
        }));

        this.grid = new Ext.grid.GridPanel({
            frame: false,
            autoScroll: true,
            store: this.store,
            columns : typesColumns,
            autoExpandColumn: "path",
            trackMouseOver: true,
            bbar: this.pagingtoolbar,
            columnLines: true,
            stripeRows: true,
            viewConfig: {
                forceFit: true
            },
            tbar: [{
                text: t("refresh"),
                iconCls: "pimcore_icon_reload",
                handler: this.reload.bind(this)
            }, "-",{
                text: t('flush'),
                handler: function () {
                    Ext.Ajax.request({
                        url: "/admin/misc/http-error-log-flush",
                        success: function () {
                            this.store.reload();
                            this.grid.getView().refresh();
                        }.bind(this)
                    });
                }.bind(this),
                iconCls: "pimcore_icon_flush_recyclebin"
            }, "-", {
                text: t("errors_from_the_last_14_days"),
                xtype: "tbtext"
            }, '-',"->",{
              text: t("filter") + "/" + t("search"),
              xtype: "tbtext",
              style: "margin: 0 10px 0 0;"
            },
            this.filterField]
        });

        return this.grid;
    },

    reload: function () {
        this.store.reload();
    }
});<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import autobind from 'core-decorators/es/autobind';
import { graphql } from 'react-apollo';
import { Spinner, NonIdealState, Button, Intent } from '@blueprintjs/core';
import { getTeamResponses } from '../../../../graphql/response';
import NotificationToaster from '../../../components/NotificationToaster';
import ResponseUpload from './ResponseUpload';
import ResponsePhrase from './ResponsePhrase';

const QueryGetTeamResponsesParams = 'responseType responseValue uploadDate uploadedBy checked responseValid pointsAwarded comment retry';

const QueryGetTeamResponsesOptions = {
	name: 'QueryGetTeamResponses',
	options: ({challengeKey, itemKey}) => {
		return {
			fetchPolicy: 'cache-and-network',
			variables: {challengeKey, itemKey}
		}
	}
};

@graphql(getTeamResponses(QueryGetTeamResponsesParams), QueryGetTeamResponsesOptions)
@autobind
class ChallengeResponse extends React.Component {
	static propTypes = {
		itemKey: PropTypes.string.isRequired,
		challengeKey: PropTypes.string.isRequired,
		responseType: PropTypes.oneOf([
			'upload', 'phrase'
		]).isRequired
	}

	async refetch() {
		try {
			await this.props.QueryGetTeamResponses.refetch();
		}
		catch (err) {
			NotificationToaster.show({
				intent: Intent.DANGER,
				message: err.toString()
			});
		}
	}

	render() {
		const { itemKey, challengeKey, responseType } = this.props;
		const { loading, getTeamResponses } = this.props.QueryGetTeamResponses;
		let classNames, title, text, canRespond, comment;
		let response, helpPhrase;

		// Create response element
		switch (responseType) {
			case 'upload': {
				helpPhrase = 'This item requires you to upload an image for us to verify.';
				response = <ResponseUpload itemKey={itemKey} challengeKey={challengeKey} onSuccess={this.refetch}/>;
				break;
			}
			case 'phrase': {
				helpPhrase = 'This item requires you enter a phrase for us to verify.';
				response = <ResponsePhrase itemKey={itemKey} challengeKey={challengeKey} onSuccess={this.refetch}/>;
				break;
			}
		}

		if (!getTeamResponses) {
			if (loading) {
				// Query loading
				return (

						<NonIdealState visual={<Spinner/>}/>

				);
			}
		}
		else if (!getTeamResponses.length) {
			// No responses yet
			classNames = 'pt-callout pt-icon-error';
			title = 'Incomplete';
			text = `${helpPhrase} Your team has not given a response yet.`;
			canRespond = true;
		}
		else {
			// Responses found
			const latestResponse = getTeamResponses[0];

			if (latestResponse.checked) {
				comment = latestResponse.comment;
				if (latestResponse.responseValid) {
					// Response valid
					classNames = 'pt-callout pt-intent-success pt-icon-endorsed';
					title = 'Correct';
					text = `Well done! You team was awarded ${latestResponse.pointsAwarded} ${latestResponse.pointsAwarded===1?'point':'points'} for your efforts.`;
				}
				else {
					// Response invalid
					classNames = `pt-callout pt-icon-delete pt-intent-danger`;
					title = 'Incorrect';
					text = `Sorry, your team's response was not accepted. You ${latestResponse.retry?'may':'may not'} try again.`;
					canRespond = latestResponse.retry;
				}
			}
			else {
				// Response pending
				classNames = 'pt-callout pt-intent-warning pt-icon-time';
				title = 'Pending';
				text = `Your team's response is being verified. Check back in a few minutes!`;
			}
		}

		return (

					<Button iconName='refresh' loading={this.props.QueryGetTeamResponses.loading} className='pt-minimal'
						style={{float:'right',margin:'-0.6rem',padding:'0'}} onClick={this.refetch}/>

{title}

					{text}
					{canRespond?response:null}
					{comment?

							{comment}

						: null }

		);
	}
}

export default ChallengeResponse;
<commit_msg>[FIX] Improve wording on ChallengeResponse component<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import autobind from 'core-decorators/es/autobind';
import { graphql } from 'react-apollo';
import { Spinner, NonIdealState, Button, Intent } from '@blueprintjs/core';
import { getTeamResponses } from '../../../../graphql/response';
import NotificationToaster from '../../../components/NotificationToaster';
import ResponseUpload from './ResponseUpload';
import ResponsePhrase from './ResponsePhrase';

const QueryGetTeamResponsesParams = 'responseType responseValue uploadDate uploadedBy checked responseValid pointsAwarded comment retry';

const QueryGetTeamResponsesOptions = {
	name: 'QueryGetTeamResponses',
	options: ({challengeKey, itemKey}) => {
		return {
			fetchPolicy: 'cache-and-network',
			variables: {challengeKey, itemKey}
		}
	}
};

@graphql(getTeamResponses(QueryGetTeamResponsesParams), QueryGetTeamResponsesOptions)
@autobind
class ChallengeResponse extends React.Component {
	static propTypes = {
		itemKey: PropTypes.string.isRequired,
		challengeKey: PropTypes.string.isRequired,
		responseType: PropTypes.oneOf([
			'upload', 'phrase'
		]).isRequired
	}

	async refetch() {
		try {
			await this.props.QueryGetTeamResponses.refetch();
		}
		catch (err) {
			NotificationToaster.show({
				intent: Intent.DANGER,
				message: err.toString()
			});
		}
	}

	render() {
		const { itemKey, challengeKey, responseType } = this.props;
		const { loading, getTeamResponses } = this.props.QueryGetTeamResponses;
		let classNames, title, text, canRespond, comment;
		let response, helpPhrase;

		// Create response element
		switch (responseType) {
			case 'upload': {
				helpPhrase = 'This item requires you to upload an image for us to review.';
				response = <ResponseUpload itemKey={itemKey} challengeKey={challengeKey} onSuccess={this.refetch}/>;
				break;
			}
			case 'phrase': {
				helpPhrase = 'This item requires you enter a phrase for us to review.';
				response = <ResponsePhrase itemKey={itemKey} challengeKey={challengeKey} onSuccess={this.refetch}/>;
				break;
			}
		}

		if (!getTeamResponses) {
			if (loading) {
				// Query loading
				return (

						<NonIdealState visual={<Spinner/>}/>

				);
			}
		}
		else if (!getTeamResponses.length) {
			// No responses yet
			classNames = 'pt-callout pt-icon-error';
			title = 'Incomplete';
			text = `${helpPhrase} Your team has not given a response yet.`;
			canRespond = true;
		}
		else {
			// Responses found
			const latestResponse = getTeamResponses[0];

			if (latestResponse.checked) {
				comment = latestResponse.comment;
				if (latestResponse.responseValid) {
					// Response valid
					classNames = 'pt-callout pt-intent-success pt-icon-tick-circle';
					title = 'Accepted';
					text = `You team was awarded ${latestResponse.pointsAwarded} ${latestResponse.pointsAwarded===1?'point':'points'} for your efforts.`;
				}
				else {
					// Response invalid
					classNames = `pt-callout pt-icon-delete pt-intent-danger`;
					title = 'Incorrect';
					text = `Sorry, your team's response was not accepted. You ${latestResponse.retry?'may':'may not'} try again.`;
					canRespond = latestResponse.retry;
				}
			}
			else {
				// Response pending
				classNames = 'pt-callout pt-intent-warning pt-icon-time';
				title = 'Pending';
				text = `Your team's response is being reviewed. Check back in a few minutes!`;
			}
		}

		return (

					<Button iconName='refresh' loading={this.props.QueryGetTeamResponses.loading} className='pt-minimal'
						style={{float:'right',margin:'-0.6rem',padding:'0'}} onClick={this.refetch}/>

{title}

					{text}
					{canRespond?response:null}
					{comment?

							{comment}

						: null }

		);
	}
}

export default ChallengeResponse;
<|endoftext|>


<commit_before>/*
Copyright 2015 OpenMarket Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

'use strict';

var React = require('react');
var Modal = require('matrix-react-sdk/lib/Modal');
var sdk = require('matrix-react-sdk')

var ServerConfigController = require('matrix-react-sdk/lib/controllers/molecules/ServerConfig')

module.exports = React.createClass({
    displayName: 'ServerConfig',
    mixins: [ServerConfigController],

    showHelpPopup: function() {
        var ErrorDialog = sdk.getComponent('organisms.ErrorDialog');
        Modal.createDialog(ErrorDialog, {
          title: 'Custom Server Options',
          description: "You can use the custom server options to log into other Matrix servers by specifying a different Home server URL. This allows you to use Vector with an existing Matrix account on a different Home server. You can also set a cutom Identity server but this will affect people ability to find you if you use a server in a group other than tha main Matrix.org group.",
          button: "Dismiss",
          focus: true
        });
    },

    render: function() {
        return (

                Home server URL
                <input className="mx_Login_field" id="hsurl" type="text" value={this.state.hs_url} onChange={this.hsChanged} />
                Identity server URL
                <input className="mx_Login_field" type="text" value={this.state.is_url} onChange={this.isChanged} />
                What does this mean?

        );
    }
});
<commit_msg>fix raging typos<commit_after>/*
Copyright 2015 OpenMarket Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

'use strict';

var React = require('react');
var Modal = require('matrix-react-sdk/lib/Modal');
var sdk = require('matrix-react-sdk')

var ServerConfigController = require('matrix-react-sdk/lib/controllers/molecules/ServerConfig')

module.exports = React.createClass({
    displayName: 'ServerConfig',
    mixins: [ServerConfigController],

    showHelpPopup: function() {
        var ErrorDialog = sdk.getComponent('organisms.ErrorDialog');
        Modal.createDialog(ErrorDialog, {
          title: 'Custom Server Options',
          description: "You can use the custom server options to log into other Matrix servers by specifying a different Home server URL. " +
                       "This allows you to use Vector with an existing Matrix account on a different Home server. " +
                       "You can also set a custom Identity server but this will affect people's ability to find you " +
                       "if you use a server in a group other than the main Matrix.org group.",
          button: "Dismiss",
          focus: true
        });
    },

    render: function() {
        return (

                Home server URL
                <input className="mx_Login_field" id="hsurl" type="text" value={this.state.hs_url} onChange={this.hsChanged} />
                Identity server URL
                <input className="mx_Login_field" type="text" value={this.state.is_url} onChange={this.isChanged} />
                What does this mean?

        );
    }
});
<|endoftext|>


<commit_before>import inflect from 'i';
import numeral from 'numeral';
import FormattedNumber from '../types/formatted_number';
import { GraphQLString } from 'graphql';

const { pluralize } = inflect();

export default fn => ({
  type: FormattedNumber,
  args: {
    format: {
      type: GraphQLString,
      description: 'Returns a `String` when format is specified. e.g.`"0,0.0000"`',
    },
    label: {
      type: GraphQLString,
    },
  },
  resolve: (obj, { format, label }, { fieldName }) => {
    let value = fn ? fn(obj) : obj[fieldName];

    if (!value) return null;

    if (!!format) {
      value = numeral(value).format(format);
    }

    if (!!label) {
      value = `${value} ${pluralize(label)}`;
    }

    return value;
  },
});
<commit_msg>Handle label if plural or singular<commit_after>import inflect from 'i';
import numeral from 'numeral';
import FormattedNumber from '../types/formatted_number';
import { GraphQLString } from 'graphql';

const { pluralize, singularize } = inflect();

export default fn => ({
  type: FormattedNumber,
  args: {
    format: {
      type: GraphQLString,
      description: 'Returns a `String` when format is specified. e.g.`"0,0.0000"`',
    },
    label: {
      type: GraphQLString,
    },
  },
  resolve: (obj, { format, label }, { fieldName }) => {
    let value = fn ? fn(obj) : obj[fieldName];

    if (!value) return null;

    const count = value;

    if (!!format) {
      value = numeral(value).format(format);
    }

    if (!!label) {
      value = `${value} ${count === 1 ? singularize(label) : pluralize(label)}`;
    }

    return value;
  },
});
<|endoftext|>


<commit_before>var map = new maptalks.Map('map', {
  center:     [-0.113049,51.498568],
  zoom:  6,
  pitch : 40,
  attribution: {
    content: '$(attribution), © BoudlessGeo'
  },
  // add 2 TileLayers with a GroupTileLayer
  baseLayer : new maptalks.GroupTileLayer('base', [
    new maptalks.TileLayer('tile2', {
      urlTemplate: 'http://{s}.basemaps.cartocdn.com/dark_only_labels/{z}/{x}/{y}.png',
      subdomains  : ['a','b','c','d']
    }),

    new maptalks.WMSTileLayer('wms', {
      'urlTemplate' : 'https://demo.boundlessgeo.com/geoserver/ows',
      'crs' : 'EPSG:3857',
      'layers' : 'ne:ne',
      'styles' : '',
      'version' : '1.3.0',
      'format': 'image/png',
      'transparent' : true,
      'uppercase' : true
    })
  ])
});
<commit_msg>fix grouptilelayer<commit_after>var map = new maptalks.Map('map', {
  center:     [-0.113049,51.498568],
  zoom:  6,
  pitch : 40,
  attribution: {
    content: '$(attribution), © BoudlessGeo'
  },
  // add 2 TileLayers with a GroupTileLayer
  baseLayer : new maptalks.GroupTileLayer('base', [
    new maptalks.TileLayer('tile2', {
      urlTemplate: 'http://{s}.basemaps.cartocdn.com/dark_nolabels/{z}/{x}/{y}.png',
      subdomains  : ['a','b','c','d']
    }),

    new maptalks.WMSTileLayer('wms', {
      'urlTemplate' : 'https://demo.boundlessgeo.com/geoserver/ows',
      'crs' : 'EPSG:3857',
      'layers' : 'ne:ne',
      'styles' : '',
      'version' : '1.3.0',
      'format': 'image/png',
      'transparent' : true,
      'uppercase' : true
    })
  ])
});
<|endoftext|>


<commit_before>/* @flow */

import React, { PropTypes, Component } from 'react';
import ReactNative from 'react-native';
import shallowEqual from 'shallowequal';
import Card from './Card';
import CardTitle from './CardTitle';
import DiscussionSummary from './DiscussionSummary';
import CardAuthor from './CardAuthor';

const {
	StyleSheet,
} = ReactNative;

const styles = StyleSheet.create({
	details: {
		paddingVertical: 12,
		marginVertical: 0,
	},

	title: {
		marginBottom: 8,
		marginHorizontal: 16,
	},

	author: {
		marginTop: 8,
		marginHorizontal: 16,
	},
});

type Props = {
	thread: {
		name: string;
		body: string;
		creator: string;
		meta?: Object;
	}
}

export default class DiscussionDetailsCard extends Component<void, Props, void> {
	static propTypes = {
		thread: PropTypes.shape({
			name: PropTypes.string.isRequired,
			body: PropTypes.string.isRequired,
			meta: PropTypes.string.isRequired,
			creator: PropTypes.string.isRequired,
		}),
	};

	shouldComponentUpdate(nextProps: Props): boolean {
		return !shallowEqual(this.props, nextProps);
	}

	render() {
		const { thread } = this.props;

		return (
			<Card style={styles.details}>
				<CardTitle style={styles.title}>{thread.name}</CardTitle>
				<DiscussionSummary text={thread.body} meta={thread.meta} />
				<CardAuthor nick={thread.creator} style={styles.author} />
			</Card>
		);
	}
}
<commit_msg>fix(ui): fix incorrect propType in DiscussionDetailsCard<commit_after>/* @flow */

import React, { PropTypes, Component } from 'react';
import ReactNative from 'react-native';
import shallowEqual from 'shallowequal';
import Card from './Card';
import CardTitle from './CardTitle';
import DiscussionSummary from './DiscussionSummary';
import CardAuthor from './CardAuthor';

const {
	StyleSheet,
} = ReactNative;

const styles = StyleSheet.create({
	details: {
		paddingVertical: 12,
		marginVertical: 0,
	},

	title: {
		marginBottom: 8,
		marginHorizontal: 16,
	},

	author: {
		marginTop: 8,
		marginHorizontal: 16,
	},
});

type Props = {
	thread: {
		name: string;
		body: string;
		creator: string;
		meta?: Object;
	}
}

export default class DiscussionDetailsCard extends Component<void, Props, void> {
	static propTypes = {
		thread: PropTypes.shape({
			name: PropTypes.string.isRequired,
			body: PropTypes.string.isRequired,
			meta: PropTypes.object,
			creator: PropTypes.string.isRequired,
		}),
	};

	shouldComponentUpdate(nextProps: Props): boolean {
		return !shallowEqual(this.props, nextProps);
	}

	render() {
		const { thread } = this.props;

		return (
			<Card style={styles.details}>
				<CardTitle style={styles.title}>{thread.name}</CardTitle>
				<DiscussionSummary text={thread.body} meta={thread.meta} />
				<CardAuthor nick={thread.creator} style={styles.author} />
			</Card>
		);
	}
}
<|endoftext|>


<commit_before>/*==================================================
 *  Exhibit.SliderFacet
 *==================================================
 */

Exhibit.SliderFacet = function(containerElmt, uiContext) {
    this._div = containerElmt;
    this._uiContext = uiContext;

    this._expression = null;
    this._settings = {};

    this._range = {min: null, max: null}; //currently selected range
    this._maxRange = {min: null, max: null}; //total range of slider
};

Exhibit.SliderFacet._settingsSpecs = {
    "facetLabel":       { type: "text" },
    "scroll":           { type: "boolean", defaultValue: true },
    "height":           { type: "text" },
    "precision":        { type: "float", defaultValue: 1 },
    "histogram":        { type: "boolean", defaultValue: true },
    "horizontal":	{ type: "boolean", defaultValue: true }
};

Exhibit.SliderFacet.create = function(configuration, containerElmt, uiContext) {
    var uiContext = Exhibit.UIContext.create(configuration, uiContext);
    var facet = new Exhibit.SliderFacet(containerElmt, uiContext);

    Exhibit.SliderFacet._configure(facet, configuration);

    facet._initializeUI();
    uiContext.getCollection().addFacet(facet);

    return facet;
};

Exhibit.SliderFacet.createFromDOM = function(configElmt, containerElmt, uiContext) {
    var configuration = Exhibit.getConfigurationFromDOM(configElmt);
    var uiContext = Exhibit.UIContext.createFromDOM(configElmt, uiContext);
    var facet = new Exhibit.SliderFacet(
	containerElmt != null? containerElmt : configElmt,
	uiContext
    );

    Exhibit.SettingsUtilities.collectSettingsFromDOM(configElmt, Exhibit.SliderFacet._settingsSpecs, facet._settings);

    try {
        var expressionString = Exhibit.getAttribute(configElmt, "expression");
        if (expressionString != null && expressionString.length > 0) {
            facet._expression = Exhibit.ExpressionParser.parse(expressionString);
        }
    } catch (e) {
        SimileAjax.Debug.exception(e, "SliderFacet: Error processing configuration of slider facet");
    }

    Exhibit.SliderFacet._configure(facet, configuration);
    facet._initializeUI();
    uiContext.getCollection().addFacet(facet);

    return facet;
};

Exhibit.SliderFacet._configure = function(facet, configuration) {
    Exhibit.SettingsUtilities.collectSettings(configuration, Exhibit.SliderFacet._settingsSpecs, facet._settings);

    if ("expression" in configuration) {
		facet._expression = Exhibit.ExpressionParser.parse(configuration.expression);
    }

    if (!("facetLabel" in facet._settings)) {
		facet._settings.facetLabel = "missing ex:facetLabel";
		if (facet._expression != null && facet._expression.isPath()) {
		    var segment = facet._expression.getPath().getLastSegment();
		    var property = facet._uiContext.getDatabase().getProperty(segment.property);
		    if (property != null) {
				facet._settings.facetLabel = segment.forward ? property.getLabel() : property.getReverseLabel();
		    }
		}
    }

    facet._maxRange = facet._getMaxRange();
};

Exhibit.SliderFacet.prototype._initializeUI = function() {
    this._dom = SimileAjax.DOM.createDOMFromString(
       this._div,
       "
" +
           "" + this._settings.facetLabel + "" +
       "
" +
       "

"
    );

    this._slider = new Exhibit.SliderFacet.slider(this._dom.slider, this, this._settings.precision, this._settings.horizontal);
};

Exhibit.SliderFacet.prototype.hasRestrictions = function() {
    return (this._range.min && this._range.min != this._maxRange.min) || (this._range.max && this._range.max != this._maxRange.max);
};

Exhibit.SliderFacet.prototype.update = function(items) {
    if (this._settings.histogram) {
		var data = [];
		var n = 75; //number of bars on histogram
		var range = (this._maxRange.max - this._maxRange.min)/n //range represented by each bar

		var database = this._uiContext.getDatabase();
		var path = this._expression.getPath();

		for(var i=0; i<n; i++) {
		    data[i] = path.rangeBackward(this._maxRange.min+i*range, this._maxRange.min+(i+1)*range, items, database).values.size();
		}

		this._slider.updateHistogram(data);
    }
};

Exhibit.SliderFacet.prototype.restrict = function(items) {
    if (!this.hasRestrictions()) {
	return items;
    }
    var path = this._expression.getPath();
    var database = this._uiContext.getDatabase();
    return path.rangeBackward(this._range.min, this._range.max, items, database).values;
};

Exhibit.SliderFacet.prototype._getMaxRange = function() {
    var path = this._expression.getPath();
    var database = this._uiContext.getDatabase();
    var propertyID = path.getLastSegment().property;
    var property = database.getProperty(propertyID);
    var rangeIndex = property.getRangeIndex();

    return {min: rangeIndex.getMin(), max: rangeIndex.getMax()};
};

Exhibit.SliderFacet.prototype.changeRange = function(range) {
    this._range = range;
    this._notifyCollection();
};

Exhibit.SliderFacet.prototype._notifyCollection = function() {
    this._uiContext.getCollection().onFacetUpdated(this);
};

Exhibit.SliderFacet.prototype.clearAllRestrictions = function() {
    this._slider.resetSliders();
    this._range = this._maxRange;
};

Exhibit.SliderFacet.prototype.dispose = function() {
    this._uiContext.getCollection().removeFacet(this);
    this._uiContext = null;
    this._colorCoder = null;

    this._div.innerHTML = "";
    this._div = null;
    this._dom = null;

    this._expression = null;
    this._settings = null;

    this._range = null; //currently selected range
    this._maxRange = null; //total range of slider
};<commit_msg>allow preconfigure slider range<commit_after>/*==================================================
 *  Exhibit.SliderFacet
 *==================================================
 */

Exhibit.SliderFacet = function(containerElmt, uiContext) {
    this._div = containerElmt;
    this._uiContext = uiContext;

    this._expression = null;
    this._settings = {};

	this._selection = {min: null, max: null};
    this._range = {min: null, max: null}; //currently selected range
    this._maxRange = {min: null, max: null}; //total range of slider
};

Exhibit.SliderFacet._settingsSpecs = {
    "facetLabel":       { type: "text" },
    "scroll":           { type: "boolean", defaultValue: true },
    "height":           { type: "text" },
    "precision":        { type: "float", defaultValue: 1 },
    "histogram":        { type: "boolean", defaultValue: true },
    "horizontal":	{ type: "boolean", defaultValue: false }
};

Exhibit.SliderFacet.create = function(configuration, containerElmt, uiContext) {
    var uiContext = Exhibit.UIContext.create(configuration, uiContext);
    var facet = new Exhibit.SliderFacet(containerElmt, uiContext);

    Exhibit.SliderFacet._configure(facet, configuration);

    facet._initializeUI();
    uiContext.getCollection().addFacet(facet);

    return facet;
};

Exhibit.SliderFacet.createFromDOM = function(configElmt, containerElmt, uiContext) {
    var configuration = Exhibit.getConfigurationFromDOM(configElmt);
    var uiContext = Exhibit.UIContext.createFromDOM(configElmt, uiContext);
    var facet = new Exhibit.SliderFacet(
	containerElmt != null? containerElmt : configElmt,
	uiContext
    );

    Exhibit.SettingsUtilities.collectSettingsFromDOM(configElmt, Exhibit.SliderFacet._settingsSpecs, facet._settings);

    try {
        var expressionString = Exhibit.getAttribute(configElmt, "expression");
        if (expressionString != null && expressionString.length > 0) {
            facet._expression = Exhibit.ExpressionParser.parse(expressionString);
        }
    } catch (e) {
        SimileAjax.Debug.exception(e, "SliderFacet: Error processing configuration of slider facet");
    }

    Exhibit.SliderFacet._configure(facet, configuration);
    facet._initializeUI();
    uiContext.getCollection().addFacet(facet);

    return facet;
};

Exhibit.SliderFacet._configure = function(facet, configuration) {
    Exhibit.SettingsUtilities.collectSettings(configuration, Exhibit.SliderFacet._settingsSpecs, facet._settings);

    if ("expression" in configuration) {
		facet._expression = Exhibit.ExpressionParser.parse(configuration.expression);
    }
    if ("selection" in configuration) {
        var selection = configuration.selection;
        facet._selection = {min: selection[0], max: selection[1]};
    }

    if (!("facetLabel" in facet._settings)) {
		facet._settings.facetLabel = "missing ex:facetLabel";
		if (facet._expression != null && facet._expression.isPath()) {
		    var segment = facet._expression.getPath().getLastSegment();
		    var property = facet._uiContext.getDatabase().getProperty(segment.property);
		    if (property != null) {
				facet._settings.facetLabel = segment.forward ? property.getLabel() : property.getReverseLabel();
		    }
		}
    }

    facet._maxRange = facet._getMaxRange();
};

Exhibit.SliderFacet.prototype._initializeUI = function() {
    this._dom = SimileAjax.DOM.createDOMFromString(
       this._div,
       "
" +
           "" + this._settings.facetLabel + "" +
       "
" +
       "

"
    );

    this._slider = new Exhibit.SliderFacet.slider(this._dom.slider, this, this._settings.precision, this._settings.horizontal);
};

Exhibit.SliderFacet.prototype.hasRestrictions = function() {
    return (this._range.min && this._range.min != this._maxRange.min) || (this._range.max && this._range.max != this._maxRange.max);
};

Exhibit.SliderFacet.prototype.update = function(items) {
    if (this._settings.histogram) {
		var data = [];
		var n = 75; //number of bars on histogram
		var range = (this._maxRange.max - this._maxRange.min)/n //range represented by each bar

		var database = this._uiContext.getDatabase();
		var path = this._expression.getPath();

		for(var i=0; i<n; i++) {
		    data[i] = path.rangeBackward(this._maxRange.min+i*range, this._maxRange.min+(i+1)*range, items, database).values.size();
		}

		this._slider.updateHistogram(data);
    }
};

Exhibit.SliderFacet.prototype.restrict = function(items) {
    /*if (!this.hasRestrictions()) {
	return items;
    }*/
    var path = this._expression.getPath();
    var database = this._uiContext.getDatabase();
    return path.rangeBackward(this._range.min, this._range.max, items, database).values;
};

Exhibit.SliderFacet.prototype._getMaxRange = function() {
    var path = this._expression.getPath();
    var database = this._uiContext.getDatabase();
    var propertyID = path.getLastSegment().property;
    var property = database.getProperty(propertyID);
    var rangeIndex = property.getRangeIndex();

    return {min: rangeIndex.getMin(), max: rangeIndex.getMax()};
};

Exhibit.SliderFacet.prototype.changeRange = function(range) {
    this._range = range;
    this._notifyCollection();
};

Exhibit.SliderFacet.prototype._notifyCollection = function() {
    this._uiContext.getCollection().onFacetUpdated(this);
};

Exhibit.SliderFacet.prototype.clearAllRestrictions = function() {
    this._slider.resetSliders();
    this._range = this._maxRange;
};

Exhibit.SliderFacet.prototype.dispose = function() {
    this._uiContext.getCollection().removeFacet(this);
    this._uiContext = null;
    this._colorCoder = null;

    this._div.innerHTML = "";
    this._div = null;
    this._dom = null;

    this._expression = null;
    this._settings = null;

    this._range = null; //currently selected range
    this._maxRange = null; //total range of slider
};<|endoftext|>


<commit_before>/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, brackets: true */

define(function (require, exports, module) {
    "use strict";

    var CommandManager = brackets.getModule("command/CommandManager");
    var EditorManager  = brackets.getModule("editor/EditorManager");
// todo - needed?
//    var Editor               = brackets.getModule("editor/Editor").Editor;
    var Commands       = brackets.getModule("command/Commands");
    var HTMLRewriter   = brackets.getModule("filesystem/impls/filer/lib/HTMLRewriter");
    var SidebarView    = brackets.getModule("project/SidebarView");
    var StatusBar      = brackets.getModule("widgets/StatusBar");
    var WorkspaceManager = brackets.getModule("view/WorkspaceManager");

    var PostMessageTransport = require("lib/PostMessageTransport");
    var Theme = require("lib/Theme");
    var UI = require("lib/UI");

    // Built-in Brackets Commands
    function _bracketsCommand(command) {
        function executeCommand() {
            CommandManager.execute(Commands[command]);
        }

        // Make sure the last-focused editor gets focus before executing
        var editor = EditorManager.getActiveEditor();
        if (editor && !editor.hasFocus()) {
            editor.one("focus", executeCommand);
            editor.focus();
        } else {
            executeCommand();
        }
    }

    // Custom Bramble commands
    function _brambleCommand(command) {
        switch(command) {
        case "BRAMBLE_RELOAD":
            PostMessageTransport.reload();
            break;
        case "BRAMBLE_MOBILE_PREVIEW":
            UI.showMobileView();
            break;
        case "BRAMBLE_DESKTOP_PREVIEW":
            UI.showDesktopView();
            break;
        case "BRAMBLE_ENABLE_SCRIPTS":
            HTMLRewriter.enableScripts();
            PostMessageTransport.reload();
            break;
        case "BRAMBLE_DISABLE_SCRIPTS":
            HTMLRewriter.disableScripts();
            PostMessageTransport.reload();
            break;
        case "BRAMBLE_LIGHT_THEME":
            Theme.setTheme("light-theme");
            break;
        case "BRAMBLE_DARK_THEME":
            Theme.setTheme("dark-theme");
            break;
        case "BRAMBLE_SHOW_SIDEBAR":
            SidebarView.show();
            break;
        case "BRAMBLE_HIDE_SIDEBAR":
            SidebarView.hide();
            break;
        case "BRAMBLE_HIDE_STATUSBAR":
            StatusBar.disable();
            break;
        case "BRAMBLE_SHOW_STATUSBAR":
            StatusBar.enable();
            break;
        case "RESIZE":
            // The host window was resized, update all panes
            WorkspaceManager.recomputeLayout(true);
            break;
        default:
            console.log('[Bramble] unknown command:', command);
            break;
        }
    }

    function handleRequest(e) {
        var remoteRequest;
        try {
            remoteRequest = JSON.parse(e.data);
        } catch(err) {
            console.log('[Bramble] unable to parse remote request:', e.data);
            return;
        }

        if (remoteRequest.type !== "bramble:remoteCommand") {
            return;
        }

        switch(remoteRequest.commandCategory) {
        case "brackets":
            _bracketsCommand(remoteRequest.command);
            break;
// todo - what is this?
//        case "editorCommand":
//  Editor[msgObj.command](msgObj.params);
//            _editorCommand(remoteRequest);
//            break;
        case "bramble":
            _brambleCommand(remoteRequest.command);
            break;
        default:
            console.error('[Bramble] unknown remote command request:', remoteRequest);
            break;
        }
    }

    exports.handleRequest = handleRequest;
});
<commit_msg>Fix #367 - Resize only works when you've first moved the divider<commit_after>/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, brackets: true */

define(function (require, exports, module) {
    "use strict";

    var CommandManager = brackets.getModule("command/CommandManager");
    var EditorManager  = brackets.getModule("editor/EditorManager");
// todo - needed?
//    var Editor               = brackets.getModule("editor/Editor").Editor;
    var Commands       = brackets.getModule("command/Commands");
    var HTMLRewriter   = brackets.getModule("filesystem/impls/filer/lib/HTMLRewriter");
    var SidebarView    = brackets.getModule("project/SidebarView");
    var StatusBar      = brackets.getModule("widgets/StatusBar");
    var WorkspaceManager = brackets.getModule("view/WorkspaceManager");
    var BrambleEvents = brackets.getModule("bramble/BrambleEvents");

    var PostMessageTransport = require("lib/PostMessageTransport");
    var Theme = require("lib/Theme");
    var UI = require("lib/UI");

    // Built-in Brackets Commands
    function _bracketsCommand(command) {
        function executeCommand() {
            CommandManager.execute(Commands[command]);
        }

        // Make sure the last-focused editor gets focus before executing
        var editor = EditorManager.getActiveEditor();
        if (editor && !editor.hasFocus()) {
            editor.one("focus", executeCommand);
            editor.focus();
        } else {
            executeCommand();
        }
    }

    // Custom Bramble commands
    function _brambleCommand(command) {
        switch(command) {
        case "BRAMBLE_RELOAD":
            PostMessageTransport.reload();
            break;
        case "BRAMBLE_MOBILE_PREVIEW":
            UI.showMobileView();
            break;
        case "BRAMBLE_DESKTOP_PREVIEW":
            UI.showDesktopView();
            break;
        case "BRAMBLE_ENABLE_SCRIPTS":
            HTMLRewriter.enableScripts();
            PostMessageTransport.reload();
            break;
        case "BRAMBLE_DISABLE_SCRIPTS":
            HTMLRewriter.disableScripts();
            PostMessageTransport.reload();
            break;
        case "BRAMBLE_LIGHT_THEME":
            Theme.setTheme("light-theme");
            break;
        case "BRAMBLE_DARK_THEME":
            Theme.setTheme("dark-theme");
            break;
        case "BRAMBLE_SHOW_SIDEBAR":
            SidebarView.show();
            break;
        case "BRAMBLE_HIDE_SIDEBAR":
            SidebarView.hide();
            break;
        case "BRAMBLE_HIDE_STATUSBAR":
            StatusBar.disable();
            break;
        case "BRAMBLE_SHOW_STATUSBAR":
            StatusBar.enable();
            break;
        case "RESIZE":
            // The host window was resized, update all panes
            WorkspaceManager.recomputeLayout(true);
            BrambleEvents.triggerUpdateLayoutEnd();
            break;
        default:
            console.log('[Bramble] unknown command:', command);
            break;
        }
    }

    function handleRequest(e) {
        var remoteRequest;
        try {
            remoteRequest = JSON.parse(e.data);
        } catch(err) {
            console.log('[Bramble] unable to parse remote request:', e.data);
            return;
        }

        if (remoteRequest.type !== "bramble:remoteCommand") {
            return;
        }

        switch(remoteRequest.commandCategory) {
        case "brackets":
            _bracketsCommand(remoteRequest.command);
            break;
// todo - what is this?
//        case "editorCommand":
//  Editor[msgObj.command](msgObj.params);
//            _editorCommand(remoteRequest);
//            break;
        case "bramble":
            _brambleCommand(remoteRequest.command);
            break;
        default:
            console.error('[Bramble] unknown remote command request:', remoteRequest);
            break;
        }
    }

    exports.handleRequest = handleRequest;
});
<|endoftext|>