<commit_before>class SearchService {
    constructor($http, configuration) {
        'ngInject';

        this.$http = $http;
        this.configuration = configuration;
    }

    get _() {
        return this.__ || (this.__ = Object.create(null, {}));
    }

    get currentDetailData() {
        return this._.currentDetailData || (this._.currentDetailData = {});
    }

    set currentDetailData(value) {
        this._.currentDetailData = value;
    }

    get currentListData() {
        return this._.currentListData || (this._.currentListData = []);
    }

    set currentListData(value) {
        this._.currentListData = value;
    }

    get helper() {
        return this._.helper || (this._.helper = {
                hasMore: true,
                emptyCurrentDataList: () => this.currentListData.length = 0,
                updateStart: (count) => {
                    if (count) {
                        this.searchParams.start = (parseInt(count) + parseInt(this.requestParams.start()));
                    } else {
                        this.searchParams.start = (parseInt(this.requestParams.count()) + parseInt(this.requestParams.start()));
                    }
                },
                resetStartAndTotal: () => {
                    this.helper.hasMore = true;
                    this.searchParams.total = 0;
                    this.searchParams.start = 0;
                },
                moreRecordsExist: () => ((parseInt(this.searchParams.total) - parseInt(this.requestParams.start())) > 0),
                clearSearchParams: (specificParam) => {
                    if (specificParam === 'location') {
                        this.searchParams.location.length = 0;
                    } else if (specificParam === 'category') {
                        this.searchParams.category.length = 0;
                    } else if (specificParam === 'text') {
                        this.searchParams.textSearch = '';
                    } else {
                        this.searchParams.textSearch = '';
                        this.searchParams.category.length = 0;
                        this.searchParams.location.length = 0;
                    }
                }
            });
    }

    get requestParams() {
        return this._.requestParams || (this._.requestParams = {
                sort: () => this.searchParams.sort || this.configuration.search.sort,
                count: () => this.searchParams.count || this.configuration.search.count,
                start: () => this.searchParams.start || this.configuration.search.start,
                publishedCategory: (isSearch, fields) => {
                    if ('publishedCategory(id,name)' !== fields) {
                        if (this.searchParams.category.length > 0) {
                            var equals = isSearch ? ':' : '=';

                            var fragment = ' AND (';
                            var first = true;

                            for (var i = 0; i < this.searchParams.category.length; i++) {
                                if (!first) {
                                    fragment += ' OR ';
                                } else {
                                    first = false;
                                }

                                fragment += 'publishedCategory.id' + equals + this.searchParams.category[i];
                            }

                            return fragment + ')';
                        }
                    }

                    return '';
                },
                location: (isSearch, fields) => {
                    if ('address(city,state)' !== fields) {
                        if (this.searchParams.location.length > 0) {
                            var delimiter = isSearch ? '"' : '\'';
                            var equals = isSearch ? ':' : '=';

                            var fragment = ' AND (';
                            var first = true;

                            for (var j = 0; j < this.searchParams.location.length; j++) {
                                if (!first) {
                                    fragment += ' OR ';
                                } else {
                                    first = false;
                                }

                                var location = this.searchParams.location[j];

                                var city = location.split('|')[0];
                                var state = location.split('|')[1];

                                fragment += '(address.city' + equals + delimiter + city + delimiter + ' AND address.state' + equals + delimiter + state + delimiter + ')';
                            }

                            return fragment + ')';
                        }
                    }

                    return '';
                },
                text: () => {
                    if (this.searchParams.textSearch) {
                        return ' AND (title:' + this.searchParams.textSearch + '* OR publicDescription:' + this.searchParams.textSearch + '*)';
                    }

                    return '';
                },
                query: (isSearch, additionalQuery, fields) => {
                    var query = '(' + (isSearch ? this.configuration.search.additionalSearchQuery : this.configuration.search.additionalQuery) + ')';

                    if (additionalQuery) {
                        query += ' AND (' + additionalQuery + ')';
                    }

                    if (isSearch) {
                        query += this.requestParams.text();
                    }

                    query += this.requestParams.publishedCategory(isSearch, fields);
                    query += this.requestParams.location(isSearch, fields);

                    return query;
                },
                whereIDs: (jobs, isSearch) => {
                    var getValue = isSearch ? (job) => 'id:' + job.id : (job) => job.id;
                    var join = isSearch ? ' OR ' : ',';
                    var prefix = isSearch ? '' : 'id IN ';

                    var values = [];

                    for (var i = 0; i < jobs.length; i++) {
                        values.push(getValue(jobs[i]));
                    }

                    return prefix + '(' + values.join(join) + ')';
                },
                relatedJobs: (publishedCategoryID, idToExclude) => {
                    var query = '(' + this.configuration.search.additionalQuery + ') AND publishedCategory.id=' + publishedCategoryID;

                    if (idToExclude && parseInt(idToExclude) > 0) {
                        query += ' AND id <>' + idToExclude;
                    }

                    return query;
                },
                find: (jobID) => {
                    return '(' + this.configuration.search.additionalQuery + ') AND id=' + jobID;
                },
                assembleForSearchWhereIDs: (jobs) => {
                    var where = this.requestParams.query(true, this.requestParams.whereIDs(jobs, true));

                    return '?useV2=true&start=0&query=' + where + '&fields=id&count=' + this.configuration.search.count;
                },
                assembleForQueryForIDs: (start, count) => {
                    return '?useV2=true&where=' + this.requestParams.query(false) + '&fields=' + this.configuration.search.fields + '&count=' + count + '&orderBy=' + this.configuration.search.sort + '&start=' + start;
                },
                assembleForGroupByWhereIDs: (fields, orderByFields, start, count, jobs) => {
                    return '?where=' + this.requestParams.whereIDs(jobs, false) + '&groupBy=' + fields + '&fields=' + fields + ',count(id)&count=' + count + '&orderBy=+' + orderByFields + ',-count.id&start=' + start + '&useV2=true';
                },
                assembleForSearchForIDs: (start, count, fields) => {
                    return '?useV2=true&showTotalMatched=true&query=' + this.requestParams.query(true, undefined, fields) + '&fields=id&sort=id&count=' + count + '&start=' + start;
                },
                assembleForRelatedJobs: (publishedCategoryID, idToExclude) => {
                    return '?useV2=true&start=0&where=' + this.requestParams.relatedJobs(publishedCategoryID, idToExclude) + '&fields=' + this.configuration.search.fields + '&sort=' + this.requestParams.sort() + '&count=' + this.configuration.search.maxRelatedJobs;
                },
                assembleForFind: (jobID) => {
                    return '?useV2=true&start=0&count=1&where=' + this.requestParams.find(jobID) + '&fields=' + this.configuration.search.fields;
                }
            });
    }

    get searchParams() {
        return this._.searchParams || (this._.searchParams = {
                textSearch: '',
                location: [],
                category: [],
                sort: '',
                count: '',
                start: '',
                total: '',
                reloadAllData: true
            });
    }

    getCountByLocation(callback, errorCallback) {
        return this.getCountBy('address(city,state)', 'address.city,address.state', callback, errorCallback);
    }

    getCountByCategory(callback, errorCallback) {
        return this.getCountBy('publishedCategory(id,name)', 'publishedCategory.name', callback, errorCallback);
    }

    getCountWhereIDs() {
        this.$http({
            method: 'GET',
            url: this.configuration.search.queryUrl + this.requestParams.assembleForGroupByWhereIDs(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4])
        }).success(data => {
            arguments[5](data);
        }).error(() => {
        });
    }

    recursiveSearchForIDs(callback, start, count, fields) {
        this.$http({
            method: 'GET',
            url: this.configuration.search.searchUrl + this.requestParams.assembleForSearchForIDs(start, count, fields)
        }).success(data => {
            callback(data);
        }).error(() => {
        });
    }

    getCountBy(fields, orderByFields, callback, errorCallback) {
        errorCallback = errorCallback || function () {
            };

        var totalRecords = [];
        var start = 0;

        var controller = this;

        var callbackIfNoMore = (data) => {
            if (data.data.length) {
                controller.getCountWhereIDs(fields, orderByFields, start, controller.configuration.search.batchSize, data.data, (counts) => {
                    totalRecords = totalRecords.concat(counts.data);

                    if (data.total > data.count) {
                        start += controller.configuration.search.batchSize;

                        controller.recursiveSearchForIDs(callbackIfNoMore, start, controller.configuration.search.batchSize);
                    } else {
                        callback(totalRecords);
                    }
                });
            } else {
                callback(totalRecords);
            }
        };

        this.recursiveSearchForIDs(callbackIfNoMore, start, this.configuration.search.batchSize, fields);
    }

    searchWhereIDs(jobs, callback) {
        this.$http({
            method: 'GET',
            url: this.configuration.search.searchUrl + this.requestParams.assembleForSearchWhereIDs(jobs)
        }).success(data => {
            callback(data.data);
        }).error(() => {
        });
    }

    recursiveQueryForIDs(callbackIfNoMore, start, count, errorCallback) {
        errorCallback = errorCallback || (() => {});

        this
            .$http({
                method: 'GET',
                url: this.configuration.search.queryUrl + this.requestParams.assembleForQueryForIDs(start, count)
            })
            .success(callbackIfNoMore)
            .error(errorCallback);
    }

    findJobs() {
        if (this.searchParams.reloadAllData) {
            this.helper.emptyCurrentDataList();
            this.helper.resetStartAndTotal();
        }

        var controller = this;

        var allJobs = [];
        var start = this.requestParams.start();
        var count = this.requestParams.count();

        this.helper.hasMore = false;

        var doneFinding = (jobs) => {
            controller.helper.updateStart();

            if (controller.searchParams.reloadAllData) {
                controller.currentListData = jobs;
            } else {
                controller.currentListData.push.apply(controller.currentListData, jobs);
            }
        };

        var callbackIfNoMore = (data) => {
            if (data.data.length) {
                controller.searchWhereIDs(data.data, (jobs) => {
                    for (var i = 0; i < data.data.length; i++) {
                        for (var i2 = 0; i2 < jobs.length; i2++) {
                            if (jobs[i2].id === data.data[i].id) {
                                allJobs.push(data.data[i]);
                            }
                        }
                    }

                    if (data.count < count) {
                        doneFinding(allJobs);
                    } else if (allJobs.length >= controller.requestParams.count()) {
                        this.helper.hasMore = true;
                        doneFinding(allJobs);
                    } else {
                        controller.helper.updateStart(count);
                        start = controller.requestParams.start();

                        if (count < controller.configuration.search.batchSize) {
                            if (jobs.length > 0) {
                                count = parseInt((controller.configuration.search.count / jobs.length) * count);
                            } else {
                                count = controller.configuration.search.count * count;
                            }
                        }

                        controller.recursiveQueryForIDs(callbackIfNoMore, start, count);
                    }
                });
            } else {
                doneFinding(allJobs);
            }
        };

        this.recursiveQueryForIDs(callbackIfNoMore, start, count);
    }

    loadJobData(jobID, callback, errorCallback) {
        errorCallback = errorCallback || function () {
            };

        this.$http({
            method: 'GET',
            url: this.configuration.search.queryUrl + this.requestParams.assembleForFind(jobID)
        }).success(data => {
            if (data && data.data && data.data.length) {
                callback(data.data[0]);
            }
            else {
                errorCallback();
            }
        }).error(() => errorCallback());
    }

    loadJobDataByCategory(categoryID, callback, errorCallback, idToExclude) {
        errorCallback = errorCallback || function () {
            };

        this.$http({
            method: 'GET',
            url: this.configuration.search.queryUrl + this.requestParams.assembleForRelatedJobs(categoryID, idToExclude)
        }).success(data => {
            if (data && data.data && data.data.length) {
                callback(data.data);
            }
            else {
                errorCallback();
            }
        }).error(() => errorCallback());
    }
}

export default SearchService;<commit_msg>BH-32132 - Checking in some logs to debug this<commit_after>class SearchService {
    constructor($http, configuration) {
        'ngInject';

        this.$http = $http;
        this.configuration = configuration;
    }

    get _() {
        return this.__ || (this.__ = Object.create(null, {}));
    }

    get currentDetailData() {
        return this._.currentDetailData || (this._.currentDetailData = {});
    }

    set currentDetailData(value) {
        this._.currentDetailData = value;
    }

    get currentListData() {
        return this._.currentListData || (this._.currentListData = []);
    }

    set currentListData(value) {
        this._.currentListData = value;
    }

    get helper() {
        return this._.helper || (this._.helper = {
                hasMore: true,
                emptyCurrentDataList: () => this.currentListData.length = 0,
                updateStart: (count) => {
                    if (count) {
                        this.searchParams.start = (parseInt(count) + parseInt(this.requestParams.start()));
                    } else {
                        this.searchParams.start = (parseInt(this.requestParams.count()) + parseInt(this.requestParams.start()));
                    }
                },
                resetStartAndTotal: () => {
                    this.helper.hasMore = true;
                    this.searchParams.total = 0;
                    this.searchParams.start = 0;
                },
                moreRecordsExist: () => ((parseInt(this.searchParams.total) - parseInt(this.requestParams.start())) > 0),
                clearSearchParams: (specificParam) => {
                    if (specificParam === 'location') {
                        this.searchParams.location.length = 0;
                    } else if (specificParam === 'category') {
                        this.searchParams.category.length = 0;
                    } else if (specificParam === 'text') {
                        this.searchParams.textSearch = '';
                    } else {
                        this.searchParams.textSearch = '';
                        this.searchParams.category.length = 0;
                        this.searchParams.location.length = 0;
                    }
                }
            });
    }

    get requestParams() {
        return this._.requestParams || (this._.requestParams = {
                sort: () => this.searchParams.sort || this.configuration.search.sort,
                count: () => this.searchParams.count || this.configuration.search.count,
                start: () => this.searchParams.start || this.configuration.search.start,
                publishedCategory: (isSearch, fields) => {
                    if ('publishedCategory(id,name)' !== fields) {
                        if (this.searchParams.category.length > 0) {
                            var equals = isSearch ? ':' : '=';

                            var fragment = ' AND (';
                            var first = true;

                            for (var i = 0; i < this.searchParams.category.length; i++) {
                                if (!first) {
                                    fragment += ' OR ';
                                } else {
                                    first = false;
                                }

                                fragment += 'publishedCategory.id' + equals + this.searchParams.category[i];
                            }

                            return fragment + ')';
                        }
                    }

                    return '';
                },
                location: (isSearch, fields) => {
                    if ('address(city,state)' !== fields) {
                        if (this.searchParams.location.length > 0) {
                            var delimiter = isSearch ? '"' : '\'';
                            var equals = isSearch ? ':' : '=';

                            var fragment = ' AND (';
                            var first = true;

                            for (var j = 0; j < this.searchParams.location.length; j++) {
                                if (!first) {
                                    fragment += ' OR ';
                                } else {
                                    first = false;
                                }

                                var location = this.searchParams.location[j];

                                var city = location.split('|')[0];
                                var state = location.split('|')[1];

                                fragment += '(address.city' + equals + delimiter + city + delimiter + ' AND address.state' + equals + delimiter + state + delimiter + ')';
                            }

                            return fragment + ')';
                        }
                    }

                    return '';
                },
                text: () => {
                    if (this.searchParams.textSearch) {
                        return ' AND (title:' + this.searchParams.textSearch + '* OR publicDescription:' + this.searchParams.textSearch + '*)';
                    }

                    return '';
                },
                query: (isSearch, additionalQuery, fields) => {
                    var query = '(' + (isSearch ? this.configuration.search.additionalSearchQuery : this.configuration.search.additionalQuery) + ')';

                    if (additionalQuery) {
                        query += ' AND (' + additionalQuery + ')';
                    }

                    if (isSearch) {
                        query += this.requestParams.text();
                    }

                    query += this.requestParams.publishedCategory(isSearch, fields);
                    query += this.requestParams.location(isSearch, fields);

                    return query;
                },
                whereIDs: (jobs, isSearch) => {
                    var getValue = isSearch ? (job) => 'id:' + job.id : (job) => job.id;
                    var join = isSearch ? ' OR ' : ',';
                    var prefix = isSearch ? '' : 'id IN ';

                    var values = [];

                    for (var i = 0; i < jobs.length; i++) {
                        values.push(getValue(jobs[i]));
                    }

                    return prefix + '(' + values.join(join) + ')';
                },
                relatedJobs: (publishedCategoryID, idToExclude) => {
                    var query = '(' + this.configuration.search.additionalQuery + ') AND publishedCategory.id=' + publishedCategoryID;

                    if (idToExclude && parseInt(idToExclude) > 0) {
                        query += ' AND id <>' + idToExclude;
                    }

                    return query;
                },
                find: (jobID) => {
                    return '(' + this.configuration.search.additionalQuery + ') AND id=' + jobID;
                },
                assembleForSearchWhereIDs: (jobs) => {
                    var where = this.requestParams.query(true, this.requestParams.whereIDs(jobs, true));

                    return '?useV2=true&start=0&query=' + where + '&fields=id&count=' + this.configuration.search.count;
                },
                assembleForQueryForIDs: (start, count) => {
                    return '?useV2=true&where=' + this.requestParams.query(false) + '&fields=' + this.configuration.search.fields + '&count=' + count + '&orderBy=' + this.configuration.search.sort + '&start=' + start;
                },
                assembleForGroupByWhereIDs: (fields, orderByFields, start, count, jobs) => {
                    return '?where=' + this.requestParams.whereIDs(jobs, false) + '&groupBy=' + fields + '&fields=' + fields + ',count(id)&count=' + count + '&orderBy=+' + orderByFields + ',-count.id&start=' + start + '&useV2=true';
                },
                assembleForSearchForIDs: (start, count, fields) => {
                    return '?useV2=true&showTotalMatched=true&query=' + this.requestParams.query(true, undefined, fields) + '&fields=id&sort=id&count=' + count + '&start=' + start;
                },
                assembleForRelatedJobs: (publishedCategoryID, idToExclude) => {
                    return '?useV2=true&start=0&where=' + this.requestParams.relatedJobs(publishedCategoryID, idToExclude) + '&fields=' + this.configuration.search.fields + '&sort=' + this.requestParams.sort() + '&count=' + this.configuration.search.maxRelatedJobs;
                },
                assembleForFind: (jobID) => {
                    return '?useV2=true&start=0&count=1&where=' + this.requestParams.find(jobID) + '&fields=' + this.configuration.search.fields;
                }
            });
    }

    get searchParams() {
        return this._.searchParams || (this._.searchParams = {
                textSearch: '',
                location: [],
                category: [],
                sort: '',
                count: '',
                start: '',
                total: '',
                reloadAllData: true
            });
    }

    getCountByLocation(callback, errorCallback) {
        return this.getCountBy('address(city,state)', 'address.city,address.state', callback, errorCallback);
    }

    getCountByCategory(callback, errorCallback) {
        return this.getCountBy('publishedCategory(id,name)', 'publishedCategory.name', callback, errorCallback);
    }

    getCountWhereIDs() {
        this.$http({
            method: 'GET',
            url: this.configuration.search.queryUrl + this.requestParams.assembleForGroupByWhereIDs(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4])
        }).success(data => {
            arguments[5](data);
        }).error(() => {
        });
    }

    recursiveSearchForIDs(callback, start, count, fields) {
        this.$http({
            method: 'GET',
            url: this.configuration.search.searchUrl + this.requestParams.assembleForSearchForIDs(start, count, fields)
        }).success(data => {
            callback(data);
        }).error(() => {
        });
    }

    getCountBy(fields, orderByFields, callback, errorCallback) {
        errorCallback = errorCallback || function () {
            };

        var totalRecords = [];
        var start = 0;

        var controller = this;

        var callbackIfNoMore = (data) => {
            if (data.data.length) {
                controller.getCountWhereIDs(fields, orderByFields, start, controller.configuration.search.batchSize, data.data, (counts) => {
                    totalRecords = totalRecords.concat(counts.data);

                    if (data.total > data.count) {
                        start += controller.configuration.search.batchSize;

                        controller.recursiveSearchForIDs(callbackIfNoMore, start, controller.configuration.search.batchSize);
                    } else {
                        callback(totalRecords);
                    }
                });
            } else {
                callback(totalRecords);
            }
        };

        this.recursiveSearchForIDs(callbackIfNoMore, start, this.configuration.search.batchSize, fields);
    }

    searchWhereIDs(jobs, callback) {
        this.$http({
            method: 'GET',
            url: this.configuration.search.searchUrl + this.requestParams.assembleForSearchWhereIDs(jobs)
        }).success(data => {
            callback(data.data);
        }).error(() => {
        });
    }

    recursiveQueryForIDs(callbackIfNoMore, start, count, errorCallback) {
        errorCallback = errorCallback || (() => {});

        this
            .$http({
                method: 'GET',
                url: this.configuration.search.queryUrl + this.requestParams.assembleForQueryForIDs(start, count)
            })
            .success(callbackIfNoMore)
            .error(errorCallback);
    }

    findJobs() {
        if (this.searchParams.reloadAllData) {
            this.helper.emptyCurrentDataList();
            this.helper.resetStartAndTotal();
        }

        var controller = this;

        var allJobs = [];
        var start = this.requestParams.start();
        var count = this.requestParams.count();

        this.helper.hasMore = false;

        var doneFinding = (jobs) => {
            controller.helper.updateStart();

            if (controller.searchParams.reloadAllData) {
                controller.currentListData = jobs;
            } else {
                controller.currentListData.push.apply(controller.currentListData, jobs);
            }
        };

        var callbackIfNoMore = (data) => {
            if (data.data.length) {
                controller.searchWhereIDs(data.data, (jobs) => {
                    for (var i = 0; i < data.data.length; i++) {
                        for (var i2 = 0; i2 < jobs.length; i2++) {
                            if (jobs[i2].id === data.data[i].id) {
                                allJobs.push(data.data[i]);
                            }
                        }
                    }

                    if (data.count < count) {
                        console.log('data.count < count', count);
                        console.log('HAS MORE', this.helper.hasMore);
                        doneFinding(allJobs);
                    } else if (allJobs.length >= controller.requestParams.count()) {
                        this.helper.hasMore = true;
                        console.log('allJobs.length >= controller.requestParams.count()', count);
                        console.log('HAS MORE', this.helper.hasMore);
                        doneFinding(allJobs);
                    } else {
                        controller.helper.updateStart(count);
                        start = controller.requestParams.start();

                        if (count < controller.configuration.search.batchSize) {
                            if (jobs.length > 0) {
                                count = parseInt((controller.configuration.search.count / jobs.length) * count);
                            } else {
                                count = controller.configuration.search.count * count;
                            }
                        }

                        controller.recursiveQueryForIDs(callbackIfNoMore, start, count);
                    }
                });
            } else {
                console.log('NO DATA LENGTH');
                console.log('HAS MORE', this.helper.hasMore);
                doneFinding(allJobs);
            }
        };

        this.recursiveQueryForIDs(callbackIfNoMore, start, count);
    }

    loadJobData(jobID, callback, errorCallback) {
        errorCallback = errorCallback || function () {
            };

        this.$http({
            method: 'GET',
            url: this.configuration.search.queryUrl + this.requestParams.assembleForFind(jobID)
        }).success(data => {
            if (data && data.data && data.data.length) {
                callback(data.data[0]);
            }
            else {
                errorCallback();
            }
        }).error(() => errorCallback());
    }

    loadJobDataByCategory(categoryID, callback, errorCallback, idToExclude) {
        errorCallback = errorCallback || function () {
            };

        this.$http({
            method: 'GET',
            url: this.configuration.search.queryUrl + this.requestParams.assembleForRelatedJobs(categoryID, idToExclude)
        }).success(data => {
            if (data && data.data && data.data.length) {
                callback(data.data);
            }
            else {
                errorCallback();
            }
        }).error(() => errorCallback());
    }
}

export default SearchService;<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';
import { pictureBox, multipleRow } from '../styles/styles.scss';
import { Row, Col, Card, CardTitle, Icon } from 'react-materialize';

const ArtShow = ({ data }) =>
    //

    //
{data.name}  {data.price}

    //
{data.artist}

    //
    //
;

      <Row className={pictureBox}>
        <Col>
          <Card header={<CardTitle reveal image={data.img} waves="light"/>}
            title={data.name}
            reveal={
Here is some more information about this product that is only revealed once clicked on.
}>

This is a link

          </Card>
        </Col>
      </Row>

;
          // <Card className="small"
          //   header={<CardTitle image= {{data.image}} > {data.name} </CardTitle>}
          //   actions={[This is a link]}>
          //   I am a simple card.  I contain small bits of info.
          // </Card>

ArtShow.propTypes = {
    data: PropTypes.object
};

export default ArtShow;
<commit_msg>kkladfskjfewMerge branch 'master' of https://github.com/BZhawaii/ArtStorm<commit_after>import React, { PropTypes } from 'react';
import { pictureBox, multipleRow } from '../styles/styles.scss';
import { Row, Col, Card, CardTitle, Icon } from 'react-materialize';

const ArtShow = ({ data }) =>
    //

    //
{data.name}  {data.price}

    //
{data.artist}

    //
    //
;

      <Row className={pictureBox}>
        <Col>
          <Card header={<CardTitle reveal image={data.img} waves="light"/>}
            title={data.name}
            reveal={
Here is some more information about this product that is only revealed once clicked on.
}>

This is a link

          </Card>
        </Col>
      </Row>

;

ArtShow.propTypes = {
    data: PropTypes.object
};

export default ArtShow;
<|endoftext|>


<commit_before>const React = require('react')
const e = React.createElement
const Component = React.Component
const bindActionCreators = require('redux').bindActionCreators
const connect = require('react-redux').connect
const LoadingActions = require('../actions/loading')
const nodegit = require('../utils/nodegit').nodegit
const hashHistory = require('react-router').hashHistory
const RaisedButton = require('material-ui/RaisedButton').default
const FlatButton = require('material-ui/FlatButton').default
const RefreshIcon = require('material-ui/svg-icons/navigation/refresh').default
const remoteCallbacks = require('../utils/remoteCallbacks')

const LIMIT = 250

class History extends Component {

	constructor(props) {
		super(props)

		this.state = {
			refreshing: false,
			tree: [],
			countLocal: 0,
			countRemote: 0,
			countCommon: 0,
		}
	}

	componentDidMount() {
		this.refresh()
	}

	setRefreshing(refreshing) {
		this.setState(Object.assign({}, this.state, { refreshing }))
		if (refreshing) {
			this.props.actions.loading.IncrementLoadingJobs()
		} else {
			this.props.actions.loading.DecrementLoadingJobs()
		}
	}

	push() {
		this.setRefreshing(true)
		let repo
		let localBranchReference
		nodegit.Repository.open(this.props.projects.active.path)
			.then((r) => {
				repo = r
				return repo.getCurrentBranch()
			})
			.then((reference) => {
				localBranchReference = reference
				return nodegit.Branch.upstream(localBranchReference)
			})
			.then((reference) => {
				const remoteName = reference.toString().split('/')[2] // Returns for example "origin"
				return repo.getRemote(remoteName)
			})
			.then((remote) => {
				const refName = localBranchReference.toString()
				return remote.push([
					`${refName}:${refName}`
				], remoteCallbacks)
			})
			.catch((error) => {
				console.error(error)
			})
			.then(() => {
				this.setRefreshing(false)
			})
	}

	refresh() {
		this.setRefreshing(true)
		const tree = []
		let commitsPool = []
		let nextIsRemote = false
		let nextIsLocal = false
		const count = {
			local: 0,
			remote: 0,
			common: 0,
		}

		const processPool = () => {
			if (commitsPool.length === 0 || tree.length === LIMIT) { // @TODO: note to user that limit was reached
				return
			}
			let nextCommit = commitsPool.reduce((accumulator, current) => {
				if (accumulator.commit.timeMs() < current.commit.timeMs()) {
					return current
				}
				return accumulator
			})
			commitsPool = commitsPool.filter((commit) => {
				if (commit.commit.sha() === nextCommit.commit.sha()) {
					if (commit.branch === 'remote') {
						nextIsRemote = true
					} else if (commit.branch === 'local') {
						nextIsLocal = true
					}
					return false
				} else {
					return true
				}
			})
			if (nextIsRemote && nextIsLocal) {
				nextCommit.branch = 'common'
			}
			count[nextCommit.branch]++
			return nextCommit.commit.getParents()
				.then((parents) => {
					tree.push({
						branch: nextCommit.branch,
						message: nextCommit.commit.message().trim(),
						sha: nextCommit.commit.sha(),
						isMergeCommit: parents.length > 1,
					})
					commitsPool = commitsPool.concat(parents.map((commit) => {
						return {
							commit,
							branch: nextCommit.branch,
						}
					}))
					return processPool()
				})
		}

		let repo
		const getTopCommit = (reference, branch) => {
			return repo.getBranchCommit(reference)
				.then((commit) => commitsPool.push({
					commit,
					branch,
				}))
				.then(() => reference)
		}

		nodegit.Repository.open(this.props.projects.active.path)
			.then((r) => {
				repo = r
				return repo.getCurrentBranch()
			})
			.then((reference) => getTopCommit(reference, 'local'))
			.then((branch) => nodegit.Branch.upstream(branch))
			.then((reference) => getTopCommit(reference, 'remote'))
			.catch((error) => {
				console.error(error)
			})
			.then(() => processPool())
			.then(() => {
				this.setState(Object.assign({}, this.state, {
					tree,
					countLocal: count.local,
					countRemote: count.remote,
					countCommon: count.common,
				}))
			})
			.catch((error) => {
				console.error(error)
			})
			.then(() => {
				this.setRefreshing(false)
			})
	}

	renderTree() {
		let lineRemote = false
		let lineLocal = false

		return (
			e(
				'div',
				{
					className: 'history-tree',
				},
				this.state.countLocal === 0 ? null : e(
					'div',
					{
						className: 'history-titles',
					},
					e(
						'h2',
						{
							className: 'history-title',
						},
						'Sdílené změny'
					),
					e(
						'h2',
						{
							className: 'history-title',
						},
						'Vaše nezazálohované změny'
					)
				),
				this.state.tree.map((node, i) => {
					const lineClasses = ['history-line']
					if (node.branch === 'common') {
						lineClasses.push('history-line-common')
					} else {
						if (node.branch === 'local') {
							lineLocal = true
						} else if (node.branch === 'remote') {
							lineRemote = true
						}
						if (lineRemote) {
							lineClasses.push('history-line-remote')
						}
						if (lineLocal) {
							lineClasses.push('history-line-local')
							if (this.state.tree[i+1] && this.state.tree[i+1].branch === 'common') {
								lineClasses.push('history-line-merge')
							}
						}
					}
					if (i === this.state.tree.length-1) {
						lineClasses.push('history-line-last')
					}
					const nodeClasses = ['history-node', `history-node-${node.branch}`]
					if (node.isMergeCommit) {
						nodeClasses.push('history-node-mergeCommit')
					}
					const message = node.message.split('\n')
					return e(
						'div',
						{
							key: i,
							className: nodeClasses.join(' '),
						},
						e(
							'div',
							{
								className: lineClasses.join(' '),
							},
							e(
								'span',
								{
									className: 'history-line-in',
								}
							)
						),
						e(
							'button',
							{
								className: 'history-node-in',
								onClick: () => {
									hashHistory.push(`/commitDetail/${node.sha}`)
								},
							},
							message[0] + (message.length > 1 ? '…' : '')
						)
					)
				})
			)
		)
	}

	render() {
		return (
			e(
				'div',
				null,
				e('h1', null, 'Historie'),
				e(
					'div',
					null,
					(this.props.settings.autoPush || this.state.countRemote !== 0 || this.state.countLocal === 0) ? null : e(
						RaisedButton,
						{
							label: 'Sdílet změny',
							primary: true,
							onTouchTap: () => this.push(),
							disabled: this.state.refreshing,
						}
					),
					e(
						FlatButton,
						{
							icon: e(RefreshIcon),
							onTouchTap: this.refresh.bind(this),
							disabled: this.state.refreshing,
						}
					)
				),
				this.renderTree()
			)
		)
	}

}

function mapStateToProps(state) {
	return {
		loading: state.loading,
		projects: state.projects,
		settings: state.settings,
	}
}

function mapDispatchToProps(dispatch) {
	return {
		actions: {
			loading: bindActionCreators(LoadingActions, dispatch),
		}
	}
}

module.exports = connect(mapStateToProps, mapDispatchToProps)(History)
<commit_msg>History: fix next is common<commit_after>const React = require('react')
const e = React.createElement
const Component = React.Component
const bindActionCreators = require('redux').bindActionCreators
const connect = require('react-redux').connect
const LoadingActions = require('../actions/loading')
const nodegit = require('../utils/nodegit').nodegit
const hashHistory = require('react-router').hashHistory
const RaisedButton = require('material-ui/RaisedButton').default
const FlatButton = require('material-ui/FlatButton').default
const RefreshIcon = require('material-ui/svg-icons/navigation/refresh').default
const remoteCallbacks = require('../utils/remoteCallbacks')

const LIMIT = 250

class History extends Component {

	constructor(props) {
		super(props)

		this.state = {
			refreshing: false,
			tree: [],
			countLocal: 0,
			countRemote: 0,
			countCommon: 0,
		}
	}

	componentDidMount() {
		this.refresh()
	}

	setRefreshing(refreshing) {
		this.setState(Object.assign({}, this.state, { refreshing }))
		if (refreshing) {
			this.props.actions.loading.IncrementLoadingJobs()
		} else {
			this.props.actions.loading.DecrementLoadingJobs()
		}
	}

	push() {
		this.setRefreshing(true)
		let repo
		let localBranchReference
		nodegit.Repository.open(this.props.projects.active.path)
			.then((r) => {
				repo = r
				return repo.getCurrentBranch()
			})
			.then((reference) => {
				localBranchReference = reference
				return nodegit.Branch.upstream(localBranchReference)
			})
			.then((reference) => {
				const remoteName = reference.toString().split('/')[2] // Returns for example "origin"
				return repo.getRemote(remoteName)
			})
			.then((remote) => {
				const refName = localBranchReference.toString()
				return remote.push([
					`${refName}:${refName}`
				], remoteCallbacks)
			})
			.catch((error) => {
				console.error(error)
			})
			.then(() => {
				this.setRefreshing(false)
			})
	}

	refresh() {
		this.setRefreshing(true)
		const tree = []
		let commitsPool = []
		let restIsCommon = false
		const count = {
			local: 0,
			remote: 0,
			common: 0,
		}

		const processPool = () => {
			let nextIsRemote = false
			let nextIsLocal = false

			if (commitsPool.length === 0 || tree.length === LIMIT) { // @TODO: note to user that limit was reached
				return
			}

			let nextCommit = commitsPool.reduce((accumulator, current) => {
				if (accumulator.commit.timeMs() < current.commit.timeMs()) {
					return current
				}
				return accumulator
			})

			commitsPool = commitsPool.filter((commit) => {
				if (commit.commit.sha() === nextCommit.commit.sha()) {
					if (commit.branch === 'remote') {
						nextIsRemote = true
					} else if (commit.branch === 'local') {
						nextIsLocal = true
					}
					return false
				} else {
					return true
				}
			})

			if (nextIsRemote && nextIsLocal) {
				restIsCommon = true
			}

			if (restIsCommon) {
				nextCommit.branch = 'common'
			}
			count[nextCommit.branch]++
			return nextCommit.commit.getParents()
				.then((parents) => {
					tree.push({
						branch: nextCommit.branch,
						message: nextCommit.commit.message().trim(),
						sha: nextCommit.commit.sha(),
						isMergeCommit: parents.length > 1,
					})
					commitsPool = commitsPool.concat(parents.map((commit) => {
						return {
							commit,
							branch: nextCommit.branch,
						}
					}))
					return processPool()
				})
		}

		let repo
		const getTopCommit = (reference, branch) => {
			return repo.getBranchCommit(reference)
				.then((commit) => commitsPool.push({
					commit,
					branch,
				}))
				.then(() => reference)
		}

		nodegit.Repository.open(this.props.projects.active.path)
			.then((r) => {
				repo = r
				return repo.getCurrentBranch()
			})
			.then((reference) => getTopCommit(reference, 'local'))
			.then((branch) => nodegit.Branch.upstream(branch))
			.then((reference) => getTopCommit(reference, 'remote'))
			.catch((error) => {
				console.error(error)
			})
			.then(() => processPool())
			.then(() => {
				this.setState(Object.assign({}, this.state, {
					tree,
					countLocal: count.local,
					countRemote: count.remote,
					countCommon: count.common,
				}))
			})
			.catch((error) => {
				console.error(error)
			})
			.then(() => {
				this.setRefreshing(false)
			})
	}

	renderTree() {
		let lineRemote = false
		let lineLocal = false

		return (
			e(
				'div',
				{
					className: 'history-tree',
				},
				this.state.countLocal === 0 ? null : e(
					'div',
					{
						className: 'history-titles',
					},
					e(
						'h2',
						{
							className: 'history-title',
						},
						'Sdílené změny'
					),
					e(
						'h2',
						{
							className: 'history-title',
						},
						'Vaše nezazálohované změny'
					)
				),
				this.state.tree.map((node, i) => {
					const lineClasses = ['history-line']
					if (node.branch === 'common') {
						lineClasses.push('history-line-common')
					} else {
						if (node.branch === 'local') {
							lineLocal = true
						} else if (node.branch === 'remote') {
							lineRemote = true
						}
						if (lineRemote) {
							lineClasses.push('history-line-remote')
						}
						if (lineLocal) {
							lineClasses.push('history-line-local')
							if (this.state.tree[i+1] && this.state.tree[i+1].branch === 'common') {
								lineClasses.push('history-line-merge')
							}
						}
					}
					if (i === this.state.tree.length-1) {
						lineClasses.push('history-line-last')
					}
					const nodeClasses = ['history-node', `history-node-${node.branch}`]
					if (node.isMergeCommit) {
						nodeClasses.push('history-node-mergeCommit')
					}
					const message = node.message.split('\n')
					return e(
						'div',
						{
							key: i,
							className: nodeClasses.join(' '),
						},
						e(
							'div',
							{
								className: lineClasses.join(' '),
							},
							e(
								'span',
								{
									className: 'history-line-in',
								}
							)
						),
						e(
							'button',
							{
								className: 'history-node-in',
								onClick: () => {
									hashHistory.push(`/commitDetail/${node.sha}`)
								},
							},
							message[0] + (message.length > 1 ? '…' : '')
						)
					)
				})
			)
		)
	}

	render() {
		return (
			e(
				'div',
				null,
				e('h1', null, 'Historie'),
				e(
					'div',
					null,
					(this.props.settings.autoPush || this.state.countRemote !== 0 || this.state.countLocal === 0) ? null : e(
						RaisedButton,
						{
							label: 'Sdílet změny',
							primary: true,
							onTouchTap: () => this.push(),
							disabled: this.state.refreshing,
						}
					),
					e(
						FlatButton,
						{
							icon: e(RefreshIcon),
							onTouchTap: this.refresh.bind(this),
							disabled: this.state.refreshing,
						}
					)
				),
				this.renderTree()
			)
		)
	}

}

function mapStateToProps(state) {
	return {
		loading: state.loading,
		projects: state.projects,
		settings: state.settings,
	}
}

function mapDispatchToProps(dispatch) {
	return {
		actions: {
			loading: bindActionCreators(LoadingActions, dispatch),
		}
	}
}

module.exports = connect(mapStateToProps, mapDispatchToProps)(History)
<|endoftext|>


<commit_before>// @flow
import React, { Component } from 'react';
import { Sidebar, Button, Form, Header, Icon, Grid } from 'semantic-ui-react';
import ToolboxComponent from './ToolboxComponent';
import styles from './Toolbox.css'; // eslint-disable-line flowtype-errors/show-errors

export default class Toolbox extends Component {
  props: {
    dispatchButtonClick: (action: string) => void,
    addResource: (resourceType: string) => void,
    isToolboxOpen: boolean
  }

  generateGrid() {
    const types = [
      { type: 'Microsoft.Web/serverfarms', name: 'App Service' },
      { type: 'Microsoft.Web/sites', name: 'Web App' },
      { type: 'Microsoft.Insights/components', name: 'Application Insights' },
      { type: 'Microsoft.Storage/storageAccounts', name: 'Storage Account' },
      { type: 'Microsoft.EventHub/namespaces', name: 'Event Hub' },
      { type: 'Microsoft.Network/trafficManagerProfiles', name: 'Traffic Manager' },
      { type: 'Microsoft.NotificationHubs/namespaces', name: 'Notification Hub' },
      { type: 'Microsoft.Network/networkInterfaces', name: 'Virtual Network' },
      { type: 'Microsoft.Compute/virtualMachines', name: 'Virtual Machine' },
      { type: 'Microsoft.Search/searchServices', name: 'Azure Search' },
      { type: 'Microsoft.Compute/virtualMachines', name: 'Virtual Machine' },
      { type: 'Microsoft.Network/applicationGateways', name: 'Application Gateway' },
      { type: 'Microsoft.ApiManagement/service', name: 'API Management' },
      { type: 'Microsoft.Backup/BackupVault', name: 'Azure Backup' }];

    const grid = [];
    for (let i = 0; i <= types.length - 1; i += 2) {
      grid.push(<Grid.Row columns={2} key={i}>
        <Grid.Column>
          <ToolboxComponent
            resourceType={types[i].type}
            addResource={(type) => this.props.addResource(type)}
            />
          {types[i].name}
        </Grid.Column>
        <Grid.Column>
          <ToolboxComponent
            resourceType={types[i + 1].type}
            addResource={(type) => this.props.addResource(type)}
            />
          {types[i + 1].name}
        </Grid.Column>
      </Grid.Row>);
    }

    return grid;
  }

  render() {
    return (<Sidebar as={Form} className={styles.toolbox} animation="overlay" width="wide" visible={this.props.isToolboxOpen} icon="labeled" inverted>

        <Icon name="sitemap" />
        Toolbox

          Build & customize a template

      <Grid>
        {this.generateGrid()}
      </Grid>

      <Form.Field><Button type="button" fluid onClick={() => this.props.dispatchButtonClick('CLOSE_TOOLBOX')}>Close</Button></Form.Field>
    </Sidebar>);
  }
}
<commit_msg>#74 - added missing items to the toolbox<commit_after>// @flow
import React, { Component } from 'react';
import { Sidebar, Button, Form, Header, Icon, Grid } from 'semantic-ui-react';
import ToolboxComponent from './ToolboxComponent';
import styles from './Toolbox.css'; // eslint-disable-line flowtype-errors/show-errors

export default class Toolbox extends Component {
  props: {
    dispatchButtonClick: (action: string) => void,
    addResource: (resourceType: string) => void,
    isToolboxOpen: boolean
  }

  generateGrid() {
    const types = [
      { type: 'Microsoft.AnalysisServices/servers', name: 'Analysis Services' },
      { type: 'Microsoft.ApiManagement/service', name: 'API Management' },
      { type: 'Microsoft.Authorization/locks', name: 'Authorization Lock' },
      { type: 'Microsoft.Automation/automationAccounts', name: 'Automation Account' },
      { type: 'Microsoft.Batch/batchAccounts', name: 'Batch Account' },
      { type: 'Microsoft.Cache/Redis', name: 'Redis Cache' },
      { type: 'Microsoft.Cdn/profiles', name: 'CDN' },
      { type: 'Microsoft.CertificateRegistration/certificateOrders', name: 'Certificate Registration' },
      { type: 'Microsoft.CognitiveServices/accounts', name: 'Cognitive Services' },
      { type: 'Microsoft.Compute/virtualMachines', name: 'Virtual Machine' },
      { type: 'Microsoft.ContainerInstance/containerGroups', name: 'Container Groups' },
      { type: 'Microsoft.ContainerRegistry/registries', name: 'Container Registry' },
      { type: 'Microsoft.ContainerService/containerServices', name: 'Container Services' },
      { type: 'Microsoft.DocumentDB/databaseAccounts', name: 'Document DB' },
      { type: 'Microsoft.CustomerInsights/hubs', name: 'Customer Insights' },
      { type: 'Microsoft.DataFactory/dataFactories', name: 'Data Factory' },
      { type: 'Microsoft.DataLakeAnalytics/accounts', name: 'Data Lake Analytics' },
      { type: 'Microsoft.DataLakeStore/accounts', name: 'Data Lake Store' },
      { type: 'Microsoft.Devices/IotHubs', name: 'IoT Hub' },
      { type: 'Microsoft.Devices/IotHubs/eventHubEndpoints/ConsumerGroups', name: 'IoT Hub Consumer Groups' },
      { type: 'Microsoft.DevTestLab/labs', name: 'DevTest Labs' },
      { type: 'Microsoft.DomainRegistration/domains', name: 'Domain Registration' },
      { type: 'Microsoft.EventHub/namespaces', name: 'Event Hub Namespace' },
      { type: 'Microsoft.HDInsight/clusters', name: 'HDInsight cluster' },
      { type: 'Microsoft.ImportExport/jobs', name: 'Import/Export' },
      { type: 'Microsoft.Insights/Components', name: 'Insights' },
      { type: 'Microsoft.KeyVault/vaults', name: 'Key Vault' },
      { type: 'Microsoft.Logic/integrationAccounts', name: 'Logic App' },
      { type: 'Microsoft.MachineLearning/commitmentPlans', name: 'Machine Learning Plan' },
      { type: 'Microsoft.Media/mediaservices', name: 'Media Services' },
      { type: 'Microsoft.Network/applicationGateways', name: 'Application Gateway' },
      { type: 'Microsoft.Network/connections', name: 'Network Connections' },
      { type: 'Microsoft.Network/loadBalancers', name: 'Load Balancer' },
      { type: 'Microsoft.Network/networkInterfaces', name: 'Network Interface' },
      { type: 'Microsoft.Network/virtualNetworks', name: 'Virtual Networks' },
      { type: 'Microsoft.NotificationHubs/namespaces', name: 'Notification Hub' },
      { type: 'Microsoft.StreamAnalytics/streamingjobs', name: 'Stream Analytics' },
      { type: 'Microsoft.StorSimple/managers', name: 'StorSimple' },
      { type: 'Microsoft.Storage/storageAccounts', name: 'Storage Account' },
      { type: 'Microsoft.Sql/servers', name: 'SQL Server' },
      { type: 'Microsoft.ServiceFabric/clusters', name: 'Service Fabric Cluster' },
      { type: 'Microsoft.ServiceBus/namespaces', name: 'Service Bus Namespace' },
      { type: 'Microsoft.ServerManagement/gateways', name: 'Server Management' },
      { type: 'Microsoft.Search/searchServices', name: 'Search Service' },
      { type: 'Microsoft.Scheduler/jobCollections', name: 'Scheduler' },
      { type: 'Microsoft.Relay/namespaces', name: 'Relay' },
      { type: 'Microsoft.Resources/deployments', name: 'Resources' },
      { type: 'Microsoft.RecoveryServices/vaults', name: 'Recovery Services' },
      { type: 'Microsoft.PowerBI/workspaceCollections', name: 'Power BI' },
      { type: 'Microsoft.Web/sites', name: 'App Service' },
    ];

    // Sort data so toolbox is more intuitive
    types.sort((a, b) => a.name.localeCompare(b.name));

    const grid = [];
    for (let i = 0; i <= types.length - 1; i += 2) {
      grid.push(<Grid.Row columns={2} key={i}>
        <Grid.Column>
          <ToolboxComponent
            resourceType={types[i].type}
            addResource={(type) => this.props.addResource(type)}
          />
          {types[i].name}
        </Grid.Column>
        <Grid.Column>
          <ToolboxComponent
            resourceType={types[i + 1].type}
            addResource={(type) => this.props.addResource(type)}
          />
          {types[i + 1].name}
        </Grid.Column>
      </Grid.Row>);
    }

    return grid;
  }

  render() {
    return (<Sidebar as={Form} className={styles.toolbox} animation="overlay" width="wide" visible={this.props.isToolboxOpen} icon="labeled" inverted>

        <Icon name="sitemap" />
        Toolbox

          Build & customize a template

      <Grid>
        {this.generateGrid()}
      </Grid>

      <Form.Field><Button type="button" fluid onClick={() => this.props.dispatchButtonClick('CLOSE_TOOLBOX')}>Close</Button></Form.Field>
    </Sidebar>);
  }
}
<|endoftext|>


<commit_before>Ficha = require('../models/').Ficha;
// CRUD Operations for Ficha Model
module.exports= {
  index(req, res) {
    Ficha.findAll({
        where: {
            autor: req.params.id
        }
    })
      .then(function (Fichas) {
        res.status(200).json(Fichas);
      })
      .catch(function (error) {
        console.log(error)
        res.status(500).json(error);
      });
  },

  show(req, res) {
    Ficha.findAll({
        where: {
          id: req.params.id
        }
    })
    .then(function (Ficha) {
      res.status(200).json(Ficha);
    })
    .catch(function (error){
      res.status(500).json(error);
    });
  },

  create(req, res) {
    // res.status(200).json(req.body);
    Ficha.create(req.body)
      .then(function (newFicha) {
        res.status(200).json(newFicha);
      })
      .catch(function (error){
        res.status(500).json(error);
      });
  },

  update(req, res) {
    Ficha.update(req.body, {
      where: {
        id: req.body.id
      }
    })
    .then(function (updatedRecords) {
      res.status(200).json(updatedRecords);
    })
    .catch(function (error){
      console.log(error)
      res.status(500).json(error);
    });
  },

  delete(req, res) {
    console.log(req.params)
    Ficha.destroy({
      where: {
        id: req.params.id
      }
    })
    .then(function (deletedRecords) {
      res.status(200).json(deletedRecords);
    })
    .catch(function (error){
      res.status(500).json(error);
    });
  },

  search(req, res){
    Ficha.findAll({
        where: {
            nombreactividad: $like:req.params.query
        }
    })
    .then(function (Fichas) {
        res.status(200).json(Fichas);
    })
    .catch(function (error) {
        console.log(error)
        res.status(500).json(error);
    });
  }
};
<commit_msg>Update fichas.js<commit_after>Ficha = require('../models/').Ficha;
// CRUD Operations for Ficha Model
module.exports= {
  index(req, res) {
    Ficha.findAll({
        where: {
            autor: req.params.id
        }
    })
      .then(function (Fichas) {
        res.status(200).json(Fichas);
      })
      .catch(function (error) {
        console.log(error)
        res.status(500).json(error);
      });
  },

  show(req, res) {
    Ficha.findAll({
        where: {
          id: req.params.id
        }
    })
    .then(function (Ficha) {
      res.status(200).json(Ficha);
    })
    .catch(function (error){
      res.status(500).json(error);
    });
  },

  create(req, res) {
    // res.status(200).json(req.body);
    Ficha.create(req.body)
      .then(function (newFicha) {
        res.status(200).json(newFicha);
      })
      .catch(function (error){
        res.status(500).json(error);
      });
  },

  update(req, res) {
    Ficha.update(req.body, {
      where: {
        id: req.body.id
      }
    })
    .then(function (updatedRecords) {
      res.status(200).json(updatedRecords);
    })
    .catch(function (error){
      console.log(error)
      res.status(500).json(error);
    });
  },

  delete(req, res) {
    console.log(req.params)
    Ficha.destroy({
      where: {
        id: req.params.id
      }
    })
    .then(function (deletedRecords) {
      res.status(200).json(deletedRecords);
    })
    .catch(function (error){
      res.status(500).json(error);
    });
  },

  search(req, res){
    Ficha.findAll({
        where: {
            nombreactividad: {
                $like:req.params.query
            }
        }
    })
    .then(function (Fichas) {
        res.status(200).json(Fichas);
    })
    .catch(function (error) {
        console.log(error)
        res.status(500).json(error);
    });
  }
};
<|endoftext|>


<commit_before>function ReplaceRow(list, rowId, data) {
	$('#' + list + '_' + rowId).replaceWith(data);
	RefreshTables(list);
	enableDatePicker();
}

function RemoveRow(list, rowId) {
	$('#' + list + '_' + rowId).remove();
	RefreshTables(list);
}

function AddRow(list, data) {
	$('#' + list + '_tbody').append(data);
	$('#' + list + '_tbody + tfoot form')[0].reset();
	RefreshTables(list);
	$('#' + list + '_form input[type=date]').each(function() {
		 reformatDateField(this);
	});
}

function RefreshTables(list) {
	var selector = 'table.table-sortable';
	if (list) {
		selector = '#' + list + '_table';
	}
	$(selector).trigger('update');
	$("table.table-sortable time[rel=timeago]").timeago();
}<commit_msg>ListUtilities an die neue Struktur angepasst<commit_after>function ReplaceRow(list, rowId, data) {
	$('#' + list + '_' + rowId).replaceWith(data);
	RefreshTables(list);
	enableDatePicker();
}

function RemoveRow(list, rowId) {
	$('#' + list + '_' + rowId).remove();
	RefreshTables(list);
}

function AddRow(list, data) {
	$('#' + list + '_tbody').append(data);
	$('#' + list + '_form')[0].reset();
	$('#' + list + '_form ~ div.alert').alert('close');
	RefreshTables(list);
}

function RefreshTables(list) {
	var selector = 'table.table-sortable';
	if (list) {
		selector = '#' + list + '_table';
	}
	$(selector).trigger('update');
	$("table.table-sortable time[rel=timeago]").timeago();
}<|endoftext|>


<commit_before>import React from 'react';
import { interpolate } from 'd3-interpolate';

class Motion extends React.Component {
    constructor(props, context) {
        super(props, context);
        this.move = this.move.bind(this);
        this.state = {items: []};
    }
    componentDidMount() {
        this.moveId = requestAnimationFrame(this.move)
    }
    componentWillUnmount() {
        cancelAnimationFrame(this.moveId);
    }
    move() {
        this.setState(({items: prevItems, update}) => {
            var items = target(prevItems, this.props);
            // Interpolate styles
            this.moveId = requestAnimationFrame(this.move);
            return {items};
        })
    }
    target(items, {data, enter, leave}) {
        // Set destinations
        var dataByKey = data.reduce((acc, dataItem) => ({...acc, [dataItem.key]: dataItem}), {});
        var itemsByKey = items.reduce((acc, item) => ({...acc, [item.key]: item}), {});
        return items
            .map(item => {
                var end = !dataByKey[item.key] ? leave(item.data) : update(item.data);
                var interpolators = this.getInterpolators(item.style, end);
                const equal = areEqual(item.style, end);
                return {...item, end, interpolators, progress: equal ? item.progress : 0, render: equal};
             })
            .concat(data
                .filter(dataItem => !itemsByKey[dataItem.key])
                .map(dataItem => {
                    var end = update(dataItem);
                    var interpolators = this.getInterpolators(enter(dataItem), end);
                    return {...dataItem, end, interpolators, progress: 0, render: false};
                })
            );
    }
    areEqual(from, to) {
        if (Object.keys(from).length !== Object.keys(to).length)
            return false;
        for(var key in from) {
            if (from[key] !== to[key])
                return false;
        }
        return true;
    }
    getInterpolators(start, end) {
        var interpolators = {};
        for(var key in start) {
            interpolators[key] = interpolate(start[key], end[key]);
        }
        return interpolators;
    }
}

export default Motion;
<commit_msg>Kept interpolators if end unchanged<commit_after>import React from 'react';
import { interpolate } from 'd3-interpolate';

class Motion extends React.Component {
    constructor(props, context) {
        super(props, context);
        this.move = this.move.bind(this);
        this.state = {items: []};
    }
    componentDidMount() {
        this.moveId = requestAnimationFrame(this.move)
    }
    componentWillUnmount() {
        cancelAnimationFrame(this.moveId);
    }
    move() {
        this.setState(({items: prevItems, update}) => {
            var items = target(prevItems, this.props);
            // Interpolate styles
            this.moveId = requestAnimationFrame(this.move);
            return {items};
        })
    }
    target(items, {data, enter, leave}) {
        // Set destinations
        var dataByKey = data.reduce((acc, dataItem) => ({...acc, [dataItem.key]: dataItem}), {});
        var itemsByKey = items.reduce((acc, item) => ({...acc, [item.key]: item}), {});
        return items
            .map(item => {
                var end = !dataByKey[item.key] ? leave(item.data) : update(item.data);
                const equal = areEqual(item.style, end);
                var progress = equal ? item.progress : 0;
                var interpolators = equal ? item.interpolators : this.getInterpolators(item.style, end);
                return {...item, end, interpolators, progress, render: equal};
             })
            .concat(data
                .filter(dataItem => !itemsByKey[dataItem.key])
                .map(dataItem => {
                    var end = update(dataItem);
                    var interpolators = this.getInterpolators(enter(dataItem), end);
                    return {...dataItem, end, interpolators, progress: 0, render: false};
                })
            );
    }
    areEqual(from, to) {
        if (Object.keys(from).length !== Object.keys(to).length)
            return false;
        for(var key in from) {
            if (from[key] !== to[key])
                return false;
        }
        return true;
    }
    getInterpolators(start, end) {
        var interpolators = {};
        for(var key in start) {
            interpolators[key] = interpolate(start[key], end[key]);
        }
        return interpolators;
    }
}

export default Motion;
<|endoftext|>


<commit_before>(function (win) {

    if (!(win.history && win.history.pushState))
        return;

    var submitData = {};
    win.document.addEventListener('click', function (e) {
        var element = e.target;
        var anchor = getAjaxTarget(element, 'A');
        if (!e.ctrlKey && !e.shiftKey && anchor) {
            e.preventDefault();
            refreshAjax(anchor.getAttribute('href'), true, anchor);
        }
        if (element.tagName === 'INPUT' && element.name) {
            if (element.type === 'submit')
                submitData[element.name] = element.value;
            if (element.type === 'image') {
                submitData[element.name + '.x'] = win.Math.max(0, e.offsetX);
                submitData[element.name + '.y'] = win.Math.max(0, e.offsetY);
            }
        }
    });

    win.document.addEventListener('submit', function (e) {
        var form = getAjaxTarget(e.target, 'FORM');
        if (form) {
            var req = new win.XMLHttpRequest();
            req.onreadystatechange = onReady(req, true);
            e.preventDefault();
            req.open('post', getAjaxLink(form.getAttribute('action'), form));
            req.setRequestHeader("Content-Type", "application/json");
            req.send(win.JSON.stringify(getFormData(form)));
        }
    });

    var tagNames = /^INPUT|TEXTAREA|SELECT$/;
    var ignoreTypes = /^button|image|submit|reset|file$/;
    var checkTypes = /^checkbox|radio$/;
    function getFormData(form) {
        var elements = form.elements;
        var data = {};
        for (var i = 0; i < elements.length; i++) {
            var element = elements[i];
            if (tagNames.test(element.tagName) && element.name
                && !ignoreTypes.test(element.type) && !element.disabled
                && (!checkTypes.test(element.type) || element.checked))
                data[element.name] = element.value;
        }
        for (var key in submitData)
            data[key] = submitData[key];
        submitData = {};
        return data;
    }

    function getAjaxTarget(element, tagName) {
        var target = null;
        while (element) {
            if (element.getAttribute) {
                var navigation = element.getAttribute('data-navigation');
                if (!target && element.tagName === tagName && navigation === 'refresh')
                    target = element;
                if (navigation === 'noajax')
                    return null;
            }
            element = element.parentNode;
        }
        return target;
    }

    var link = win.location.pathname + win.location.search;
    function refreshAjax(newLink, addHistory, target, title) {
        var req = new win.XMLHttpRequest();
        req.onreadystatechange = onReady(req, addHistory, title);
        req.open('get', getAjaxLink(newLink, target));
        req.send();
    }

    function getAjaxLink(baseLink, target) {
        baseLink += baseLink.indexOf('?') > 0 ? '&' : '?';
        baseLink += 'refreshajax=' + win.encodeURIComponent(link);
        baseLink += '&navigation=' + (target ? 'refresh' : 'history');
        if (target) {
            baseLink = setLinkData(target, baseLink, 'include-current');
            baseLink = setLinkData(target, baseLink, 'current-keys');
            baseLink = setLinkData(target, baseLink, 'to-keys');
        }
        return baseLink;
    }

    function setLinkData(target, link, name) {
        var value = target.getAttribute('data-' + name);
        if (value)
            link += '&' + name.replace('-','') + '=' + win.encodeURIComponent(value);
        return link;
    }

    var cache = {};
    function onReady(req, addHistory, title) {
        var oldLink = link;
        return function () {
            if (req.readyState === 4 && req.status === 200) {
                var resp = win.JSON.parse(req.responseText);
                if (!resp.Title)
                    resp.Title = title ? title : win.document.title;
                handleRespone(resp, addHistory, oldLink);
            }
        };
    }

    var neighbourhood = {};
    neighbourhood[link] = [];
    var links = [link];
    function handleRespone(resp, addHistory, oldLink) {
        if (resp.RedirectLink) {
            win.location.href = resp.RedirectLink;
            return;
        }
        if (link !== oldLink)
            return;
        var backResp = {};
        backResp.Link = link;
        backResp.Title = win.document.title;
        backResp.Panels = {};
        for (var id in resp.Panels) {
            var panel = win.document.getElementById(id);
            backResp.Panels[id] = panel.innerHTML;
            panel.innerHTML = resp.Panels[id];
            var evt;
            if (typeof win.Event === 'function')
                evt = new win.Event('refreshajax');
            else {
                evt = win.document.createEvent('Event');
                evt.initEvent('refreshajax', false, false);
            }
            panel.dispatchEvent(evt);
        }
        cacheResponse(resp, backResp);
        var newLink = resp.Link;
        if (addHistory && link !== newLink)
            win.history.pushState(resp.Title, resp.Title, newLink);
        win.document.title = resp.Title;
        link = newLink;
    }

    function cacheResponse(resp, backResp) {
        var newLink = resp.Link;
        cache[link + '&' + newLink] = resp;
        cache[newLink + '&' + link] = backResp;
        if (links.indexOf(newLink) === -1) {
            neighbourhood[newLink] = [];
            links.push(newLink);
        }
        if (neighbourhood[link].indexOf(newLink) === -1) {
            neighbourhood[link].push(newLink);
            neighbourhood[newLink].push(link);
        }
    }

    win.addEventListener('popstate', function (e) {
        var newLink = win.location.pathname + win.location.search;
        if (link !== newLink) {
            var path = getShortestPath(link, newLink);
            if (path) {
                for (var i = 0; i < path.length - 1; i++) {
                    var resp = cache[path[i] + '&' + path[i + 1]];
                    handleRespone(resp, false, path[i]);
                }
            } else
                refreshAjax(newLink, false, null, e.state);
        }
    });

    function getShortestPath(fromLink, toLink) {
        var previous = {};
        var distances = {};
        var unlinks = [];
        var max = links.length;
        for (var i = 0; i < links.length; i++) {
            unlinks.push(links[i]);
            distances[links[i]] = max;
        }
        var distance = distances[fromLink] = 0;
        while (unlinks.length !== 0) {
            distance++;
            var link = unlinks.sort(function (x, y) {
                return distances[x] - distances[y]
            })[0];
            if (link === toLink) {
                var path = [];
                while (toLink) {
                    path.push(toLink);
                    toLink = previous[toLink];
                }
                return path.reverse();
            }
            var neighbours = neighbourhood[link];
            for (var i = 0; i < neighbours.length; i++) {
                var neighbour = neighbours[i];
                if (distances[neighbour] === max) {
                    distances[neighbour] = distance;
                    previous[neighbour] = link;
                }
            }
            unlinks.shift();
        }
        return null;
    }
})(window);<commit_msg>Don't cache A -> A because never use cache to return from A to A. It can't take part in the shortest route and is confusing to see in the cache and neighbourhood<commit_after>(function (win) {

    if (!(win.history && win.history.pushState))
        return;

    var submitData = {};
    win.document.addEventListener('click', function (e) {
        var element = e.target;
        var anchor = getAjaxTarget(element, 'A');
        if (!e.ctrlKey && !e.shiftKey && anchor) {
            e.preventDefault();
            refreshAjax(anchor.getAttribute('href'), true, anchor);
        }
        if (element.tagName === 'INPUT' && element.name) {
            if (element.type === 'submit')
                submitData[element.name] = element.value;
            if (element.type === 'image') {
                submitData[element.name + '.x'] = win.Math.max(0, e.offsetX);
                submitData[element.name + '.y'] = win.Math.max(0, e.offsetY);
            }
        }
    });

    win.document.addEventListener('submit', function (e) {
        var form = getAjaxTarget(e.target, 'FORM');
        if (form) {
            var req = new win.XMLHttpRequest();
            req.onreadystatechange = onReady(req, true);
            e.preventDefault();
            req.open('post', getAjaxLink(form.getAttribute('action'), form));
            req.setRequestHeader("Content-Type", "application/json");
            req.send(win.JSON.stringify(getFormData(form)));
        }
    });

    var tagNames = /^INPUT|TEXTAREA|SELECT$/;
    var ignoreTypes = /^button|image|submit|reset|file$/;
    var checkTypes = /^checkbox|radio$/;
    function getFormData(form) {
        var elements = form.elements;
        var data = {};
        for (var i = 0; i < elements.length; i++) {
            var element = elements[i];
            if (tagNames.test(element.tagName) && element.name
                && !ignoreTypes.test(element.type) && !element.disabled
                && (!checkTypes.test(element.type) || element.checked))
                data[element.name] = element.value;
        }
        for (var key in submitData)
            data[key] = submitData[key];
        submitData = {};
        return data;
    }

    function getAjaxTarget(element, tagName) {
        var target = null;
        while (element) {
            if (element.getAttribute) {
                var navigation = element.getAttribute('data-navigation');
                if (!target && element.tagName === tagName && navigation === 'refresh')
                    target = element;
                if (navigation === 'noajax')
                    return null;
            }
            element = element.parentNode;
        }
        return target;
    }

    var link = win.location.pathname + win.location.search;
    function refreshAjax(newLink, addHistory, target, title) {
        var req = new win.XMLHttpRequest();
        req.onreadystatechange = onReady(req, addHistory, title);
        req.open('get', getAjaxLink(newLink, target));
        req.send();
    }

    function getAjaxLink(baseLink, target) {
        baseLink += baseLink.indexOf('?') > 0 ? '&' : '?';
        baseLink += 'refreshajax=' + win.encodeURIComponent(link);
        baseLink += '&navigation=' + (target ? 'refresh' : 'history');
        if (target) {
            baseLink = setLinkData(target, baseLink, 'include-current');
            baseLink = setLinkData(target, baseLink, 'current-keys');
            baseLink = setLinkData(target, baseLink, 'to-keys');
        }
        return baseLink;
    }

    function setLinkData(target, link, name) {
        var value = target.getAttribute('data-' + name);
        if (value)
            link += '&' + name.replace('-','') + '=' + win.encodeURIComponent(value);
        return link;
    }

    var cache = {};
    function onReady(req, addHistory, title) {
        var oldLink = link;
        return function () {
            if (req.readyState === 4 && req.status === 200) {
                var resp = win.JSON.parse(req.responseText);
                if (!resp.Title)
                    resp.Title = title ? title : win.document.title;
                handleRespone(resp, addHistory, oldLink);
            }
        };
    }

    var neighbourhood = {};
    neighbourhood[link] = [];
    var links = [link];
    function handleRespone(resp, addHistory, oldLink) {
        if (resp.RedirectLink) {
            win.location.href = resp.RedirectLink;
            return;
        }
        if (link !== oldLink)
            return;
        var backResp = {};
        backResp.Link = link;
        backResp.Title = win.document.title;
        backResp.Panels = {};
        for (var id in resp.Panels) {
            var panel = win.document.getElementById(id);
            backResp.Panels[id] = panel.innerHTML;
            panel.innerHTML = resp.Panels[id];
            var evt;
            if (typeof win.Event === 'function')
                evt = new win.Event('refreshajax');
            else {
                evt = win.document.createEvent('Event');
                evt.initEvent('refreshajax', false, false);
            }
            panel.dispatchEvent(evt);
        }
        var newLink = resp.Link;
        if (link !== newLink) {
            cacheResponse(resp, backResp);
            if (addHistory)
                win.history.pushState(resp.Title, resp.Title, newLink);
        }
        win.document.title = resp.Title;
        link = newLink;
    }

    function cacheResponse(resp, backResp) {
        var newLink = resp.Link;
        cache[link + '&' + newLink] = resp;
        cache[newLink + '&' + link] = backResp;
        if (links.indexOf(newLink) === -1) {
            neighbourhood[newLink] = [];
            links.push(newLink);
        }
        if (neighbourhood[link].indexOf(newLink) === -1) {
            neighbourhood[link].push(newLink);
            neighbourhood[newLink].push(link);
        }
    }

    win.addEventListener('popstate', function (e) {
        var newLink = win.location.pathname + win.location.search;
        if (link !== newLink) {
            var path = getShortestPath(link, newLink);
            if (path) {
                for (var i = 0; i < path.length - 1; i++) {
                    var resp = cache[path[i] + '&' + path[i + 1]];
                    handleRespone(resp, false, path[i]);
                }
            } else
                refreshAjax(newLink, false, null, e.state);
        }
    });

    function getShortestPath(fromLink, toLink) {
        var previous = {};
        var distances = {};
        var unlinks = [];
        var max = links.length;
        for (var i = 0; i < links.length; i++) {
            unlinks.push(links[i]);
            distances[links[i]] = max;
        }
        var distance = distances[fromLink] = 0;
        while (unlinks.length !== 0) {
            distance++;
            var link = unlinks.sort(function (x, y) {
                return distances[x] - distances[y]
            })[0];
            if (link === toLink) {
                var path = [];
                while (toLink) {
                    path.push(toLink);
                    toLink = previous[toLink];
                }
                return path.reverse();
            }
            var neighbours = neighbourhood[link];
            for (var i = 0; i < neighbours.length; i++) {
                var neighbour = neighbours[i];
                if (distances[neighbour] === max) {
                    distances[neighbour] = distance;
                    previous[neighbour] = link;
                }
            }
            unlinks.shift();
        }
        return null;
    }
})(window);<|endoftext|>


<commit_before>(function (win) {

    if (!(win.history && win.history.pushState))
        return;

    win.document.addEventListener('click', function (e) {
        if (e.target.tagName && e.target.tagName == 'A') {
            e.preventDefault();
            refreshAjax(e.target.getAttribute('href'), true)
        }
    });

    win.addEventListener('popstate', function (e) {
        refreshAjax(win.location.pathname + win.location.search, false)
    });

    var link = win.location.pathname + win.location.search;
    function refreshAjax(newLink, addHistory)
    {
        var req = new XMLHttpRequest();
        req.onreadystatechange = function () {
            if (req.readyState == 4 && req.status == 200) {
                var panels = JSON.parse(req.responseText);
                for(var id in panels)
                    document.getElementById(id).innerHTML = panels[id];
                if (addHistory)
                    history.pushState(newLink, win.document.title, newLink);
                link = newLink;
            }
        };
        req.open('get', newLink, true);
        req.setRequestHeader('Navigation-Link', link);
        req.send();
    }

})(window);<commit_msg>Added call to unobtrusive validation for when there's a form inside new content. Note, BeginForm doesn't work inside template - need to investigate (manually creating form works)<commit_after>(function (win) {

    if (!(win.history && win.history.pushState))
        return;

    win.document.addEventListener('click', function (e) {
        if (e.target.tagName && e.target.tagName == 'A') {
            e.preventDefault();
            refreshAjax(e.target.getAttribute('href'), true)
        }
    });

    win.addEventListener('popstate', function (e) {
        refreshAjax(win.location.pathname + win.location.search, false)
    });

    var link = win.location.pathname + win.location.search;
    function refreshAjax(newLink, addHistory)
    {
        var req = new XMLHttpRequest();
        req.onreadystatechange = function () {
            if (req.readyState == 4 && req.status == 200) {
                var panels = JSON.parse(req.responseText);
                for (var id in panels) {
                    document.getElementById(id).innerHTML = panels[id];
                    if (win.jQuery && jQuery.validator)
                        jQuery.validator.unobtrusive.parse('#' + id);
                }
                if (addHistory)
                    history.pushState(newLink, win.document.title, newLink);
                link = newLink;
            }
        };
        req.open('get', newLink, true);
        req.setRequestHeader('Navigation-Link', link);
        req.send();
    }

})(window);<|endoftext|>


<commit_before>var hostProcess = process;
var hostRequire = require;

process.once('loaded', function(){
  electron = hostRequire('electron')

  global.host = {};

  ipc = electron.ipcRenderer;

  webFrame = hostRequire('electron').webFrame;
  webFrame.registerURLSchemeAsBypassingCSP("hax")
  webFrame.registerURLSchemeAsBypassingCSP("haxs")
  webFrame.registerURLSchemeAsBypassingCSP("localhax")
  webFrame.registerURLSchemeAsSecure("hax")
  webFrame.registerURLSchemeAsSecure("haxs")
  webFrame.registerURLSchemeAsSecure("localhax")

  global.host.zoom = {

    localStorageKey: "default-zoom",

    setZoom: function(zoom) {
      webFrame.setZoomFactor(zoom);
      localStorage.setItem(global.host.zoom.localStorageKey, zoom);
    },

    increase: function() {
      zoom = webFrame.getZoomFactor();
      global.host.zoom.setZoom(zoom + 0.1);
    },

    decrease: function() {
      zoom = webFrame.getZoomFactor();
      global.host.zoom.setZoom(zoom - 0.1);
    },

    reset: function() {
      global.host.zoom.setZoom(1);
    }
  }

  var defaultZoom = localStorage.getItem(global.host.zoom.localStorageKey);
  if (defaultZoom != null) {
    // set the default zoom that we saved previously
    global.host.zoom.setZoom(parseFloat(defaultZoom));
  }

  //TS.client.ui.active_highlight_count
  //TS.model.prefs.mac_ssb_bounce, "short" or "long"
  global.dock = {
    bounce: function() {
      var preference, type;
      preference = TS.model.prefs.mac_ssb_bounce;
      if (!(preference === "long" || preference === "short")) {
        return;
      }
      type = TS.model.prefs.mac_ssb_bounce === "short" ? "informational" : "critical";
      return ipc.send('bounce', {
        type: type
      });
    },

    badge: function(message) {
      return ipc.send('badge', {
        badge_text: message
      });
    }
  };

  global.reportLogin = function() {
    var team_name = TS.boot_data.team_url.match(/https:\/\/([^\.]+).slack.com/)[1]
    var icon_url
    if (TS.model.team.icon != null && TS.model.team.icon != "undefined") {
      icon_url = TS.model.team.icon.image_34
    } else {
      setTimeout(function() { window.reportLogin() }, 3000 );
    }
    ipc.sendToHost('login', {
      icon_url: icon_url,
      team_name: team_name
    });
  }
  global.ipc = ipc;

  const Menu = electron.remote.Menu;
  const MenuItem = electron.remote.MenuItem;
  const Clipboard = electron.remote.clipboard;

  var rightClickPosition, rightClickElement = null

  var regularMenu = new Menu();
  var linkMenu = new Menu();

  var copyLinkLocation = new MenuItem({ label: "Copy Link Location", click: function() {
    Clipboard.writeText(rightClickElement.href)
  }});
  var inspectElement = new MenuItem({ label: 'Inspect Element', click: function() {
    electron.remote.getCurrentWebContents().inspectElement(rightClickPosition.x, rightClickPosition.y);
  }});
  var inspectParentElement = new MenuItem({ label: 'Inspect Parent Element', click: function() {
    electron.remote.getCurrentWindow().inspectElement(rightClickPosition.x, rightClickPosition.y)
  }});
  var separator = new MenuItem({ type: 'separator' });

  regularMenu.append(inspectElement)
  regularMenu.append(separator)
  regularMenu.append(inspectParentElement)

  linkMenu.append(inspectElement)
  linkMenu.append(copyLinkLocation)
  linkMenu.append(separator)
  linkMenu.append(inspectParentElement)

  window.addEventListener('contextmenu', function (e) {
    e.preventDefault();
    rightClickPosition = {x: e.x, y: e.y}
    rightClickElement = e.srcElement || e.target;
    href = rightClickElement.href
    if (typeof href == "string") {
      linkMenu.popup(electron.remote.getCurrentWindow());
    } else {
      regularMenu.popup(electron.remote.getCurrentWindow());
    }
  }, false);
});
<commit_msg>Open external links from teams<commit_after>var hostProcess = process;
var hostRequire = require;

process.once('loaded', function(){
  electron = hostRequire('electron')
  shell = hostRequire('shell')
  electron.remote.getCurrentWebContents().on('new-window', function(e, url) {
    console.log("new window event for " + url);
    e.preventDefault();
    if (url.indexOf("http") != 0) {
      return;
    }
    shell.openExternal(url);
  });

  global.host = {};

  ipc = electron.ipcRenderer;

  webFrame = hostRequire('electron').webFrame;
  webFrame.registerURLSchemeAsBypassingCSP("hax")
  webFrame.registerURLSchemeAsBypassingCSP("haxs")
  webFrame.registerURLSchemeAsBypassingCSP("localhax")
  webFrame.registerURLSchemeAsSecure("hax")
  webFrame.registerURLSchemeAsSecure("haxs")
  webFrame.registerURLSchemeAsSecure("localhax")

  global.host.zoom = {

    localStorageKey: "default-zoom",

    setZoom: function(zoom) {
      webFrame.setZoomFactor(zoom);
      localStorage.setItem(global.host.zoom.localStorageKey, zoom);
    },

    increase: function() {
      zoom = webFrame.getZoomFactor();
      global.host.zoom.setZoom(zoom + 0.1);
    },

    decrease: function() {
      zoom = webFrame.getZoomFactor();
      global.host.zoom.setZoom(zoom - 0.1);
    },

    reset: function() {
      global.host.zoom.setZoom(1);
    }
  }

  var defaultZoom = localStorage.getItem(global.host.zoom.localStorageKey);
  if (defaultZoom != null) {
    // set the default zoom that we saved previously
    global.host.zoom.setZoom(parseFloat(defaultZoom));
  }

  //TS.client.ui.active_highlight_count
  //TS.model.prefs.mac_ssb_bounce, "short" or "long"
  global.dock = {
    bounce: function() {
      var preference, type;
      preference = TS.model.prefs.mac_ssb_bounce;
      if (!(preference === "long" || preference === "short")) {
        return;
      }
      type = TS.model.prefs.mac_ssb_bounce === "short" ? "informational" : "critical";
      return ipc.send('bounce', {
        type: type
      });
    },

    badge: function(message) {
      return ipc.send('badge', {
        badge_text: message
      });
    }
  };

  global.reportLogin = function() {
    var team_name = TS.boot_data.team_url.match(/https:\/\/([^\.]+).slack.com/)[1]
    var icon_url
    if (TS.model.team.icon != null && TS.model.team.icon != "undefined") {
      icon_url = TS.model.team.icon.image_34
    } else {
      setTimeout(function() { window.reportLogin() }, 3000 );
    }
    ipc.sendToHost('login', {
      icon_url: icon_url,
      team_name: team_name
    });
  }
  global.ipc = ipc;

  const Menu = electron.remote.Menu;
  const MenuItem = electron.remote.MenuItem;
  const Clipboard = electron.remote.clipboard;

  var rightClickPosition, rightClickElement = null

  var regularMenu = new Menu();
  var linkMenu = new Menu();

  var copyLinkLocation = new MenuItem({ label: "Copy Link Location", click: function() {
    Clipboard.writeText(rightClickElement.href)
  }});
  var inspectElement = new MenuItem({ label: 'Inspect Element', click: function() {
    electron.remote.getCurrentWebContents().inspectElement(rightClickPosition.x, rightClickPosition.y);
  }});
  var inspectParentElement = new MenuItem({ label: 'Inspect Parent Element', click: function() {
    electron.remote.getCurrentWindow().inspectElement(rightClickPosition.x, rightClickPosition.y)
  }});
  var separator = new MenuItem({ type: 'separator' });

  regularMenu.append(inspectElement)
  regularMenu.append(separator)
  regularMenu.append(inspectParentElement)

  linkMenu.append(inspectElement)
  linkMenu.append(copyLinkLocation)
  linkMenu.append(separator)
  linkMenu.append(inspectParentElement)

  window.addEventListener('contextmenu', function (e) {
    e.preventDefault();
    rightClickPosition = {x: e.x, y: e.y}
    rightClickElement = e.srcElement || e.target;
    href = rightClickElement.href
    if (typeof href == "string") {
      linkMenu.popup(electron.remote.getCurrentWindow());
    } else {
      regularMenu.popup(electron.remote.getCurrentWindow());
    }
  }, false);
});
<|endoftext|>