<commit_before>define('app/views/machine', ['app/views/mistscreen'],
    //
    //  Machine View
    //
    //  @returns Class
    //
    function(MistScreen) {

        'use strict';

        return MistScreen.extend({

            //
            //
            //  Properties
            //
            //

            rules: [],
            metrics: [],
            machine: null,

            //
            //
            //  Initialization
            //
            //

            load: function() {

                // Add Event listeners
                Mist.backendsController.on('onMachineListChange', this, 'load');
                Mist.metricsController.on('onMetricListChange', this, 'updateMetrics');

                Ember.run(this, function() {
                    this.updateCurrentMachine();
                    if (this.machine.id) {
                        this.updateUptime();
                        this.updateFooter();
                        this.updateMetrics();
                    }
                });
            }.on('didInsertElement'),

            unload: function() {

                // Remove event listeners
                Mist.backendsController.off('onMachineListChange', this, 'load');
                Mist.metricsController.off('onMetricListChange', this, 'updateMetrics');

                this.stopPolling();

            }.on('willDestroyElement'),

            //
            //
            //  Methods
            //
            //

            updateCurrentMachine: function() {
                Ember.run(this, function() {
                    var machine = Mist.backendsController.getRequestedMachine();
                    if (machine)
                        this.get('controller').set('model', machine);

                    this.set('machine', this.get('controller').get('model'));
                    if (this.machine.id)
                        this.machine.set('keysCount',
                            Mist.keysController.getMachineKeysCount(this.machine)
                        );
                });
            },

            updateFooter: function() {

                if (this.machine.can_tag)
                    $('#single-machine-tags-btn').removeClass('ui-state-disabled');
                else
                    $('#single-machine-tags-btn').addClass('ui-state-disabled');

                if (Mist.keysController.getMachineKeysCount(this.machine) && this.machine.state == 'running')
                    $('#single-machine-shell-btn').removeClass('ui-state-disabled');
                else
                    $('#single-machine-shell-btn').addClass('ui-state-disabled');

                if (this.machine.id)
                    $('#single-machine-power-btn').removeClass('ui-state-disabled');
                else
                    $('#single-machine-power-btn').addClass('ui-state-disabled');
            },

            updateKeysButton: function() {
                if (this.machine.state == 'running')
                    $('#mist-manage-keys').removeClass('ui-state-disabled');
                else
                    $('#mist-manage-keys').addClass('ui-state-disabled');
            },

            updateEnableButton: function() {
                Ember.run.next(this, function() {
                    if (this.machine.id && this.machine.state == 'running') {
                        $('#enable-monitor-btn').removeClass('ui-state-disabled');
                    } else {
                        $('#enable-monitor-btn').addClass('ui-state-disabled');
                    }
                });
            },

            updateMonitoringCollapsible: function() {
                Ember.run.next(this, function() {
                    if (Mist.backendsController.checkedMonitoring && this.machine.id) {
                        $('#monitoring-collapsible').show();
                    } else {
                        $('#monitoring-collapsible').hide();
                    }
                });
            },

            updateChangeMonitoringButton: function() {

                Ember.run.next(this, function() {
                    $('#enable-monitor-btn').addClass('ui-state-disabled');
                    if (this.machine.disablingMonitoring) {
                        $('#disable-monitor-btn').addClass('ui-state-disabled');
                    } else if (!this.machine.pendingMonitoring) {
                        $('#disable-monitor-btn').removeClass('ui-state-disabled');
                        if (!this.machine.enablingMonitoring)
                            $('#enable-monitor-btn').removeClass('ui-state-disabled');
                    }
                });
            },

            rulesObserver: function(){
                var rules = [];
                var machine = this.machine;

                if (!machine.equals)
                    return;

                Mist.rulesController.content.forEach(function(rule) {
                    if (machine.equals(rule.machine))
                        rules.push(rule);
                });
                this.set('rules', rules);
            }.observes('Mist.rulesController.@each', 'Mist.rulesController.@each.machine', 'machine'),

            updateMetrics: function () {

                var metrics = [];
                var machine = this.machine;

                if (!machine.id)
                    return;

                Mist.metricsController.customMetrics.forEach(function(metric) {
                    metric.machines.forEach(function(metricMachine) {
                        if (machine.equals(metricMachine))
                            metrics.push(metric);
                    });
                });
                Mist.metricsController.builtInMetrics.forEach(function(metric) {
                    metrics.push(metric);
                });

                this.set('metrics', metrics);

                Ember.run.next(function () {
                    if ($('#metrics-container').listview)
                        $('#metrics-container').listview()
                            .listview('refresh');
                });
            },

            stopPolling: function() {
                // if it polls for stats, stop it
                if ('context' in Mist)
                    Mist.context.stop();
            }.observes('controller.model.hasMonitoring'),

            updateUptime: function() {
                if ($('#single-machine-page').length) {

                    // Rescedule updateUptime
                    Ember.run.later(this, function() {
                        this.updateUptime();
                    }, 1000);

                    // Calculate uptime
                    var machine = this.machine;
                    if (!machine) return 0;
                    if (!machine.uptimeChecked) return 0;
                    if (!machine.uptimeFromServer) return 0;
                    machine.set('uptime', machine.uptimeFromServer + (Date.now() - machine.uptimeChecked));
                }
            },

            //
            //
            //  Actions
            //
            //

            actions: {

                manageKeysClicked: function() {
                    Mist.machineKeysController.open(this.machine);
                },

                addKeyClicked: function() {
                    Mist.machineKeysController.openKeyList(this.machine);
                },

                tagsClicked: function () {
                    Mist.machineTagsController.open(this.machine);
                },

                powerClicked: function () {
                    Mist.machinePowerController.open(this.machine);
                },

                shellClicked: function () {
                    Mist.machineShellController.open(this.machine);
                },

                addMetricClicked: function () {
                    Mist.metricAddController.open(this.machine);
                },

                deleteMetric: function (metric) {
                    Mist.metricsController.deleteMetric(metric);
                },

                enableMonitoringClicked: function () {

                    if (Mist.authenticated) {
                        if (Mist.current_plan) {
                            if (this.machine.probed) {
                                var machine = this.machine;
                                Mist.confirmationController.set('title', 'Enable monitoring');
                                Mist.confirmationController.set('text', 'Are you sure you want to enable monitoring for this machine?');
                                Mist.confirmationController.set('callback', function () {
                                    Mist.monitoringController.changeMonitoring(machine);
                                });
                                Mist.confirmationController.show();
                            } else {
                                Mist.machineManualMonitoringController.open(this.machine);
                            }
                        } else {
                            Mist.notificationController.set('msgHeader', 'No plan');
                            Mist.notificationController.set('msgPart1', 'In order to use our monitoring service' +
                                                                        ' you have to purchase a plan');
                            Mist.notificationController.set('msgPart2', 'You can do that in the Account page, which can ' +
                                                                        'be accessed from the menu button on the top right corner');
                            Mist.notificationController.showMessagebox();
                        }
                    } else {
                        Mist.loginController.open();
                    }
                },

                disableMonitoringClicked: function() {
                    var machine = this.machine;
                    Mist.confirmationController.set('title', 'Disable monitoring');
                    Mist.confirmationController.set('text', 'Are you sure you want to disable monitoring for this machine?');
                    Mist.confirmationController.set('callback', function () {
                        Mist.monitoringController.changeMonitoring(machine);
                    });
                    Mist.confirmationController.show();
                },

                addRuleClicked: function() {
                    var operator = {'title': 'gt', 'symbol': '>'};
                    Mist.rulesController.newRule(
                        this.machine,
                        Mist.metricsController.getMetric('load.shortterm'),
                        operator,
                        5,
                        'alert'
                    );
                },

                probeClicked: function() {
                    this.machine.probe(null, function(success) {
                        if (!success)
                            Mist.notificationController.notify('Failed to probe machine');
                    });
                },

                closeManualMonitoringPopup: function() {
                    $('#manual-monitoring-popup').popup('close');
                }
            },

            //
            //
            //  Computed Properties
            //
            //

            providerIconClass: function() {
                if (!this.machine || !this.machine.backend || !this.machine.backend.provider)
                    return '';
                return 'provider-' + this.machine.backend.getSimpleProvider();
            }.property('machine', 'machine.backend.provider'),

            imageIconClass: function () {

                if (!this.machine || !this.machine.extra ||
                    !this.machine.backend || !this.machine.backend.provider)
                    return 'image-generic';

                var imageId = this.machine.extra.image_id || this.machine.extra.imageId || '';

                // Use .toString() because digital ocean returns
                // an number instead of a string which breaks the search
                return 'image-' + this.machine.backend.images.getImageOS(imageId.toString());

            }.property('machine', 'machine.extra', 'machine.extra.@each'),

            upFor: function() {
                var ret = '';
                if (this.machine && this.machine.uptime) {
                    var x = Math.floor(this.machine.uptime / 1000);
                    var seconds = x % 60;
                    x = Math.floor(x / 60);
                    var minutes = x % 60;
                    x = Math.floor(x / 60);
                    var hours = x % 24;
                    x = Math.floor(x / 24);
                    var days = x;

                    if (days) ret = ret + days + ' days, ';
                    if (hours) ret = ret + hours + ' hours, ';
                    if (minutes) ret = ret + minutes + ' minutes, ';
                    if (seconds) {
                        ret = ret + seconds + ' seconds';
                    } else {
                        ret = ret + '0 seconds';
                    }
                }
                return ret;
            }.property('machine.uptime'),

            lastProbe: function(){
                var ret = 'never';
                if (this.machine && this.machine.uptimeChecked > 0) {
                    var x = (Date.now()-this.machine.uptimeChecked) / 1000;
                    var minutes = Math.floor(x / 60);
                    if (minutes > 1)
                        ret = minutes + ' minutes ago';
                    else if (minutes == 1)
                        ret = "1 minute ago";
                    else
                        ret = "just now";
                }
                return ret;
            }.property('machine.uptime'),

            basicInfo: function() {
                if (!this.machine) return;

                var basicInfo = {};

                if (this.machine.public_ips instanceof Array) {
                    this.set('public_ips', this.machine.public_ips);
                } else if (typeof this.machine.public_ips == 'string') {
                    this.set('public_ips', [this.machine.public_ips]);
                }

                if (this.machine.backend.provider != 'docker') {
                    if (this.machine.private_ips instanceof Array) {
                        this.set('private_ips', this.machine.private_ips);
                    } else if (typeof this.machine.public_ips == 'string') {
                        this.set('private_ips', [this.machine.private_ips]);
                    }
                }
                if (this.machine.extra) {
                    if (this.machine.backend.provider == 'docker') {
                        basicInfo['Image'] = this.machine.extra.image;
                        basicInfo['Status'] = this.machine.extra.status;
                        basicInfo['Command'] = this.machine.extra.command;
                    }
                    if (this.machine.extra.dns_name) {
                        basicInfo['DNS Name'] = this.machine.extra.dns_name;
                    }
                    if (this.machine.extra.launchdatetime) {
                        basicInfo['Launch Date'] = this.machine.extra.launchdatetime;
                    }
                }
                if (this.machine.image && this.machine.image.name) {
                    basicInfo.image = this.machine.image.name;
                }

                var ret = [];
                for (var item in basicInfo) {
                    if (typeof basicInfo[item] == 'string') {
                        ret.push({key:item, value: basicInfo[item]});
                    }
                }
                return ret;
            }.property('machine', 'machine.public_ips', 'machine.private_ips'),

            metadata: function() {
                if (!this.machine || !this.machine.extra) return;
                var ret = [];

                for (var item in this.machine.extra) {
                    var value = this.machine.extra[item];
                    if (typeof value == 'string' || typeof value == 'number') {
                        ret.push({key:item, value: value});
                    }
                }

                Ember.run.next(function() {
                    if ($('#single-machine-metadata').collapsible) {
                        $('#single-machine-metadata').collapsible();
                    }
                });
                return ret;

            }.property('machine', 'machine.extra'),

            //
            //
            //  Observers
            //
            //

            modelObserver: function() {
                Ember.run.once(this, 'load');
                Ember.run.once(this, 'updateEnableButton');
            }.observes('controller.model'),

            footerObserver: function() {
                Ember.run.once(this, 'updateFooter');
            }.observes('machine.probed', 'machine.can_tag'),

            stateObserver: function () {
                Ember.run.once(this, 'updateKeysButton');
                Ember.run.once(this, 'updateEnableButton');
            }.observes('machine.state'),

            changeMonitoringObserver: function() {
                Ember.run.once(this,  'updateChangeMonitoringButton');
            }.observes('machine.disablingMonitoring', 'machine.enablingMonitoring', 'machine.pendingMonitoring'),

            checkedMonitoringObserver: function() {
                Ember.run.once(this, 'updateMonitoringCollapsible');
            }.observes('Mist.backendsController.checkedMonitoring', 'machine')
        });
    }
);
<commit_msg>Alphabetically order machine metadata<commit_after>define('app/views/machine', ['app/views/mistscreen'],
    //
    //  Machine View
    //
    //  @returns Class
    //
    function(MistScreen) {

        'use strict';

        return MistScreen.extend({

            //
            //
            //  Properties
            //
            //

            rules: [],
            metrics: [],
            machine: null,

            //
            //
            //  Initialization
            //
            //

            load: function() {

                // Add Event listeners
                Mist.backendsController.on('onMachineListChange', this, 'load');
                Mist.metricsController.on('onMetricListChange', this, 'updateMetrics');

                Ember.run(this, function() {
                    this.updateCurrentMachine();
                    if (this.machine.id) {
                        this.updateUptime();
                        this.updateFooter();
                        this.updateMetrics();
                    }
                });
            }.on('didInsertElement'),

            unload: function() {

                // Remove event listeners
                Mist.backendsController.off('onMachineListChange', this, 'load');
                Mist.metricsController.off('onMetricListChange', this, 'updateMetrics');

                this.stopPolling();

            }.on('willDestroyElement'),

            //
            //
            //  Methods
            //
            //

            updateCurrentMachine: function() {
                Ember.run(this, function() {
                    var machine = Mist.backendsController.getRequestedMachine();
                    if (machine)
                        this.get('controller').set('model', machine);

                    this.set('machine', this.get('controller').get('model'));
                    if (this.machine.id)
                        this.machine.set('keysCount',
                            Mist.keysController.getMachineKeysCount(this.machine)
                        );
                });
            },

            updateFooter: function() {

                if (this.machine.can_tag)
                    $('#single-machine-tags-btn').removeClass('ui-state-disabled');
                else
                    $('#single-machine-tags-btn').addClass('ui-state-disabled');

                if (Mist.keysController.getMachineKeysCount(this.machine) && this.machine.state == 'running')
                    $('#single-machine-shell-btn').removeClass('ui-state-disabled');
                else
                    $('#single-machine-shell-btn').addClass('ui-state-disabled');

                if (this.machine.id)
                    $('#single-machine-power-btn').removeClass('ui-state-disabled');
                else
                    $('#single-machine-power-btn').addClass('ui-state-disabled');
            },

            updateKeysButton: function() {
                if (this.machine.state == 'running')
                    $('#mist-manage-keys').removeClass('ui-state-disabled');
                else
                    $('#mist-manage-keys').addClass('ui-state-disabled');
            },

            updateEnableButton: function() {
                Ember.run.next(this, function() {
                    if (this.machine.id && this.machine.state == 'running') {
                        $('#enable-monitor-btn').removeClass('ui-state-disabled');
                    } else {
                        $('#enable-monitor-btn').addClass('ui-state-disabled');
                    }
                });
            },

            updateMonitoringCollapsible: function() {
                Ember.run.next(this, function() {
                    if (Mist.backendsController.checkedMonitoring && this.machine.id) {
                        $('#monitoring-collapsible').show();
                    } else {
                        $('#monitoring-collapsible').hide();
                    }
                });
            },

            updateChangeMonitoringButton: function() {

                Ember.run.next(this, function() {
                    $('#enable-monitor-btn').addClass('ui-state-disabled');
                    if (this.machine.disablingMonitoring) {
                        $('#disable-monitor-btn').addClass('ui-state-disabled');
                    } else if (!this.machine.pendingMonitoring) {
                        $('#disable-monitor-btn').removeClass('ui-state-disabled');
                        if (!this.machine.enablingMonitoring)
                            $('#enable-monitor-btn').removeClass('ui-state-disabled');
                    }
                });
            },

            rulesObserver: function(){
                var rules = [];
                var machine = this.machine;

                if (!machine.equals)
                    return;

                Mist.rulesController.content.forEach(function(rule) {
                    if (machine.equals(rule.machine))
                        rules.push(rule);
                });
                this.set('rules', rules);
            }.observes('Mist.rulesController.@each', 'Mist.rulesController.@each.machine', 'machine'),

            updateMetrics: function () {

                var metrics = [];
                var machine = this.machine;

                if (!machine.id)
                    return;

                Mist.metricsController.customMetrics.forEach(function(metric) {
                    metric.machines.forEach(function(metricMachine) {
                        if (machine.equals(metricMachine))
                            metrics.push(metric);
                    });
                });
                Mist.metricsController.builtInMetrics.forEach(function(metric) {
                    metrics.push(metric);
                });

                this.set('metrics', metrics);

                Ember.run.next(function () {
                    if ($('#metrics-container').listview)
                        $('#metrics-container').listview()
                            .listview('refresh');
                });
            },

            stopPolling: function() {
                // if it polls for stats, stop it
                if ('context' in Mist)
                    Mist.context.stop();
            }.observes('controller.model.hasMonitoring'),

            updateUptime: function() {
                if ($('#single-machine-page').length) {

                    // Rescedule updateUptime
                    Ember.run.later(this, function() {
                        this.updateUptime();
                    }, 1000);

                    // Calculate uptime
                    var machine = this.machine;
                    if (!machine) return 0;
                    if (!machine.uptimeChecked) return 0;
                    if (!machine.uptimeFromServer) return 0;
                    machine.set('uptime', machine.uptimeFromServer + (Date.now() - machine.uptimeChecked));
                }
            },

            renderMetadata: function () {
                Ember.run.next(function() {
                    if ($('#single-machine-metadata').collapsible)
                        $('#single-machine-metadata').collapsible();
                });
            },

            //
            //
            //  Actions
            //
            //

            actions: {

                manageKeysClicked: function() {
                    Mist.machineKeysController.open(this.machine);
                },

                addKeyClicked: function() {
                    Mist.machineKeysController.openKeyList(this.machine);
                },

                tagsClicked: function () {
                    Mist.machineTagsController.open(this.machine);
                },

                powerClicked: function () {
                    Mist.machinePowerController.open(this.machine);
                },

                shellClicked: function () {
                    Mist.machineShellController.open(this.machine);
                },

                addMetricClicked: function () {
                    Mist.metricAddController.open(this.machine);
                },

                deleteMetric: function (metric) {
                    Mist.metricsController.deleteMetric(metric);
                },

                enableMonitoringClicked: function () {

                    if (Mist.authenticated) {
                        if (Mist.current_plan) {
                            if (this.machine.probed) {
                                var machine = this.machine;
                                Mist.confirmationController.set('title', 'Enable monitoring');
                                Mist.confirmationController.set('text', 'Are you sure you want to enable monitoring for this machine?');
                                Mist.confirmationController.set('callback', function () {
                                    Mist.monitoringController.changeMonitoring(machine);
                                });
                                Mist.confirmationController.show();
                            } else {
                                Mist.machineManualMonitoringController.open(this.machine);
                            }
                        } else {
                            Mist.notificationController.set('msgHeader', 'No plan');
                            Mist.notificationController.set('msgPart1', 'In order to use our monitoring service' +
                                                                        ' you have to purchase a plan');
                            Mist.notificationController.set('msgPart2', 'You can do that in the Account page, which can ' +
                                                                        'be accessed from the menu button on the top right corner');
                            Mist.notificationController.showMessagebox();
                        }
                    } else {
                        Mist.loginController.open();
                    }
                },

                disableMonitoringClicked: function() {
                    var machine = this.machine;
                    Mist.confirmationController.set('title', 'Disable monitoring');
                    Mist.confirmationController.set('text', 'Are you sure you want to disable monitoring for this machine?');
                    Mist.confirmationController.set('callback', function () {
                        Mist.monitoringController.changeMonitoring(machine);
                    });
                    Mist.confirmationController.show();
                },

                addRuleClicked: function() {
                    var operator = {'title': 'gt', 'symbol': '>'};
                    Mist.rulesController.newRule(
                        this.machine,
                        Mist.metricsController.getMetric('load.shortterm'),
                        operator,
                        5,
                        'alert'
                    );
                },

                probeClicked: function() {
                    this.machine.probe(null, function(success) {
                        if (!success)
                            Mist.notificationController.notify('Failed to probe machine');
                    });
                },

                closeManualMonitoringPopup: function() {
                    $('#manual-monitoring-popup').popup('close');
                }
            },

            //
            //
            //  Computed Properties
            //
            //

            providerIconClass: function() {
                if (!this.machine || !this.machine.backend || !this.machine.backend.provider)
                    return '';
                return 'provider-' + this.machine.backend.getSimpleProvider();
            }.property('machine', 'machine.backend.provider'),

            imageIconClass: function () {

                if (!this.machine || !this.machine.extra ||
                    !this.machine.backend || !this.machine.backend.provider)
                    return 'image-generic';

                var imageId = this.machine.extra.image_id || this.machine.extra.imageId || '';

                // Use .toString() because digital ocean returns
                // an number instead of a string which breaks the search
                return 'image-' + this.machine.backend.images.getImageOS(imageId.toString());

            }.property('machine', 'machine.extra', 'machine.extra.@each'),

            upFor: function() {
                var ret = '';
                if (this.machine && this.machine.uptime) {
                    var x = Math.floor(this.machine.uptime / 1000);
                    var seconds = x % 60;
                    x = Math.floor(x / 60);
                    var minutes = x % 60;
                    x = Math.floor(x / 60);
                    var hours = x % 24;
                    x = Math.floor(x / 24);
                    var days = x;

                    if (days) ret = ret + days + ' days, ';
                    if (hours) ret = ret + hours + ' hours, ';
                    if (minutes) ret = ret + minutes + ' minutes, ';
                    if (seconds) {
                        ret = ret + seconds + ' seconds';
                    } else {
                        ret = ret + '0 seconds';
                    }
                }
                return ret;
            }.property('machine.uptime'),

            lastProbe: function(){
                var ret = 'never';
                if (this.machine && this.machine.uptimeChecked > 0) {
                    var x = (Date.now()-this.machine.uptimeChecked) / 1000;
                    var minutes = Math.floor(x / 60);
                    if (minutes > 1)
                        ret = minutes + ' minutes ago';
                    else if (minutes == 1)
                        ret = "1 minute ago";
                    else
                        ret = "just now";
                }
                return ret;
            }.property('machine.uptime'),

            basicInfo: function() {
                if (!this.machine) return;

                var basicInfo = {};

                if (this.machine.public_ips instanceof Array) {
                    this.set('public_ips', this.machine.public_ips);
                } else if (typeof this.machine.public_ips == 'string') {
                    this.set('public_ips', [this.machine.public_ips]);
                }

                if (this.machine.backend.provider != 'docker') {
                    if (this.machine.private_ips instanceof Array) {
                        this.set('private_ips', this.machine.private_ips);
                    } else if (typeof this.machine.public_ips == 'string') {
                        this.set('private_ips', [this.machine.private_ips]);
                    }
                }
                if (this.machine.extra) {
                    if (this.machine.backend.provider == 'docker') {
                        basicInfo['Image'] = this.machine.extra.image;
                        basicInfo['Status'] = this.machine.extra.status;
                        basicInfo['Command'] = this.machine.extra.command;
                    }
                    if (this.machine.extra.dns_name) {
                        basicInfo['DNS Name'] = this.machine.extra.dns_name;
                    }
                    if (this.machine.extra.launchdatetime) {
                        basicInfo['Launch Date'] = this.machine.extra.launchdatetime;
                    }
                }
                if (this.machine.image && this.machine.image.name) {
                    basicInfo.image = this.machine.image.name;
                }

                var ret = [];
                forIn(basicInfo, function (value, key) {
                    if (typeof value == 'string')
                        ret.push({key:key, value: value});
                });

                sortInfo(ret);
                return ret;

            }.property('machine', 'machine.public_ips', 'machine.private_ips'),

            metadata: function() {

                if (!this.machine || !this.machine.extra) return;

                var ret = [];
                forIn(this.machine.extra, function (value, key) {
                    if (typeof value == 'string' || typeof value == 'number')
                        ret.push({key:key, value: value});
                });

                this.renderMetadata();
                sortInfo(ret);
                return ret;

            }.property('machine', 'machine.extra'),

            //
            //
            //  Observers
            //
            //

            modelObserver: function() {
                Ember.run.once(this, 'load');
                Ember.run.once(this, 'updateEnableButton');
            }.observes('controller.model'),

            footerObserver: function() {
                Ember.run.once(this, 'updateFooter');
            }.observes('machine.probed', 'machine.can_tag'),

            stateObserver: function () {
                Ember.run.once(this, 'updateKeysButton');
                Ember.run.once(this, 'updateEnableButton');
            }.observes('machine.state'),

            changeMonitoringObserver: function() {
                Ember.run.once(this,  'updateChangeMonitoringButton');
            }.observes('machine.disablingMonitoring', 'machine.enablingMonitoring', 'machine.pendingMonitoring'),

            checkedMonitoringObserver: function() {
                Ember.run.once(this, 'updateMonitoringCollapsible');
            }.observes('Mist.backendsController.checkedMonitoring', 'machine')
        });

        function sortInfo (array) {
            array.sort(function (a, b) {
                if (a.key > b.key) return 1;
                if (b.key < a.key) return -1;
                return 0;
            });
        }
    }
);
<|endoftext|>


<commit_before>// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

goog.provide('goog.ui.acTest');
goog.setTestOnly('goog.ui.acTest');

goog.require('goog.array');
goog.require('goog.asserts');
goog.require('goog.dom');
goog.require('goog.dom.NodeType');
goog.require('goog.dom.classlist');
goog.require('goog.dom.selection');
goog.require('goog.events');
goog.require('goog.events.BrowserEvent');
goog.require('goog.events.Event');
goog.require('goog.events.EventType');
goog.require('goog.events.KeyCodes');
goog.require('goog.style');
goog.require('goog.testing.MockClock');
goog.require('goog.testing.jsunit');
goog.require('goog.ui.ac');
goog.require('goog.userAgent');
var autocomplete;
var data = ['ab', 'aab', 'aaab'];
var input;
var mockClock;

function setUpPage() {
  goog.ui.ac.createSimpleAutoComplete(
      data, goog.dom.getElement('user'), true, false);
}

function setUp() {
  mockClock = new goog.testing.MockClock(true);
  input = goog.dom.getElement('input');
  input.value = '';
  autocomplete = goog.ui.ac.createSimpleAutoComplete(data, input, true, false);
}

function tearDown() {
  autocomplete.dispose();
  mockClock.dispose();
}

//=========================================================================
// Utility methods

/**
 * Fire listeners of a given type that are listening to the event's
 * currentTarget.
 *
 * @param {goog.events.BrowserEvent} event
 */
function simulateEvent(event) {
  goog.events.fireListeners(event.currentTarget, event.type, true, event);
  goog.events.fireListeners(event.currentTarget, event.type, false, event);
}

/**
 * Fire all key event listeners that are listening to the input element.
 *
 * @param {number} keyCode The key code.
 */
function simulateAllKeyEventsOnInput(keyCode) {
  var eventTypes = [
    goog.events.EventType.KEYDOWN, goog.events.EventType.KEYPRESS,
    goog.events.EventType.KEYUP
  ];

  goog.array.forEach(eventTypes, function(type) {
    var event = new goog.events.Event(type, input);
    event.keyCode = keyCode;
    simulateEvent(new goog.events.BrowserEvent(event, input));
  });
}

/**
 * @param {string} text
 * @return {Node} Node whose inner text maches the given text.
 */
function findNodeByInnerText(text) {
  return goog.dom.findNode(document.body, function(node) {
    try {
      var display = goog.userAgent.IE ?
          goog.style.getCascadedStyle(node, 'display') :
          goog.style.getComputedStyle(node, 'display');

      return goog.dom.getRawTextContent(node) == text && 'none' != display &&
          node.nodeType == goog.dom.NodeType.ELEMENT;
    } catch (e) {
      return false;
    }
  });
}

//=========================================================================
// Tests

/**
 * Ensure that the display of the autocompleter works.
 */
function testBasicDisplay() {
  simulateAllKeyEventsOnInput(goog.events.KeyCodes.DOWN);

  input.value = 'a';
  simulateAllKeyEventsOnInput(goog.events.KeyCodes.A);
  mockClock.tick(500);

  var nodes = [
    findNodeByInnerText(data[0]), findNodeByInnerText(data[1]),
    findNodeByInnerText(data[2])
  ];
  assert(!!nodes[0]);
  assert(!!nodes[1]);
  assert(!!nodes[2]);
  assert(goog.style.isUnselectable(nodes[0]));
  assert(goog.style.isUnselectable(nodes[1]));
  assert(goog.style.isUnselectable(nodes[2]));

  input.value = 'aa';
  simulateAllKeyEventsOnInput(goog.events.KeyCodes.A);
  mockClock.tick(500);

  assertFalse(!!findNodeByInnerText(data[0]));
  assert(!!findNodeByInnerText(data[1]));
  assert(!!findNodeByInnerText(data[2]));
}

/**
 * Ensure that key navigation with multiple inputs work
 */
function testKeyNavigation() {
  simulateAllKeyEventsOnInput(goog.events.KeyCodes.DOWN);

  input.value = 'c, a';
  goog.dom.selection.setCursorPosition(input, 'c, a'.length);
  simulateAllKeyEventsOnInput(goog.events.KeyCodes.A);
  mockClock.tick(500);

  assert(document.body.innerHTML, !!findNodeByInnerText(data[1]));
  assert(!!findNodeByInnerText(data[2]));

  var selected = goog.asserts.assertElement(findNodeByInnerText(data[0]));
  assertTrue(
      'Should have new standard active class',
      goog.dom.classlist.contains(selected, 'ac-active'));
  assertTrue(
      'Should have legacy active class',
      goog.dom.classlist.contains(selected, 'active'));

  simulateAllKeyEventsOnInput(goog.events.KeyCodes.DOWN);
  assertFalse(
      goog.dom.classlist.contains(
          goog.asserts.assertElement(findNodeByInnerText(data[0])),
          'ac-active'));
  assert(
      goog.dom.classlist.contains(
          goog.asserts.assertElement(findNodeByInnerText(data[1])),
          'ac-active'));

  simulateAllKeyEventsOnInput(goog.events.KeyCodes.ENTER);
  assertEquals('c, aab, ', input.value);
}

/**
 * Ensure that mouse navigation with multiple inputs works.
 */
function testMouseNavigation() {
  simulateAllKeyEventsOnInput(goog.events.KeyCodes.DOWN);

  input.value = 'c, a';
  goog.dom.selection.setCursorPosition(input, 'c, a'.length);
  simulateAllKeyEventsOnInput(goog.events.KeyCodes.A);
  mockClock.tick(500);

  var secondOption = goog.asserts.assertElement(findNodeByInnerText(data[1]));
  var parent = secondOption.parentNode;
  assertFalse(goog.dom.classlist.contains(secondOption, 'ac-active'));

  var mouseOver =
      new goog.events.Event(goog.events.EventType.MOUSEOVER, secondOption);
  simulateEvent(new goog.events.BrowserEvent(mouseOver, parent));
  assert(goog.dom.classlist.contains(secondOption, 'ac-active'));

  var mouseDown =
      new goog.events.Event(goog.events.EventType.MOUSEDOWN, secondOption);
  simulateEvent(new goog.events.BrowserEvent(mouseDown, parent));
  var mouseClick =
      new goog.events.Event(goog.events.EventType.CLICK, secondOption);
  simulateEvent(new goog.events.BrowserEvent(mouseClick, parent));

  assertEquals('c, aab, ', input.value);
}
<commit_msg>Update ac_test to use goog.testing.events.fireKeySequence rather than always firing KEYDOWN -> KEYPRESS -> KEYUP. This makes the test only consider sequences that browsers actually fire (eg. not all keys fire KEYPRESS, which fireKeySequence checks for).<commit_after>// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

goog.provide('goog.ui.acTest');
goog.setTestOnly('goog.ui.acTest');

goog.require('goog.asserts');
goog.require('goog.dom');
goog.require('goog.dom.NodeType');
goog.require('goog.dom.classlist');
goog.require('goog.dom.selection');
goog.require('goog.events');
goog.require('goog.events.BrowserEvent');
goog.require('goog.events.Event');
goog.require('goog.events.EventType');
goog.require('goog.events.KeyCodes');
goog.require('goog.style');
goog.require('goog.testing.MockClock');
goog.require('goog.testing.events');
goog.require('goog.testing.jsunit');
goog.require('goog.ui.ac');
goog.require('goog.userAgent');
var autocomplete;
var data = ['ab', 'aab', 'aaab'];
var input;
var mockClock;

function setUpPage() {
  goog.ui.ac.createSimpleAutoComplete(
      data, goog.dom.getElement('user'), true, false);
}

function setUp() {
  mockClock = new goog.testing.MockClock(true);
  input = goog.dom.getElement('input');
  input.value = '';
  autocomplete = goog.ui.ac.createSimpleAutoComplete(data, input, true, false);
}

function tearDown() {
  autocomplete.dispose();
  mockClock.dispose();
}

//=========================================================================
// Utility methods

/**
 * Fire listeners of a given type that are listening to the event's
 * currentTarget.
 *
 * @param {goog.events.BrowserEvent} event
 */
function simulateEvent(event) {
  goog.events.fireListeners(event.currentTarget, event.type, true, event);
  goog.events.fireListeners(event.currentTarget, event.type, false, event);
}

/**
 * Fire all key event listeners that are listening to the input element.
 *
 * @param {number} keyCode The key code.
 */
function simulateAllKeyEventsOnInput(keyCode) {
  goog.testing.events.fireKeySequence(input, keyCode);
}

/**
 * @param {string} text
 * @return {Node} Node whose inner text maches the given text.
 */
function findNodeByInnerText(text) {
  return goog.dom.findNode(document.body, function(node) {
    try {
      var display = goog.userAgent.IE ?
          goog.style.getCascadedStyle(node, 'display') :
          goog.style.getComputedStyle(node, 'display');

      return goog.dom.getRawTextContent(node) == text && 'none' != display &&
          node.nodeType == goog.dom.NodeType.ELEMENT;
    } catch (e) {
      return false;
    }
  });
}

//=========================================================================
// Tests

/**
 * Ensure that the display of the autocompleter works.
 */
function testBasicDisplay() {
  simulateAllKeyEventsOnInput(goog.events.KeyCodes.DOWN);

  input.value = 'a';
  simulateAllKeyEventsOnInput(goog.events.KeyCodes.A);
  mockClock.tick(500);

  var nodes = [
    findNodeByInnerText(data[0]), findNodeByInnerText(data[1]),
    findNodeByInnerText(data[2])
  ];
  assert(!!nodes[0]);
  assert(!!nodes[1]);
  assert(!!nodes[2]);
  assert(goog.style.isUnselectable(nodes[0]));
  assert(goog.style.isUnselectable(nodes[1]));
  assert(goog.style.isUnselectable(nodes[2]));

  input.value = 'aa';
  simulateAllKeyEventsOnInput(goog.events.KeyCodes.A);
  mockClock.tick(500);

  assertFalse(!!findNodeByInnerText(data[0]));
  assert(!!findNodeByInnerText(data[1]));
  assert(!!findNodeByInnerText(data[2]));
}

/**
 * Ensure that key navigation with multiple inputs work
 */
function testKeyNavigation() {
  simulateAllKeyEventsOnInput(goog.events.KeyCodes.DOWN);

  input.value = 'c, a';
  goog.dom.selection.setCursorPosition(input, 'c, a'.length);
  simulateAllKeyEventsOnInput(goog.events.KeyCodes.A);
  mockClock.tick(500);

  assert(document.body.innerHTML, !!findNodeByInnerText(data[1]));
  assert(!!findNodeByInnerText(data[2]));

  var selected = goog.asserts.assertElement(findNodeByInnerText(data[0]));
  assertTrue(
      'Should have new standard active class',
      goog.dom.classlist.contains(selected, 'ac-active'));
  assertTrue(
      'Should have legacy active class',
      goog.dom.classlist.contains(selected, 'active'));

  simulateAllKeyEventsOnInput(goog.events.KeyCodes.DOWN);
  assertFalse(
      goog.dom.classlist.contains(
          goog.asserts.assertElement(findNodeByInnerText(data[0])),
          'ac-active'));
  assert(
      goog.dom.classlist.contains(
          goog.asserts.assertElement(findNodeByInnerText(data[1])),
          'ac-active'));

  simulateAllKeyEventsOnInput(goog.events.KeyCodes.ENTER);
  assertEquals('c, aab, ', input.value);
}

/**
 * Ensure that mouse navigation with multiple inputs works.
 */
function testMouseNavigation() {
  simulateAllKeyEventsOnInput(goog.events.KeyCodes.DOWN);

  input.value = 'c, a';
  goog.dom.selection.setCursorPosition(input, 'c, a'.length);
  simulateAllKeyEventsOnInput(goog.events.KeyCodes.A);
  mockClock.tick(500);

  var secondOption = goog.asserts.assertElement(findNodeByInnerText(data[1]));
  var parent = secondOption.parentNode;
  assertFalse(goog.dom.classlist.contains(secondOption, 'ac-active'));

  var mouseOver =
      new goog.events.Event(goog.events.EventType.MOUSEOVER, secondOption);
  simulateEvent(new goog.events.BrowserEvent(mouseOver, parent));
  assert(goog.dom.classlist.contains(secondOption, 'ac-active'));

  var mouseDown =
      new goog.events.Event(goog.events.EventType.MOUSEDOWN, secondOption);
  simulateEvent(new goog.events.BrowserEvent(mouseDown, parent));
  var mouseClick =
      new goog.events.Event(goog.events.EventType.CLICK, secondOption);
  simulateEvent(new goog.events.BrowserEvent(mouseClick, parent));

  assertEquals('c, aab, ', input.value);
}
<|endoftext|>


<commit_before>// Copyright 2006 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Utilities for window manipulation.
 */

goog.provide('goog.window');

goog.require('goog.string');
goog.require('goog.userAgent');

/**
 * Default height for popup windows
 * @type {number}
 */
goog.window.DEFAULT_POPUP_HEIGHT = 500;

/**
 * Default width for popup windows
 * @type {number}
 */
goog.window.DEFAULT_POPUP_WIDTH = 690;

/**
 * Default target for popup windows
 * @type {string}
 */
goog.window.DEFAULT_POPUP_TARGET = 'google_popup';

/**
 * Opens a new window.
 *
 * @param {string|Object} linkRef A string or an object that supports toString,
 *     for example goog.Uri.  If this is an object with a 'href' attribute, such
 *     as HTMLAnchorElement, it will be used instead.
 *
 * @param {Object=} opt_options supports the following options:
 *  'target': (string) target (window name). If null, linkRef.target will
 *          be used.
 *  'width': (number) window width.
 *  'height': (number) window height.
 *  'top': (number) distance from top of screen
 *  'left': (number) distance from left of screen
 *  'toolbar': (boolean) show toolbar
 *  'scrollbars': (boolean) show scrollbars
 *  'location': (boolean) show location
 *  'statusbar': (boolean) show statusbar
 *  'menubar': (boolean) show menubar
 *  'resizable': (boolean) resizable
 *  'noreferrer': (boolean) whether to attempt to remove the referrer header
 *      from the request headers. Does this by opening a blank window that
 *      then redirects to the target url, so users may see some flickering.
 *
 * @param {Window=} opt_parentWin Parent window that should be used to open the
 *                 new window.
 *
 * @return {Window} Returns the window object that was opened. This returns
 *                  null if a popup blocker prevented the window from being
 *                  opened.
 */
goog.window.open = function(linkRef, opt_options, opt_parentWin) {
  if (!opt_options) {
    opt_options = {};
  }
  var parentWin = opt_parentWin || window;

  // HTMLAnchorElement has a toString() method with the same behavior as
  // goog.Uri in all browsers except for Safari, which returns
  // '[object HTMLAnchorElement]'.  We check for the href first, then
  // assume that it's a goog.Uri or String otherwise.
  var href = typeof linkRef.href != 'undefined' ? linkRef.href :
      String(linkRef);
  var target = opt_options.target || linkRef.target;

  var sb = [];
  for (var option in opt_options) {
    switch (option) {
      case 'width':
      case 'height':
      case 'top':
      case 'left':
        sb.push(option + '=' + opt_options[option]);
        break;
      case 'target':
      case 'noreferrer':
        break;
      default:
        sb.push(option + '=' + (opt_options[option] ? 1 : 0));
    }
  }
  var optionString = sb.join(',');

  var newWin;
  if (opt_options['noreferrer']) {
    // Use a meta-refresh to stop the referrer from being included in the
    // request headers.
    newWin = parentWin.open('', target, optionString);
    if (newWin) {
      if (goog.userAgent.IE) {
        // IE has problems parsing the content attribute if the url contains
        // a semicolon. We can fix this by adding quotes around the url, but
        // then we can't parse quotes in the URL correctly. We take a
        // best-effort approach.
        //
        // If the URL has semicolons, wrap it in single quotes to protect
        // the semicolons.
        // If the URL has semicolons and single quotes, url-encode the single
        // quotes as well.
        //
        // This is imperfect. Notice that both ' and ; are reserved characters
        // in URIs, so this could do the wrong thing, but at least it will
        // do the wrong thing in only rare cases.
        // ugh.
        if (href.indexOf(';') != -1) {
          href = "'" + href.replace(/'/g, '%27') + "'";
        }
      }
      href = goog.string.htmlEscape(href);
      newWin.document.write('<META HTTP-EQUIV="refresh" content="0; url=' +
                            href + '">');
      newWin.document.close();
    }
  } else {
    newWin = parentWin.open(href, target, optionString);
  }
  // newWin is null if a popup blocker prevented the window open.
  return newWin;
};

/**
 * Opens a new window without any real content in it.
 *
 * This can be used to get around popup blockers if you need to open a window
 * in response to a user event, but need to do asynchronous work to determine
 * the URL to open, and then set the URL later.
 *
 * Example usage:
 *
 * var newWin = goog.window.openBlank('Loading...');
 * setTimeout(
 *     function() {
 *       newWin.location.href = 'http://www.google.com';
 *     }, 100);
 *
 * @param {string=} opt_message String to show in the new window. This string
 *     will be HTML-escaped to avoid XSS issues.
 * @param {Object=} opt_options Options to open window with.
 *     {@see goog.window.open for exact option semantics}.
 * @param {Window=} opt_parentWin Parent window that should be used to open the
 *                 new window.
 * @return {Window} Returns the window object that was opened. This returns
 *                  null if a popup blocker prevented the window from being
 *                  opened.
 */
goog.window.openBlank = function(opt_message, opt_options, opt_parentWin) {

  // Open up a window with the loading message and nothing else.
  // This will be interpreted as HTML content type with a missing doctype
  // and html/body tags, but is otherwise acceptable.
  var loadingMessage = opt_message ? goog.string.htmlEscape(opt_message) : '';
  return /** @type {Window} */ (goog.window.open(
      'javascript:"' + encodeURI(loadingMessage) + '"',
      opt_options, opt_parentWin));
};

/**
 * Raise a help popup window, defaulting to "Google standard" size and name.
 *
 * (If your project is using GXPs, consider using {@link PopUpLink.gxp}.)
 *
 * @param {string|Object} linkRef if this is a string, it will be used as the
 * URL of the popped window; otherwise it's assumed to be an HTMLAnchorElement
 * (or some other object with "target" and "href" properties).
 *
 * @param {Object=} opt_options Options to open window with.
 *     {@see goog.window.open for exact option semantics}
 *     Additional wrinkles to the options:
 *     - if 'target' field is null, linkRef.target will be used. If *that's*
 *     null, the default is "google_popup".
 *     - if 'width' field is not specified, the default is 690.
 *     - if 'height' field is not specified, the default is 500.
 *
 * @return {boolean} true if the window was not popped up, false if it was.
 */
goog.window.popup = function(linkRef, opt_options) {
  if (!opt_options) {
    opt_options = {};
  }

  // set default properties
  opt_options['target'] = opt_options['target'] ||
      linkRef['target'] || goog.window.DEFAULT_POPUP_TARGET;
  opt_options['width'] = opt_options['width'] ||
      goog.window.DEFAULT_POPUP_WIDTH;
  opt_options['height'] = opt_options['height'] ||
      goog.window.DEFAULT_POPUP_HEIGHT;

  var newWin = goog.window.open(linkRef, opt_options);
  if (!newWin) {
    return true;
  }
  newWin.focus();

  return false;
};
<commit_msg><commit_after>// Copyright 2006 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Utilities for window manipulation.
 */

goog.provide('goog.window');

goog.require('goog.string');
goog.require('goog.userAgent');

/**
 * Default height for popup windows
 * @type {number}
 */
goog.window.DEFAULT_POPUP_HEIGHT = 500;

/**
 * Default width for popup windows
 * @type {number}
 */
goog.window.DEFAULT_POPUP_WIDTH = 690;

/**
 * Default target for popup windows
 * @type {string}
 */
goog.window.DEFAULT_POPUP_TARGET = 'google_popup';

/**
 * Opens a new window.
 *
 * @param {string|Object} linkRef A string or an object that supports toString,
 *     for example goog.Uri.  If this is an object with a 'href' attribute, such
 *     as HTMLAnchorElement, it will be used instead.
 *
 * @param {Object=} opt_options supports the following options:
 *  'target': (string) target (window name). If null, linkRef.target will
 *          be used.
 *  'width': (number) window width.
 *  'height': (number) window height.
 *  'top': (number) distance from top of screen
 *  'left': (number) distance from left of screen
 *  'toolbar': (boolean) show toolbar
 *  'scrollbars': (boolean) show scrollbars
 *  'location': (boolean) show location
 *  'statusbar': (boolean) show statusbar
 *  'menubar': (boolean) show menubar
 *  'resizable': (boolean) resizable
 *  'noreferrer': (boolean) whether to attempt to remove the referrer header
 *      from the request headers. Does this by opening a blank window that
 *      then redirects to the target url, so users may see some flickering.
 *
 * @param {Window=} opt_parentWin Parent window that should be used to open the
 *                 new window.
 *
 * @return {Window} Returns the window object that was opened. This returns
 *                  null if a popup blocker prevented the window from being
 *                  opened.
 */
goog.window.open = function(linkRef, opt_options, opt_parentWin) {
  if (!opt_options) {
    opt_options = {};
  }
  var parentWin = opt_parentWin || window;

  // HTMLAnchorElement has a toString() method with the same behavior as
  // goog.Uri in all browsers except for Safari, which returns
  // '[object HTMLAnchorElement]'.  We check for the href first, then
  // assume that it's a goog.Uri or String otherwise.
  var href = typeof linkRef.href != 'undefined' ? linkRef.href :
      String(linkRef);
  var target = opt_options.target || linkRef.target;

  var sb = [];
  for (var option in opt_options) {
    switch (option) {
      case 'width':
      case 'height':
      case 'top':
      case 'left':
        sb.push(option + '=' + opt_options[option]);
        break;
      case 'target':
      case 'noreferrer':
        break;
      default:
        sb.push(option + '=' + (opt_options[option] ? 1 : 0));
    }
  }
  var optionString = sb.join(',');

  var newWin;
  if (opt_options['noreferrer']) {
    // Use a meta-refresh to stop the referrer from being included in the
    // request headers.
    newWin = parentWin.open('', target, optionString);
    if (newWin) {
      if (goog.userAgent.IE) {
        // IE has problems parsing the content attribute if the url contains
        // a semicolon. We can fix this by adding quotes around the url, but
        // then we can't parse quotes in the URL correctly. We take a
        // best-effort approach.
        //
        // If the URL has semicolons, wrap it in single quotes to protect
        // the semicolons.
        // If the URL has semicolons and single quotes, url-encode the single
        // quotes as well.
        //
        // This is imperfect. Notice that both ' and ; are reserved characters
        // in URIs, so this could do the wrong thing, but at least it will
        // do the wrong thing in only rare cases.
        // ugh.
        if (href.indexOf(';') != -1) {
          href = "'" + href.replace(/'/g, '%27') + "'";
        }
      }
      newWin.opener = null;
      if (goog.userAgent.WEBKIT) {
        // In some versions of Chrome (tested on 15), using meta refresh won't
        // put the new page in a new process, but setting location.href does. If
        // Chrome fixes that bug, we can get rid of this conditional.
        // http://code.google.com/p/chromium/issues/detail?id=93517
        newWin.location.href = href;
      } else {
        href = goog.string.htmlEscape(href);
        newWin.document.write('<META HTTP-EQUIV="refresh" content="0; url=' +
                              href + '">');
        newWin.document.close();
      }
    }
  } else {
    newWin = parentWin.open(href, target, optionString);
  }
  // newWin is null if a popup blocker prevented the window open.
  return newWin;
};

/**
 * Opens a new window without any real content in it.
 *
 * This can be used to get around popup blockers if you need to open a window
 * in response to a user event, but need to do asynchronous work to determine
 * the URL to open, and then set the URL later.
 *
 * Example usage:
 *
 * var newWin = goog.window.openBlank('Loading...');
 * setTimeout(
 *     function() {
 *       newWin.location.href = 'http://www.google.com';
 *     }, 100);
 *
 * @param {string=} opt_message String to show in the new window. This string
 *     will be HTML-escaped to avoid XSS issues.
 * @param {Object=} opt_options Options to open window with.
 *     {@see goog.window.open for exact option semantics}.
 * @param {Window=} opt_parentWin Parent window that should be used to open the
 *                 new window.
 * @return {Window} Returns the window object that was opened. This returns
 *                  null if a popup blocker prevented the window from being
 *                  opened.
 */
goog.window.openBlank = function(opt_message, opt_options, opt_parentWin) {

  // Open up a window with the loading message and nothing else.
  // This will be interpreted as HTML content type with a missing doctype
  // and html/body tags, but is otherwise acceptable.
  var loadingMessage = opt_message ? goog.string.htmlEscape(opt_message) : '';
  return /** @type {Window} */ (goog.window.open(
      'javascript:"' + encodeURI(loadingMessage) + '"',
      opt_options, opt_parentWin));
};

/**
 * Raise a help popup window, defaulting to "Google standard" size and name.
 *
 * (If your project is using GXPs, consider using {@link PopUpLink.gxp}.)
 *
 * @param {string|Object} linkRef if this is a string, it will be used as the
 * URL of the popped window; otherwise it's assumed to be an HTMLAnchorElement
 * (or some other object with "target" and "href" properties).
 *
 * @param {Object=} opt_options Options to open window with.
 *     {@see goog.window.open for exact option semantics}
 *     Additional wrinkles to the options:
 *     - if 'target' field is null, linkRef.target will be used. If *that's*
 *     null, the default is "google_popup".
 *     - if 'width' field is not specified, the default is 690.
 *     - if 'height' field is not specified, the default is 500.
 *
 * @return {boolean} true if the window was not popped up, false if it was.
 */
goog.window.popup = function(linkRef, opt_options) {
  if (!opt_options) {
    opt_options = {};
  }

  // set default properties
  opt_options['target'] = opt_options['target'] ||
      linkRef['target'] || goog.window.DEFAULT_POPUP_TARGET;
  opt_options['width'] = opt_options['width'] ||
      goog.window.DEFAULT_POPUP_WIDTH;
  opt_options['height'] = opt_options['height'] ||
      goog.window.DEFAULT_POPUP_HEIGHT;

  var newWin = goog.window.open(linkRef, opt_options);
  if (!newWin) {
    return true;
  }
  newWin.focus();

  return false;
};
<|endoftext|>


<commit_before>module.exports = {
    ':first'   : ':first-child',
    ':last'    : ':last-child',
    ':even'    : ':nth-child(even)',
    ':odd'     : ':nth-child(odd)',
    ':text'    : '[type="text"]',
    ':password': '[type="password"]',
    ':radio'   : '[type="radio"]',
    ':checkbox': '[type="checkbox"]',
    ':submit'  : '[type="submit"]',
    ':reset'   : '[type="reset"]',
    ':button'  : '[type="button"]',
    ':image'   : '[type="image"]',
    ':input'   : '[type="input"]',
    ':file'    : '[type="file"]',
    ':enabled' : ':not([disabled])',
    ':disabled': '[disabled]',
    ':selected': '[selected]',
    ':checked' : '[checked="checked"]'
};
<commit_msg>Minor - Added TODO<commit_after>module.exports = {
    // TODO: Document differences between jQuery and D.js behavior for these selectors
    ':first'   : ':first-child',
    ':last'    : ':last-child',
    ':even'    : ':nth-child(even)',
    ':odd'     : ':nth-child(odd)',

    ':text'    : '[type="text"]',
    ':password': '[type="password"]',
    ':radio'   : '[type="radio"]',
    ':checkbox': '[type="checkbox"]',
    ':submit'  : '[type="submit"]',
    ':reset'   : '[type="reset"]',
    ':button'  : '[type="button"]',
    ':image'   : '[type="image"]',
    ':input'   : '[type="input"]',
    ':file'    : '[type="file"]',
    ':enabled' : ':not([disabled])',
    ':disabled': '[disabled]',
    ':selected': '[selected]',
    ':checked' : '[checked="checked"]'
};
<|endoftext|>


<commit_before>import { observable } from "mobx";
import uuidv4 from "uuid/v4";

export default class Suite {
  id = null;
  @observable name = "Untitled Suite";
  @observable tests = [];

  store = null;

  constructor(store, id = uuidv4()) {
    this.store = store;
    this.id = id;
  }
}
<commit_msg>addTest function<commit_after>import { observable } from "mobx";
import uuidv4 from "uuid/v4";

export default class Suite {
  id = null;
  @observable name = "Untitled Suite";
  @observable tests = [];

  store = null;

  constructor(store, id = uuidv4()) {
    this.store = store;
    this.id = id;
    this.addTest = this.addTest.bind(this);
  }

  addTest(test) {
    if (!test || test.constructor.name !== "Test") {
      throw new Error(`Expected to receive Test instead received ${test ? test.constructor.name : test}`);
    } else {
      this.tests.push(test);
    }
  }
}
<|endoftext|>