<commit_before>$(document).ready(function() {
    if ($('body.homepage').length) {
        var getOutputDomainFromWebsiteUrl = function (websiteUrl) {
            var outputDomain = websiteUrl.replace('http://', '').replace('https://', '')

            if (outputDomain.charAt(outputDomain.length - 1) == '/') {
                outputDomain = outputDomain.substr(0, outputDomain.length - 1);
            }

            return outputDomain;
        };

        var getTotalTaskCount = function (taskCountByState) {
            var totalTaskCount = 0;

            for (var stateName in taskCountByState) {
                if (taskCountByState.hasOwnProperty(stateName)) {
                    totalTaskCount += taskCountByState[stateName];
                }
            }

            return totalTaskCount;
        };

        var getQueuedTaskCount = function (taskCountByState) {
            var statesToCount = [
                'queued-for-assignment',
                'queued'
            ];

            var queuedTaskCount = 0;

            for (var stateIndex = 0; stateIndex < statesToCount.length; stateIndex++) {
                if (taskCountByState[statesToCount[stateIndex]] != undefined) {
                    queuedTaskCount += taskCountByState[statesToCount[stateIndex]];
                }
            }

            return queuedTaskCount;
        };

        var getFinishedTaskCount = function (taskCountByState) {
            return taskCountByState['completed'] + taskCountByState['cancelled'];
        };

        var getCompletionPercent = function (taskCountByState) {
            if (taskCountByState['completed'] == 0) {
                return 0;
            }

            var finishedTaskCount = taskCountByState['completed'] + taskCountByState['cancelled'];
            var totalTaskCount = getTotalTaskCount(taskCountByState);

            if (finishedTaskCount == totalTaskCount) {
                return 100;
            }

            return ((finishedTaskCount / totalTaskCount) * 100).toFixed(1);
        };

        var getStateIcon = function (state) {
            if (state == 'new') {
                return 'icon-off';
            }

            if (state == 'queued') {
                return 'icon-off';
            }

            if (state == 'preparing') {
                return 'icon-cog';
            }

            if (state == 'in-progress') {
                return 'icon-play-circle';
            }

            if (state == 'completed') {
                return 'icon-bar-chart';
            }

            if (state == 'cancelled') {
                return 'icon-bar-chart';
            }
        };

        var getStateLabelClass = function (state) {
            if (state == 'new') {
                return '';
            }

            if (state == 'queued') {
                return 'info';
            }

            if (state == 'preparing') {
                return 'warning';
            }

            if (state == 'in-progress') {
                return 'warning';
            }

            if (state == 'completed') {
                return 'success';
            }

            if (state == 'cancelled') {
                return 'success';
            }
        };

        var updateRecentTests = function (data) {
           var recentSiteTestsList = $('#recent-site-tests-list');
           recentSiteTestsList.html('');

            $(data).each(function () {

                var siteListItem = $('
').append(
                    $('
').append(
                        ''+getOutputDomainFromWebsiteUrl(this.website)+''
                    ).append(
                        $('
').append(
                            $('').append(
                                $('  #'+this.id+'  ')
                            )
                        )
                    ).append(
                        $('
').append(
                            $('
').append(
                                ''+getTotalTaskCount(this.task_count_by_state)+'tests overall'
                            )
                        ).append(
                            $('
').append(
                                ''+getCompletionPercent(this.task_count_by_state)+'%finished'
                            )
                        ).append(
                            $('
').append(
                                '
'+getQueuedTaskCount(this.task_count_by_state)+' queued
'
                            ).append(
                                '
'+this.task_count_by_state['in-progress']+' in progress
'
                            ).append(
                                '
'+getFinishedTaskCount(this.task_count_by_state)+' finished
'
                            )
                        )
                    )
                );

                recentSiteTestsList.append(siteListItem);
            });
        };

        var requestRecentTestData = function () {
            $.get('/core-application-proxy/?url=http://app.simplytestable.com/tests/list/3/', function(data) {
                updateRecentTests(data);
            }, "json");
        };

        $.get('/core-application-proxy/?url=http://app.simplytestable.com/tasks/HTML%20validation/completed/count/', function(data) {
            $('#html-validation-completed-count').text(data);
        }, "json");

        requestRecentTestData();

        window.setInterval(function () {
            requestRecentTestData();
        }, 1000);
    }

    $('body.homepage .carousel').carousel('pause');

    $('body.roadmap .timeline').each(function () {
        var futureEvents = [];
        var pastEvents = [];
        var currentEvents = [];
        var now = new Date();

        var isToday = function (eventTime) {
            if (eventTime.getDate() != now.getDate()) {
                return false;
            }

            if (eventTime.getMonth() != now.getMonth()) {
                return false;
            }

            if (eventTime.getFullYear() != now.getFullYear()) {
                return false;
            }

            return true;
        };

        var isFuture = function (eventTime) {
            return eventTime.getTime() > now.getTime();
        };

        var parseEventTimeParts = function (timeAttribute) {
            var monthPart = timeAttribute.substring(5, 7);
            if (monthPart.length == 2 && monthPart.substr(0, 1) == 0) {
                monthPart = monthPart.substr(1, 1);
            }

            var dayPart = timeAttribute.substring(8, 10);
            if (dayPart.length == 2 && dayPart.substr(0, 1) == 0) {
                dayPart = dayPart.substr(1, 1);
            }

            return {
                'year':parseInt(timeAttribute.substring(0, 4), 10),
                'month':parseInt(monthPart, 10) - 1,
                'day':parseInt(dayPart, 10)
            }
        };

        $('.event', this).each(function () {
            var event = $(this);
            var eventTimeParts = parseEventTimeParts($('time', event).attr('datetime'));
            var eventTime = new Date(eventTimeParts.year, eventTimeParts.month, eventTimeParts.day);

            if (isToday(eventTime)) {
                currentEvents.push(event);
                event.addClass('next');
            } else if (isFuture(eventTime)) {
                futureEvents.push(event);
                event.addClass('future');
            } else {
                pastEvents.push(event);
                event.addClass('past');
            }
        });

        if (currentEvents.length === 0) {
            if (futureEvents.length > 0) {
                futureEvents[futureEvents.length - 1].removeClass('future').addClass('next');
            } else if (pastEvents.length > 0) {
                pastEvents[0].removeClass('future').addClass('next');
            }
        }

        $('.next', this).each(function () {
            var event = $(this);
            var time = $('time', event);

            time.after('');
        });

        $('.past', this).each(function () {
            var event = $(this);
            var time = $('time', event);

            time.after('');
        });

        $('.future', this).each(function () {
            var event = $(this);
            var time = $('time', event);

            time.after('');
        });
    });

    getTwitters('footer-tweet', {
        id: 'simplytestable',
        count: 1,
        enableLinks: true,
        ignoreReplies: true,
        clearContents: true,
        template: '%text% %time%',
        callback: function () {
            $('.tweet-container .tweet').html($('#footer-tweet').html()).animate({
                'opacity':1
            });
        }
    });
});<commit_msg>Updated route for retrieving test list<commit_after>$(document).ready(function() {
    if ($('body.homepage').length) {
        var getOutputDomainFromWebsiteUrl = function (websiteUrl) {
            var outputDomain = websiteUrl.replace('http://', '').replace('https://', '')

            if (outputDomain.charAt(outputDomain.length - 1) == '/') {
                outputDomain = outputDomain.substr(0, outputDomain.length - 1);
            }

            return outputDomain;
        };

        var getTotalTaskCount = function (taskCountByState) {
            var totalTaskCount = 0;

            for (var stateName in taskCountByState) {
                if (taskCountByState.hasOwnProperty(stateName)) {
                    totalTaskCount += taskCountByState[stateName];
                }
            }

            return totalTaskCount;
        };

        var getQueuedTaskCount = function (taskCountByState) {
            var statesToCount = [
                'queued-for-assignment',
                'queued'
            ];

            var queuedTaskCount = 0;

            for (var stateIndex = 0; stateIndex < statesToCount.length; stateIndex++) {
                if (taskCountByState[statesToCount[stateIndex]] != undefined) {
                    queuedTaskCount += taskCountByState[statesToCount[stateIndex]];
                }
            }

            return queuedTaskCount;
        };

        var getFinishedTaskCount = function (taskCountByState) {
            return taskCountByState['completed'] + taskCountByState['cancelled'];
        };

        var getCompletionPercent = function (taskCountByState) {
            if (taskCountByState['completed'] == 0) {
                return 0;
            }

            var finishedTaskCount = taskCountByState['completed'] + taskCountByState['cancelled'];
            var totalTaskCount = getTotalTaskCount(taskCountByState);

            if (finishedTaskCount == totalTaskCount) {
                return 100;
            }

            return ((finishedTaskCount / totalTaskCount) * 100).toFixed(1);
        };

        var getStateIcon = function (state) {
            if (state == 'new') {
                return 'icon-off';
            }

            if (state == 'queued') {
                return 'icon-off';
            }

            if (state == 'preparing') {
                return 'icon-cog';
            }

            if (state == 'in-progress') {
                return 'icon-play-circle';
            }

            if (state == 'completed') {
                return 'icon-bar-chart';
            }

            if (state == 'cancelled') {
                return 'icon-bar-chart';
            }
        };

        var getStateLabelClass = function (state) {
            if (state == 'new') {
                return '';
            }

            if (state == 'queued') {
                return 'info';
            }

            if (state == 'preparing') {
                return 'warning';
            }

            if (state == 'in-progress') {
                return 'warning';
            }

            if (state == 'completed') {
                return 'success';
            }

            if (state == 'cancelled') {
                return 'success';
            }
        };

        var updateRecentTests = function (data) {
           var recentSiteTestsList = $('#recent-site-tests-list');
           recentSiteTestsList.html('');

            $(data).each(function () {

                var siteListItem = $('
').append(
                    $('
').append(
                        ''+getOutputDomainFromWebsiteUrl(this.website)+''
                    ).append(
                        $('
').append(
                            $('').append(
                                $('  #'+this.id+'  ')
                            )
                        )
                    ).append(
                        $('
').append(
                            $('
').append(
                                ''+getTotalTaskCount(this.task_count_by_state)+'tests overall'
                            )
                        ).append(
                            $('
').append(
                                ''+getCompletionPercent(this.task_count_by_state)+'%finished'
                            )
                        ).append(
                            $('
').append(
                                '
'+getQueuedTaskCount(this.task_count_by_state)+' queued
'
                            ).append(
                                '
'+this.task_count_by_state['in-progress']+' in progress
'
                            ).append(
                                '
'+getFinishedTaskCount(this.task_count_by_state)+' finished
'
                            )
                        )
                    )
                );

                recentSiteTestsList.append(siteListItem);
            });
        };

        var requestRecentTestData = function () {
            $.get('/core-application-proxy/?url=http://app.simplytestable.com/jobs/list/3/', function(data) {
                updateRecentTests(data);
            }, "json");
        };

        $.get('/core-application-proxy/?url=http://app.simplytestable.com/tasks/HTML%20validation/completed/count/', function(data) {
            $('#html-validation-completed-count').text(data);
        }, "json");

        requestRecentTestData();

        window.setInterval(function () {
            requestRecentTestData();
        }, 1000);
    }

    $('body.homepage .carousel').carousel('pause');

    $('body.roadmap .timeline').each(function () {
        var futureEvents = [];
        var pastEvents = [];
        var currentEvents = [];
        var now = new Date();

        var isToday = function (eventTime) {
            if (eventTime.getDate() != now.getDate()) {
                return false;
            }

            if (eventTime.getMonth() != now.getMonth()) {
                return false;
            }

            if (eventTime.getFullYear() != now.getFullYear()) {
                return false;
            }

            return true;
        };

        var isFuture = function (eventTime) {
            return eventTime.getTime() > now.getTime();
        };

        var parseEventTimeParts = function (timeAttribute) {
            var monthPart = timeAttribute.substring(5, 7);
            if (monthPart.length == 2 && monthPart.substr(0, 1) == 0) {
                monthPart = monthPart.substr(1, 1);
            }

            var dayPart = timeAttribute.substring(8, 10);
            if (dayPart.length == 2 && dayPart.substr(0, 1) == 0) {
                dayPart = dayPart.substr(1, 1);
            }

            return {
                'year':parseInt(timeAttribute.substring(0, 4), 10),
                'month':parseInt(monthPart, 10) - 1,
                'day':parseInt(dayPart, 10)
            }
        };

        $('.event', this).each(function () {
            var event = $(this);
            var eventTimeParts = parseEventTimeParts($('time', event).attr('datetime'));
            var eventTime = new Date(eventTimeParts.year, eventTimeParts.month, eventTimeParts.day);

            if (isToday(eventTime)) {
                currentEvents.push(event);
                event.addClass('next');
            } else if (isFuture(eventTime)) {
                futureEvents.push(event);
                event.addClass('future');
            } else {
                pastEvents.push(event);
                event.addClass('past');
            }
        });

        if (currentEvents.length === 0) {
            if (futureEvents.length > 0) {
                futureEvents[futureEvents.length - 1].removeClass('future').addClass('next');
            } else if (pastEvents.length > 0) {
                pastEvents[0].removeClass('future').addClass('next');
            }
        }

        $('.next', this).each(function () {
            var event = $(this);
            var time = $('time', event);

            time.after('');
        });

        $('.past', this).each(function () {
            var event = $(this);
            var time = $('time', event);

            time.after('');
        });

        $('.future', this).each(function () {
            var event = $(this);
            var time = $('time', event);

            time.after('');
        });
    });

    getTwitters('footer-tweet', {
        id: 'simplytestable',
        count: 1,
        enableLinks: true,
        ignoreReplies: true,
        clearContents: true,
        template: '%text% %time%',
        callback: function () {
            $('.tweet-container .tweet').html($('#footer-tweet').html()).animate({
                'opacity':1
            });
        }
    });
});<|endoftext|>


<commit_before>/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */
'use strict';

var React = require('react-native');
var moment = require('moment');

var {
  StyleSheet,
  Text,
  View,
  ListView
} = React;

var BuildsScreen = React.createClass({
  getInitialState: function() {
    return {
      loading: false,
      builds: new ListView.DataSource({
          rowHasChanged: (row1, row2) => row1 !== row2,
        }).cloneWithRows([])
    };
  },

  componentWillMount: function() {
    var self = this;
    fetch('https://api.travis-ci.org/repos/ekonstantinidis/gitify/builds', {
      headers: {
        'Accept': 'application/vnd.travis-ci.2+json'
      }
    })
      .then(function(response) {
        return response.json()
      }).then(function(json) {
        self.setState({
          loading: false,
          builds: self.state.builds.cloneWithRows(json.builds)
        });
      })
      .catch((error) => {
        console.warn(error);
      });
  },

  _renderBuildRow: function (rowData: string, sectionID: number, rowID: number) {
    var finishedDate = moment(rowData.finished_at).format("YYYY-MM-DD")

    return (
      <View style={styles.buildRow}>
        <View style={styles.buildStatus}>
          <Text>✔</Text>
          <Text>{rowData.number}</Text>
        </View>
        <View style={styles.buildInfo}>
          <Text>{rowData.id}</Text>
          <Text>{finishedDate}</Text>
          <Text>{rowData.state}</Text>
        </View>
      </View>
    );
  },

  render: function() {
    return (
      <ListView
        dataSource={this.state.builds}
        renderRow={this._renderBuildRow}
        style={styles.container} />
    );
  }
});

var styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F5FCFF'
  },
  buildRow: {
    flex: 1,
    flexDirection: 'row',
    padding: 0,
    marginBottom: 1
  },
  buildStatus: {
    flex: 0.1,
    padding: 10,
    backgroundColor: 'red',
    color: 'white'
  },
  buildInfo: {
    flex: 0.9,
    padding: 10
  }
});

module.exports = BuildsScreen;
<commit_msg>ActivityIndicatorIOS<commit_after>/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */
'use strict';

var React = require('react-native');
var moment = require('moment');

var {
  ActivityIndicatorIOS,
  StyleSheet,
  Text,
  View,
  ListView
} = React;

var BuildsScreen = React.createClass({
  getInitialState: function() {
    return {
      loading: false,
      builds: new ListView.DataSource({
          rowHasChanged: (row1, row2) => row1 !== row2,
        }).cloneWithRows([])
    };
  },

  componentWillMount: function() {
    var self = this;
    this.setState({
      loading: true
    });
    fetch('https://api.travis-ci.org/repos/ekonstantinidis/gitify/builds', {
      headers: {
        'Accept': 'application/vnd.travis-ci.2+json'
      }
    })
      .then(function(response) {
        return response.json()
      }).then(function(json) {
        self.setState({
          loading: false,
          builds: self.state.builds.cloneWithRows(json.builds)
        });
      })
      .catch((error) => {
        console.warn(error);
      });
  },

  _renderBuildRow: function (rowData: string, sectionID: number, rowID: number) {
    var finishedDate = moment(rowData.finished_at).format("YYYY-MM-DD")

    return (
      <View style={styles.buildRow}>
        <View style={styles.buildStatus}>
          <Text>✔</Text>
          <Text>{rowData.number}</Text>
        </View>
        <View style={styles.buildInfo}>
          <Text>{rowData.id}</Text>
          <Text>{finishedDate}</Text>
          <Text>{rowData.state}</Text>
        </View>
      </View>
    );
  },

  render: function() {
    var loading = this.state.loading ?
      ( <ActivityIndicatorIOS
          animating={this.state.loading}
          style={styles.loading}
          size="large" />) :
      ( <View/>);

    return (
      <View style={styles.container}>
        {loading}
        <ListView
          dataSource={this.state.builds}
          renderRow={this._renderBuildRow} />
      </View>
    );
  }
});

var styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F5FCFF'
  },
  loading: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center'
  },
  buildRow: {
    flex: 1,
    flexDirection: 'row',
    padding: 0,
    marginBottom: 1
  },
  buildStatus: {
    flex: 0.1,
    padding: 10,
    backgroundColor: 'red',
    color: 'white'
  },
  buildInfo: {
    flex: 0.9,
    padding: 10
  }
});

module.exports = BuildsScreen;
<|endoftext|>


<commit_before>/*!
 * Cookie Bar component (https://github.com/kovarp/jquery.cookieBar)
 * Version 1.0.0
 *
 * Copyright 2016 Pavel Kovář - Frontend developer [www.pavelkovar.cz]
 * Licensed under MIT (https://github.com/kovarp/jquery.cookieBar/blob/master/LICENSE)
 */
if("undefined"==typeof jQuery)throw new Error("Cookie Bar component requires jQuery");/**
 * ------------------------------------------------------------------------
 * Cookie Bar component
 * ------------------------------------------------------------------------
 */
!function(a){
// Global variables
var b,c,d=[];d.en={message:"To provide services we use cookies. By using this site you agree.",acceptText:"OK",infoText:"More information"},d.de={message:"Zur Bereitstellung von Diensten verwenden wir Cookies. Durch die Nutzung dieser Website stimmen Sie zu.",acceptText:"OK",infoText:"Mehr Informationen"},d.cs={message:"K poskytování služeb využíváme soubory cookie. Používáním tohoto webu s tím souhlasíte.",acceptText:"V pořádku",infoText:"Více informací"},d.sk={message:"Na poskytovanie služieb využívame súbory cookie. Používaním tohto webu s tým súhlasíte.",acceptText:"V poriadku",infoText:"Viac informácií"};var e={init:function(d){b="#cookie-bar";var f={infoLink:"https://www.google.com/policies/technologies/cookies/",infoTarget:"_blank",wrapper:"body",expireDays:365,style:"top",language:a("html").attr("lang")||"en"};c=a.extend(f,d),"accepted"!=e.getCookie("cookies-state")&&e.displayBar(),
// Accept cookies
a(document).on("click",b+" .cookie-bar__btn",function(a){a.preventDefault(),e.setCookie("cookies-state","accepted",c.expireDays),e.hideBar()})},displayBar:function(){
// Display Cookie Bar on page
var b='<button type="button" class="cookie-bar__btn">'+d[c.language].acceptText+"</button>",e=''+d[c.language].infoText+"",f='

'+d[c.language].message+''+b+e+"

";a(c.wrapper).prepend(f)},hideBar:function(){
// Hide Cookie Bar
a(b).slideUp()},addTranslation:function(a,b){d[a]=b},setCookie:function(a,b,c){
// Helpful method for set cookies
var d=new Date;d.setTime(d.getTime()+24*c*60*60*1e3);var e="expires="+d.toUTCString();document.cookie=a+"="+b+";"+e+";path=/"},getCookie:function(a){for(var b=a+"=",c=document.cookie.split(";"),d=0;d<c.length;d++){for(var e=c[d];" "==e.charAt(0);)e=e.substring(1);if(0==e.indexOf(b))return e.substring(b.length,e.length)}return""}};
// Create jQuery cookieBar function
a.cookieBar=function(b){return e[b]?e[b].apply(this,Array.prototype.slice.call(arguments,1)):"object"!=typeof b&&b?void a.error("Method "+b+" does not exist on Cookie Bar component"):e.init.apply(this,arguments)}}(jQuery);<commit_msg>EN translate update minify<commit_after>/*!
 * Cookie Bar component (https://github.com/kovarp/jquery.cookieBar)
 * Version 1.0.0
 *
 * Copyright 2016 Pavel Kovář - Frontend developer [www.pavelkovar.cz]
 * Licensed under MIT (https://github.com/kovarp/jquery.cookieBar/blob/master/LICENSE)
 */
if("undefined"==typeof jQuery)throw new Error("Cookie Bar component requires jQuery");/**
 * ------------------------------------------------------------------------
 * Cookie Bar component
 * ------------------------------------------------------------------------
 */
!function(a){
// Global variables
var b,c,d=[];d.en={message:"We use cookies to provide our services. By using this website, you agree to this.",acceptText:"OK",infoText:"More information"},d.de={message:"Zur Bereitstellung von Diensten verwenden wir Cookies. Durch die Nutzung dieser Website stimmen Sie zu.",acceptText:"OK",infoText:"Mehr Informationen"},d.cs={message:"K poskytování služeb využíváme soubory cookie. Používáním tohoto webu s tím souhlasíte.",acceptText:"V pořádku",infoText:"Více informací"},d.sk={message:"Na poskytovanie služieb využívame súbory cookie. Používaním tohto webu s tým súhlasíte.",acceptText:"V poriadku",infoText:"Viac informácií"};var e={init:function(d){b="#cookie-bar";var f={infoLink:"https://www.google.com/policies/technologies/cookies/",infoTarget:"_blank",wrapper:"body",expireDays:365,style:"top",language:a("html").attr("lang")||"en"};c=a.extend(f,d),"accepted"!=e.getCookie("cookies-state")&&e.displayBar(),
// Accept cookies
a(document).on("click",b+" .cookie-bar__btn",function(a){a.preventDefault(),e.setCookie("cookies-state","accepted",c.expireDays),e.hideBar()})},displayBar:function(){
// Display Cookie Bar on page
var b='<button type="button" class="cookie-bar__btn">'+d[c.language].acceptText+"</button>",e=''+d[c.language].infoText+"",f='

'+d[c.language].message+''+b+e+"

";a(c.wrapper).prepend(f)},hideBar:function(){
// Hide Cookie Bar
a(b).slideUp()},addTranslation:function(a,b){d[a]=b},setCookie:function(a,b,c){
// Helpful method for set cookies
var d=new Date;d.setTime(d.getTime()+24*c*60*60*1e3);var e="expires="+d.toUTCString();document.cookie=a+"="+b+";"+e+";path=/"},getCookie:function(a){for(var b=a+"=",c=document.cookie.split(";"),d=0;d<c.length;d++){for(var e=c[d];" "==e.charAt(0);)e=e.substring(1);if(0==e.indexOf(b))return e.substring(b.length,e.length)}return""}};
// Create jQuery cookieBar function
a.cookieBar=function(b){return e[b]?e[b].apply(this,Array.prototype.slice.call(arguments,1)):"object"!=typeof b&&b?void a.error("Method "+b+" does not exist on Cookie Bar component"):e.init.apply(this,arguments)}}(jQuery);<|endoftext|>


<commit_before>//
// ========================================================
// Copyright (c) 2012 Whamcloud, Inc.  All rights reserved.
// ========================================================

function uri_properties_link(resource_uri, label)
{
  if (resource_uri) {
    var url = resource_uri.replace("/api/", "/");
    return "" + label + ""
  } else {
    return ""
  }
}

function object_properties_link(object, label)
{
  if (!label) {
    label = LiveObject.label(object);
  }
  return uri_properties_link(object.resource_uri, label);
}

/* FIXME: if router callbacks throw an exception when called
 * as a result of Backbone.history.navigate({trigger:true}),
 * the exception isn't visible at the console, and the URL
 * just gets appended to window.location.href.  Is this a
 * backbone bug?  Should we override History to fix this?
 */
var ChromaRouter = Backbone.Router.extend({
  routes: {
    "configure/filesystem/detail/:id/": "filesystemDetail",
    "configure/filesystem/list/": "filesystemList",
    "configure/filesystem/create/": "filesystemCreate",
    "configure/:tab/": "configure",
    "configure/": "configureIndex",
    "dashboard/": "dashboard",
    "dashboard/:type/": "dashboard_type",
    "dashboard/filesystem/:filesystem_id/": "dashboard_filesystems",
    "dashboard/filesystem/:filesystem_id/target/:target_id/": "dashboard_filesystems",
    "dashboard/server/:server_id/": "dashboard_servers",
    "dashboard/server/:server_id/target/:target_id/": "dashboard_servers",
    "command/:id/": 'command_detail',
    "target/:id/": 'target_detail',
    "host/:id/": 'server_detail',
    "storage_resource/:id/": 'storage_resource_detail',
    "job/:id/": 'job_detail',
    "": "dashboard",
    "alert/": "alert",
    "event/": "event",
    "log/": "log",
    "about/": "about"
  },
  object_detail: function(id, model_class, view_class, title_attr)
  {
    var c = new model_class({id: id});
    c.fetch({success: function(model, response) {
      // Remove existing dialog if present, create a new one.
      var dialog_id = view_class.prototype.className + "_" + id;
      $('#' + dialog_id).remove();
      var mydiv = $("

");

      var title;
      if (title_attr){
        title = c.get(title_attr);
      } else {
        title = undefined;
      }
      mydiv.dialog({
        buttons: [{text: "Close", 'class': "close", click: function(){
          $(this).dialog('close');
        }}],
        close: function(event, ui) {
          window.history.back();
          $(this).remove();
        },
        width: 600,
        height: 600,
        modal: true,
        title: title
      });
      var cd = new view_class({model: c, el: mydiv.parent()});
      cd.render();
    }})
  },
  command_detail: function(id)
  {
    this.object_detail(id, Command, CommandDetail);
  },
  target_detail: function(id)
  {
    this.object_detail(id, Target, TargetDetail, 'label');
  },
  storage_resource_detail: function(id)
  {
    this.object_detail(id, StorageResource, StorageResourceDetail, 'class_name');
  },
  job_detail: function(id)
  {
    this.object_detail(id, Job, JobDetail, 'description');
  },
  server_detail: function(id)
  {
    this.object_detail(id, Server, ServerDetail, 'label');
  },
  alert: function()
  {
    this.toplevel('alert');
  },
  event: function()
  {
    this.toplevel('event');
  },
  log: function()
  {
    this.toplevel('log');
  },
  about:function () {
    this.toplevel('about');
  },
  failed_filesystem_admin_check: function() {
    if ( Login.userHasGroup('filesystem_administrator') )
      return false;
    this.navigate('dashboard/',{replace: true});
    this.dashboard();
    return true;
  },
  configureIndex: function()
  {
    if ( this.failed_filesystem_admin_check() )
      return;
    this.filesystemList();
  },
  toplevel: function(name)
  {
    $('div.toplevel').hide();
    $("#toplevel-" + name).show();

    $('a.navigation').removeClass('active');
    $("#" + name + "_menu").addClass('active');

    if (name == 'alert') {
      AlertView.draw();
    } else if (name == 'event') {
      EventView.draw();
    } else if (name == 'log') {
      LogView.draw();
    }

    // FIXME: generalise this once there is a global ChartManager
    if (name != 'dashboard') {
      Dashboard.stopCharts();
    }
  },
  configureTab: function(tab)
  {
    this.toplevel('configure');
    $("#tabs").tabs('select', '#' + tab + "-tab");
  },
  configure: function(tab) {
    if ( this.failed_filesystem_admin_check() )
      return;
    this.configureTab(tab);
    if (tab == 'filesystem') {
      this.filesystemList();
    } else if (tab == 'server') {
      ServerView.draw()
    } else if (tab == 'volume') {
      VolumeView.draw()
    } else if (tab == 'user') {
      UserView.draw()
    } else if (tab == 'storage') {
      StorageView.draw()
    } else if (tab == 'mgt') {
      MgtView.draw()
    }
  },
  filesystemPage: function(page) {
    this.configureTab('filesystem');
    $('#filesystem-tab-list').hide();
    $('#filesystem-tab-create').hide();
    $('#filesystem-tab-detail').hide();
    $('#filesystem-tab-' + page).show();
  },
  filesystemList: function() {
    if ( this.failed_filesystem_admin_check() )
      return;
    this.filesystemPage('list');
    FilesystemListView.draw()
  },
  filesystemDetail: function(id) {
    if ( this.failed_filesystem_admin_check() )
      return;
    this.filesystemPage('detail');
    FilesystemDetailView.draw(id)
  },
  filesystemCreate: function() {
    if ( this.failed_filesystem_admin_check() )
      return;
    this.filesystemPage('create');
    FilesystemCreateView.draw()
  },
  dashboard: function() {
    this.dashboard_type('filesystem');
  },
  dashboard_type: function(type) {
    this.toplevel('dashboard');
    Dashboard.setPath(type);
  },
  dashboard_servers: function(server_id, target_id) {
    this.toplevel('dashboard');
    Dashboard.setPath('server', server_id, target_id);
  },
  dashboard_filesystems: function(filesystem_id, target_id) {
    this.toplevel('dashboard');
    Dashboard.setPath('filesystem', filesystem_id, target_id);
  }
});
<commit_msg>HYD-1299 - Invalid Configure link for File System Admin User - permissions check was wrong filesystem_administrator -> filesystem_administrators<commit_after>//
// ========================================================
// Copyright (c) 2012 Whamcloud, Inc.  All rights reserved.
// ========================================================

function uri_properties_link(resource_uri, label)
{
  if (resource_uri) {
    var url = resource_uri.replace("/api/", "/");
    return "" + label + ""
  } else {
    return ""
  }
}

function object_properties_link(object, label)
{
  if (!label) {
    label = LiveObject.label(object);
  }
  return uri_properties_link(object.resource_uri, label);
}

/* FIXME: if router callbacks throw an exception when called
 * as a result of Backbone.history.navigate({trigger:true}),
 * the exception isn't visible at the console, and the URL
 * just gets appended to window.location.href.  Is this a
 * backbone bug?  Should we override History to fix this?
 */
var ChromaRouter = Backbone.Router.extend({
  routes: {
    "configure/filesystem/detail/:id/": "filesystemDetail",
    "configure/filesystem/list/": "filesystemList",
    "configure/filesystem/create/": "filesystemCreate",
    "configure/:tab/": "configure",
    "configure/": "configureIndex",
    "dashboard/": "dashboard",
    "dashboard/:type/": "dashboard_type",
    "dashboard/filesystem/:filesystem_id/": "dashboard_filesystems",
    "dashboard/filesystem/:filesystem_id/target/:target_id/": "dashboard_filesystems",
    "dashboard/server/:server_id/": "dashboard_servers",
    "dashboard/server/:server_id/target/:target_id/": "dashboard_servers",
    "command/:id/": 'command_detail',
    "target/:id/": 'target_detail',
    "host/:id/": 'server_detail',
    "storage_resource/:id/": 'storage_resource_detail',
    "job/:id/": 'job_detail',
    "": "dashboard",
    "alert/": "alert",
    "event/": "event",
    "log/": "log",
    "about/": "about"
  },
  object_detail: function(id, model_class, view_class, title_attr)
  {
    var c = new model_class({id: id});
    c.fetch({success: function(model, response) {
      // Remove existing dialog if present, create a new one.
      var dialog_id = view_class.prototype.className + "_" + id;
      $('#' + dialog_id).remove();
      var mydiv = $("

");

      var title;
      if (title_attr){
        title = c.get(title_attr);
      } else {
        title = undefined;
      }
      mydiv.dialog({
        buttons: [{text: "Close", 'class': "close", click: function(){
          $(this).dialog('close');
        }}],
        close: function(event, ui) {
          window.history.back();
          $(this).remove();
        },
        width: 600,
        height: 600,
        modal: true,
        title: title
      });
      var cd = new view_class({model: c, el: mydiv.parent()});
      cd.render();
    }})
  },
  command_detail: function(id)
  {
    this.object_detail(id, Command, CommandDetail);
  },
  target_detail: function(id)
  {
    this.object_detail(id, Target, TargetDetail, 'label');
  },
  storage_resource_detail: function(id)
  {
    this.object_detail(id, StorageResource, StorageResourceDetail, 'class_name');
  },
  job_detail: function(id)
  {
    this.object_detail(id, Job, JobDetail, 'description');
  },
  server_detail: function(id)
  {
    this.object_detail(id, Server, ServerDetail, 'label');
  },
  alert: function()
  {
    this.toplevel('alert');
  },
  event: function()
  {
    this.toplevel('event');
  },
  log: function()
  {
    this.toplevel('log');
  },
  about:function () {
    this.toplevel('about');
  },
  failed_filesystem_admin_check: function() {
    if ( Login.userHasGroup('filesystem_administrators') )
      return false;
    this.navigate('dashboard/',{replace: true});
    this.dashboard();
    return true;
  },
  configureIndex: function()
  {
    if ( this.failed_filesystem_admin_check() )
      return;
    this.filesystemList();
  },
  toplevel: function(name)
  {
    $('div.toplevel').hide();
    $("#toplevel-" + name).show();

    $('a.navigation').removeClass('active');
    $("#" + name + "_menu").addClass('active');

    if (name == 'alert') {
      AlertView.draw();
    } else if (name == 'event') {
      EventView.draw();
    } else if (name == 'log') {
      LogView.draw();
    }

    // FIXME: generalise this once there is a global ChartManager
    if (name != 'dashboard') {
      Dashboard.stopCharts();
    }
  },
  configureTab: function(tab)
  {
    this.toplevel('configure');
    $("#tabs").tabs('select', '#' + tab + "-tab");
  },
  configure: function(tab) {
    if ( this.failed_filesystem_admin_check() )
      return;
    this.configureTab(tab);
    if (tab == 'filesystem') {
      this.filesystemList();
    } else if (tab == 'server') {
      ServerView.draw()
    } else if (tab == 'volume') {
      VolumeView.draw()
    } else if (tab == 'user') {
      UserView.draw()
    } else if (tab == 'storage') {
      StorageView.draw()
    } else if (tab == 'mgt') {
      MgtView.draw()
    }
  },
  filesystemPage: function(page) {
    this.configureTab('filesystem');
    $('#filesystem-tab-list').hide();
    $('#filesystem-tab-create').hide();
    $('#filesystem-tab-detail').hide();
    $('#filesystem-tab-' + page).show();
  },
  filesystemList: function() {
    if ( this.failed_filesystem_admin_check() )
      return;
    this.filesystemPage('list');
    FilesystemListView.draw()
  },
  filesystemDetail: function(id) {
    if ( this.failed_filesystem_admin_check() )
      return;
    this.filesystemPage('detail');
    FilesystemDetailView.draw(id)
  },
  filesystemCreate: function() {
    if ( this.failed_filesystem_admin_check() )
      return;
    this.filesystemPage('create');
    FilesystemCreateView.draw()
  },
  dashboard: function() {
    this.dashboard_type('filesystem');
  },
  dashboard_type: function(type) {
    this.toplevel('dashboard');
    Dashboard.setPath(type);
  },
  dashboard_servers: function(server_id, target_id) {
    this.toplevel('dashboard');
    Dashboard.setPath('server', server_id, target_id);
  },
  dashboard_filesystems: function(filesystem_id, target_id) {
    this.toplevel('dashboard');
    Dashboard.setPath('filesystem', filesystem_id, target_id);
  }
});
<|endoftext|>


<commit_before>/*
 * Return the provided string with the first letter of each word capitalized. Make sure the rest of the word is in lower case.
 * For the purpose of this exercise, you should also capitalize connecting words like "the" and "of".
 */

 function titleCase(str) {
    var newTitle = str.split(' ');
    var updatedTitle = [];
    for (var st in newTitle) {
        updatedTitle[st] = newTitle[st].toLowerCase().replaceAt(0, newTitle[st].charAt(0).toUpperCase());
    }
    return updatedTitle.join(' ');
}

//test method
titleCase("I'm a little tea pot");
<commit_msg>Update titleCase.js<commit_after>/*
 * Return the provided string with the first letter of each word capitalized. Make sure the rest of the word is in lower case.
 * For the purpose of this exercise, you should also capitalize connecting words like "the" and "of".
 */

function titleCase(str) {
    var newTitle = str.split(' ');
    var updatedTitle = [];
    for (var st in newTitle) {
        updatedTitle[st] = newTitle[st].toLowerCase().replaceAt(0, newTitle[st].charAt(0).toUpperCase());
    }
    return updatedTitle.join(' ');
}

//test method
titleCase("I'm a little tea pot");
<|endoftext|>


<commit_before>var keystone = require('keystone'),
	async = require('async'),
	_ = require('underscore'),
	moment = require('moment');

exports = module.exports = function(req, res) {

	var data = {};

	async.series([
		function(next) {
			if (!req.body.user) return next();
			keystone.list('User').model.findById(req.body.user).exec(function(err, user) {
				if (err || !user) return res.apiResponse({ success: false });
				data.user = user;
				return next();
			});
		},
		function(next) {
			keystone.list('Meetup').model.findOne()
				.where('date').gte(moment().startOf('day').toDate())
				.where('state', 'active')
				.sort('date')
				.exec(function(err, meetup) {
					data.meetup = meetup;
					return next();
				});
		},
		function(next) {
			keystone.list('Talk').model.find()
				.where('meetup', data.meetup)
				.populate('who')
				.sort('sortOrder')
				.exec(function(err, talks) {
					data.talks = talks;
					return next();
				});
		},
		function(next) {
			if (!req.body.user) return next();
			keystone.list('RSVP').model.findOne()
				.where('who', data.user)
				.where('meetup', data.meetup)
				.exec(function(err, rsvp) {
					data.rsvp = rsvp;
					return next();
				});
		}
	], function(err) {
		var response = {
			success: true,
			meetup: false,
			user: false
		}
		// TODO: Would really help if meetups had an actual time field
		var day = moment(data.meetup.date).format('YYYY-MM-DD'),
			from = data.meetup ? _.first(data.meetup.time.split('-')).trim() : false,
			date = data.meetup ? moment(day + (from ? ' ' + from : ''), 'YYYY-MM-DD' + (from ? ' ha' : '')) : false;
		if (data.meetup && moment().isBefore(date)) {
			response.meetup = {
				id: data.meetup._id,

				name: data.meetup.name,

				date: date.toDate(),

				ticketsAvailable: data.meetup.rsvpsAvailable,
				ticketsRemaining: data.meetup.remainingRSVPs,

				talks: data.talks,

				rsvped: data.rsvp ? true : false,
				attending: data.rsvp && data.rsvp.attending ? true : false,
			}
		}
		if (data.user) {
			response.user = {
				date: new Date().getTime(),
				userId: data.user.id,
				name: {
					first: data.user.name.first,
					last: data.user.name.last,
					full: data.user.name.full
				},
				email: data.user.email,
				services: {
					github: {},
					facebook: {},
					twitter: {},
					pushNotifications: data.user.services.pushNotifications
				}
			}
		}
		res.apiResponse(response);
	});
}
<commit_msg>Adding place to meet up data.<commit_after>var keystone = require('keystone'),
	async = require('async'),
	_ = require('underscore'),
	moment = require('moment');

exports = module.exports = function(req, res) {

	var data = {};

	async.series([
		function(next) {
			if (!req.body.user) return next();
			keystone.list('User').model.findById(req.body.user).exec(function(err, user) {
				if (err || !user) return res.apiResponse({ success: false });
				data.user = user;
				return next();
			});
		},
		function(next) {
			keystone.list('Meetup').model.findOne()
				.where('date').gte(moment().startOf('day').toDate())
				.where('state', 'active')
				.sort('date')
				.exec(function(err, meetup) {
					data.meetup = meetup;
					return next();
				});
		},
		function(next) {
			keystone.list('Talk').model.find()
				.where('meetup', data.meetup)
				.populate('who')
				.sort('sortOrder')
				.exec(function(err, talks) {
					data.talks = talks;
					return next();
				});
		},
		function(next) {
			if (!req.body.user) return next();
			keystone.list('RSVP').model.findOne()
				.where('who', data.user)
				.where('meetup', data.meetup)
				.exec(function(err, rsvp) {
					data.rsvp = rsvp;
					return next();
				});
		}
	], function(err) {
		var response = {
			success: true,
			meetup: false,
			user: false
		}
		// TODO: Would really help if meetups had an actual time field
		var day = moment(data.meetup.date).format('YYYY-MM-DD'),
			from = data.meetup ? _.first(data.meetup.time.split('-')).trim() : false,
			date = data.meetup ? moment(day + (from ? ' ' + from : ''), 'YYYY-MM-DD' + (from ? ' ha' : '')) : false;
		if (data.meetup && moment().isBefore(date)) {
			response.meetup = {
				id: data.meetup._id,

				name: data.meetup.name,

				date: date.toDate(),

				place: data.meetup.place,

				ticketsAvailable: data.meetup.rsvpsAvailable,
				ticketsRemaining: data.meetup.remainingRSVPs,

				talks: data.talks,

				rsvped: data.rsvp ? true : false,
				attending: data.rsvp && data.rsvp.attending ? true : false,
			}
		}
		if (data.user) {
			response.user = {
				date: new Date().getTime(),
				userId: data.user.id,
				name: {
					first: data.user.name.first,
					last: data.user.name.last,
					full: data.user.name.full
				},
				email: data.user.email,
				services: {
					github: {},
					facebook: {},
					twitter: {},
					pushNotifications: data.user.services.pushNotifications
				}
			}
		}
		res.apiResponse(response);
	});
}
<|endoftext|>


<commit_before>const HTMLElement=(e=>{function t(){}return t.prototype=window.HTMLElement.prototype,t})();class TokenList{constructor(e){const t=e=>/{(\w+|#)}/.test(e.textContent)&&(e.text=e.textContent).match(/[^{]+(?=})/g).map(t=>(this[t]||(this[t]=[])).push(e)),n=document.createNodeIterator(e,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT,e=>e.attributes&&[].slice.call(e.attributes).map(t)||t(e),null);for(;n.nextNode(););}bind(e){const t=t=>n=>n.textContent=n.textContent.split("{"+t+"}").join(e[t]);for(let n in this)"bind"!=n&&this[n].map(e=>e.textContent=e.text);for(let n in this)"bind"!=n&&this[n].map(t(n))}}(e=>{function t(e){let t=new XMLHttpRequest;t.link=e,t.onload=n,t.open("GET",e.href),t.responseType="document",t.send()}function n(){let e=this.link,t=this.response,n=e.nextChild,o=e.content=t.querySelector("template");for(let s of document.querySelectorAll(e.id))o&&l.call(s,o);for(let l of t.querySelectorAll("style,link,script"))s(e,l,n)}function s(e,t,n){let s=t.getAttribute("as"),l=document.createElement("script"==s?s:t.localName);["id","rel","href","src","textContent","as","defer","crossOrigin"].map(e=>t[e]&&e in l&&(l[e]=t[e])),"style"==s&&(l.rel="stylesheet"),"script"==s&&(l.src=l.href),e.parentNode.insertBefore(l,n)}function l(e){let t;e=document.importNode(e,!0),[].slice.call(e.attributes).map(e=>!this.attributes[e.name]&&this.setAttribute(e.name,e.value));for(let n of this.querySelectorAll("[slot]"))(t=(e.content||e).querySelector("slot[name="+n.getAttribute("slot")+"]"))&&t.parentNode.replaceChild(n,t);return this.innerHTML=e.innerHTML}new MutationObserver(e=>{for(let n of e)for(let e of n.addedNodes)/^p/.test(e.rel)&&/\-/.test(e.id)&&t(e),/\-/.test(e.localName)&&(link=document.querySelector("#"+e.localName))&&link.content&&l.call(e,link.content)&&customElements.upgrade(e)}).observe(document.documentElement,{childList:!0,subtree:!0}),[].slice.call(document.querySelectorAll('[rel^=pre][id~="-"]')).map(t)})();const Template=e=>{let t=document.createRange();e="string"==typeof e?document.querySelector("template[name="+e+"]"):e,t.selectNodeContents(e.content);let n=t.cloneContents(),s=(e,t)=>{let s=n.cloneNode(!0);return"object"!=typeof e&&(e={self:e}),e["#"]=t,new TokenList(s).bind(e),s};return t.setStartAfter(e),e.bind=(e=>{t.deleteContents(),e&&[].concat(e).map(s).reverse().map(e=>t.insertNode(e))}),e};window.customElements=window.customElements||{},customElements.define=((e,t)=>{/\-/.test(e)&&(customElements[e]=t)&&[].slice.call(document.querySelectorAll(e)).map(customElements.upgrade)}),customElements.upgrade=function(e){Object.setPrototypeOf(e,customElements[e.localName].prototype),e.connectedCallback()},new MutationObserver(e=>{for(let t of e)for(let e of t.addedNodes)/\-/.test(e.localName)&&customElements[e.localName]&&customElements.upgrade(e)}).observe(document.documentElement,{childList:!0,subtree:!0});const ParentNode=e=>(class extends e{select(){return this.selectAll(...arguments)[0]}selectAll(e,...t){return e=[].concat(e),[].slice.call(this.querySelectorAll(t.reduce((t,n)=>t+n+e.shift(),e.shift())))}}),EventTarget=e=>(class extends e{on(e,t){this.addEventListener(e,this.renderable(t))}renderable(e){return t=>!1!==e.call(this,t)&&t.defaultPrevented||this.render()}reflect(t){/^on/.test(t)&&t in e.prototype&&this.on(t.substr(2),this[t])}register(e,t,n){for(let s of[].slice.call(e.attributes))/^on/.test(n=s.name)&&(t=(/{\s*(\w+)/.exec(e[n])||[])[1])&&(e[n]=this.renderable(this[t]))}}),GlobalEventHandlers=e=>(class extends e{onconnect(e){this.templates=this.selectAll("template[name]").map(Template),this.tokens=new TokenList(this),super.onconnect&&super.onconnect(e)}}),Custom=e=>(class extends(ParentNode(EventTarget(GlobalEventHandlers(e)))){connectedCallback(){this.context={},super.initialize&&super.initialize(),Object.getOwnPropertyNames(e.prototype).map(this.reflect,this),this.addEventListener("connect",this.onconnect),this.addEventListener("idle",super.onidle),this.dispatchEvent(new Event("connect")),this.render()}render(){for(let e of this.templates)e.bind(this[e.getAttribute("name")]);this.tokens.bind(this),this.register(this),this.selectAll("*").map(this.register,this),this.dispatchEvent(new Event("idle"))}}),Element=e=>t=>customElements.define(e+"",Custom(t));<commit_msg>:muscle: bump ??? distribution dist/snuggsi.min.es.js<commit_after>const HTMLElement=(e=>{function t(){}return t.prototype=window.HTMLElement.prototype,t})();class TokenList{constructor(e){const t=e=>/{(\w+|#)}/.test(e.textContent)&&(e.text=e.textContent).match(/[^{]+(?=})/g).map(t=>(this[t]||(this[t]=[])).push(e)),n=document.createNodeIterator(e,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT,e=>e.attributes&&[].slice.call(e.attributes).map(t)||t(e),null);for(;n.nextNode(););}bind(e){const t=t=>n=>n.textContent=n.textContent.split("{"+t+"}").join(e[t]);for(let n in this)"bind"!=n&&this[n].map(e=>e.textContent=e.text);for(let n in this)"bind"!=n&&this[n].map(t(n))}}(e=>{function t(e){let t=new XMLHttpRequest;t.link=e,t.onload=n,t.open("GET",e.href),t.responseType="document",t.send()}function n(){let e=this.link,t=this.response,n=e.nextChild,l=e.content=t.querySelector("template");for(let s of document.querySelectorAll(e.id))l&&o.call(s,l);for(let o of t.querySelectorAll("style,link,script"))s(e,o,n)}function s(e,t,n){let s=t.getAttribute("as"),o=document.createElement("script"==s?s:t.localName);["id","rel","href","src","textContent","as","defer","crossOrigin"].map(e=>t[e]&&e in o&&(o[e]=t[e])),"style"==s&&(o.rel="stylesheet"),"script"==s&&(o.src=o.href),e.parentNode.insertBefore(o,n)}function o(e){let t;e=document.importNode(e,!0),[].slice.call(e.attributes).map(e=>!this.attributes[e.name]&&this.setAttribute(e.name,e.value));for(let n of this.querySelectorAll("[slot]"))(t=(e.content||e).querySelector("slot[name="+n.getAttribute("slot")+"]"))&&t.parentNode.replaceChild(n,t);return this.innerHTML=e.innerHTML}new MutationObserver(e=>{for(let n of e)for(let e of n.addedNodes)/^p/.test(e.rel)&&/\-/.test(e.id)&&t(e),/\-/.test(e.localName)&&(link=document.querySelector("#"+e.localName))&&link.content&&o.call(e,link.content)&&customElements.upgrade(e)}).observe(document.documentElement,{childList:!0,subtree:!0}),[].slice.call(document.querySelectorAll('[rel^=pre][id~="-"]')).map(t)})();const Template=e=>{let t=document.createRange();e="string"==typeof e?document.querySelector("template[name="+e+"]"):e,t.selectNodeContents(e.content);let n=t.cloneContents(),s=(e,t)=>{let s=n.cloneNode(!0);return"object"!=typeof e&&(e={self:e}),e["#"]=t,new TokenList(s).bind(e),s};return t.setStartAfter(e),e.bind=(e=>{t.deleteContents(),e&&[].concat(e).map(s).reverse().map(e=>t.insertNode(e))}),e};function ParentNode(e){return class extends e{select(){return this.selectAll(...arguments)[0]}selectAll(e,...t){return e=[].concat(e),[].slice.call(this.querySelectorAll(t.reduce((t,n)=>t+n+e.shift(),e.shift())))}}}function EventTarget(e){return class extends e{on(e,t){this.addEventListener(e,this.renderable(t))}renderable(e){return t=>!1!==e.call(this,t)&&t.defaultPrevented||this.render()}reflect(t){/^on/.test(t)&&t in e.prototype&&this.on(t.substr(2),this[t])}register(e,t,n){for(let s of[].slice.call(e.attributes))/^on/.test(n=s.name)&&(t=(/{\s*(\w+)/.exec(e[n])||[])[1])&&(e[n]=this.renderable(this[t]))}}}function GlobalEventHandlers(e){return class extends e{onconnect(e){this.templates=this.selectAll("template[name]").map(Template),this.tokens=new TokenList(this),super.onconnect&&super.onconnect(e)}}}window.customElements=window.customElements||{},customElements.define=((e,t)=>{/\-/.test(e)&&(customElements[e]=t)&&[].slice.call(document.querySelectorAll(e)).map(customElements.upgrade)}),customElements.upgrade=function(e){Object.setPrototypeOf(e,customElements[e.localName].prototype),e.connectedCallback()},new MutationObserver(e=>{for(let t of e)for(let e of t.addedNodes)/\-/.test(e.localName)&&customElements[e.localName]&&customElements.upgrade(e)}).observe(document.documentElement,{childList:!0,subtree:!0});const Custom=e=>(class extends(ParentNode(EventTarget(GlobalEventHandlers(e)))){connectedCallback(){this.context={},super.initialize&&super.initialize(),Object.getOwnPropertyNames(e.prototype).map(this.reflect,this),this.addEventListener("connect",this.onconnect),this.addEventListener("idle",super.onidle),this.dispatchEvent(new Event("connect")),this.render()}render(){for(let e of this.templates)e.bind(this[e.getAttribute("name")]);this.tokens.bind(this),this.register(this),this.selectAll("*").map(this.register,this),this.dispatchEvent(new Event("idle"))}}),Element=e=>t=>customElements.define(e+"",Custom(t));<|endoftext|>


<commit_before>import React from "react";
import NativeList from "./NativeList";
import * as TYPES from "../middleware/constants.js";

export default function SingleList(props) {
	return (
		<NativeList
			{...props}
			component="SingleList"
			multipleSelect={false}
		/>
	);
}

SingleList.propTypes = {
	componentId: React.PropTypes.string.isRequired,
	dataField: React.PropTypes.string.isRequired,
	title: React.PropTypes.oneOfType([
		React.PropTypes.string,
		React.PropTypes.element
	]),
	defaultSelected: React.PropTypes.string,
	size: React.PropTypes.number,
	showCount: React.PropTypes.bool,
	sortBy: React.PropTypes.string,
	showSearch: React.PropTypes.bool,
	placeholder: React.PropTypes.string,
	customQuery: React.PropTypes.func,
	initialLoader: React.PropTypes.oneOfType([
		React.PropTypes.string,
		React.PropTypes.element
	]),
	react: React.PropTypes.object,
	componentStyle: React.PropTypes.object,
	showRadio: React.PropTypes.bool,
	URLParams: React.PropTypes.bool,
	showFilter: React.PropTypes.bool
};

// Default props value
SingleList.defaultProps = {
	showCount: true,
	sort: "count",
	size: 100,
	showSearch: false,
	title: null,
	placeholder: "Search",
	componentStyle: {},
	showRadio: true,
	URLParams: false
};

// context type
SingleList.contextTypes = {
	appbaseRef: React.PropTypes.any.isRequired,
	type: React.PropTypes.any.isRequired
};

SingleList.types = {
	componentId: TYPES.STRING,
	dataField: TYPES.STRING,
	dataFieldType: TYPES.KEYWORD,
	react: TYPES.OBJECT,
	title: TYPES.STRING,
	defaultSelected: TYPES.STRING,
	size: TYPES.NUMBER,
	sortBy: TYPES.STRING,
	showCount: TYPES.BOOLEAN,
	showSearch: TYPES.BOOLEAN,
	placeholder: TYPES.STRING,
	customQuery: TYPES.FUNCTION,
	initialLoader: TYPES.OBJECT,
	componentStyle: TYPES.OBJECT,
	URLParams: TYPES.BOOLEAN,
	showRadio: TYPES.BOOLEAN,
	showFilter: TYPES.BOOLEAN
};
<commit_msg>Add SingleList propTypes for #172<commit_after>import React from "react";
import NativeList from "./NativeList";
import * as TYPES from "../middleware/constants.js";

export default function SingleList(props) {
	return (
		<NativeList
			{...props}
			component="SingleList"
			multipleSelect={false}
		/>
	);
}

SingleList.propTypes = {
	componentId: React.PropTypes.string.isRequired,
	dataField: React.PropTypes.string.isRequired,
	title: React.PropTypes.oneOfType([
		React.PropTypes.string,
		React.PropTypes.element
	]),
	defaultSelected: React.PropTypes.string,
	size: React.PropTypes.number,
	showCount: React.PropTypes.bool,
	sortBy: React.PropTypes.string,
	showSearch: React.PropTypes.bool,
	placeholder: React.PropTypes.string,
	customQuery: React.PropTypes.func,
	initialLoader: React.PropTypes.oneOfType([
		React.PropTypes.string,
		React.PropTypes.element
	]),
	react: React.PropTypes.object,
	componentStyle: React.PropTypes.object,
	showRadio: React.PropTypes.bool,
	onQueryChange: React.PropTypes.func,
	URLParams: React.PropTypes.bool,
	showFilter: React.PropTypes.bool
};

// Default props value
SingleList.defaultProps = {
	showCount: true,
	sort: "count",
	size: 100,
	showSearch: false,
	title: null,
	placeholder: "Search",
	componentStyle: {},
	showRadio: true,
	URLParams: false
};

// context type
SingleList.contextTypes = {
	appbaseRef: React.PropTypes.any.isRequired,
	type: React.PropTypes.any.isRequired
};

SingleList.types = {
	componentId: TYPES.STRING,
	dataField: TYPES.STRING,
	dataFieldType: TYPES.KEYWORD,
	react: TYPES.OBJECT,
	title: TYPES.STRING,
	defaultSelected: TYPES.STRING,
	size: TYPES.NUMBER,
	sortBy: TYPES.STRING,
	showCount: TYPES.BOOLEAN,
	showSearch: TYPES.BOOLEAN,
	placeholder: TYPES.STRING,
	customQuery: TYPES.FUNCTION,
	initialLoader: TYPES.OBJECT,
	componentStyle: TYPES.OBJECT,
	URLParams: TYPES.BOOLEAN,
	showRadio: TYPES.BOOLEAN,
	onQueryChange: TYPES.FUNCTION,
	showFilter: TYPES.BOOLEAN
};
<|endoftext|>


<commit_before>var app = angular.module('Twitter', ['ngResource', 'ngSanitize']);

app.controller('TweetList', function($scope, $resource, $sce) {

    /**
     * change the date format with moment.js depending on how long ago it was
     **/
    function processTime (dateStr) {

      var twtDate = moment( new Date(dateStr) ),
      now = new Date();

      if (twtDate.diff(now, 'hours') > -24) {
        // less than 24 hours ago - how long ago was it posted?
        dateStr = twtDate.fromNow()
      } else {
        // more than 24 hours ago - just the date/time
        dateStr = twtDate.format('MMM D, YYYY h:mm a')
      }

      return dateStr;
    };

    /**
     * calculate image sizes so masonry can layout correctly
     **/
    function processPhotos (media) {

      var photos = [], IMAGE_WIDTH = 243, scale;

      if( angular.isDefined(media) ) {
        angular.forEach(media, function(mediaItem, key) {
          if( mediaItem.type == 'photo' ) {

            // the API return images sizes so we can no the image size without loading an image
            scale = IMAGE_WIDTH / mediaItem.sizes.small.w;

            photos.push({
              url: mediaItem.media_url + ':small',
              permalink: mediaItem.url,
              width: IMAGE_WIDTH,
              height: Math.floor(mediaItem.sizes.small.h * scale)
            });
          }
        });

        console.log(photos);
      }

      return photos;
    };

    /**
     * requests and processes tweet data
     **/
    function getTweets (paging) {

      var params = {
        action: 'user_timeline',
        user: $scope.username
      };

      if ($scope.maxId) {
        params.max_id = $scope.maxId;
      }

      // create tweet resource
      $scope.tweets = $resource('/tweets/:action/:user', params);

      // GET request using the resource
      $scope.tweets.query( { }, function (res) {

        if(!paging) {
          $scope.tweetsResult = [];
        }

        var tweetObj,
        i = 0, len = res.length;

        angular.forEach(res, function(tweet, key) {
          tweet.created_at = processTime(tweet.created_at);
          tweet.photos = processPhotos(tweet.entities.media);

          // add to model
          $scope.tweetsResult.push(tweet);
        });

        // for paging
        $scope.maxId = res[res.length - 1].id;

        setTimeout(function () {
          msnry.reloadItems();
          msnry.layout();
        }, 75);
      });
    }

    $scope.getTweets = function () {
      $scope.maxId = undefined;
      getTweets();
    };

    $scope.getMoreTweets = function () {
      getTweets(true);
    };

    // initiate masonry
    var msnry = new Masonry('#tweet-list', {
      columnWidth: 295,
      itemSelector: '.tweet-item',
      transitionDuration: 0,
      isFitWidth: true
    });

    msnry.bindResize(function () {
      console.log('resize');
    });

    // set a default username value
    $scope.username = "twoffice";

    // empty tweet model
    $scope.tweetsResult = [];

    getTweets();
})
.directive('tweetItem', function() {
  return {
    templateUrl: 'tweet-item.html'
  };
});<commit_msg>removng console log<commit_after>var app = angular.module('Twitter', ['ngResource', 'ngSanitize']);

app.controller('TweetList', function($scope, $resource, $sce) {

    /**
     * change the date format with moment.js depending on how long ago it was
     **/
    function processTime (dateStr) {

      var twtDate = moment( new Date(dateStr) ),
      now = new Date();

      if (twtDate.diff(now, 'hours') > -24) {
        // less than 24 hours ago - how long ago was it posted?
        dateStr = twtDate.fromNow()
      } else {
        // more than 24 hours ago - just the date/time
        dateStr = twtDate.format('MMM D, YYYY h:mm a')
      }

      return dateStr;
    };

    /**
     * calculate image sizes so masonry can layout correctly
     **/
    function processPhotos (media) {

      var photos = [], IMAGE_WIDTH = 243, scale;

      if( angular.isDefined(media) ) {
        angular.forEach(media, function(mediaItem, key) {
          if( mediaItem.type == 'photo' ) {

            // the API return images sizes so we can no the image size without loading an image
            scale = IMAGE_WIDTH / mediaItem.sizes.small.w;

            photos.push({
              url: mediaItem.media_url + ':small',
              permalink: mediaItem.url,
              width: IMAGE_WIDTH,
              height: Math.floor(mediaItem.sizes.small.h * scale)
            });
          }
        });
      }

      return photos;
    };

    /**
     * requests and processes tweet data
     **/
    function getTweets (paging) {

      var params = {
        action: 'user_timeline',
        user: $scope.username
      };

      if ($scope.maxId) {
        params.max_id = $scope.maxId;
      }

      // create tweet resource
      $scope.tweets = $resource('/tweets/:action/:user', params);

      // GET request using the resource
      $scope.tweets.query( { }, function (res) {

        if(!paging) {
          $scope.tweetsResult = [];
        }

        var tweetObj,
        i = 0, len = res.length;

        angular.forEach(res, function(tweet, key) {
          tweet.created_at = processTime(tweet.created_at);
          tweet.photos = processPhotos(tweet.entities.media);

          // add to model
          $scope.tweetsResult.push(tweet);
        });

        // for paging
        $scope.maxId = res[res.length - 1].id;

        setTimeout(function () {
          msnry.reloadItems();
          msnry.layout();
        }, 75);
      });
    }

    $scope.getTweets = function () {
      $scope.maxId = undefined;
      getTweets();
    };

    $scope.getMoreTweets = function () {
      getTweets(true);
    };

    // initiate masonry
    var msnry = new Masonry('#tweet-list', {
      columnWidth: 295,
      itemSelector: '.tweet-item',
      transitionDuration: 0,
      isFitWidth: true
    });

    msnry.bindResize(function () {
      console.log('resize');
    });

    // set a default username value
    $scope.username = "twoffice";

    // empty tweet model
    $scope.tweetsResult = [];

    getTweets();
})
.directive('tweetItem', function() {
  return {
    templateUrl: 'tweet-item.html'
  };
});<|endoftext|>


<commit_before>import React from 'react'
import {appFactory, notifier, errorLogging, actionEmitter, externalEvents} from 'tocco-util'

import reducers, {sagas} from './modules/reducers'
import EntityListContainer from './containers/EntityListContainer'
import {getDispatchActions} from './input'
const packageName = 'entity-list'

const EXTERNAL_EVENTS = [
  'onRowClick',
  'emitAction'
]

const initApp = (id, input, events, publicPath) => {
  const content = <EntityListContainer/>

  const store = appFactory.createStore(reducers, sagas, input, packageName)

  externalEvents.addToStore(store, events)
  actionEmitter.addToStore(store, events.emitAction)
  errorLogging.addToStore(store, false)
  notifier.addToStore(store, false)

  const actions = getDispatchActions(input)

  return appFactory.createApp(
    packageName,
    content,
    store,
    {
      input,
      events,
      actions,
      publicPath,
      textResourceModules: ['component', 'common']
    }
  )
}

(() => {
  if (__DEV__ && __PACKAGE_NAME__ === 'entity-list') {
    require('tocco-theme/src/ToccoTheme/theme.scss')
    const input = require('./dev/input.json')

    if (!__NO_MOCK__) {
      const fetchMock = require('fetch-mock')
      const setupFetchMocks = require('./dev/fetchMocks')
      setupFetchMocks(fetchMock)
      fetchMock.spy()
    }

    const app = initApp('id', input)

    if (module.hot) {
      module.hot.accept('./modules/reducers', () => {
        const reducers = require('./modules/reducers').default
        appFactory.hotReloadReducers(app.store, reducers)
      })
    }

    appFactory.renderApp(app.renderComponent())
  } else {
    appFactory.registerAppInRegistry(packageName, initApp)
  }
})()

class EntityListApp extends React.Component {
  constructor(props) {
    super(props)

    const events = EXTERNAL_EVENTS.reduce((events, event) => {
      if (props[event]) {
        events[event] = props[event]
      }
      return events
    }, {})

    this.app = initApp('id', props, events)
  }

  render() {
    return (

{this.app.renderComponent()}

    )
  }
}

EntityListApp.propTypes = {
  entityName: React.PropTypes.string.isRequired,
  formBase: React.PropTypes.string.isRequired,
  limit: React.PropTypes.number,
  showSearchForm: React.PropTypes.bool,
  searchFilters: React.PropTypes.arrayOf(React.PropTypes.string),
  preselectedSearchFields: React.PropTypes.arrayOf(
    React.PropTypes.shape({
      id: React.PropTypes.string,
      value: React.PropTypes.oneOfType([
        React.PropTypes.string,
        React.PropTypes.number,
        React.PropTypes.arrayOf(React.PropTypes.number),
        React.PropTypes.arrayOf(React.PropTypes.string)
      ]),
      hidden: React.PropTypes.bool
    })
  ),
  disableSimpleSearch: React.PropTypes.bool,
  simpleSearchFields: React.PropTypes.string,
  ...EXTERNAL_EVENTS.reduce((propTypes, event) => {
    propTypes[event] = React.PropTypes.func
    return propTypes
  }, {})
}

export default EntityListApp
<commit_msg>fix(entity-list): Avoid null pointer in mock environment (`events`)<commit_after>import React from 'react'
import {appFactory, notifier, errorLogging, actionEmitter, externalEvents} from 'tocco-util'

import reducers, {sagas} from './modules/reducers'
import EntityListContainer from './containers/EntityListContainer'
import {getDispatchActions} from './input'
const packageName = 'entity-list'

const EXTERNAL_EVENTS = [
  'onRowClick',
  'emitAction'
]

const initApp = (id, input, events = {}, publicPath) => {
  const content = <EntityListContainer/>

  const store = appFactory.createStore(reducers, sagas, input, packageName)

  externalEvents.addToStore(store, events)
  actionEmitter.addToStore(store, events.emitAction)
  errorLogging.addToStore(store, false)
  notifier.addToStore(store, false)

  const actions = getDispatchActions(input)

  return appFactory.createApp(
    packageName,
    content,
    store,
    {
      input,
      events,
      actions,
      publicPath,
      textResourceModules: ['component', 'common']
    }
  )
}

(() => {
  if (__DEV__ && __PACKAGE_NAME__ === 'entity-list') {
    require('tocco-theme/src/ToccoTheme/theme.scss')
    const input = require('./dev/input.json')

    if (!__NO_MOCK__) {
      const fetchMock = require('fetch-mock')
      const setupFetchMocks = require('./dev/fetchMocks')
      setupFetchMocks(fetchMock)
      fetchMock.spy()
    }

    const app = initApp('id', input)

    if (module.hot) {
      module.hot.accept('./modules/reducers', () => {
        const reducers = require('./modules/reducers').default
        appFactory.hotReloadReducers(app.store, reducers)
      })
    }

    appFactory.renderApp(app.renderComponent())
  } else {
    appFactory.registerAppInRegistry(packageName, initApp)
  }
})()

class EntityListApp extends React.Component {
  constructor(props) {
    super(props)

    const events = EXTERNAL_EVENTS.reduce((events, event) => {
      if (props[event]) {
        events[event] = props[event]
      }
      return events
    }, {})

    this.app = initApp('id', props, events)
  }

  render() {
    return (

{this.app.renderComponent()}

    )
  }
}

EntityListApp.propTypes = {
  entityName: React.PropTypes.string.isRequired,
  formBase: React.PropTypes.string.isRequired,
  limit: React.PropTypes.number,
  showSearchForm: React.PropTypes.bool,
  searchFilters: React.PropTypes.arrayOf(React.PropTypes.string),
  preselectedSearchFields: React.PropTypes.arrayOf(
    React.PropTypes.shape({
      id: React.PropTypes.string,
      value: React.PropTypes.oneOfType([
        React.PropTypes.string,
        React.PropTypes.number,
        React.PropTypes.arrayOf(React.PropTypes.number),
        React.PropTypes.arrayOf(React.PropTypes.string)
      ]),
      hidden: React.PropTypes.bool
    })
  ),
  disableSimpleSearch: React.PropTypes.bool,
  simpleSearchFields: React.PropTypes.string,
  ...EXTERNAL_EVENTS.reduce((propTypes, event) => {
    propTypes[event] = React.PropTypes.func
    return propTypes
  }, {})
}

export default EntityListApp
<|endoftext|>


<commit_before>/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */
'use strict';

var React = require('react-native');
var moment = require('moment');
require("moment-duration-format");

var {
  ActivityIndicatorIOS,
  StyleSheet,
  Text,
  View,
  ListView
} = React;

var BuildsScreen = React.createClass({
  displayName: 'BuildsScreen',

  getInitialState: function() {
    return {
      loading: false,
      builds: new ListView.DataSource({
          rowHasChanged: (row1, row2) => row1 !== row2,
        }).cloneWithRows([])
    };
  },

  componentWillMount: function() {
    var self = this;
    this.setState({
      loading: true
    });
    fetch('https://api.travis-ci.org/repos/ekonstantinidis/gitify/builds', {
      headers: {
        'Accept': 'application/vnd.travis-ci.2+json'
      }
    })
      .then(function(response) {
        return response.json()
      }).then(function(json) {
        self.setState({
          loading: false,
          builds: self.state.builds.cloneWithRows(json.builds)
        });
      })
      .catch((error) => {
        console.warn(error);
      });
  },

  _renderBuildRow: function (rowData: string, sectionID: number, rowID: number) {
    var finishedDate = moment(rowData.finished_at).fromNow();
    var duration = moment.duration(rowData.duration, "seconds").format("[Run for] m [minutes], s [seconds]");

    var stateClass;

    switch(rowData.state) {
      case "passed":
        stateClass = styles.statePassed;
        break;
      case "failed":
        stateClass = styles.stateFailed;
        break;
      default:
        stateClass = styles.stateErrored;
    }

    return (
      <View style={styles.buildRow}>
        <View style={[styles.buildStatus, stateClass]}>
          <Text style={styles.stateIcon}>✔</Text>
          <Text style={styles.buildType}>{rowData.pull_request}</Text>
        </View>
        <View style={styles.buildInfo}>
          <View style={{flexDirection: 'row'}}>
            <Text style={styles.buildNumber}>#{rowData.number}</Text>
            <Text style={styles.buildFinished}>{finishedDate}</Text>
          </View>
          <Text style={styles.buildDuration}>Run for {duration}</Text>
          <Text>{rowData.state}</Text>
        </View>
      </View>
    );
  },

  render: function() {
    var loading = this.state.loading ?
      ( <ActivityIndicatorIOS
          animating={this.state.loading}
          style={styles.loading}
          size="large" />) :
      ( <View/>);

    return (
      <View style={styles.container}>
        {loading}
        <ListView
          dataSource={this.state.builds}
          renderRow={this._renderBuildRow} />
      </View>
    );
  }
});

var styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F5FCFF'
  },
  loading: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center'
  },
  buildRow: {
    flex: 1,
    flexDirection: 'row',
    padding: 0,
    marginBottom: 1
  },
  buildStatus: {
    flex: 0.1,
    padding: 10
  },
  stateIcon: {
    fontSize: 20,
    textAlign: 'center',
    color: 'white'
  },

  buildType: {

  },
  buildInfo: {
    flex: 0.9,
    padding: 10
  },
  buildNumber: {
    flexDirection: 'column',
    flex: 0.2,
    fontWeight: 'bold'
  },
  buildFinished: {
    flexDirection: 'column',
    flex: 0.8,
  },
  buildDuration: {
  },
  statePassed: {
    backgroundColor: '#3FA75F'
  },
  stateFailed: {
    backgroundColor: '#DB423C'
  },
  stateErrored: {
    backgroundColor: '#A1A0A0'
  }
});

module.exports = BuildsScreen;
<commit_msg>Display commit message<commit_after>/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */
'use strict';

var React = require('react-native');
var _ = require('underscore');
var moment = require('moment');
require("moment-duration-format");

var {
  ActivityIndicatorIOS,
  StyleSheet,
  Text,
  View,
  ListView
} = React;

var BuildsScreen = React.createClass({
  displayName: 'BuildsScreen',

  getInitialState: function() {
    return {
      loading: false,
      builds: new ListView.DataSource({
          rowHasChanged: (row1, row2) => row1 !== row2,
        }).cloneWithRows([])
    };
  },

  componentWillMount: function() {
    var self = this;
    this.setState({
      loading: true
    });
    fetch('https://api.travis-ci.org/repos/ekonstantinidis/gitify/builds', {
      headers: {
        'Accept': 'application/vnd.travis-ci.2+json'
      }
    })
      .then(function(response) {
        return response.json()
      }).then(function(json) {
        var builds = json.builds;

        _.map(builds, function (obj) {
          var commit = _.find(json.commits, function(commit){
            return obj.commit_id == commit.id;
          });
          obj.commit = commit;
        });

        self.setState({
          loading: false,
          builds: self.state.builds.cloneWithRows(builds)
        });
      })
      .catch((error) => {
        console.warn(error);
      });
  },

  _renderBuildRow: function (rowData: string, sectionID: number, rowID: number) {
    var finishedDate = moment(rowData.finished_at).fromNow();
    var duration = moment.duration(rowData.duration, "seconds").format("[Run for] m [minutes], s [seconds]");

    var stateClass;

    switch(rowData.state) {
      case "passed":
        stateClass = styles.statePassed;
        break;
      case "failed":
        stateClass = styles.stateFailed;
        break;
      default:
        stateClass = styles.stateErrored;
    }

    return (
      <View style={styles.buildRow}>
        <View style={[styles.buildStatus, stateClass]}>
          <Text style={styles.stateIcon}>✔</Text>
          <Text style={styles.buildType}>{rowData.pull_request}</Text>
        </View>
        <View style={styles.buildInfo}>
          <View style={{flexDirection: 'row'}}>
            <Text style={styles.buildNumber}>#{rowData.number}</Text>
            <Text style={styles.buildFinished}>{finishedDate}</Text>
          </View>
          <Text style={styles.buildMessage} numberOfLines={1}>{rowData.commit.message}</Text>
          <Text style={styles.buildDuration}>Run for {duration}</Text>
        </View>
      </View>
    );
  },

  render: function() {
    var loading = this.state.loading ?
      ( <ActivityIndicatorIOS
          animating={this.state.loading}
          style={styles.loading}
          size="large" />) :
      ( <View/>);

    return (
      <View style={styles.container}>
        {loading}
        <ListView
          dataSource={this.state.builds}
          renderRow={this._renderBuildRow} />
      </View>
    );
  }
});

var styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F5FCFF'
  },
  loading: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center'
  },
  buildRow: {
    flex: 1,
    flexDirection: 'row',
    padding: 0,
    marginBottom: 1
  },
  buildStatus: {
    flex: 0.1,
    padding: 10
  },
  stateIcon: {
    fontSize: 20,
    textAlign: 'center',
    color: 'white'
  },
  buildMessage: {
    flex: 1
  },
  buildType: {

  },
  buildInfo: {
    flex: 0.9,
    padding: 10
  },
  buildNumber: {
    flexDirection: 'column',
    flex: 0.2,
    fontWeight: 'bold'
  },
  buildFinished: {
    flexDirection: 'column',
    flex: 0.8,
  },
  buildDuration: {
  },
  statePassed: {
    backgroundColor: '#3FA75F'
  },
  stateFailed: {
    backgroundColor: '#DB423C'
  },
  stateErrored: {
    backgroundColor: '#A1A0A0'
  }
});

module.exports = BuildsScreen;
<|endoftext|>