<commit_before>'use strict';

angular.module('tmtControllers')
  .controller('TestcaseTreeController',
             ['$scope', 'Testcase', '$stateParams', '$log',
    function ( $scope,   Testcase,   $stateParams,   $log) {

    $log.info('init TestcaseTreeController')

    $scope.typesConfig = {
      /*"default": {
        "icon": "jstree-icon jstree-folder"
      },*/
      "tc": {
        "icon": "jstree-icon jstree-file"
      }
    }
    $scope.treeModel = [];

    var addNode = function(node){
      $scope.treeModel.push(node);
    }
    var clearTree = function(){ $scope.treeModel = []; }

    addNode({
      id: 'bluetooth',
      parent: '#',
      text: 'Bluetooth'
    });

    var ListOfTcs = []

    var doRest = function(listOfTcs, component){
      if( component ) {
        Testcase.query({t: 'distinct', f: 'tcid', s: {'tcid': -1},
            q: {
              'other_info.components': component,
              'tcid': { $nin: [ listOfTcs ] }
            }
        }).$promise.then( function(tcs){
          _.each(tcs, doTc(component, ''));
        });
      } else {
        addNode({
          id: '.uncategory',
          parent: '#',
          text: 'Unknown'
        });
        Testcase.query({t: 'distinct', f: 'tcid', s: {'tcid': -1},
            q: { 'tcid': { $nin: [ listOfTcs] } }
        }).$promise.then( function(tcs){
          _.each(tcs, doTc('', 'uncategory', true));
        });
      }
    }

    var doTc = function(component, feature, rest){
      return function(tc){
        if(!rest)ListOfTcs.push(tc);
        var parent = component;
        if( feature ) parent += '.'+feature;
        addNode({
          id: parent+'.'+tc,
          parent: parent,
          text: tc,
          type: "tc"
        });
      }
    }
    var doFeature = function(component){
      return function(feature) {
        addNode({
          id: component+'.'+feature,
          parent: component,
          text: feature,
        });
        Testcase.query({t: 'distinct', f: 'tcid',
          q: {
            $and: [
              {'other_info.components': component},
              {'other_info.features': feature}
            ]
          }})
        .$promise.then( function(tcs){
          _.each(tcs, doTc(component, feature));
          doRest(tcs, component);
        });
      }
    }
    var doComponent = function(component){
      addNode({
        id: component,
        parent: '#',
        text: component,
      });
      Testcase.query({t: 'distinct', f: "other_info.features", q: {'other_info.components': component}})
      .$promise.then( function(features){
        _.each(features, doFeature(component) );
      });
    }

    Testcase.query({t: 'distinct', f: "other_info.components"}).$promise.then(
      function(components) {
        _.each( components, doComponent );
        doRest(ListOfTcs)
      }
    );
  }])
;<commit_msg>Little tweak tc tree<commit_after>'use strict';

angular.module('tmtControllers')
  .controller('TestcaseTreeController',
             ['$scope', 'Testcase', '$stateParams', '$log',
    function ( $scope,   Testcase,   $stateParams,   $log) {

    $log.info('init TestcaseTreeController')

    $scope.typesConfig = {
      /*"default": {
        "icon": "jstree-icon jstree-folder"
      },*/
      "tc": {
        "icon": "jstree-icon jstree-file"
      }
    }
    $scope.treeModel = [];

    var addNode = function(node){
      if( node.text !== '' ) {
        $scope.treeModel.push(node);
      }
    }
    var clearTree = function(){ $scope.treeModel = []; }

    addNode({
      id: 'bluetooth',
      parent: '#',
      text: 'Bluetooth'
    });

    var ListOfTcs = [];
    var listOfComponents = [];
    var listOfFeatures = [];

    var doRest = function(listOfTcs, component){
      if( component ) {
        Testcase.query({t: 'distinct', f: 'tcid', s: {'tcid': -1},
            q: {
              'other_info.components': component,
              'tcid': { $nin: [ listOfTcs ] }
            }
        }).$promise.then( function(tcs){
          _.each(tcs, doTc(component, ''));
        });
      } else {
        addNode({
          id: '.uncategory',
          parent: '#',
          text: 'Unknown'
        });
        Testcase.query({t: 'distinct', f: 'tcid', s: {'tcid': -1},
            q: {
                $and: [
                {'other_info.components':
                    { $nin: [listOfComponents] } },
                {'other_info.features':
                    { $nin: [listOfFeatures] } }
                ]
            }
        }).$promise.then( function(tcs){
          _.each(tcs, doTc('', 'uncategory', true));
        });
      }
    }

    var doTc = function(component, feature, rest){
      return function(tc){
        if(!rest){
            ListOfTcs.push(tc);
        }
        var parent = component;
        if( feature ) parent += '.'+feature;
        addNode({
          id: parent+'.'+tc,
          parent: parent,
          text: tc,
          type: "tc"
        });
      }
    }
    var doFeature = function(component){
      return function(feature) {
        listOfFeatures.push(feature);
        addNode({
          id: component+'.'+feature,
          parent: component,
          text: feature,
        });
        Testcase.query({t: 'distinct', f: 'tcid',
          q: {
            $and: [
              {'other_info.components': component},
              {'other_info.features': feature}
            ]
          }})
        .$promise.then( function(tcs){
          _.each(tcs, doTc(component, feature));
        });
      }
    }
    var doComponent = function(component){
      listOfComponents.push(component)
      addNode({
        id: component,
        parent: '#',
        text: component,
      });
      Testcase.query({t: 'distinct', f: "other_info.features", q: {'other_info.components': component}})
      .$promise.then( function(features){
        _.each(features, doFeature(component) );
      });
      doRest(ListOfTcs, component);
    }

    Testcase.query({t: 'distinct', f: "other_info.components"}).$promise.then(
      function(components) {
        _.each( components, doComponent );
        doRest(ListOfTcs)
      }
    );
  }])
;<|endoftext|>


<commit_before>// (C) Copyright 2015 Martin Dougiamas
//
// 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.

angular.module('mm.core')

/**
 * The default priority for init processes.
 * @module mm.core
 * @ngdoc constant
 * @name mmInitDelegateDefaultPriority
 */
.constant('mmInitDelegateDefaultPriority', 100)

/**
 * The maximum priority that an addon can use for init process, anything over that is reserved for core use.
 * @module mm.core
 * @ngdoc constant
 * @name mmInitDelegateMaxAddonPriority
 */
.constant('mmInitDelegateMaxAddonPriority', 599)

/**
 * Provider for initialisation mechanisms.
 *
 * @module mm.core
 * @ngdoc provider
 * @name $mmInitDelegate
 */
.provider('$mmInitDelegate', function(mmInitDelegateDefaultPriority) {
    var initProcesses = {},
        self = {};

    /**
     * Registers an initialisation process.
     *
     * @description
     * Init processes can be used to add initialisation logic to the app. Anything that should
     * block the user interface while some processes are done should be an init process. When defining
     * an init process make sure you do not set a priority higher than mmInitDelegateMaxAddonPriority
     * in your addons. This is to make sure that your process does not happen before some essential
     * other core processes such as the upgrade, and restoring the user session.
     *
     * An init process should never change state or prompt user interaction.
     *
     * @module mm.core
     * @ngdoc method
     * @name $mmInitDelegateProvider#registerProcess
     * @param {String} name The name of the process.
     * @param {String|Function} callable The callable of the process. See {@link $mmUtil.resolveObject}.
     *                                   The resolved function will get $injector as first argument.
     * @param {Number} [priority=100] The priority of the process, the highest priority is executed first.
     * @param {Boolean} [blocking=false] Set this to true when this process should be resolved before any following one.
     * @return {Void}
     */
    self.registerProcess = function(name, callable, priority, blocking) {
        priority = typeof priority === 'undefined' ? mmInitDelegateDefaultPriority : priority;

        if (typeof initProcesses[name] !== 'undefined') {
            console.log('$mmInitDelegateProvider: Process \'' + name + '\' already defined.');
            return;
        }

        console.log('$mmInitDelegateProvider: Registered process \'' + name + '\'.');
        initProcesses[name] = {
            blocking: blocking,
            callable: callable,
            name: name,
            priority: priority
        };
    };

    self.$get = function($q, $log, $injector, $mmUtil) {

        $log = $log.getInstance('$mmInitDelegate');

        var self = {},
            readiness;

        /**
         * Convenience function to return a function that executes the process.
         *
         * @param  {Object} data The data of the process.
         * @return {Function}
         */
        function prepareProcess(data) {
            return function() {
                var promise,
                    fn;

                $log.debug('Executing init process \'' + data.name + '\'');

                try {
                    fn = $mmUtil.resolveObject(data.callable);
                } catch (e) {
                    $log.error('Could not resolve object of init process \'' + data.name + '\'. ' + e);
                    return;
                }

                try {
                    promise = fn($injector);
                } catch (e) {
                    $log.error('Error while calling the init process \'' + data.name + '\'. ' + e);
                    return;
                }

                return promise;
            };
        }

        /**
         * Executes the registered init processes.
         *
         * Reserved for core use, do not call directly.
         *
         * @module mm.core
         * @ngdoc service
         * @name $mmInitDelegate#executeInitProcesses
         * @protected
         * @return {Void}
         */
        self.executeInitProcesses = function() {
            var ordered = [],
                promises = [],
                dependency = $q.when();

            if (typeof readiness === 'undefined') {
                readiness = $q.defer();
            }

            // Re-ordering by priority.
            angular.forEach(initProcesses, function(data) {
                ordered.push(data);
            });
            ordered.sort(function(a, b) {
                return b.priority - a.priority;
            });

            // Execute all the processes.
            angular.forEach(ordered, function(data) {
                var promise;

                // Add the process to the dependency stack.
                promise = dependency.finally(prepareProcess(data));
                promises.push(promise);

                // If the new process is blocking, we set it as the dependency.
                if (data.blocking) {
                    dependency = promise;
                }
            });

            $q.all(promises).finally(readiness.resolve);
        };

        /**
         * Notifies when the app is ready.
         *
         * This returns a promise that is resolved when the app is initialised.
         *
         * Reserved for core use, do not call directly, use {@link $mmApp.ready} instead.
         *
         * @module mm.core
         * @ngdoc service
         * @name $mmInitDelegate#ready
         * @protected
         * @return {Promise} Resolved when the app is initialised. Never rejected.
         */
        self.ready = function() {
            if (typeof readiness === 'undefined') {
                // Prevent race conditions if this is called before executeInitProcesses.
                readiness = $q.defer();
            }

            return readiness.promise;
        };

        return self;
    };

    return self;
});
<commit_msg>MOBILE-1599 init: Don't finish init if 1 promise fails<commit_after>// (C) Copyright 2015 Martin Dougiamas
//
// 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.

angular.module('mm.core')

/**
 * The default priority for init processes.
 * @module mm.core
 * @ngdoc constant
 * @name mmInitDelegateDefaultPriority
 */
.constant('mmInitDelegateDefaultPriority', 100)

/**
 * The maximum priority that an addon can use for init process, anything over that is reserved for core use.
 * @module mm.core
 * @ngdoc constant
 * @name mmInitDelegateMaxAddonPriority
 */
.constant('mmInitDelegateMaxAddonPriority', 599)

/**
 * Provider for initialisation mechanisms.
 *
 * @module mm.core
 * @ngdoc provider
 * @name $mmInitDelegate
 */
.provider('$mmInitDelegate', function(mmInitDelegateDefaultPriority) {
    var initProcesses = {},
        self = {};

    /**
     * Registers an initialisation process.
     *
     * @description
     * Init processes can be used to add initialisation logic to the app. Anything that should
     * block the user interface while some processes are done should be an init process. When defining
     * an init process make sure you do not set a priority higher than mmInitDelegateMaxAddonPriority
     * in your addons. This is to make sure that your process does not happen before some essential
     * other core processes such as the upgrade, and restoring the user session.
     *
     * An init process should never change state or prompt user interaction.
     *
     * @module mm.core
     * @ngdoc method
     * @name $mmInitDelegateProvider#registerProcess
     * @param {String} name The name of the process.
     * @param {String|Function} callable The callable of the process. See {@link $mmUtil.resolveObject}.
     *                                   The resolved function will get $injector as first argument.
     * @param {Number} [priority=100] The priority of the process, the highest priority is executed first.
     * @param {Boolean} [blocking=false] Set this to true when this process should be resolved before any following one.
     * @return {Void}
     */
    self.registerProcess = function(name, callable, priority, blocking) {
        priority = typeof priority === 'undefined' ? mmInitDelegateDefaultPriority : priority;

        if (typeof initProcesses[name] !== 'undefined') {
            console.log('$mmInitDelegateProvider: Process \'' + name + '\' already defined.');
            return;
        }

        console.log('$mmInitDelegateProvider: Registered process \'' + name + '\'.');
        initProcesses[name] = {
            blocking: blocking,
            callable: callable,
            name: name,
            priority: priority
        };
    };

    self.$get = function($q, $log, $injector, $mmUtil) {

        $log = $log.getInstance('$mmInitDelegate');

        var self = {},
            readiness;

        /**
         * Convenience function to return a function that executes the process.
         *
         * @param  {Object} data The data of the process.
         * @return {Function}
         */
        function prepareProcess(data) {
            return function() {
                var promise,
                    fn;

                $log.debug('Executing init process \'' + data.name + '\'');

                try {
                    fn = $mmUtil.resolveObject(data.callable);
                } catch (e) {
                    $log.error('Could not resolve object of init process \'' + data.name + '\'. ' + e);
                    return;
                }

                try {
                    promise = fn($injector);
                } catch (e) {
                    $log.error('Error while calling the init process \'' + data.name + '\'. ' + e);
                    return;
                }

                return promise;
            };
        }

        /**
         * Executes the registered init processes.
         *
         * Reserved for core use, do not call directly.
         *
         * @module mm.core
         * @ngdoc service
         * @name $mmInitDelegate#executeInitProcesses
         * @protected
         * @return {Void}
         */
        self.executeInitProcesses = function() {
            var ordered = [],
                promises = [],
                dependency = $q.when();

            if (typeof readiness === 'undefined') {
                readiness = $q.defer();
            }

            // Re-ordering by priority.
            angular.forEach(initProcesses, function(data) {
                ordered.push(data);
            });
            ordered.sort(function(a, b) {
                return b.priority - a.priority;
            });

            // Execute all the processes.
            angular.forEach(ordered, function(data) {
                var promise;

                // Add the process to the dependency stack.
                promise = dependency.finally(prepareProcess(data));
                promises.push(promise);

                // If the new process is blocking, we set it as the dependency.
                if (data.blocking) {
                    dependency = promise;
                }
            });

            $mmUtil.allPromises(promises).finally(readiness.resolve);
        };

        /**
         * Notifies when the app is ready.
         *
         * This returns a promise that is resolved when the app is initialised.
         *
         * Reserved for core use, do not call directly, use {@link $mmApp.ready} instead.
         *
         * @module mm.core
         * @ngdoc service
         * @name $mmInitDelegate#ready
         * @protected
         * @return {Promise} Resolved when the app is initialised. Never rejected.
         */
        self.ready = function() {
            if (typeof readiness === 'undefined') {
                // Prevent race conditions if this is called before executeInitProcesses.
                readiness = $q.defer();
            }

            return readiness.promise;
        };

        return self;
    };

    return self;
});
<|endoftext|>


<commit_before>/*
 * Copyright 2014-2015 Hewlett-Packard Development Company, L.P.
 * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
 */

define([
    'js-whatever/js/base-page',
    'find/app/model/entity-collection',
    'find/app/model/documents-collection',
    'find/app/model/promotions-collection',
    'find/app/model/indexes-collection',
    'find/app/model/parametric-collection',
    'find/app/page/parametric/parametric-controller',
    'find/app/router',
    'find/app/vent',
    'i18n!find/nls/bundle',
    'find/app/util/view-server-client',
    'jquery',
    'underscore',
    'text!find/templates/app/page/find-search.html',
    'text!find/templates/app/page/results-container.html',
    'text!find/templates/app/page/suggestions-container.html',
    'text!find/templates/app/page/loading-spinner.html',
    'text!find/templates/app/page/colorbox-controls.html',
    'text!find/templates/app/page/index-popover.html',
    'text!find/templates/app/page/index-popover-contents.html',
    'text!find/templates/app/page/top-results-popover-contents.html',
    'text!find/templates/app/page/view/audio-player.html',
    'colorbox'
], function(BasePage, EntityCollection, DocumentsCollection, PromotionsCollection, IndexesCollection, ParametricCollection, ParametricController, router, vent, i18n, viewClient, $, _, template, resultsTemplate,
            suggestionsTemplate, loadingSpinnerTemplate, colorboxControlsTemplate, indexPopover, indexPopoverContents, topResultsPopoverContents, audioPlayer) {

    return BasePage.extend({

        template: _.template(template),
        resultsTemplate: _.template(resultsTemplate),
        noResultsTemplate: _.template('
<%- i18n["search.noResults"] %>
'),
        suggestionsTemplate: _.template(suggestionsTemplate),
        indexPopover: _.template(indexPopover),
        indexPopoverContents: _.template(indexPopoverContents),
        topResultsPopoverContents: _.template(topResultsPopoverContents),
        audioPlayerTemplate: _.template(audioPlayer),

        events: {
            'keyup .find-input': 'keyupAnimation',
            'change .indexCheckbox': function(e) {
                var toggledIndex = $(e.currentTarget).val();
                var checked = $(e.currentTarget).is(':checked');

                this.parametricController.view.clearFieldText();

                this.indexes[toggledIndex] = checked;

                if(this.$('.find-input').val()){
                    this.searchRequest(this.$('.find-input').val());
                }
            },
            'mouseover .suggestions-content a': _.debounce(function(e) {
                this.$('.suggestions-content  .popover-content').append(_.template(loadingSpinnerTemplate));

                this.topResultsCollection.fetch({
                    data: {
                        text: $(e.currentTarget).html(),
                        max_results: 3,
                        summary: 'quick',
                        index: this.selectedIndexes()
                    }
                });
            }, 800),
            'mouseover .entity-to-summary': function(e) {
                var title = $(e.currentTarget).find('a').html();
                this.$('[data-title="'+ title +'"]').addClass('label label-primary entity-to-summary').removeClass('label-info');
            },
            'mouseleave .entity-to-summary': function() {
                this.$('.suggestions-content li a').removeClass('label label-primary entity-to-summary');
                this.$('.main-results-content .entity-to-summary').removeClass('label-primary').addClass('label-info');
            }
        },

        initialize: function() {
            this.entityCollection = new EntityCollection();
            this.documentsCollection = new DocumentsCollection();
            this.promotionsCollection = new PromotionsCollection();
            this.topResultsCollection = new DocumentsCollection();
            this.indexesCollection = new IndexesCollection();
            this.parametricCollection = new ParametricCollection([], {singleRequest: true});

            this.parametricController = new ParametricController({
                parametricCollection: this.parametricCollection
            });

            router.on('route:search', function(text) {
                this.entityCollection.reset();
                this.documentsCollection.set([]);
                this.promotionsCollection.set([]);

                if (text) {
                    this.$('.find-input').val(text); //when clicking one of the suggested search links
                    this.keyupAnimation();
                } else {
                    this.reverseAnimation(); //when clicking the small 'find' logo
                }
            }, this);

            this.indexes = {};
            this.indexesCollection.fetch();

            this.listenTo(this.indexesCollection, 'sync', function() {
                // Default to searching against all indexes
                this.indexesCollection.forEach(_.bind(function(indexModel) {
                    this.indexes[indexModel.get('index')] = true;
                }, this));

                this.$indexesDisplay = $(this.indexPopover());

                this.indexesCollection.each(function(model) {
                    var htmlTemplateOutput = $(this.indexPopoverContents({
                        index: model.get('index')
                    }));

                    this.$indexesDisplay.find('.indexes-list').append(htmlTemplateOutput);

                    if (this.indexes[model.get('index')]) { // If index is selected, set the checkbox to checked
                        htmlTemplateOutput.find('input').prop('checked', true);
                    }
                }, this);

                this.$('.list-indexes').popover({
                    html: true,
                    content: this.$indexesDisplay,
                    placement: 'bottom'
                });
            }, this);

            this.listenTo(this.parametricController.logic, 'change', function(fieldText) {
                var newFieldText = fieldText;

                if(newFieldText) {
                    this.fieldText = newFieldText.toString();
                } else {
                    this.fieldText = null;
                }

                this.searchRequest();
            });
        },

        render: function() {
            this.$el.html(this.template);

            this.$('.find-form').submit(function(e){ //preventing input form submit and page reload
                e.preventDefault();
            });

            this.parametricController.view.setElement(this.$('.parametric-container')).render();

            /*top 3 results popover*/
            this.listenTo(this.topResultsCollection, 'add', function(model){
                this.$('.suggestions-content .popover-content .loading-spinner').remove();

                this.$('.suggestions-content .popover-content').append(this.topResultsPopoverContents({
                    title: model.get('title'),
                    summary: model.get('summary').trim().substring(0, 100) + "..."
                }));
            });

            /*suggested links*/
            this.listenTo(this.entityCollection, 'request', function() {
                if(!this.$('.suggestions-content ul').length) {
                    this.$('.suggestions-content').append(_.template(loadingSpinnerTemplate));
                }

                this.$('.suggested-links-header').removeClass('hide')
            });

            this.listenTo(this.entityCollection, 'reset', function() {
                this.$('.suggestions-content').empty();

                if (this.entityCollection.isEmpty()) {
                    this.$('.suggested-links-header').addClass('hide')
                }
                else {
                    var clusters = this.entityCollection.groupBy('cluster');

                    _.each(clusters, function(entities) {
                        this.$('.suggestions-content').append(this.suggestionsTemplate({
                            entities: entities
                        }));

                        this.$('.suggestions-content li a').popover({
                            html: true,
                            content: '
Top Results
',
                            placement: 'right',
                            trigger: 'hover'
                        })
                    }, this);

                    this.documentsCollection.each(function(document) {
                        var summary = this.addLinksToSummary(document.get('summary'));

                        this.$('[data-reference="' + document.get('reference') + '"] .result-summary').html(summary);
                    }, this);

                    this.promotionsCollection.each(function(document) {
                        var summary = this.addLinksToSummary(document.get('summary'));

                        this.$('[data-reference="' + document.get('reference') + '"] .result-summary').html(summary);
                    }, this);
                }
            });

            /*main results content*/
            this.listenTo(this.documentsCollection, 'request', function() {
                this.$('.main-results-content').empty();
                this.$('.main-results-content').append(_.template(loadingSpinnerTemplate));
            });

            this.listenTo(this.promotionsCollection, 'add', function(model) {
                var reference = model.get('reference');
                var summary = model.get('summary');

                // Remove existing document with this reference
                this.$("[data-reference='" + reference + "']").remove();

                summary = this.addLinksToSummary(summary);

                this.$('.main-results-content .loading-spinner').remove();

                var href = viewClient.getHref(reference, model.get('index'));

                var $newResult = $(_.template(resultsTemplate ,{
                    title: model.get('title'),
                    reference: reference,
                    href: href,
                    index: model.get('index'),
                    summary: summary,
                    promotion: true
                }));

                $newResult.addClass("promotion-result");

                this.$('.main-results-content').prepend($newResult);

                $newResult.find('.result-header').colorbox({
                    iframe: true,
                    width:'70%',
                    height:'70%',
                    rel: 'results',
                    current: '{current} of {total}',
                    onComplete: _.bind(function() {
                        $('#cboxPrevious, #cboxNext').remove(); //removing default colorbox nav buttons
                    }, this)
                });

                $newResult.find('.dots').click(function (e) {
                    e.preventDefault();
                    $newResult.find('.result-header').trigger('click'); //dot-dot-dot triggers the colorbox event
                });
            });

            this.listenTo(this.documentsCollection, 'add', function(model) {
                var reference = model.get('reference');
                var summary = model.get('summary');

                summary = this.addLinksToSummary(summary);

                this.$('.main-results-content .loading-spinner').remove();

                var href = viewClient.getHref(reference, model.get('index'));

                var $newResult = $(_.template(resultsTemplate ,{
                    title: model.get('title'),
                    reference: reference,
                    href: href,
                    index: model.get('index'),
                    summary: summary,
                    promotion: false
                }));

                this.$('.main-results-content').append($newResult);

                var fields = model.get('fields');
                if (fields.content_type && fields.url && fields.content_type[0].indexOf('audio') == 0) {
                    // This is an audio file with a URL, use the audio player template

                    var url = fields.url[0];
                    var offset = fields.offset ? fields.offset[0] : 0;

                    $newResult.find('.result-header').colorbox({
                        iframe: false,
                        width:'70%',
                        height:'70%',
                        rel: 'results',
                        current: '{current} of {total}',
                        onComplete: _.bind(function() {
                            $('#cboxPrevious, #cboxNext').remove(); //removing default colorbox nav buttons
                        }, this),
                        html: this.audioPlayerTemplate({
                            url: url,
                            offset: offset
                        })
                    })

                } else {
                    // Use the standard Viewserver display

                    $newResult.find('.result-header').colorbox({
                        iframe: true,
                        width:'70%',
                        height:'70%',
                        rel: 'results',
                        current: '{current} of {total}',
                        onComplete: _.bind(function() {
                            $('#cboxPrevious, #cboxNext').remove(); //removing default colorbox nav buttons
                        }, this)
                    });
                }

                $newResult.find('.dots').click(function (e) {
                    e.preventDefault();
                    $newResult.find('.result-header').trigger('click'); //dot-dot-dot triggers the colorbox event
                });
            });

            this.listenTo(this.documentsCollection, 'sync', function() {
                if(this.documentsCollection.isEmpty()) {
                    this.$('.main-results-content .loading-spinner').remove();
                    this.$('.main-results-content').append(this.noResultsTemplate({i18n: i18n}));
                }
            });

            /*colorbox fancy button override*/
            $('#colorbox').append(_.template(colorboxControlsTemplate));
            $('.nextBtn').on('click', this.handleNextResult);
            $('.prevBtn').on('click', this.handlePrevResult);
        },

        addLinksToSummary: function(summary) {
            //creating an array of the entity titles, longest first
            var entities = this.entityCollection.map(function(entity) {
                return {
                    text: entity.get('text'),
                    id:  _.uniqueId('Find-IOD-Entity-Placeholder')
                }
            }).sort(function(a,b) {
                return b.text.length - a.text.length;
            });

            _.each(entities, function(entity) {
                summary = summary.replace(new RegExp('(^|\\s|[,.-:;?\'"!\\(\\)\\[\\]{}])' + entity.text + '($|\\s|[,.-:;?\'"!\\(\\)\\[\\]{}])', 'gi'), '$1' + entity.id + '$2');
            });

            _.each(entities, function(entity) {
                summary = summary.replace(new RegExp(entity.id, 'g'), '' + entity.text + '');
            });

            return summary;
        },

        keyupAnimation: _.debounce(function() {
            /*fancy animation*/
            if($.trim(this.$('.find-input').val()).length) { // input has at least one non whitespace character
                this.$('.find').addClass('animated-container').removeClass('reverse-animated-container');

                this.$('.main-results-content').show();
                this.$('.suggested-links-container').show();
                this.$('.parametric-container').show();
                this.changeQueryText(this.$('.find-input').val());
                this.searchRequest();
            } else {
                this.reverseAnimation();
                vent.navigate('find/search', {trigger: false});
            }
            this.$('.popover').remove();
        }, 500),

        handlePrevResult: function() {
            $.colorbox.prev();
        },

        handleNextResult: function() {
            $.colorbox.next();
        },

        reverseAnimation: function() {
            /*fancy reverse animation*/
            this.$('.find').removeClass('animated-container').addClass('reverse-animated-container');

            this.$('.main-results-content').hide();
            this.$('.suggested-links-container').hide();
            this.$('.parametric-container').hide();
            this.$('.find-input').val('');
            this.$('.popover').remove();
        },

        changeQueryText: function(queryText) {
            this.queryText = queryText;
            this.parametricController.view.clearFieldText();
        },

        searchRequest: function() {
            if (!_.isEmpty(this.indexes)) { // Do we have the list of indexes yet?
                var selectedIndexes = this.selectedIndexes();

                this.parametricController.logic.setQueryText(this.queryText);
                this.parametricController.logic.setIndexes(selectedIndexes);

                this.documentsCollection.fetch({
                    data: {
                        text: this.queryText,
                        max_results: 30,
                        summary: 'quick',
                        index: selectedIndexes,
                        field_text: this.fieldText || null
                    }
                }, this);

                this.promotionsCollection.fetch({
                    data: {
                        text: this.queryText,
                        max_results: 30, // TODO maybe less?
                        summary: 'quick',
                        index: selectedIndexes,
                        field_text: this.fieldText || null
                    }
                }, this);

                this.entityCollection.fetch({
                    data: {
                        text: this.queryText,
                        index: selectedIndexes,
                        field_text: this.fieldText || null
                    }
                });

                vent.navigate('find/search/' + encodeURIComponent(this.queryText), {trigger: false});
            }
            else {
                this.indexesCollection.once('sync', function() {
                    this.searchRequest();
                }, this);
            }
        },

        selectedIndexes: function() {
            return _.chain(this.indexes).map(function(value, key) {
                return (value ? key : undefined); // Return names of selected indexes and undefined for unselected ones
            }).compact().value();
        }
    });
});
<commit_msg>Refactor to share code between promotions and results<commit_after>/*
 * Copyright 2014-2015 Hewlett-Packard Development Company, L.P.
 * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
 */

define([
    'js-whatever/js/base-page',
    'find/app/model/entity-collection',
    'find/app/model/documents-collection',
    'find/app/model/promotions-collection',
    'find/app/model/indexes-collection',
    'find/app/model/parametric-collection',
    'find/app/page/parametric/parametric-controller',
    'find/app/router',
    'find/app/vent',
    'i18n!find/nls/bundle',
    'find/app/util/view-server-client',
    'jquery',
    'underscore',
    'text!find/templates/app/page/find-search.html',
    'text!find/templates/app/page/results-container.html',
    'text!find/templates/app/page/suggestions-container.html',
    'text!find/templates/app/page/loading-spinner.html',
    'text!find/templates/app/page/colorbox-controls.html',
    'text!find/templates/app/page/index-popover.html',
    'text!find/templates/app/page/index-popover-contents.html',
    'text!find/templates/app/page/top-results-popover-contents.html',
    'text!find/templates/app/page/view/audio-player.html',
    'colorbox'
], function(BasePage, EntityCollection, DocumentsCollection, PromotionsCollection, IndexesCollection, ParametricCollection, ParametricController, router, vent, i18n, viewClient, $, _, template, resultsTemplate,
            suggestionsTemplate, loadingSpinnerTemplate, colorboxControlsTemplate, indexPopover, indexPopoverContents, topResultsPopoverContents, audioPlayer) {

    return BasePage.extend({

        template: _.template(template),
        resultsTemplate: _.template(resultsTemplate),
        noResultsTemplate: _.template('
<%- i18n["search.noResults"] %>
'),
        suggestionsTemplate: _.template(suggestionsTemplate),
        indexPopover: _.template(indexPopover),
        indexPopoverContents: _.template(indexPopoverContents),
        topResultsPopoverContents: _.template(topResultsPopoverContents),
        audioPlayerTemplate: _.template(audioPlayer),

        events: {
            'keyup .find-input': 'keyupAnimation',
            'change .indexCheckbox': function(e) {
                var toggledIndex = $(e.currentTarget).val();
                var checked = $(e.currentTarget).is(':checked');

                this.parametricController.view.clearFieldText();

                this.indexes[toggledIndex] = checked;

                if(this.$('.find-input').val()){
                    this.searchRequest(this.$('.find-input').val());
                }
            },
            'mouseover .suggestions-content a': _.debounce(function(e) {
                this.$('.suggestions-content  .popover-content').append(_.template(loadingSpinnerTemplate));

                this.topResultsCollection.fetch({
                    data: {
                        text: $(e.currentTarget).html(),
                        max_results: 3,
                        summary: 'quick',
                        index: this.selectedIndexes()
                    }
                });
            }, 800),
            'mouseover .entity-to-summary': function(e) {
                var title = $(e.currentTarget).find('a').html();
                this.$('[data-title="'+ title +'"]').addClass('label label-primary entity-to-summary').removeClass('label-info');
            },
            'mouseleave .entity-to-summary': function() {
                this.$('.suggestions-content li a').removeClass('label label-primary entity-to-summary');
                this.$('.main-results-content .entity-to-summary').removeClass('label-primary').addClass('label-info');
            }
        },

        initialize: function() {
            this.entityCollection = new EntityCollection();
            this.documentsCollection = new DocumentsCollection();
            this.promotionsCollection = new PromotionsCollection();
            this.topResultsCollection = new DocumentsCollection();
            this.indexesCollection = new IndexesCollection();
            this.parametricCollection = new ParametricCollection([], {singleRequest: true});

            this.parametricController = new ParametricController({
                parametricCollection: this.parametricCollection
            });

            router.on('route:search', function(text) {
                this.entityCollection.reset();
                this.documentsCollection.set([]);
                this.promotionsCollection.set([]);

                if (text) {
                    this.$('.find-input').val(text); //when clicking one of the suggested search links
                    this.keyupAnimation();
                } else {
                    this.reverseAnimation(); //when clicking the small 'find' logo
                }
            }, this);

            this.indexes = {};
            this.indexesCollection.fetch();

            this.listenTo(this.indexesCollection, 'sync', function() {
                // Default to searching against all indexes
                this.indexesCollection.forEach(_.bind(function(indexModel) {
                    this.indexes[indexModel.get('index')] = true;
                }, this));

                this.$indexesDisplay = $(this.indexPopover());

                this.indexesCollection.each(function(model) {
                    var htmlTemplateOutput = $(this.indexPopoverContents({
                        index: model.get('index')
                    }));

                    this.$indexesDisplay.find('.indexes-list').append(htmlTemplateOutput);

                    if (this.indexes[model.get('index')]) { // If index is selected, set the checkbox to checked
                        htmlTemplateOutput.find('input').prop('checked', true);
                    }
                }, this);

                this.$('.list-indexes').popover({
                    html: true,
                    content: this.$indexesDisplay,
                    placement: 'bottom'
                });
            }, this);

            this.listenTo(this.parametricController.logic, 'change', function(fieldText) {
                var newFieldText = fieldText;

                if(newFieldText) {
                    this.fieldText = newFieldText.toString();
                } else {
                    this.fieldText = null;
                }

                this.searchRequest();
            });
        },

        render: function() {
            this.$el.html(this.template);

            this.$('.find-form').submit(function(e){ //preventing input form submit and page reload
                e.preventDefault();
            });

            this.parametricController.view.setElement(this.$('.parametric-container')).render();

            /*top 3 results popover*/
            this.listenTo(this.topResultsCollection, 'add', function(model){
                this.$('.suggestions-content .popover-content .loading-spinner').remove();

                this.$('.suggestions-content .popover-content').append(this.topResultsPopoverContents({
                    title: model.get('title'),
                    summary: model.get('summary').trim().substring(0, 100) + "..."
                }));
            });

            /*suggested links*/
            this.listenTo(this.entityCollection, 'request', function() {
                if(!this.$('.suggestions-content ul').length) {
                    this.$('.suggestions-content').append(_.template(loadingSpinnerTemplate));
                }

                this.$('.suggested-links-header').removeClass('hide')
            });

            this.listenTo(this.entityCollection, 'reset', function() {
                this.$('.suggestions-content').empty();

                if (this.entityCollection.isEmpty()) {
                    this.$('.suggested-links-header').addClass('hide')
                }
                else {
                    var clusters = this.entityCollection.groupBy('cluster');

                    _.each(clusters, function(entities) {
                        this.$('.suggestions-content').append(this.suggestionsTemplate({
                            entities: entities
                        }));

                        this.$('.suggestions-content li a').popover({
                            html: true,
                            content: '
Top Results
',
                            placement: 'right',
                            trigger: 'hover'
                        })
                    }, this);

                    this.documentsCollection.each(function(document) {
                        var summary = this.addLinksToSummary(document.get('summary'));

                        this.$('[data-reference="' + document.get('reference') + '"] .result-summary').html(summary);
                    }, this);

                    this.promotionsCollection.each(function(document) {
                        var summary = this.addLinksToSummary(document.get('summary'));

                        this.$('[data-reference="' + document.get('reference') + '"] .result-summary').html(summary);
                    }, this);
                }
            });

            /*main results content*/
            this.listenTo(this.documentsCollection, 'request', function() {
                this.$('.main-results-content').empty();
                this.$('.main-results-content').append(_.template(loadingSpinnerTemplate));
            });

            this.listenTo(this.promotionsCollection, 'add', function(model) {
                this.formatResult(model, true)
            });

            this.listenTo(this.documentsCollection, 'add', function(model) {
                this.formatResult(model, false);
            });

            this.listenTo(this.documentsCollection, 'sync', function() {
                if(this.documentsCollection.isEmpty()) {
                    this.$('.main-results-content .loading-spinner').remove();
                    this.$('.main-results-content').append(this.noResultsTemplate({i18n: i18n}));
                }
            });

            /*colorbox fancy button override*/
            $('#colorbox').append(_.template(colorboxControlsTemplate));
            $('.nextBtn').on('click', this.handleNextResult);
            $('.prevBtn').on('click', this.handlePrevResult);
        },

        addLinksToSummary: function(summary) {
            //creating an array of the entity titles, longest first
            var entities = this.entityCollection.map(function(entity) {
                return {
                    text: entity.get('text'),
                    id:  _.uniqueId('Find-IOD-Entity-Placeholder')
                }
            }).sort(function(a,b) {
                return b.text.length - a.text.length;
            });

            _.each(entities, function(entity) {
                summary = summary.replace(new RegExp('(^|\\s|[,.-:;?\'"!\\(\\)\\[\\]{}])' + entity.text + '($|\\s|[,.-:;?\'"!\\(\\)\\[\\]{}])', 'gi'), '$1' + entity.id + '$2');
            });

            _.each(entities, function(entity) {
                summary = summary.replace(new RegExp(entity.id, 'g'), '' + entity.text + '');
            });

            return summary;
        },

        keyupAnimation: _.debounce(function() {
            /*fancy animation*/
            if($.trim(this.$('.find-input').val()).length) { // input has at least one non whitespace character
                this.$('.find').addClass('animated-container').removeClass('reverse-animated-container');

                this.$('.main-results-content').show();
                this.$('.suggested-links-container').show();
                this.$('.parametric-container').show();
                this.changeQueryText(this.$('.find-input').val());
                this.searchRequest();
            } else {
                this.reverseAnimation();
                vent.navigate('find/search', {trigger: false});
            }
            this.$('.popover').remove();
        }, 500),

        handlePrevResult: function() {
            $.colorbox.prev();
        },

        handleNextResult: function() {
            $.colorbox.next();
        },

        reverseAnimation: function() {
            /*fancy reverse animation*/
            this.$('.find').removeClass('animated-container').addClass('reverse-animated-container');

            this.$('.main-results-content').hide();
            this.$('.suggested-links-container').hide();
            this.$('.parametric-container').hide();
            this.$('.find-input').val('');
            this.$('.popover').remove();
        },

        changeQueryText: function(queryText) {
            this.queryText = queryText;
            this.parametricController.view.clearFieldText();
        },

        searchRequest: function() {
            if (!_.isEmpty(this.indexes)) { // Do we have the list of indexes yet?
                var selectedIndexes = this.selectedIndexes();

                this.parametricController.logic.setQueryText(this.queryText);
                this.parametricController.logic.setIndexes(selectedIndexes);

                this.documentsCollection.fetch({
                    data: {
                        text: this.queryText,
                        max_results: 30,
                        summary: 'quick',
                        index: selectedIndexes,
                        field_text: this.fieldText || null
                    }
                }, this);

                this.promotionsCollection.fetch({
                    data: {
                        text: this.queryText,
                        max_results: 30, // TODO maybe less?
                        summary: 'quick',
                        index: selectedIndexes,
                        field_text: this.fieldText || null
                    }
                }, this);

                this.entityCollection.fetch({
                    data: {
                        text: this.queryText,
                        index: selectedIndexes,
                        field_text: this.fieldText || null
                    }
                });

                vent.navigate('find/search/' + encodeURIComponent(this.queryText), {trigger: false});
            }
            else {
                this.indexesCollection.once('sync', function() {
                    this.searchRequest();
                }, this);
            }
        },

        selectedIndexes: function() {
            return _.chain(this.indexes).map(function(value, key) {
                return (value ? key : undefined); // Return names of selected indexes and undefined for unselected ones
            }).compact().value();
        },

        formatResult: function(model, isPromotion) {
            var reference = model.get('reference');
            var summary = model.get('summary');

            // Remove existing document with this reference
            this.$("[data-reference='" + reference + "']").remove();

            summary = this.addLinksToSummary(summary);

            this.$('.main-results-content .loading-spinner').remove();

            var href = viewClient.getHref(reference, model.get('index'));

            var $newResult = $(_.template(resultsTemplate ,{
                title: model.get('title'),
                reference: reference,
                href: href,
                index: model.get('index'),
                summary: summary,
                promotion: isPromotion
            }));

            if (isPromotion) {
                this.$('.main-results-content').prepend($newResult);
            } else {
                this.$('.main-results-content').append($newResult);
            }

            var fields = model.get('fields');
            if (fields.content_type && fields.url && fields.content_type[0].indexOf('audio') == 0) {
                // This is an audio file with a URL, use the audio player template

                var url = fields.url[0];
                var offset = fields.offset ? fields.offset[0] : 0;

                $newResult.find('.result-header').colorbox({
                    iframe: false,
                    width:'70%',
                    height:'70%',
                    rel: 'results',
                    current: '{current} of {total}',
                    onComplete: _.bind(function() {
                        $('#cboxPrevious, #cboxNext').remove(); //removing default colorbox nav buttons
                    }, this),
                    html: this.audioPlayerTemplate({
                        url: url,
                        offset: offset
                    })
                })

            } else {
                // Use the standard Viewserver display

                $newResult.find('.result-header').colorbox({
                    iframe: true,
                    width:'70%',
                    height:'70%',
                    rel: 'results',
                    current: '{current} of {total}',
                    onComplete: _.bind(function() {
                        $('#cboxPrevious, #cboxNext').remove(); //removing default colorbox nav buttons
                    }, this)
                });
            }

            $newResult.find('.dots').click(function (e) {
                e.preventDefault();
                $newResult.find('.result-header').trigger('click'); //dot-dot-dot triggers the colorbox event
            });
        }
    });
});
<|endoftext|>


<commit_before>'use strict';

exports.BattleLearnsets = {
	/*rb202: {learnset: {
		absorb: ["3L126", "3L144"],
		aurorabeam: ["3L32"],
		barrage: ["3L1"],
		clamp: ["3L1"],
		doubleslap: ["3L254"],
		flash: ["3L250"],
		fly: ["3L114"],
		highjumpkick: ["3L1"],
		horndrill: ["3L167"],
		karatechop: ["3L40"],
		leechlife: ["3L1"],
		leechseed: ["3L234"],
		pound: ["3L225"],
		sandattack: ["3L1"],
		slam: ["3L11", "3L205"],
		superglitch00: ["3L28", "3L62"],
		superglitcha7: ["3L207"],
		swordsdance: ["3L9"],
		tackle: ["3L204", "3L229"],
		tm05: ["3L119", "3L163"],
		tm07: ["3L145", "3L146", "3L148", "3L185"],
		tm09: ["3L30", "3L36", "3L99"],
		tm29: ["3L33"],
		tm34: ["3L241"],
		tm45: ["3L209"],
		tm50: ["3L19", "3L48"],
	}},*/
};
<commit_msg>phancero and RB:202 learnsets<commit_after>'use strict';

exports.BattleLearnsets = {
	///////////////////////////////////
	// Prism Fakemon
	///////////////////////////////////
	phancero: {learnset: {
		acidarmor: ["3L30"],
		agility: ["3L20"],
		airslash: ["3L90"],
		ancientpower: ["3M"],
		attract: ["3M"],
		bodyslam: ["3M"],
		bulkup: ["3M"],
		counter: ["3M"],
		curse: ["3M"],
		cut: ["3M"],
		darkpulse: ["3M"],
		defensecurl: ["3M"],
		dig: ["3M"],
		doubleedge: ["3M"],
		doubleteam: ["3M"],
		dragonbreath: ["3M"],
		dragonclaw: ["3M"],
		earthquake: ["3M"],
		endure: ["3M"],
		energyball: ["3M"],
		fireblast: ["3M"],
		flamethrower: ["3M"],
		flash: ["3M"],
		flashcannon: ["3M"],
		frustration: ["3M"],
		gust: ["3L7"],
		headbutt: ["3M"],
		hiddenpower: ["3M"],
		highjumpkick: ["3L100"],
		hyperbeam: ["3M"],
		hypervoice: ["3M"],
		ironhead: ["3M"],
		irontail: ["3M"],
		leechseed: ["3L35"],
		lick: ["3L10"],
		metronome: ["3M"],
		mudslap: ["3M"],
		poisonjab: ["3M"],
		pound: ["3L1"],
		protect: ["3M"],
		raindance: ["3M"],
		rest: ["3M"],
		return: ["3M"],
		rockslide: ["3M"],
		rocksmash: ["3M"],
		safeguard: ["3M"],
		sandstorm: ["3M"],
		shadowball: ["3L40"],
		shadowclaw: ["3L80", "3M"],
		signalbeam: ["3M"],
		skyattack: ["3L50"],
		sleeptalk: ["3M"],
		sludgebomb: ["3M"],
		solarbeam: ["3M"],
		strength: ["3M"],
		substitute: ["3M"],
		sunnyday: ["3M"],
		surf: ["3M"],
		swagger: ["3M"],
		swift: ["3M"],
		swordsdance: ["3M"],
		teleport: ["3L4"],
		thief: ["3M"],
		thunder: ["3M"],
		thunderbolt: ["3M"],
		toxic: ["3M"],
		triattack: ["3L95", "3M"],
		waterfall: ["3M"],
		watergun: ["3L15", "3L60"],
		willowisp: ["3M"],
		wingattack: ["3L25"],
		wrap: ["3L70"],
	}},

	///////////////////////////////////
	// Gen 1 Glitchmon
	///////////////////////////////////
	rb202: {learnset: {
		absorb: ["3L126", "3L144"],
		aurorabeam: ["3L32"],
		barrage: ["3L1"],
		bide: ["3M"],
		bodyslam: ["3M"],
		clamp: ["3L1"],
		counter: ["3M"],
		doubleslap: ["3L254"],
		doubleteam: ["3M"],
		fissure: ["3M"],
		flash: ["3L250"],
		fly: ["3L114"],
		highjumpkick: ["3L1"],
		horndrill: ["3L167"],
		hyperbeam: ["3M"],
		icebeam: ["3M"],
		karatechop: ["3L40"],
		leechlife: ["3L1"],
		leechseed: ["3L234"],
		megadrain: ["3M"],
		metronome: ["3M"],
		pound: ["3L225"],
		psychic: ["3M"],
		razorwind: ["3M"],
		reflect: ["3M"],
		rockslide: ["3M"],
		sandattack: ["3L1"],
		selfdestruct: ["3M"],
		skullbash: ["3M"],
		skyattack: ["3M"],
		slam: ["3L11", "3L205"],
		superglitch00: ["3L28", "3L62"],
		superglitcha7: ["3L207"],
		surf: ["3M"],
		swordsdance: ["3L9"],
		tackle: ["3L204", "3L229"],
		thunderbolt: ["3M"],
		tm05: ["3L119", "3L163"],
		tm07: ["3L145", "3L146", "3L148", "3L185"],
		tm09: ["3L30", "3L36", "3L99"],
		tm29: ["3L33"],
		tm34: ["3L241"],
		tm45: ["3L209"],
		tm50: ["3L19", "3L48"],
		triattack: ["3M"],
	}},
};
<|endoftext|>


<commit_before>/* global forge, module, asyncTest, start, ok, askQuestion */

module("forge.file");

asyncTest("Select image from gallery and check file info", 2, function() {
    var runTest = function () {
        forge.file.getImage(function (file) {
            forge.file.info(file, function (info) {
                ok(true, "file.info claims success");
                askQuestion("Does the following file information describe the file: " +
                            JSON.stringify(info), {
                                Yes: function () {
                                    ok(true, "File information is correct");
                                    start();
                                },
                                No: function () {
                                    ok(false, "User claims failure");
                                    start();
                                }
                            });
            }, function (e) {
                ok(false, "API call failure: " + e.message);
                start();
            });
        });
    };
    askQuestion("When prompted select a file from the gallery", { Ok: runTest });
});

asyncTest("Embedding video in webview", 1, function() {
    forge.file.getVideo({
        source: "gallery",
        videoQuality: "low"
    }, function (file) {
        forge.file.URL(file, function (url) {
            askQuestion("Did your video just play: <video controls autoplay width=192 src='" + url + "'></video>", {
                Yes: function () {
                    ok(true, "video capture successful");
                    start();
                }, No: function () {
                    ok(false, "didn't play back just-captured video");
                    start();
                }
            });
        }, function (e) {
            ok(false, "API call failure: "+e.message);
            start();
        });
    }, function (e) {
        ok(false, "API call failure: "+e.message);
        start();
    });
});

asyncTest("Gallery", 5, function() {
    var runTest = function () {
        forge.file.getImage({
            source: "gallery",
            width: 100,
            height: 100
        }, function (file) {
            askQuestion("Were you just prompted to select an image?", { Yes: function () {
                ok(true, "Success");
                forge.file.isFile(file, function (is) {
                    if (is) {
                        ok(true, "forge.file.isFile is true");
                    } else {
                        ok(false, "forge.file.isFile is false");
                    }
                    forge.file.isFile(file, function (is) {
                        if (is) {
                            ok(true, "forge.file.isFile is true");
                        } else {
                            ok(false, "forge.file.isFile is false");
                        }
                        forge.file.URL(file, function (url) {
                            askQuestion("Is this your image:
", { Yes: function () {
                                ok(true, "Success with forge.file.URL");
                                forge.file.base64(file, function (data) {
                                    askQuestion("Is this also your image:
", { Yes: function () {
                                        ok(true, "Success with forge.file.base64");
                                        start();
                                    }, No: function () {
                                        ok(false, "User claims failure with forge.file.base64");
                                        start();
                                    }});
                                }, function (e) {
                                    ok(false, "API call failure: "+e.message);
                                    start();
                                });
                            }, No: function () {
                                ok(false, "User claims failure with forge.file.URL");
                                start();
                            }});
                        }, function (e) {
                            ok(false, "API call failure: "+e.message);
                            start();
                        });
                    }, function (e) {
                        ok(false, "API call failure: "+e.message);
                        start();
                    });
                }, function (e) {
                    ok(false, "API call failure: "+e.message);
                    start();
                });

            }, No: function () {
                ok(false, "User claims failure");
                start();
            }});
        }, function (e) {
            ok(false, "API call failure: "+e.message);
            start();
        });
    };
    askQuestion("In this test use the gallery to select a picture when prompted", { Ok: runTest });
});

asyncTest("Cancel", 1, function() {
    var runTest = function () {
        forge.file.getImage(function () {
            ok(false, "forge.file.getImage returned success");
            start();
        }, function (e) {
            ok(true, "API error callback: "+e.message);
            start();
        });
    };
    askQuestion("In this test press back or cancel rather than choosing an image", { Ok: runTest });
});

asyncTest("File cache - With delete", 6, function () {
    askQuestion("Can you see the following image (loaded from trigger.io):
", { Yes: function () {
        ok(true, "Image loaded from trigger.io");
        forge.file.cacheURL("https://trigger.io/forge-static/img/trigger-light/trigger-io-command-line.jpg", function (file) {
            ok(true, "file.cacheURL claims success");
            forge.file.URL(file, function (url) {
                ok(true, "file.URL claims success");
                askQuestion("Is this the same image:
", { Yes: function () {
                    ok(true, "Image cached correctly");
                    forge.file.remove(file, function () {
                        ok(true, "file.remove claims success");
                        forge.file.isFile(file, function (exists) {
                            ok(!exists, "File deleted");
                            start();
                        });
                    }, function (e) {
                        ok(false, "API error callback: "+e.message);
                        start();
                    });
                }, No: function () {
                    ok(false, "User claims failure");
                    start();
                }});
            }, function (e) {
                ok(false, "API error callback: "+e.message);
                start();
            });
        }, function (e) {
            ok(false, "API error callback: "+e.message);
            start();
        });
    }, No: function () {
        ok(false, "Image not loaded");
        start();
    }});
});

asyncTest("File saving", 4, function () {
    askQuestion("Can you see the following image (loaded from trigger.io):
", { Yes: function () {
        ok(true, "Trigger T loaded from trigger.io");
        forge.file.saveURL("https://trigger.io/forge-static/img/trigger-t.png", function (file) {
            ok(true, "file.saveURL claims success");
            forge.file.URL(file, function (url) {
                ok(true, "file.URL claims success");
                askQuestion("Is this the same image:
", { Yes: function () {
                    ok(true, "Image cached correctly");
                    start();
                }, No: function () {
                    ok(false, "User claims failure");
                    start();
                }});
            }, function (e) {
                ok(false, "API error callback: "+e.message);
                start();
            });
        }, function (e) {
            ok(false, "API error callback: "+e.message);
            start();
        });
    }, No: function () {
        ok(false, "Image not loaded");
        start();
    }});
});

asyncTest("File cache - With clearCache", 6, function () {
    askQuestion("Can you see the following image (loaded from trigger.io):
", { Yes: function () {
        ok(true, "Image loaded from trigger.io");
        forge.file.cacheURL("https://trigger.io/forge-static/img/trigger-light/trigger-io-command-line.jpg", function (file) {
            ok(true, "file.cacheURL claims success");
            forge.file.URL(file, function (url) {
                ok(true, "file.URL claims success");
                askQuestion("Is this the same image:
", { Yes: function () {
                    ok(true, "Image cached correctly");
                    forge.file.clearCache(function () {
                        ok(true, "file.clearCache claims success");
                        forge.file.isFile(file, function (exists) {
                            ok(!exists, "File deleted");
                            start();
                        });
                    }, function (e) {
                        ok(false, "API error callback: "+e.message);
                        start();
                    });
                }, No: function () {
                    ok(false, "User claims failure");
                    start();
                }});
            }, function (e) {
                ok(false, "API error callback: "+e.message);
                start();
            });
        }, function (e) {
            ok(false, "API error callback: "+e.message);
            start();
        });
    }, No: function () {
        ok(false, "Image not loaded");
        start();
    }});
});

asyncTest("Diskspace", 1, function () {
    forge.file.getStorageInformation(function (info) {
        var msg = "Device storage information:
";
        var gig = Math.pow(1024, 3);
        msg += "
Total: " + info.total / gig + "
";
        msg += "
Free: " + info.free / gig + "
";
        msg += "
App: " + info.app / gig + "
";
        msg += "
Cache: " + info.cache / gig + "
";
        msg += "
Does this look correct?";
        askQuestion(msg, {
            Yes: function () {
                ok(true, "Success with forge.file.getStorageInformation");
                start();

            }, No: function () {
                ok(false, "User claims failure with forge.file.getStorageInformation");
                start();
            }
        });
    }, function (e) {
        ok(false, "API call failure: "+e.message);
        start();
    });
});
<commit_msg>Add iOS tests to support move of forge.permissions native code to forge.file<commit_after>/* global forge, module, asyncTest, start, ok, askQuestion */

module("forge.file");

// permissions module native code has to be baked into the file module to avoid app store rejections
if (forge.is.ios()) {
    if (!forge.permissions) {
        forge.permissions = {
            check: function (permission, success, error) {
                forge.internal.call("file.permissions_check", {
                    permission: "ios.permission.photos"
                }, success, error);

            },
            request: function (permission, rationale, success, error) {
                forge.internal.call("file.permissions_request", {
                    permission: "ios.permission.photos",
                    rationale: rationale
                }, success, error);
            },
            photos: {
                "read": "photos_read"
            }
        };
    }

    var rationale = "Can haz fileburger?";

    asyncTest("File permission request denied.", 1, function() {
        var runTest = function() {
            forge.permissions.request(forge.permissions.photos.read, rationale, function (allowed) {
                if (!allowed) {
                    ok(true, "Permission request denied.");
                    start();
                } else {
                    ok(false, "Permission request was allowed. Expected permission denied.");
                    start();
                }
            }, function () {
                ok(false, "API method returned failure");
                start();
            });
        };
        askQuestion("When prompted, deny the permission request", { Ok: runTest });
    });

    asyncTest("File permission request allowed.", 1, function() {
        var runTest = function() {
            forge.permissions.request(forge.permissions.photos.read, rationale, function (allowed) {
                if (allowed) {
                    ok(true, "Permission request allowed.");
                    start();
                } else {
                    ok(false, "Permission request was denied. Expected permission allowed.");
                    start();
                }
            }, function () {
                ok(false, "API method returned failure");
                start();
            });
        };
        askQuestion("When prompted, allow the permission request", { Ok: runTest });
    });
}

asyncTest("Select image from gallery and check file info", 2, function() {
    var runTest = function () {
        forge.file.getImage(function (file) {
            forge.file.info(file, function (info) {
                ok(true, "file.info claims success");
                askQuestion("Does the following file information describe the file: " +
                            JSON.stringify(info), {
                                Yes: function () {
                                    ok(true, "File information is correct");
                                    start();
                                },
                                No: function () {
                                    ok(false, "User claims failure");
                                    start();
                                }
                            });
            }, function (e) {
                ok(false, "API call failure: " + e.message);
                start();
            });
        });
    };
    askQuestion("When prompted select a file from the gallery", { Ok: runTest });
});

asyncTest("Embedding video in webview", 1, function() {
    forge.file.getVideo({
        source: "gallery",
        videoQuality: "low"
    }, function (file) {
        forge.file.URL(file, function (url) {
            askQuestion("Did your video just play: <video controls autoplay width=192 src='" + url + "'></video>", {
                Yes: function () {
                    ok(true, "video capture successful");
                    start();
                }, No: function () {
                    ok(false, "didn't play back just-captured video");
                    start();
                }
            });
        }, function (e) {
            ok(false, "API call failure: "+e.message);
            start();
        });
    }, function (e) {
        ok(false, "API call failure: "+e.message);
        start();
    });
});

asyncTest("Gallery", 5, function() {
    var runTest = function () {
        forge.file.getImage({
            source: "gallery",
            width: 100,
            height: 100
        }, function (file) {
            askQuestion("Were you just prompted to select an image?", { Yes: function () {
                ok(true, "Success");
                forge.file.isFile(file, function (is) {
                    if (is) {
                        ok(true, "forge.file.isFile is true");
                    } else {
                        ok(false, "forge.file.isFile is false");
                    }
                    forge.file.isFile(file, function (is) {
                        if (is) {
                            ok(true, "forge.file.isFile is true");
                        } else {
                            ok(false, "forge.file.isFile is false");
                        }
                        forge.file.URL(file, function (url) {
                            askQuestion("Is this your image:
", { Yes: function () {
                                ok(true, "Success with forge.file.URL");
                                forge.file.base64(file, function (data) {
                                    askQuestion("Is this also your image:
", { Yes: function () {
                                        ok(true, "Success with forge.file.base64");
                                        start();
                                    }, No: function () {
                                        ok(false, "User claims failure with forge.file.base64");
                                        start();
                                    }});
                                }, function (e) {
                                    ok(false, "API call failure: "+e.message);
                                    start();
                                });
                            }, No: function () {
                                ok(false, "User claims failure with forge.file.URL");
                                start();
                            }});
                        }, function (e) {
                            ok(false, "API call failure: "+e.message);
                            start();
                        });
                    }, function (e) {
                        ok(false, "API call failure: "+e.message);
                        start();
                    });
                }, function (e) {
                    ok(false, "API call failure: "+e.message);
                    start();
                });

            }, No: function () {
                ok(false, "User claims failure");
                start();
            }});
        }, function (e) {
            ok(false, "API call failure: "+e.message);
            start();
        });
    };
    askQuestion("In this test use the gallery to select a picture when prompted", { Ok: runTest });
});

asyncTest("Cancel", 1, function() {
    var runTest = function () {
        forge.file.getImage(function () {
            ok(false, "forge.file.getImage returned success");
            start();
        }, function (e) {
            ok(true, "API error callback: "+e.message);
            start();
        });
    };
    askQuestion("In this test press back or cancel rather than choosing an image", { Ok: runTest });
});

asyncTest("File cache - With delete", 6, function () {
    askQuestion("Can you see the following image (loaded from trigger.io):
", { Yes: function () {
        ok(true, "Image loaded from trigger.io");
        forge.file.cacheURL("https://trigger.io/forge-static/img/trigger-light/trigger-io-command-line.jpg", function (file) {
            ok(true, "file.cacheURL claims success");
            forge.file.URL(file, function (url) {
                ok(true, "file.URL claims success");
                askQuestion("Is this the same image:
", { Yes: function () {
                    ok(true, "Image cached correctly");
                    forge.file.remove(file, function () {
                        ok(true, "file.remove claims success");
                        forge.file.isFile(file, function (exists) {
                            ok(!exists, "File deleted");
                            start();
                        });
                    }, function (e) {
                        ok(false, "API error callback: "+e.message);
                        start();
                    });
                }, No: function () {
                    ok(false, "User claims failure");
                    start();
                }});
            }, function (e) {
                ok(false, "API error callback: "+e.message);
                start();
            });
        }, function (e) {
            ok(false, "API error callback: "+e.message);
            start();
        });
    }, No: function () {
        ok(false, "Image not loaded");
        start();
    }});
});

asyncTest("File saving", 4, function () {
    askQuestion("Can you see the following image (loaded from trigger.io):
", { Yes: function () {
        ok(true, "Trigger T loaded from trigger.io");
        forge.file.saveURL("https://trigger.io/forge-static/img/trigger-t.png", function (file) {
            ok(true, "file.saveURL claims success");
            forge.file.URL(file, function (url) {
                ok(true, "file.URL claims success");
                askQuestion("Is this the same image:
", { Yes: function () {
                    ok(true, "Image cached correctly");
                    start();
                }, No: function () {
                    ok(false, "User claims failure");
                    start();
                }});
            }, function (e) {
                ok(false, "API error callback: "+e.message);
                start();
            });
        }, function (e) {
            ok(false, "API error callback: "+e.message);
            start();
        });
    }, No: function () {
        ok(false, "Image not loaded");
        start();
    }});
});

asyncTest("File cache - With clearCache", 6, function () {
    askQuestion("Can you see the following image (loaded from trigger.io):
", { Yes: function () {
        ok(true, "Image loaded from trigger.io");
        forge.file.cacheURL("https://trigger.io/forge-static/img/trigger-light/trigger-io-command-line.jpg", function (file) {
            ok(true, "file.cacheURL claims success");
            forge.file.URL(file, function (url) {
                ok(true, "file.URL claims success");
                askQuestion("Is this the same image:
", { Yes: function () {
                    ok(true, "Image cached correctly");
                    forge.file.clearCache(function () {
                        ok(true, "file.clearCache claims success");
                        forge.file.isFile(file, function (exists) {
                            ok(!exists, "File deleted");
                            start();
                        });
                    }, function (e) {
                        ok(false, "API error callback: "+e.message);
                        start();
                    });
                }, No: function () {
                    ok(false, "User claims failure");
                    start();
                }});
            }, function (e) {
                ok(false, "API error callback: "+e.message);
                start();
            });
        }, function (e) {
            ok(false, "API error callback: "+e.message);
            start();
        });
    }, No: function () {
        ok(false, "Image not loaded");
        start();
    }});
});

asyncTest("Diskspace", 1, function () {
    forge.file.getStorageInformation(function (info) {
        var msg = "Device storage information:
";
        var gig = Math.pow(1024, 3);
        msg += "
Total: " + info.total / gig + "
";
        msg += "
Free: " + info.free / gig + "
";
        msg += "
App: " + info.app / gig + "
";
        msg += "
Cache: " + info.cache / gig + "
";
        msg += "
Does this look correct?";
        askQuestion(msg, {
            Yes: function () {
                ok(true, "Success with forge.file.getStorageInformation");
                start();

            }, No: function () {
                ok(false, "User claims failure with forge.file.getStorageInformation");
                start();
            }
        });
    }, function (e) {
        ok(false, "API call failure: "+e.message);
        start();
    });
});
<|endoftext|>