<commit_before>/** @lends InlineEditableViewComponent */
define(function(require) {
    'use strict';

    /**
     * Allows to connect inline editors on view pages.
     * Currently used only for tags-editor. See [index of supported editors](../editor)
     * @TODO update after connecting other editors
     *
     * Sample:
     *
     * ```twig
     * {% import 'OroUIBundle::macros.html.twig' as UI %}
     * <div class="tags-view-form-container" {{ UI.renderPageComponentAttributes({
     *    module: 'oroform/js/app/components/inline-editable-view-component',
     *    options: {
     *        frontend_type: 'tags',
     *        value: oro_tag_get_list(entity),
     *        fieldName: 'tags',
     *        metadata: {
     *            inline_editing: {
     *                enable: resource_granted('oro_tag_assign_unassign'),
     *                save_api_accessor: {
     *                    route: 'oro_api_post_taggable',
     *                    http_method: 'POST',
     *                    default_route_parameters: {
     *                        entity: oro_class_name(entity, true),
     *                        entityId: entity.id
     *                    }
     *                },
     *                autocomplete_api_accessor: {
     *                    class: 'oroui/js/tools/search-api-accessor',
     *                    search_handler_name: 'tags',
     *                    label_field_name: 'name'
     *                },
     *                editor: {
     *                    view_options: {
     *                        permissions: {
     *                            oro_tag_create: resource_granted('oro_tag_create'),
     *                            oro_tag_unassign_global: resource_granted('oro_tag_unassign_global')
     *                        }
     *                    }
     *                }
     *            }
     *        }
     *    }
     * }) }}></div>
     * ```
     *
     * @class
     * @param {Object} options - Options container
     * @param {Object} options._sourceElement - Element where to connect this view (passed automatically when
     *                                          page component is [connected through DOM attributes](../../../../UIBundle/Resources/doc/reference/page-component.md))
     * @param {string} options.frontend_type - frontend type, please find [available keys here](../../public/js/tools/frontend-type-map.js)
     * @param {*} options.value - value to edit
     * @param {string} options.fieldName - field name to use when sending value to server
     * @param {Object} options.metadata - Editor metadata
     * @param {Object} options.metadata.inline_editing - inline-editing configuration
     *
     * @augments BaseComponent
     * @exports InlineEditableViewComponent
     */
    var InlineEditableViewComponent;
    var _ = require('underscore');
    var __ = require('orotranslation/js/translator');
    var mediator = require('oroui/js/mediator');
    var $ = require('jquery');
    var BaseComponent = require('oroui/js/app/components/base/component');
    var BaseModel = require('oroui/js/app/models/base/model');
    var InlineEditorWrapperView = require('../views/inline-editable-wrapper-view');
    var frontendTypeMap = require('../../tools/frontend-type-map');
    var overlayTool = require('oroui/js/tools/overlay');
    var tools = require('oroui/js/tools');

    InlineEditableViewComponent = BaseComponent.extend(/** @exports InlineEditableViewComponent.prototype */{
        OVERLAY_TOOL_DEFAULTS: {
            position: {
                my: 'left top',
                at: 'left-10 top-6',
                collision: 'flipfit'
            },
            backdrop: true
        },

        METADATA_DEFAULTS: {
            inline_editing: {
                enable: false,
                save_api_accessor: {
                    'class': 'oroui/js/tools/api-accessor'
                }
            }
        },

        WIDTH_INCREMENT: 15,

        /**
         * @constructor
         * @param {Object} options
         */
        initialize: function(options) {
            options.metadata = $.extend(true, {}, this.METADATA_DEFAULTS, options.metadata);
            this.inlineEditingOptions = options.metadata.inline_editing;
            var waitors = [];
            this.fieldName = options.fieldName || 'value';
            // frontend type mapped to viewer/editor/reader
            var classes = frontendTypeMap[options.frontend_type];
            this.classes = classes;
            this.metadata = options.metadata;
            this.model = new BaseModel();
            this.model.set(this.fieldName, options.value);
            if (this.inlineEditingOptions.enable) {
                this.wrapper = new InlineEditorWrapperView({
                    el: options._sourceElement,
                    autoRender: true
                });
                this.view = new classes.viewer(_.extend({
                    el: this.wrapper.getContainer(),
                    autoRender: true,
                    model: this.model,
                    fieldName: this.fieldName
                }));
                if (this.classes.editor.processMetadata) {
                    waitors.push(this.classes.editor.processMetadata(this.metadata));
                }
                this.wrapper.on('start-editing', this.enterEditMode, this);
                waitors.push(tools.loadModuleAndReplace(this.inlineEditingOptions.save_api_accessor, 'class').then(
                    _.bind(function() {
                        var ConcreteApiAccessor = this.inlineEditingOptions.save_api_accessor['class'];
                        this.saveApiAccessor = new ConcreteApiAccessor(
                            _.omit(this.inlineEditingOptions.save_api_accessor, 'class'));
                    }, this)
                ));
            } else {
                this.view = new classes.viewer(_.extend({
                    el: options._sourceElement,
                    autoRender: true,
                    model: this.model,
                    fieldName: this.fieldName
                }));
            }
            this.deferredInit = $.when.apply($, waitors);
        },

        enterEditMode: function() {
            var View = this.classes.editor;
            var viewConfiguration = this.inlineEditingOptions.editor ?
                this.inlineEditingOptions.editor.view_options :
                {};
            var viewInstance = new View(_.extend({}, viewConfiguration, {
                className: 'inline-view-editor',
                autoRender: true,
                model: this.model,
                fieldName: this.fieldName,
                metadata: this.metadata
            }));

            this.editorView = viewInstance;

            viewInstance.$el.addClass('inline-editor-wrapper');

            var overlayOptions = $.extend(true, {}, this.OVERLAY_TOOL_DEFAULTS, {
                position: {
                    of: this.wrapper.$el
                }
            });
            this.resizeTo(viewInstance, this.wrapper);
            this.overlay = overlayTool.createOverlay(viewInstance.$el, overlayOptions);

            this.listenTo(viewInstance, 'saveAction', this.saveCurrentCell);
            this.listenTo(viewInstance, 'saveAndExitAction', this.saveCurrentCellAndExit);
            this.listenTo(viewInstance, 'cancelAction', this.exitEditMode, true);
            this.listenTo(viewInstance, 'saveAndEditNextAction', this.saveCurrentCellAndExit);
            this.listenTo(viewInstance, 'cancelAndEditNextAction', this.exitEditMode);
            this.listenTo(viewInstance, 'saveAndEditPrevAction', this.saveCurrentCellAndExit);
            this.listenTo(viewInstance, 'cancelAndEditPrevAction', this.exitEditMode);
            this.listenTo(viewInstance, 'saveAndEditNextRowAction', this.saveCurrentCellAndExit);
            this.listenTo(viewInstance, 'cancelAndEditNextRowAction', this.exitEditMode);
            this.listenTo(viewInstance, 'saveAndEditPrevRowAction', this.saveCurrentCellAndExit);
            this.listenTo(viewInstance, 'cancelAndEditPrevRowAction', this.exitEditMode);

            return viewInstance;
        },

        exitEditMode: function() {
            this.overlay.remove();
            this.editorView.dispose();
            delete this.editorView;
        },

        saveCurrentCellAndExit: function() {
            if (this.saveCurrentCell(false)) {
                this.exitEditMode(true);
            }
        },

        saveCurrentCell: function(exit) {
            if (!this.editorView) {
                throw Error('Edit mode disabled');
            }
            if (!this.editorView.isChanged()) {
                return true;
            }
            if (!this.editorView.isValid()) {
                this.editorView.focus();
                return false;
            }
            var wrapper = this.wrapper;
            var serverUpdateData = this.editorView.getServerUpdateData();
            var modelUpdateData = this.editorView.getModelUpdateData();
            wrapper.$el.addClass('loading');
            var ctx = {
                wrapper: wrapper,
                oldState: _.pick(this.model.toJSON(), _.keys(modelUpdateData))
            };
            this.updateModel(this.model, this.editorView, modelUpdateData);
            if (this.saveApiAccessor.initialOptions.field_name) {
                var keys = _.keys(serverUpdateData);
                if (keys.length > 1) {
                    throw new Error('Only single field editors are supported with field_name option');
                }
                var newData = {};
                newData[this.saveApiAccessor.initialOptions.field_name] = serverUpdateData[keys[0]];
                serverUpdateData = newData;
            }
            var savePromise = this.saveApiAccessor.send(this.model.toJSON(), serverUpdateData, {}, {
                processingMessage: __('oro.form.inlineEditing.saving_progress'),
                preventWindowUnload: __('oro.form.inlineEditing.inline_edits')
            });

            if (this.classes.editor.processSavePromise) {
                savePromise = this.classes.editor.component.processSavePromise(savePromise, this.metadata);
            }
            savePromise.done(_.bind(InlineEditableViewComponent.onSaveSuccess, ctx))
                .fail(_.bind(InlineEditableViewComponent.onSaveError, ctx))
                .always(function() {
                    wrapper.$el.removeClass('loading');
                });
            if (exit !== false) {
                this.exitEditMode();
            }
            return true;
        },

        updateModel: function(model, editorView, updateData) {
            // assume "undefined" as delete value request
            for (var key in updateData) {
                if (updateData.hasOwnProperty(key)) {
                    if (updateData[key] === editorView.UNSET_FIELD_VALUE) {
                        model.unset(key);
                        delete updateData[key];
                    }
                }
            }
            model.set(updateData);
        },

        /**
         * Resizes editor to base view width
         */
        resizeTo: function(view, baseView) {
            view.$el.css({
                width: baseView.$el.outerWidth() + this.WIDTH_INCREMENT
            });
        }
    }, {
        onSaveSuccess: function() {
            if (!this.wrapper.disposed && this.wrapper.$el) {
                var _this = this;
                this.wrapper.$el.addClass('save-success');
                _.delay(function() {
                    _this.wrapper.$el.removeClass('save-success');
                }, 2000);
            }
            mediator.execute('showFlashMessage', 'success', __('oro.form.inlineEditing.successMessage'));
        },

        onSaveError: function(jqXHR) {
            var errorCode = 'responseJSON' in jqXHR ? jqXHR.responseJSON.code : jqXHR.status;
            if (!this.wrapper.disposed && this.wrapper.$el) {
                var _this = this;
                this.wrapper.$el.addClass('save-fail');
                _.delay(function() {
                    _this.wrapper.$el.removeClass('save-fail');
                }, 2000);
            }
            this.wrapper.model.set(this.oldState);
            this.main.trigger('content:update');

            var errors = [];
            switch (errorCode) {
                case 400:
                    var jqXHRerrors = jqXHR.responseJSON.errors.children;
                    for (var i in jqXHRerrors) {
                        if (jqXHRerrors.hasOwnProperty(i) && jqXHRerrors[i].errors) {
                            errors.push.apply(errors, _.values(jqXHRerrors[i].errors));
                        }
                    }
                    break;
                case 403:
                    errors.push(__('You do not have permission to perform this action.'));
                    break;
                default:
                    errors.push(__('oro.ui.unexpected_error'));
            }

            _.each(errors, function(value) {
                mediator.execute('showFlashMessage', 'error', value);
            });
        }
    });

    return InlineEditableViewComponent;
});
<commit_msg>CRM-4769 Existing tag displayed as new<commit_after>/** @lends InlineEditableViewComponent */
define(function(require) {
    'use strict';

    /**
     * Allows to connect inline editors on view pages.
     * Currently used only for tags-editor. See [index of supported editors](../editor)
     * @TODO update after connecting other editors
     *
     * Sample:
     *
     * ```twig
     * {% import 'OroUIBundle::macros.html.twig' as UI %}
     * <div class="tags-view-form-container" {{ UI.renderPageComponentAttributes({
     *    module: 'oroform/js/app/components/inline-editable-view-component',
     *    options: {
     *        frontend_type: 'tags',
     *        value: oro_tag_get_list(entity),
     *        fieldName: 'tags',
     *        metadata: {
     *            inline_editing: {
     *                enable: resource_granted('oro_tag_assign_unassign'),
     *                save_api_accessor: {
     *                    route: 'oro_api_post_taggable',
     *                    http_method: 'POST',
     *                    default_route_parameters: {
     *                        entity: oro_class_name(entity, true),
     *                        entityId: entity.id
     *                    }
     *                },
     *                autocomplete_api_accessor: {
     *                    class: 'oroui/js/tools/search-api-accessor',
     *                    search_handler_name: 'tags',
     *                    label_field_name: 'name'
     *                },
     *                editor: {
     *                    view_options: {
     *                        permissions: {
     *                            oro_tag_create: resource_granted('oro_tag_create'),
     *                            oro_tag_unassign_global: resource_granted('oro_tag_unassign_global')
     *                        }
     *                    }
     *                }
     *            }
     *        }
     *    }
     * }) }}></div>
     * ```
     *
     * @class
     * @param {Object} options - Options container
     * @param {Object} options._sourceElement - Element where to connect this view (passed automatically when
     *                                          page component is [connected through DOM attributes](../../../../UIBundle/Resources/doc/reference/page-component.md))
     * @param {string} options.frontend_type - frontend type, please find [available keys here](../../public/js/tools/frontend-type-map.js)
     * @param {*} options.value - value to edit
     * @param {string} options.fieldName - field name to use when sending value to server
     * @param {Object} options.metadata - Editor metadata
     * @param {Object} options.metadata.inline_editing - inline-editing configuration
     *
     * @augments BaseComponent
     * @exports InlineEditableViewComponent
     */
    var InlineEditableViewComponent;
    var _ = require('underscore');
    var __ = require('orotranslation/js/translator');
    var mediator = require('oroui/js/mediator');
    var $ = require('jquery');
    var BaseComponent = require('oroui/js/app/components/base/component');
    var BaseModel = require('oroui/js/app/models/base/model');
    var InlineEditorWrapperView = require('../views/inline-editable-wrapper-view');
    var frontendTypeMap = require('../../tools/frontend-type-map');
    var overlayTool = require('oroui/js/tools/overlay');
    var tools = require('oroui/js/tools');

    InlineEditableViewComponent = BaseComponent.extend(/** @exports InlineEditableViewComponent.prototype */{
        OVERLAY_TOOL_DEFAULTS: {
            position: {
                my: 'left top',
                at: 'left-10 top-6',
                collision: 'flipfit'
            },
            backdrop: true
        },

        METADATA_DEFAULTS: {
            inline_editing: {
                enable: false,
                save_api_accessor: {
                    'class': 'oroui/js/tools/api-accessor'
                }
            }
        },

        WIDTH_INCREMENT: 15,

        /**
         * @constructor
         * @param {Object} options
         */
        initialize: function(options) {
            options.metadata = $.extend(true, {}, this.METADATA_DEFAULTS, options.metadata);
            this.inlineEditingOptions = options.metadata.inline_editing;
            var waitors = [];
            this.fieldName = options.fieldName || 'value';
            // frontend type mapped to viewer/editor/reader
            var classes = frontendTypeMap[options.frontend_type];
            this.classes = classes;
            this.metadata = options.metadata;
            this.model = new BaseModel();
            this.model.set(this.fieldName, options.value);
            if (this.inlineEditingOptions.enable) {
                this.wrapper = new InlineEditorWrapperView({
                    el: options._sourceElement,
                    autoRender: true
                });
                this.view = new classes.viewer(_.extend({
                    el: this.wrapper.getContainer(),
                    autoRender: true,
                    model: this.model,
                    fieldName: this.fieldName
                }));
                if (this.classes.editor.processMetadata) {
                    waitors.push(this.classes.editor.processMetadata(this.metadata));
                }
                this.wrapper.on('start-editing', this.enterEditMode, this);
                waitors.push(tools.loadModuleAndReplace(this.inlineEditingOptions.save_api_accessor, 'class').then(
                    _.bind(function() {
                        var ConcreteApiAccessor = this.inlineEditingOptions.save_api_accessor['class'];
                        this.saveApiAccessor = new ConcreteApiAccessor(
                            _.omit(this.inlineEditingOptions.save_api_accessor, 'class'));
                    }, this)
                ));
            } else {
                this.view = new classes.viewer(_.extend({
                    el: options._sourceElement,
                    autoRender: true,
                    model: this.model,
                    fieldName: this.fieldName
                }));
            }
            this.deferredInit = $.when.apply($, waitors);
        },

        enterEditMode: function() {
            var View = this.classes.editor;
            var viewConfiguration = this.inlineEditingOptions.editor ?
                this.inlineEditingOptions.editor.view_options :
                {};
            var viewInstance = new View(_.extend({}, viewConfiguration, {
                className: 'inline-view-editor',
                autoRender: true,
                model: this.model,
                fieldName: this.fieldName,
                metadata: this.metadata
            }));

            this.editorView = viewInstance;

            viewInstance.$el.addClass('inline-editor-wrapper');

            var overlayOptions = $.extend(true, {}, this.OVERLAY_TOOL_DEFAULTS, {
                position: {
                    of: this.wrapper.$el
                }
            });
            this.resizeTo(viewInstance, this.wrapper);
            this.overlay = overlayTool.createOverlay(viewInstance.$el, overlayOptions);

            this.listenTo(viewInstance, 'saveAction', this.saveCurrentCell);
            this.listenTo(viewInstance, 'saveAndExitAction', this.saveCurrentCellAndExit);
            this.listenTo(viewInstance, 'cancelAction', this.exitEditMode, true);
            this.listenTo(viewInstance, 'saveAndEditNextAction', this.saveCurrentCellAndExit);
            this.listenTo(viewInstance, 'cancelAndEditNextAction', this.exitEditMode);
            this.listenTo(viewInstance, 'saveAndEditPrevAction', this.saveCurrentCellAndExit);
            this.listenTo(viewInstance, 'cancelAndEditPrevAction', this.exitEditMode);
            this.listenTo(viewInstance, 'saveAndEditNextRowAction', this.saveCurrentCellAndExit);
            this.listenTo(viewInstance, 'cancelAndEditNextRowAction', this.exitEditMode);
            this.listenTo(viewInstance, 'saveAndEditPrevRowAction', this.saveCurrentCellAndExit);
            this.listenTo(viewInstance, 'cancelAndEditPrevRowAction', this.exitEditMode);

            return viewInstance;
        },

        exitEditMode: function() {
            this.overlay.remove();
            this.editorView.dispose();
            delete this.editorView;
        },

        saveCurrentCellAndExit: function() {
            if (this.saveCurrentCell(false)) {
                this.exitEditMode(true);
            }
        },

        saveCurrentCell: function(exit) {
            if (!this.editorView) {
                throw Error('Edit mode disabled');
            }
            if (!this.editorView.isChanged()) {
                return true;
            }
            if (!this.editorView.isValid()) {
                this.editorView.focus();
                return false;
            }
            var wrapper = this.wrapper;
            var serverUpdateData = this.editorView.getServerUpdateData();
            var modelUpdateData = this.editorView.getModelUpdateData();
            wrapper.$el.addClass('loading');
            var ctx = {
                wrapper: wrapper,
                oldState: _.pick(this.model.toJSON(), _.keys(modelUpdateData))
            };
            this.updateModel(this.model, this.editorView, modelUpdateData);
            if (this.saveApiAccessor.initialOptions.field_name) {
                var keys = _.keys(serverUpdateData);
                if (keys.length > 1) {
                    throw new Error('Only single field editors are supported with field_name option');
                }
                var newData = {};
                newData[this.saveApiAccessor.initialOptions.field_name] = serverUpdateData[keys[0]];
                serverUpdateData = newData;
            }
            var savePromise = this.saveApiAccessor.send(this.model.toJSON(), serverUpdateData, {}, {
                processingMessage: __('oro.form.inlineEditing.saving_progress'),
                preventWindowUnload: __('oro.form.inlineEditing.inline_edits')
            });

            if (this.classes.editor.processSavePromise) {
                savePromise = this.classes.editor.processSavePromise(savePromise, this.metadata);
            }
            savePromise.done(_.bind(InlineEditableViewComponent.onSaveSuccess, ctx))
                .fail(_.bind(InlineEditableViewComponent.onSaveError, ctx))
                .always(function() {
                    wrapper.$el.removeClass('loading');
                });
            if (exit !== false) {
                this.exitEditMode();
            }
            return true;
        },

        updateModel: function(model, editorView, updateData) {
            // assume "undefined" as delete value request
            for (var key in updateData) {
                if (updateData.hasOwnProperty(key)) {
                    if (updateData[key] === editorView.UNSET_FIELD_VALUE) {
                        model.unset(key);
                        delete updateData[key];
                    }
                }
            }
            model.set(updateData);
        },

        /**
         * Resizes editor to base view width
         */
        resizeTo: function(view, baseView) {
            view.$el.css({
                width: baseView.$el.outerWidth() + this.WIDTH_INCREMENT
            });
        }
    }, {
        onSaveSuccess: function() {
            if (!this.wrapper.disposed && this.wrapper.$el) {
                var _this = this;
                this.wrapper.$el.addClass('save-success');
                _.delay(function() {
                    _this.wrapper.$el.removeClass('save-success');
                }, 2000);
            }
            mediator.execute('showFlashMessage', 'success', __('oro.form.inlineEditing.successMessage'));
        },

        onSaveError: function(jqXHR) {
            var errorCode = 'responseJSON' in jqXHR ? jqXHR.responseJSON.code : jqXHR.status;
            if (!this.wrapper.disposed && this.wrapper.$el) {
                var _this = this;
                this.wrapper.$el.addClass('save-fail');
                _.delay(function() {
                    _this.wrapper.$el.removeClass('save-fail');
                }, 2000);
            }
            this.wrapper.model.set(this.oldState);
            this.main.trigger('content:update');

            var errors = [];
            switch (errorCode) {
                case 400:
                    var jqXHRerrors = jqXHR.responseJSON.errors.children;
                    for (var i in jqXHRerrors) {
                        if (jqXHRerrors.hasOwnProperty(i) && jqXHRerrors[i].errors) {
                            errors.push.apply(errors, _.values(jqXHRerrors[i].errors));
                        }
                    }
                    break;
                case 403:
                    errors.push(__('You do not have permission to perform this action.'));
                    break;
                default:
                    errors.push(__('oro.ui.unexpected_error'));
            }

            _.each(errors, function(value) {
                mediator.execute('showFlashMessage', 'error', value);
            });
        }
    });

    return InlineEditableViewComponent;
});
<|endoftext|>


<commit_before>/** Restful API for gradeeditor RegistryItems */
Ext.syncRequire('devilry.extjshelpers.RestProxy');
Ext.define('devilry.gradeeditors.RestfulRegistryItem', {
    extend: 'Ext.data.Model',
    requires: ['devilry.extjshelpers.RestProxy'],

    fields: [
        {name: 'gradeeditorid', type: 'string'},
        {name: 'title', type: 'string'},
        {name: 'description', type: 'string'},
        {name: 'config_editor_url', type: 'string'},
        {name: 'draft_editor_url', type: 'string'}
    ],

    proxy: Ext.create('devilry.extjshelpers.RestProxy', {
        url: DevilrySettings.DEVILRY_URLPATH_PREFIX + '/gradeeditors/restfulgradeeditorconfig/',
        headers: {
            'X_DEVILRY_USE_EXTJS': true
        },
        reader: {
            type: 'json',
            root: 'items',
            totalProperty: 'total'
        }
    })
});
<commit_msg>apps.gradeeditors....RestfulRegistryItem: Use the devilryrestproxy alias.<commit_after>/** Restful API for gradeeditor RegistryItems */
Ext.define('devilry.gradeeditors.RestfulRegistryItem', {
    extend: 'Ext.data.Model',

    fields: [
        {name: 'gradeeditorid', type: 'string'},
        {name: 'title', type: 'string'},
        {name: 'description', type: 'string'},
        {name: 'config_editor_url', type: 'string'},
        {name: 'draft_editor_url', type: 'string'}
    ],

    proxy: {
        type: 'devilryrestproxy',
        url: DevilrySettings.DEVILRY_URLPATH_PREFIX + '/gradeeditors/restfulgradeeditorconfig/',
        headers: {
            'X_DEVILRY_USE_EXTJS': true
        },
        reader: {
            type: 'json',
            root: 'items',
            totalProperty: 'total'
        }
    }
});
<|endoftext|>


<commit_before>if (process.BROWSER_BUILD) {
    (function (i, s, o, g, r, a, m) {
        i.GoogleAnalyticsObject = r; i[r] = i[r] || function () {
            (i[r].q = i[r].q || []).push(arguments);
        }, i[r].l = Number(new Date()); a = s.createElement(o),
        m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m);
    })(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');
    ga('create', 'UA-89526435-1', 'auto');
    ga('require', 'linkid', {
        cookieName: '_ela',
        duration: 300,
        levels: 10
    });
}
<commit_msg>Improve ga<commit_after>// https://nuxtjs.org/faq/google-analytics/

/*
 ** Only run on client-side and only in production mode
 */
if (process.BROWSER_BUILD && process.env.NODE_ENV === 'production') {
    /*
     ** Include Google Analytics Script
     */
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
            (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
        m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
    /*
     ** Set the current page
     */
    ga('create', 'UA-89526435-1', 'auto')
    ga('send', 'pageview')
    /*
     ** When the app is mounted
     */
    window.onNuxtReady((app) => {
        /*
         ** Every time the route changes
         */
        app.$nuxt.$on('routeChanged', (to, from) => {
            /*
             ** We tell Google Analytic to add a page view
             */
            ga('set', 'page', to.fullPath)
            ga('send', 'pageview')
        })
    })
}<|endoftext|>


<commit_before>
import { NSObject } from '$pirouette/foundation';
import { NSWindow, NSApplicationDelegate, NSApplication, NSButton, NSBezelStyle, NSSlider, NSTextField } from '$pirouette/appkit';
import { outlet } from '$pirouette/objc';

class Track {
    constructor() {
        this.volume = 0;
    }
}

let AppDelegate = NSObject.extendClass("AppDelegate", () => ({

    didFinishLaunching: function () {
        let window = this.window;
        let contentView = window.contentView;

        window.title = "Track Mix";
        window.frame = { x: 335, y: 390, width: 300, height: 480 };

        let button = NSButton.newWithFrame({ x: 107, y: 17, width: 82, height: 32 });
        button.title = "Mute";
        button.bezelStyle = NSBezelStyle.Rounded;
        button.clicked = () => this.mute();

        let slider = NSSlider.newWithFrame({ x:138, y: 62, width: 21, height: 321 });
        slider.minValue = 0;
        slider.maxValue = 11;
        slider.valueChanged = () => this.takeValueForVolumeFrom(this.slider);

        let textField = NSTextField.newWithFrame({ x: 80, y: 398, width: 136, height: 22});
        textField.alignment = 2;
        textField.textChanged = () => this.takeValueForVolumeFrom(this.textField);

        contentView.addSubview(button);
        contentView.addSubview(slider);
        contentView.addSubview(textField);

        this.button = button;
        this.slider = slider;
        this.textField = textField;
        this.track = new Track();
        this.updateUserInterface();
    },

    mute: function () {
        this.track.volume = 0;
        this.updateUserInterface();
    },

    takeValueForVolumeFrom: function(sender) {
        this.track.volume = sender.floatValue;
        this.updateUserInterface();
    },

    updateUserInterface: function() {
        let volume = this.track.volume;
        this.textField.floatValue = volume;
        this.slider.floatValue = volume;
    },

    window: outlet(NSWindow)
}), [
    NSApplicationDelegate
]);

NSApplication.main (process.argv);

<commit_msg>Finish our trackmixcode sample after closing the window.<commit_after>
import { NSObject } from '$pirouette/foundation';
import { NSWindow, NSApplicationDelegate, NSApplication, NSButton, NSBezelStyle, NSSlider, NSTextField } from '$pirouette/appkit';
import { outlet } from '$pirouette/objc';

class Track {
    constructor() {
        this.volume = 0;
    }
}

let AppDelegate = NSObject.extendClass("AppDelegate", () => ({

    didFinishLaunching: function () {
        let window = this.window;
        let contentView = window.contentView;

        window.title = "Track Mix";
        window.frame = { x: 335, y: 390, width: 300, height: 480 };

        let button = NSButton.newWithFrame({ x: 107, y: 17, width: 82, height: 32 });
        button.title = "Mute";
        button.bezelStyle = NSBezelStyle.Rounded;
        button.clicked = () => this.mute();

        let slider = NSSlider.newWithFrame({ x:138, y: 62, width: 21, height: 321 });
        slider.minValue = 0;
        slider.maxValue = 11;
        slider.valueChanged = () => this.takeValueForVolumeFrom(this.slider);

        let textField = NSTextField.newWithFrame({ x: 80, y: 398, width: 136, height: 22});
        textField.alignment = 2;
        textField.textChanged = () => this.takeValueForVolumeFrom(this.textField);

        contentView.addSubview(button);
        contentView.addSubview(slider);
        contentView.addSubview(textField);

        this.button = button;
        this.slider = slider;
        this.textField = textField;
        this.track = new Track();
        this.updateUserInterface();
    },

    mute: function () {
        this.track.volume = 0;
        this.updateUserInterface();
    },

    takeValueForVolumeFrom: function(sender) {
        this.track.volume = sender.floatValue;
        this.updateUserInterface();
    },

    updateUserInterface: function() {
        let volume = this.track.volume;
        this.textField.floatValue = volume;
        this.slider.floatValue = volume;
    },

    shouldTerminateAfterLastWindowClosed: function () {
        return false;
    },

    window: outlet(NSWindow)
}), [
    NSApplicationDelegate
]);

NSApplication.main (process.argv);

<|endoftext|>


<commit_before>define(function(require) {
    'use strict';

    var ColumnManagerItemView;
    var $ = require('jquery');
    var tools = require('oroui/js/tools');
    var BaseView = require('oroui/js/app/views/base/view');

    ColumnManagerItemView = BaseView.extend({
        template: require('tpl!orodatagrid/templates/column-manager/column-manager-item.html'),
        tagName: 'tr',

        events: {
            'change input[type=checkbox][data-role=renderable]': 'updateModel'
        },

        listen: {
            // for some reason events delegated in view constructor does not work
            addedToParent: 'delegateEvents',
            // update view on model change
            'change:disabledVisibilityChange model': 'render',
            'change:renderable model': 'updateView'
        },

        /**
         * @inheritDoc
         */
        getTemplateData: function() {
            var data = ColumnManagerItemView.__super__.getTemplateData.call(this);
            data.cid = this.model.cid;
            return data;
        },

        /**
         * Handles DOM event for a column visibility change and updates model's attribute
         *
         * @param {jQuery.Event} e
         */
        updateModel: function(e) {
            var renderable = $(e.target).prop('checked');
            this.model.set('renderable', renderable);
        },

        /**
         * Handles model event and updates the view
         */
        updateView: function() {
            var renderable = this.model.get('renderable');
            this.$('input[type=checkbox][data-role=renderable]').prop('checked', renderable);
        }
    });

    return ColumnManagerItemView;
});
<commit_msg>AEIV-143: Manage Columns<commit_after>define(function(require) {
    'use strict';

    var ColumnManagerItemView;
    var $ = require('jquery');
    var BaseView = require('oroui/js/app/views/base/view');

    ColumnManagerItemView = BaseView.extend({
        template: require('tpl!orodatagrid/templates/column-manager/column-manager-item.html'),
        tagName: 'tr',

        events: {
            'change input[type=checkbox][data-role=renderable]': 'updateModel'
        },

        listen: {
            // for some reason events delegated in view constructor does not work
            addedToParent: 'delegateEvents',
            // update view on model change
            'change:disabledVisibilityChange model': 'render',
            'change:renderable model': 'updateView'
        },

        /**
         * @inheritDoc
         */
        getTemplateData: function() {
            var data = ColumnManagerItemView.__super__.getTemplateData.call(this);
            data.cid = this.model.cid;
            return data;
        },

        /**
         * Handles DOM event for a column visibility change and updates model's attribute
         *
         * @param {jQuery.Event} e
         */
        updateModel: function(e) {
            var renderable = $(e.target).prop('checked');
            this.model.set('renderable', renderable);
        },

        /**
         * Handles model event and updates the view
         */
        updateView: function() {
            var renderable = this.model.get('renderable');
            this.$('input[type=checkbox][data-role=renderable]').prop('checked', renderable);
        }
    });

    return ColumnManagerItemView;
});
<|endoftext|>


<commit_before>var radii = (function(){
    'use strict';

    var dims             = getViewportDimensions();
    var el               = getSVG('foo', dims, '#container');
    var height           = dims.height;
    var width            = dims.width;
    var group            = el.append('g').attr('transform', getCenterTranslation(dims));
    var SIZE             = 20;
    var MAX              = 1;
    var START_RADIUS  = height / 5;
    var OFFSET = 10;
    var data = d3.range(8).map(function(d){return 360 / 8;});
    var pie = d3.layout.pie()(data);
    // create arc path generator, using a fraction
    // of the data size to generate a "growing" spiral

    var radii = [
        [
            10,
            START_RADIUS
        ],
        [
            START_RADIUS + OFFSET,
            START_RADIUS + OFFSET * 2 + START_RADIUS / 2.4
        ],
        [
            START_RADIUS + OFFSET * 2 + START_RADIUS / 2.4 + OFFSET,
            START_RADIUS + OFFSET * 2 + START_RADIUS / 2 + START_RADIUS / 2
        ]
    ];

    function init() {
        var arc1 = d3.svg.arc()
        .innerRadius(function(d){return radii[0][0];})
        .outerRadius(function(d){return radii[0][1];});

        var arc2 = d3.svg.arc()
        .innerRadius(function(d){return radii[1][0];})
        .outerRadius(function(d){return radii[1][1];});

        var arc3 = d3.svg.arc()
        .innerRadius(function(d){return radii[2][0];})
        .outerRadius(function(d){return radii[2][1];});

        createArcGroup([[arc1, 1], [arc2, 0.66], [arc3, 0.33]]);

        circleGroup(20, 100, 1000, 0.6);
        circleGroup(20, 200, 2000, 0.6);
        circleGroup(20, 300, 3000, 0.6);

        circleGroup(5, 100, 1000, 1);
        circleGroup(5, 200, 2000, 1);
        circleGroup(5, 300, 3000, 1);
    }

    function createArcGroup(opacities) {
        for(var i = 0; i < opacities.length; i++) {
            createArc('path-' + i, opacities[i][0], opacities[i][1], i * 500);
        }
    }

    function circleGroup(radius, size, delay, opacity) {
        group
        .selectAll('.dot')
        .data(data)
        .enter()
        .append('circle')
        .attr('r', 0)
        .attr('fill', 'white')
        .transition()
        .delay(function(d, i){return i * 100 + delay;})
        .attr('opacity', opacity)
        .attr('r', radius)
        .attr('cx', function(d, i){return calculateRadialAngle(d, i, size)[0];})
        .attr('cy', function(d, i){return calculateRadialAngle(d, i, size)[1]});
    }

    function createArc(classname, arc, opacity, delay) {
        var paths = group.selectAll(classname)
        .data(pie)
        .enter()
        .append('path')
        .attr('transform', 'rotate(0)')
        .attr('stroke', 'white')
        .attr('fill', 'white')
        .attr('stroke-width', 2)
        .transition()
        .delay(delay)
        .attr('transform', 'rotate(180)')
        .attr('opacity', opacity || 1)
        .attr('fill', function(d, i){return emotions[i].color;})
        .attr('d', arc);
    }

    return {
        'init': init
    };
})();

window.onload = radii.init;
<commit_msg>Out <== baby, bathwater<commit_after>var radii = (function(){
    'use strict';

    var dims             = getViewportDimensions();
    var el               = getSVG('foo', dims, '#container');
    var height           = dims.height;
    var width            = dims.width;
    var group            = el.append('g').attr('transform', getCenterTranslation(dims));
    var SIZE             = 20;
    var MAX              = 1;
    var START_RADIUS  = height / 5;
    var OFFSET = 10;
    var data = d3.range(8).map(function(d){return 360 / 8;});
    var pie = d3.layout.pie()(data);
    var colors = [
        {'color': 'yellow'},
        {'color': 'green'},
        {'color': 'darkGreen'},
        {'color': 'blue'},
        {'color': 'darkBlue'},
        {'color': 'pink'},
        {'color': 'red'},
        {'color': 'orange'}
    ];

    var radii = [
        [
            10,
            START_RADIUS
        ],
        [
            START_RADIUS + OFFSET,
            START_RADIUS + OFFSET * 2 + START_RADIUS / 2.4
        ],
        [
            START_RADIUS + OFFSET * 2 + START_RADIUS / 2.4 + OFFSET,
            START_RADIUS + OFFSET * 2 + START_RADIUS / 2 + START_RADIUS / 2
        ]
    ];

    function init() {
        var arc1 = d3.svg.arc()
        .innerRadius(function(d){return radii[0][0];})
        .outerRadius(function(d){return radii[0][1];});

        var arc2 = d3.svg.arc()
        .innerRadius(function(d){return radii[1][0];})
        .outerRadius(function(d){return radii[1][1];});

        var arc3 = d3.svg.arc()
        .innerRadius(function(d){return radii[2][0];})
        .outerRadius(function(d){return radii[2][1];});

        createArcGroup([[arc1, 1], [arc2, 0.66], [arc3, 0.33]]);

        circleGroup(20, 100, 1000, 0.6);
        circleGroup(20, 200, 2000, 0.6);
        circleGroup(20, 300, 3000, 0.6);

        circleGroup(5, 100, 1000, 1);
        circleGroup(5, 200, 2000, 1);
        circleGroup(5, 300, 3000, 1);
    }

    function createArcGroup(opacities) {
        for(var i = 0; i < opacities.length; i++) {
            createArc('path-' + i, opacities[i][0], opacities[i][1], i * 500);
        }
    }

    function circleGroup(radius, size, delay, opacity) {
        group
        .selectAll('.dot')
        .data(data)
        .enter()
        .append('circle')
        .attr('r', 0)
        .attr('fill', 'white')
        .transition()
        .delay(function(d, i){return i * 100 + delay;})
        .attr('opacity', opacity)
        .attr('r', radius)
        .attr('cx', function(d, i){return calculateRadialAngle(d, i, size)[0];})
        .attr('cy', function(d, i){return calculateRadialAngle(d, i, size)[1]});
    }

    function createArc(classname, arc, opacity, delay) {
        var paths = group.selectAll(classname)
        .data(pie)
        .enter()
        .append('path')
        .attr('transform', 'rotate(0)')
        .attr('stroke', 'white')
        .attr('fill', 'white')
        .attr('stroke-width', 2)
        .transition()
        .delay(delay)
        .attr('transform', 'rotate(180)')
        .attr('opacity', opacity || 1)
        .attr('fill', function(d, i){return colors[i].color;})
        .attr('d', arc);
    }

    return {
        'init': init
    };
})();

window.onload = radii.init;
<|endoftext|>


<commit_before>const fs = require('fs-extra')
const path = require('path')
const CONFIG = require('../config')

module.exports = function () {
  if (fs.existsSync(CONFIG.buildOutputPath)) {
    console.log(`Cleaning ${CONFIG.buildOutputPath}...`);
    fs.removeSync(CONFIG.buildOutputPath)
  }
}
<commit_msg>:art:<commit_after>const fs = require('fs-extra')
const path = require('path')
const CONFIG = require('../config')

module.exports = function () {
  if (fs.existsSync(CONFIG.buildOutputPath)) {
    console.log(`Cleaning ${CONFIG.buildOutputPath}...`)
    fs.removeSync(CONFIG.buildOutputPath)
  }
}
<|endoftext|>


<commit_before>// ==UserScript==
// @name        ic_imgur_stats
// @namespace   foo
// @include     https://community.imgur.com/*
// @version     0.3.1
// @grant       none
// ==/UserScript==

// hook history functions to detect "ajax site changes"
// are there any problems with this approach ? Seem to work like a charm.
// tested with ff (greasemonkey) and chrome (tampermonkey)
var lastUrl = "";
var _oldHistory_pushState = history.pushState;
history.pushState = function(){
  _oldHistory_pushState.apply(this, arguments);
  if(lastUrl != arguments[2]){
    lastUrl = arguments[2];
    $(history).trigger("history_state_changed", arguments);
  }
}
var _oldHistory_replaceState = history.replaceState;
history.replaceState = function(){
  _oldHistory_replaceState.apply(this, arguments);
  if(lastUrl != arguments[2]){
    lastUrl = arguments[2];
    $(history).trigger("history_state_changed", arguments);
  }
}

$(history).on("history_state_changed", function(evt, ob, title, url){
  window.setTimeout(function(){  // TODO: wait till loaded
    if(url.indexOf("/users/") != 0) return;
    var username = $('.primary-textual h1').html().trim().match(/([^\s]*)/)[1];

    if($('#imgur_link').length === 0)
     showImgurInfo(username.trim());
  }, 1000);
  return true;
});

// inject css because why not ?
$(document).ready(function(){
  var node = document.createElement('style');
  node.innerHTML = "#imgur_stats{display: none; width: 70%;}" +
    "#imgur_link:hover #imgur_stats{display: block}";
  document.body.appendChild(node);
});

// create, inject and fill the imgur stats
function showImgurInfo(username){
  var link = $('
'+ username + '

' + '');
  $('.primary-textual h2').replaceWith(link);

  var CLIENT_ID = "cd0695f1226536b";
  var newBox = $('#imgur_stats');
  var tble = $('
' +
               '
Imgur statistics
'+
               '
Account creation	 -
'+
               '
Comments	 -
'+
               '
Submissions	 -
'+
               '
Albums	 -
'+
               '
Images	 -
'+
               '
Favorites	 -
'+
               '
 -
'+
               '
 -
'+
               '
');
  newBox.append(tble);

  // get coments / submission stats
  $.ajax({
    url: 'https://api.imgur.com/3/account/'+username+'/gallery_profile',
    method: 'GET',
    headers: {
      Authorization: 'Client-ID ' + CLIENT_ID,
      Accept: 'application/json'
    },
    success: function(result, status, request) {
      $('#stats_comments').html(result.data.total_gallery_comments.toLocaleString());
      $('#stats_submissions').html(result.data.total_gallery_submissions.toLocaleString());
      $('#stats_favorites').html(result.data.total_gallery_favorites.toLocaleString());
    },
    error: function(a, b, c){
      console.log('Failed to load', a, b, c);
    }
  });

  // get the exact (*) join date. TODO: I bet i messed up the time(zones) here.
  $.ajax({
    url: 'https://api.imgur.com/3/account/'+username,
    method: 'GET',
    headers: {
      Authorization: 'Client-ID ' + CLIENT_ID,
      Accept: 'application/json'
    },
    success: function(result, status, request) {
      $('#stats_created').html( new Date(result.data.created * 1000).toLocaleDateString() );
    },
    error: function(a, b, c){
      console.log('Failed to load', a, b, c);
    }
  });

  // album count (inklusive not submitted to gallery), if album settings are set to public.
  $.ajax({
    url: 'https://api.imgur.com/3/account/'+username + '/albums/count',
    method: 'GET',
    headers: {
      Authorization: 'Client-ID ' + CLIENT_ID,
      Accept: 'application/json'
    },
    success: function(result, status, request) {
      $('#stats_albums').html( result.data.toLocaleString() );
    },
    error: function(a, b, c){
      console.log('Failed to load', a, b, c);
      $('#stats_albums').html( "private" );
    }
  });

  // image count (inklusive not submitted to gallery), if image settings are set to public.
  $.ajax({
    url: 'https://api.imgur.com/3/account/'+username + '/images/count',
    method: 'GET',
    headers: {
      Authorization: 'Client-ID ' + CLIENT_ID,
      Accept: 'application/json'
    },
    success: function(result, status, request) {
      $('#stats_images').html( result.data.toLocaleString() );
    },
    error: function(a, b, c){
      console.log('Failed to load', a, b, c);
      $('#stats_images').html( "private" );
    }
  });

  // creadits remaining (TODO: Remove as soon as imgur api allows the credit fields per CORS)
  $.ajax({
    url: 'https://api.imgur.com/3/credits',
    method: 'GET',
    headers: {
      Authorization: 'Client-ID ' + CLIENT_ID,
      Accept: 'application/json'
    },
    success: function(result, status, request) {
      console.log( result.data );
      $('#stats_credits_user').html( "User Credits: " + result.data.UserRemaining + " / " + result.data.UserLimit);
      $('#stats_credits_script').html( "Script Credits: : " +  result.data.ClientRemaining + " / " + result.data.ClientLimit);
    },
    error: function(a, b, c){
      console.log('Failed to load', a, b, c);
      $('#stats_images').html( "private" );
    }
  });
}
<commit_msg>Made the last patch a bit more stable<commit_after>// ==UserScript==
// @name        ic_imgur_stats
// @namespace   foo
// @include     https://community.imgur.com/*
// @version     0.3.2
// @grant       none
// ==/UserScript==

// hook history functions to detect "ajax site changes"
// are there any problems with this approach ? Seem to work like a charm.
// tested with ff (greasemonkey) and chrome (tampermonkey)
var lastUrl = "";
var _oldHistory_pushState = history.pushState;
history.pushState = function(){
  _oldHistory_pushState.apply(this, arguments);
  if(lastUrl != arguments[2]){
    lastUrl = arguments[2];
    $(history).trigger("history_state_changed", arguments);
  }
}
var _oldHistory_replaceState = history.replaceState;
history.replaceState = function(){
  _oldHistory_replaceState.apply(this, arguments);
  if(lastUrl != arguments[2]){
    lastUrl = arguments[2];
    $(history).trigger("history_state_changed", arguments);
  }
}

$(history).on("history_state_changed", function(evt, ob, title, url){
  window.setTimeout(function(){  // TODO: wait till loaded
    if(url.indexOf("/users/") != 0) return;
    // TODO: [alowed chars in imgur nick]* would be a beter approach, but what is allowed ?
    var username = $('.primary-textual h1').html().trim().match(/([^\s<>'"]*)/)[1];

    if($('#imgur_link').length === 0)
     showImgurInfo(username.trim());
  }, 1000);
  return true;
});

// inject css because why not ?
$(document).ready(function(){
  var node = document.createElement('style');
  node.innerHTML = "#imgur_stats{display: none; width: 70%;}" +
    "#imgur_link:hover #imgur_stats{display: block}";
  document.body.appendChild(node);
});

// create, inject and fill the imgur stats
function showImgurInfo(username){
  var link = $('
'+ username + '

' + '');
  $('.primary-textual h2').replaceWith(link);

  var CLIENT_ID = "cd0695f1226536b";
  var newBox = $('#imgur_stats');
  var tble = $('
' +
               '
Imgur statistics
'+
               '
Account creation	 -
'+
               '
Comments	 -
'+
               '
Submissions	 -
'+
               '
Albums	 -
'+
               '
Images	 -
'+
               '
Favorites	 -
'+
               '
 -
'+
               '
 -
'+
               '
');
  newBox.append(tble);

  // get coments / submission stats
  $.ajax({
    url: 'https://api.imgur.com/3/account/'+username+'/gallery_profile',
    method: 'GET',
    headers: {
      Authorization: 'Client-ID ' + CLIENT_ID,
      Accept: 'application/json'
    },
    success: function(result, status, request) {
      $('#stats_comments').html(result.data.total_gallery_comments.toLocaleString());
      $('#stats_submissions').html(result.data.total_gallery_submissions.toLocaleString());
      $('#stats_favorites').html(result.data.total_gallery_favorites.toLocaleString());
    },
    error: function(a, b, c){
      console.log('Failed to load', a, b, c);
    }
  });

  // get the exact (*) join date. TODO: I bet i messed up the time(zones) here.
  $.ajax({
    url: 'https://api.imgur.com/3/account/'+username,
    method: 'GET',
    headers: {
      Authorization: 'Client-ID ' + CLIENT_ID,
      Accept: 'application/json'
    },
    success: function(result, status, request) {
      $('#stats_created').html( new Date(result.data.created * 1000).toLocaleDateString() );
    },
    error: function(a, b, c){
      console.log('Failed to load', a, b, c);
    }
  });

  // album count (inklusive not submitted to gallery), if album settings are set to public.
  $.ajax({
    url: 'https://api.imgur.com/3/account/'+username + '/albums/count',
    method: 'GET',
    headers: {
      Authorization: 'Client-ID ' + CLIENT_ID,
      Accept: 'application/json'
    },
    success: function(result, status, request) {
      $('#stats_albums').html( result.data.toLocaleString() );
    },
    error: function(a, b, c){
      console.log('Failed to load', a, b, c);
      $('#stats_albums').html( "private" );
    }
  });

  // image count (inklusive not submitted to gallery), if image settings are set to public.
  $.ajax({
    url: 'https://api.imgur.com/3/account/'+username + '/images/count',
    method: 'GET',
    headers: {
      Authorization: 'Client-ID ' + CLIENT_ID,
      Accept: 'application/json'
    },
    success: function(result, status, request) {
      $('#stats_images').html( result.data.toLocaleString() );
    },
    error: function(a, b, c){
      console.log('Failed to load', a, b, c);
      $('#stats_images').html( "private" );
    }
  });

  // creadits remaining (TODO: Remove as soon as imgur api allows the credit fields per CORS)
  $.ajax({
    url: 'https://api.imgur.com/3/credits',
    method: 'GET',
    headers: {
      Authorization: 'Client-ID ' + CLIENT_ID,
      Accept: 'application/json'
    },
    success: function(result, status, request) {
      console.log( result.data );
      $('#stats_credits_user').html( "User Credits: " + result.data.UserRemaining + " / " + result.data.UserLimit);
      $('#stats_credits_script').html( "Script Credits: : " +  result.data.ClientRemaining + " / " + result.data.ClientLimit);
    },
    error: function(a, b, c){
      console.log('Failed to load', a, b, c);
      $('#stats_images').html( "private" );
    }
  });
}
<|endoftext|>


<commit_before>export default angular.module('superdesk.settings', [])
    .config(['superdeskProvider', function(superdesk) {
        superdesk.activity('/settings', {
            label: gettext('Settings'),
            description: gettext('Do some admin chores'),
            controller: angular.noop,
            templateUrl: 'scripts/superdesk-settings/views/main.html',
            category: superdesk.MENU_MAIN,
            priority: 1000,
            adminTools: true,
            _settings: 1
        });
    }])
    .directive('sdSettingsView', ['$route', 'superdesk', function($route, superdesk) {
        return {
            scope: {},
            transclude: true,
            templateUrl: 'scripts/superdesk-settings/views/settings-view.html',
            link: function(scope, elem, attrs) {
                superdesk.getMenu(superdesk.MENU_SETTINGS).then(function(menu) {
                    scope.settings = menu;
                });

                scope.currentRoute = $route.current;
            }
        };
    }])
    .directive('sdDateParam', ['$location', function($location) {
        return {
            scope: true,
            link: function(scope, elem, attrs) {

                var search = $location.search();
                if (search[attrs.location]) {
                    scope.date = search[attrs.location];
                }

                scope.$watch('date', function(date) {
                    if (date != null) {
                        $location.search(attrs.location, date);
                    }
                });
            }
        };
    }])
    .directive('sdValidError', function() {
        return {
            link: function (scope, element) {
                element.addClass('validation-error');
            }
        };
    })
    .directive('sdRoleUnique', ['api', '$q', function(api, $q) {
        return {
            require: 'ngModel',
            link: function (scope, element, attrs, ctrl) {

                /**
                 * Test if given value is unique for seleted field
                 */
                function testUnique(modelValue, viewValue) {
                    var value = modelValue || viewValue;
                    if (value) {
                        var criteria = {where: {'name': value}};
                        if (scope.editRole != null && scope.editRole._id != null) {
                            criteria.where._id = {'$ne': scope.editRole._id};
                        }
                        return api.roles.query(criteria)
                            .then(function(roles) {
                                if (roles._items.length) {
                                    return $q.reject(roles);
                                }
                                return roles;
                            });
                    }

                    // mark as ok
                    return $q.when();
                }

                ctrl.$asyncValidators.unique = testUnique;
            }
        };
    }]);
<commit_msg>fix(date param): SD-5086 Refreshing date param after route change<commit_after>export default angular.module('superdesk.settings', [])
    .config(['superdeskProvider', function(superdesk) {
        superdesk.activity('/settings', {
            label: gettext('Settings'),
            description: gettext('Do some admin chores'),
            controller: angular.noop,
            templateUrl: 'scripts/superdesk-settings/views/main.html',
            category: superdesk.MENU_MAIN,
            priority: 1000,
            adminTools: true,
            _settings: 1
        });
    }])
    .directive('sdSettingsView', ['$route', 'superdesk', function($route, superdesk) {
        return {
            scope: {},
            transclude: true,
            templateUrl: 'scripts/superdesk-settings/views/settings-view.html',
            link: function(scope, elem, attrs) {
                superdesk.getMenu(superdesk.MENU_SETTINGS).then(function(menu) {
                    scope.settings = menu;
                });

                scope.currentRoute = $route.current;
            }
        };
    }])
    .directive('sdDateParam', ['$location', function($location) {
        return {
            scope: true,
            link: function(scope, elem, attrs) {

                var search = $location.search();
                if (search[attrs.location]) {
                    scope.date = search[attrs.location];
                }

                scope.$watch('date', function(date) {
                    if (date != null) {
                        $location.search(attrs.location, date);
                    }
                });

                scope.$on('$routeUpdate', function(event, route) {
                    scope.date = route.params[attrs.location];
                });
            }
        };
    }])
    .directive('sdValidError', function() {
        return {
            link: function (scope, element) {
                element.addClass('validation-error');
            }
        };
    })
    .directive('sdRoleUnique', ['api', '$q', function(api, $q) {
        return {
            require: 'ngModel',
            link: function (scope, element, attrs, ctrl) {

                /**
                 * Test if given value is unique for seleted field
                 */
                function testUnique(modelValue, viewValue) {
                    var value = modelValue || viewValue;
                    if (value) {
                        var criteria = {where: {'name': value}};
                        if (scope.editRole != null && scope.editRole._id != null) {
                            criteria.where._id = {'$ne': scope.editRole._id};
                        }
                        return api.roles.query(criteria)
                            .then(function(roles) {
                                if (roles._items.length) {
                                    return $q.reject(roles);
                                }
                                return roles;
                            });
                    }

                    // mark as ok
                    return $q.when();
                }

                ctrl.$asyncValidators.unique = testUnique;
            }
        };
    }]);
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you 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.
 */

var renderAssets, mouseStop, renderAssetsScroll;

(function () {
    renderAssets = function (data) {
        var el = $('.store-left');
        caramel.css($('head'), data.body['sort-assets'].resources.css, 'sort-assets');
        caramel.code($('head'), data.body['assets'].resources.code);
        caramel.partials(data._.partials, function () {
            var assets = Handlebars.partials['assets'](data.body.assets.context),
                sort = Handlebars.partials['sort-assets'](data.body['sort-assets'].context);
            theme.loaded(el, sort);
            el.append(assets);
            caramel.js($('body'), data.body['assets'].resources.js, 'assets', function () {
                renderAssetsForPagination(data);
                renderPageIndices(data)
            });
            caramel.js($('body'), data.body['sort-assets'].resources.js, 'sort-assets', function () {
                updateSortUI();
            });
            $(document).scrollTop(0);

            infiniteScroll = data.body.assets.context.assets.length >= 12;
        });
    };

    renderAssetsForPagination = function(data){
        var temp = '{{#slice assets size="4"}}
';
        temp += '{{#each .}}';
        temp += '
';
        temp += '	{{#attributes}}';
        temp += '{{#if ../isSubscribed}}';
        temp +=  '

Subscribed

';
        temp +=  '{{/if}}'
        temp += '	';
        temp += '
';
        temp += '		{{#if ../indashboard}}';
        temp += '				';
        temp += '		{{/if}}';
        temp += '	';
        temp += '
 ';
        temp += '
';
        temp += '
';
        temp += '
{{overview_displayName}}
 ';
        temp += '
';
        temp += '
';
        temp += '
';
        temp += '
';
        temp += '
';
        temp += '
';
        temp += '
';
        temp += '
';
        temp += '
{{t "Version"}}
';
        temp += '					{{overview_version}}';
        temp += '
';
        temp += '
';
        temp += '
{{t "Category"}}
';
        temp += '					{{cap ../type}}';
        temp += '
';
        temp += '
';
        temp += '
{{t "Author"}}
';
        temp += '					{{overview_provider}}';
        temp += '
';
        temp += '
';
        temp += '			{{#if ../indashboard}}';
        temp += '			{{t "Bookmarked"}}';
        temp += '			{{else}}';
        temp += '				{{# if ../../../../sso}}';
        temp += '				{{t "Bookmark"}}';
        temp += '				{{else}}';
        temp += '					{{t "Bookmark"}}';
        temp += '				{{/if}}';
        temp += '				{{# if ../../../../user.username}}';
        temp += '				{{t "Bookmark"}}';
        temp += '				{{/if}}';
        temp += '			{{/if}}';
        temp += '
';
        temp += '
';
        temp += '	{{/attributes}}';
        temp += '
';
        temp += '{{/each}}';
        temp += '
{{/slice}}';

        var assetsTemp = Handlebars.compile(temp);
        var render = assetsTemp(data.body.assets.context);
        $('#assets-container').html(render);

        caramel.js($('body'), data.body['assets'].resources.js, 'assets', function () {
//                mouseStop();
        });

    };

    renderPageIndices = function(data){
        var temp = '
';
        temp+= '{{#if leftNav}}';
        temp+= '
«
';
        temp+= '{{/if}}';
        temp+= '{{#each pageIndeces}}';
        temp+= '   {{#if this.isDisabled}}';
        temp+= '
{{this.index}}
';
        temp+= '   {{else}}';
        temp+= '
{{this.index}}
';
        temp+= '   {{/if}}';
        temp+= '{{/each}}';
        temp+= '{{#if rightNav}}';
        temp+= '
»
';
        temp+= '{{/if}}';
        temp+= '
';

        var assetsTemp = Handlebars.compile(temp);
        var render = assetsTemp(data.body.assets.context);
        $('#paging-indices').html(render);

    };

    renderAssetsScroll = function(data){
    	var temp = '{{#slice assets size="4"}}
';
        	temp += '{{#each .}}';
			temp += '
';
			temp += '	{{#attributes}}';
			temp += '	';
			temp += '
';
			temp += '		{{#if ../indashboard}}';
			temp += '				';
			temp += '		{{/if}}';
			temp += '	';
			temp += '
 ';
			temp += '
';
			temp += '
';
			temp += '
{{overview_displayName}}
 ';
			temp += '
';
			temp += '
';
			temp += '
';
			temp += '
';
			temp += '
';
			temp += '
';
			temp += '
';
			temp += '
';
			temp += '
{{t "Version"}}
';
			temp += '					{{overview_version}}';
			temp += '
';
			temp += '
';
			temp += '
{{t "Category"}}
';
			temp += '					{{cap ../type}}';
			temp += '
';
			temp += '
';
			temp += '
{{t "Author"}}
';
			temp += '					{{overview_provider}}';
			temp += '
';
			temp += '
';
			temp += '			{{#if ../indashboard}}';
			temp += '			{{t "Bookmarked"}}';
			temp += '			{{else}}';
			temp += '				{{# if ../../../../sso}}';
			temp += '				{{t "Bookmark"}}';
			temp += '				{{else}}';
			temp += '					{{t "Bookmark"}}';
			temp += '				{{/if}}';
			temp += '				{{# if ../../../../user.username}}';
			temp += '				{{t "Bookmark"}}';
			temp += '				{{/if}}';
			temp += '			{{/if}}';
			temp += '
';
			temp += '
';
			temp += '	{{/attributes}}';
			temp += '
';
			temp += '{{/each}}';
			temp += '
{{/slice}}';

      var assetsTemp = Handlebars.compile(temp);
 	  var render = assetsTemp(data.body.assets.context);
      $('#assets-container').append(render);

       caramel.js($('body'), data.body['assets'].resources.js, 'assets', function () {
//                mouseStop();
            });

    };

//    mouseStop = function () {
//    	var windowWidth = $(window).width();
//    	var offsetTop = windowWidth < 980 ? 167 : 200;
//        var id;
//        $('.asset').mousestop(function () {
//            var that = $(this);
//            id = setTimeout(function () {
//		that.find('.store-bookmark-icon').animate({
//		    top : -200
//		}, 200);
//                that.find('.asset-details').animate({
//                    top: 0
//                }, 200);
//            }, 300);
//        }).mouseleave(function () {
//                clearTimeout(id);
//		$(this).find('.store-bookmark-icon').animate({top: -4}, 200);
//                $(this).find('.asset-details').animate({top: offsetTop}, 200);
//            });
//    };
}());
<commit_msg>fixed the jira APPM-992<commit_after>/*
 * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you 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.
 */

var renderAssets, mouseStop, renderAssetsScroll;

(function () {
    renderAssets = function (data) {
        var el = $('.store-left');
        caramel.css($('head'), data.body['sort-assets'].resources.css, 'sort-assets');
        caramel.code($('head'), data.body['assets'].resources.code);
        caramel.partials(data._.partials, function () {
            var assets = Handlebars.partials['assets'](data.body.assets.context),
                sort = Handlebars.partials['sort-assets'](data.body['sort-assets'].context);
            theme.loaded(el, sort);
            el.append(assets);
            caramel.js($('body'), data.body['assets'].resources.js, 'assets', function () {
                renderAssetsForPagination(data);
                renderPageIndices(data)
            });
            caramel.js($('body'), data.body['sort-assets'].resources.js, 'sort-assets', function () {
                updateSortUI();
            });
            $(document).scrollTop(0);

            infiniteScroll = data.body.assets.context.assets.length >= 12;
        });
    };

    renderAssetsForPagination = function(data){
        var temp = '{{#slice assets size="4"}}
';
        temp += '{{#each .}}';
        temp += '
';
        temp += '	{{#attributes}}';
        temp +=         '{{#if ../isSubscribed}}';
        temp +=             '

Subscribed

';
        temp +=         '{{/if}}'
        temp += '	';
        temp += '
';
        temp += '		{{#if ../indashboard}}';
        temp += '				';
        temp += '		{{/if}}';
        temp += '	';
        temp += '
 ';
        temp += '
';
        temp += '
';
        temp += '
{{overview_displayName}}
 ';
        temp += '
';
        temp += '
';
        temp += '
';
        temp += '
';
        temp += '
';
        temp += '
';
        temp += '
';
        temp += '
';
        temp += '
{{t "Version"}}
';
        temp += '					{{overview_version}}';
        temp += '
';
        temp += '
';
        temp += '
{{t "Category"}}
';
        temp += '					{{cap ../type}}';
        temp += '
';
        temp += '
';
        temp += '
{{t "Author"}}
';
        temp += '					{{overview_provider}}';
        temp += '
';
        temp += '
';
        temp += '			{{#if ../indashboard}}';
        temp += '			{{t "Bookmarked"}}';
        temp += '			{{else}}';
        temp += '				{{# if ../../../../sso}}';
        temp += '				{{t "Bookmark"}}';
        temp += '				{{else}}';
        temp += '					{{t "Bookmark"}}';
        temp += '				{{/if}}';
        temp += '				{{# if ../../../../user.username}}';
        temp += '				{{t "Bookmark"}}';
        temp += '				{{/if}}';
        temp += '			{{/if}}';
        temp += '
';
        temp += '
';
        temp += '	{{/attributes}}';
        temp += '
';
        temp += '{{/each}}';
        temp += '
{{/slice}}';

        var assetsTemp = Handlebars.compile(temp);
        var render = assetsTemp(data.body.assets.context);
        $('#assets-container').html(render);

        caramel.js($('body'), data.body['assets'].resources.js, 'assets', function () {
//                mouseStop();
        });

    };

    renderPageIndices = function(data){
        var temp = '
';
        temp+= '{{#if leftNav}}';
        temp+= '
«
';
        temp+= '{{/if}}';
        temp+= '{{#each pageIndeces}}';
        temp+= '   {{#if this.isDisabled}}';
        temp+= '
{{this.index}}
';
        temp+= '   {{else}}';
        temp+= '
{{this.index}}
';
        temp+= '   {{/if}}';
        temp+= '{{/each}}';
        temp+= '{{#if rightNav}}';
        temp+= '
»
';
        temp+= '{{/if}}';
        temp+= '
';

        var assetsTemp = Handlebars.compile(temp);
        var render = assetsTemp(data.body.assets.context);
        $('#paging-indices').html(render);

    };

    renderAssetsScroll = function(data){
    	var temp = '{{#slice assets size="4"}}
';
        	temp += '{{#each .}}';
			temp += '
';
			temp += '	{{#attributes}}';
			temp += '	';
			temp += '
';
			temp += '		{{#if ../indashboard}}';
			temp += '				';
			temp += '		{{/if}}';
			temp += '	';
			temp += '
 ';
			temp += '
';
			temp += '
';
			temp += '
{{overview_displayName}}
 ';
			temp += '
';
			temp += '
';
			temp += '
';
			temp += '
';
			temp += '
';
			temp += '
';
			temp += '
';
			temp += '
';
			temp += '
{{t "Version"}}
';
			temp += '					{{overview_version}}';
			temp += '
';
			temp += '
';
			temp += '
{{t "Category"}}
';
			temp += '					{{cap ../type}}';
			temp += '
';
			temp += '
';
			temp += '
{{t "Author"}}
';
			temp += '					{{overview_provider}}';
			temp += '
';
			temp += '
';
			temp += '			{{#if ../indashboard}}';
			temp += '			{{t "Bookmarked"}}';
			temp += '			{{else}}';
			temp += '				{{# if ../../../../sso}}';
			temp += '				{{t "Bookmark"}}';
			temp += '				{{else}}';
			temp += '					{{t "Bookmark"}}';
			temp += '				{{/if}}';
			temp += '				{{# if ../../../../user.username}}';
			temp += '				{{t "Bookmark"}}';
			temp += '				{{/if}}';
			temp += '			{{/if}}';
			temp += '
';
			temp += '
';
			temp += '	{{/attributes}}';
			temp += '
';
			temp += '{{/each}}';
			temp += '
{{/slice}}';

      var assetsTemp = Handlebars.compile(temp);
 	  var render = assetsTemp(data.body.assets.context);
      $('#assets-container').append(render);

       caramel.js($('body'), data.body['assets'].resources.js, 'assets', function () {
//                mouseStop();
            });

    };

//    mouseStop = function () {
//    	var windowWidth = $(window).width();
//    	var offsetTop = windowWidth < 980 ? 167 : 200;
//        var id;
//        $('.asset').mousestop(function () {
//            var that = $(this);
//            id = setTimeout(function () {
//		that.find('.store-bookmark-icon').animate({
//		    top : -200
//		}, 200);
//                that.find('.asset-details').animate({
//                    top: 0
//                }, 200);
//            }, 300);
//        }).mouseleave(function () {
//                clearTimeout(id);
//		$(this).find('.store-bookmark-icon').animate({top: -4}, 200);
//                $(this).find('.asset-details').animate({top: offsetTop}, 200);
//            });
//    };
}());
<|endoftext|>


<commit_before>({

	/**
	 * Test Flow:
	 * For each position:
	 * 1. Set the inputDate at the correct position on screen
	 * 2. Check if datepicker is closed initially
	 * 3. Click on calendar icon in inputDate to open datePicker
	 * 4. Wait for datePicker to open
	 * 5. Check if datePicker is positioned below the inputDate and aligned to its left margin
	 */

	testDPPositioningAtPos1 : {
		test : [
		        function(cmp) {
		        	this.setPosition(cmp, "1");
		        },
		        function(cmp) {
		        	this.verifyDatePickerIsClosed(cmp);
		        },
		        function (cmp) {
		        	this.openDatePicker(cmp);
		        },
		        function (cmp) {
		        	this.verifyDatePickerPositioning(cmp);
		        }
		        ]
	},
	testDPPositioningAtPos2 : {
		test : [
		        function(cmp) {
		        	this.setPosition(cmp, "2");
		        },
		        function(cmp) {
		        	this.verifyDatePickerIsClosed(cmp);
		        },
		        function (cmp) {
		        	this.openDatePicker(cmp);
		        },
		        function (cmp) {
		        	this.verifyDatePickerPositioning(cmp);
		        }
		        ]
	},
	testDPPositioningAtPos3 : {
		test : [
		        function(cmp) {
		        	this.setPosition(cmp, "3");
		        },
		        function(cmp) {
		        	this.verifyDatePickerIsClosed(cmp);
		        },
		        function (cmp) {
		        	this.openDatePicker(cmp);
		        },
		        function (cmp) {
		        	this.verifyDatePickerPositioning(cmp);
		        }
		        ]
	},
	testDPPositioningAtPos4 : {
		test : [
		        function(cmp) {
		        	this.setPosition(cmp, "4");
		        },
		        function(cmp) {
		        	this.verifyDatePickerIsClosed(cmp);
		        },
		        function (cmp) {
		        	this.openDatePicker(cmp);
		        },
		        function (cmp) {
		        	this.verifyDatePickerPositioning(cmp);
		        }
		        ]
	},
	testDPPositioningAtPos5 : {
		test : [
		        function(cmp) {
		        	this.setPosition(cmp, "5");
		        },
		        function(cmp) {
		        	this.verifyDatePickerIsClosed(cmp);
		        },
		        function (cmp) {
		        	this.openDatePicker(cmp);
		        },
		        function (cmp) {
		        	this.verifyDatePickerPositioning(cmp);
		        }
		        ]
	},

	testDPPositioningAtPos6 : {
		test : [
		        function(cmp) {
		        	this.setPosition(cmp, "6");
		        },
		        function(cmp) {
		        	this.verifyDatePickerIsClosed(cmp);
		        },
		        function (cmp) {
		        	this.openDatePicker(cmp);
		        },
		        function (cmp) {
		        	this.verifyDatePickerPositioning(cmp);
		        }
		        ]
	},
	testDPPositioningAtPos7 : {
		test : [
		        function(cmp) {
		        	this.setPosition(cmp, "7");
		        },
		        function(cmp) {
		        	this.verifyDatePickerIsClosed(cmp);
		        },
		        function (cmp) {
		        	this.openDatePicker(cmp);
		        },
		        function (cmp) {
		        	this.verifyDatePickerPositioning(cmp);
		        }
		        ]
	},
	testDPPositioningAtPos8 : {
		test : [
		        function(cmp) {
		        	this.setPosition(cmp, "8");
		        },
		        function(cmp) {
		        	this.verifyDatePickerIsClosed(cmp);
		        },
		        function (cmp) {
		        	this.openDatePicker(cmp);
		        },
		        function (cmp) {
		        	this.verifyDatePickerPositioning(cmp);
		        }
		        ]
	},
	testDPPositioningAtPos9 : {
		test : [
		        function(cmp) {
		        	this.setPosition(cmp, "9");
		        },
		        function(cmp) {
		        	this.verifyDatePickerIsClosed(cmp);
		        },
		        function (cmp) {
		        	this.openDatePicker(cmp);
		        },
		        function (cmp) {
		        	this.verifyDatePickerPositioning(cmp);
		        }
		        ]
	},

	setPosition : function(cmp, position) {
		 var newClass = "pos" + position;
		 var inputDateDiv = cmp.find('inputDateDiv').getElement();
		 cmp.find("pos1").set('v.value', "Position 1");

		 cmp.set('v.pos', position);
		 cmp.find(newClass).set('v.value', '');
		 $A.util.swapClass(inputDateDiv, "pos1", newClass);
	},

	verifyDatePickerIsClosed : function (cmp) {
		var datePicker = cmp.find('inputDate').find('datePicker').getElement();
		$A.test.addWaitForWithFailureMessage(false, function(){
			return $A.util.hasClass(datePicker,"visible");
		},"datePicker didn't close");
	},

	openDatePicker : function(cmp) {

		var calendarIcon = $A.test.select('.datePicker-openIcon')[0];
		$A.test.clickOrTouch(calendarIcon);

		$A.test.addWaitForWithFailureMessage(true, function(){
	        var datePicker = cmp.find('inputDate').find('datePicker').getElement();
		    if(($A.util.hasClass(datePicker,"visible"))) {
	          return true;
	        }
		    return false;
   		}, "Date Picker not visible or was not visible at the correct position");
	},

	verifyDatePickerPositioning : function(cmp) {

		var datePicker = cmp.find('inputDate').find('datePicker').getElement();
	    var datePickerRect = datePicker.getBoundingClientRect();
	    var inputDateRect = cmp.find('inputDate').getElement().getBoundingClientRect();

		$A.test.addWaitForWithFailureMessage(true, function(){
			//this is the accepted delta in the positioning of the datePicker with respect to the inputDate
			var epsilon = 15;

		    datePickerRect = datePicker.getBoundingClientRect();
		    inputDateRect = cmp.find('inputDate').getElement().getBoundingClientRect();

	        // check if datePicker is positioned immediately below inputDate and if its left margin is aligned to left margin of inputDate
	        if(((datePickerRect.top + epsilon) >= inputDateRect.bottom) && ((datePickerRect.top - epsilon) <= inputDateRect.bottom)
	         && (datePickerRect.left + epsilon >= 0)
	         && (datePickerRect.top + epsilon >= 0)
	         && (datePickerRect.left + epsilon >= inputDateRect.left) && (datePickerRect.left - epsilon <= inputDateRect.left)){
	            	return true;
	        	}
	        return false;

   		}, "Date Picker not visible or was not visible at the correct position. **DEBUG INFO**:\n datePickerTop=" + datePickerRect.top + "; inputDateBottom=" + inputDateRect.bottom + "; datePickerLeft=" + datePickerRect.left+ "; inputDateLeft=" + inputDateRect.left +"\n");
	}

})
<commit_msg>Disabling datePicker tests for Mobile and Tablet These tests are meant to be run for the desktop version of the datePicker @bug W-2783853@ @rev ctatlah@<commit_after>({

	/**
	 * Test Flow:
	 * For each position:
	 * 1. Set the inputDate at the correct position on screen
	 * 2. Check if datepicker is closed initially
	 * 3. Click on calendar icon in inputDate to open datePicker
	 * 4. Wait for datePicker to open
	 * 5. Check if datePicker is positioned below the inputDate and aligned to its left margin
	 */

	testDPPositioningAtPos1 : {
		browsers: ["-ANDROID_PHONE", "-ANDROID_TABLET", "-IPHONE", "-IPAD"],
		test : [
		        function(cmp) {
		        	this.setPosition(cmp, "1");
		        },
		        function(cmp) {
		        	this.verifyDatePickerIsClosed(cmp);
		        },
		        function (cmp) {
		        	this.openDatePicker(cmp);
		        },
		        function (cmp) {
		        	this.verifyDatePickerPositioning(cmp);
		        }
		        ]
	},
	testDPPositioningAtPos2 : {
		browsers: ["-ANDROID_PHONE", "-ANDROID_TABLET", "-IPHONE", "-IPAD"],
		test : [
		        function(cmp) {
		        	this.setPosition(cmp, "2");
		        },
		        function(cmp) {
		        	this.verifyDatePickerIsClosed(cmp);
		        },
		        function (cmp) {
		        	this.openDatePicker(cmp);
		        },
		        function (cmp) {
		        	this.verifyDatePickerPositioning(cmp);
		        }
		        ]
	},
	testDPPositioningAtPos3 : {
		browsers: ["-ANDROID_PHONE", "-ANDROID_TABLET", "-IPHONE", "-IPAD"],
		test : [
		        function(cmp) {
		        	this.setPosition(cmp, "3");
		        },
		        function(cmp) {
		        	this.verifyDatePickerIsClosed(cmp);
		        },
		        function (cmp) {
		        	this.openDatePicker(cmp);
		        },
		        function (cmp) {
		        	this.verifyDatePickerPositioning(cmp);
		        }
		        ]
	},
	testDPPositioningAtPos4 : {
		browsers: ["-ANDROID_PHONE", "-ANDROID_TABLET", "-IPHONE", "-IPAD"],
		test : [
		        function(cmp) {
		        	this.setPosition(cmp, "4");
		        },
		        function(cmp) {
		        	this.verifyDatePickerIsClosed(cmp);
		        },
		        function (cmp) {
		        	this.openDatePicker(cmp);
		        },
		        function (cmp) {
		        	this.verifyDatePickerPositioning(cmp);
		        }
		        ]
	},
	testDPPositioningAtPos5 : {
		browsers: ["-ANDROID_PHONE", "-ANDROID_TABLET", "-IPHONE", "-IPAD"],
		test : [
		        function(cmp) {
		        	this.setPosition(cmp, "5");
		        },
		        function(cmp) {
		        	this.verifyDatePickerIsClosed(cmp);
		        },
		        function (cmp) {
		        	this.openDatePicker(cmp);
		        },
		        function (cmp) {
		        	this.verifyDatePickerPositioning(cmp);
		        }
		        ]
	},

	testDPPositioningAtPos6 : {
		browsers: ["-ANDROID_PHONE", "-ANDROID_TABLET", "-IPHONE", "-IPAD"],
		test : [
		        function(cmp) {
		        	this.setPosition(cmp, "6");
		        },
		        function(cmp) {
		        	this.verifyDatePickerIsClosed(cmp);
		        },
		        function (cmp) {
		        	this.openDatePicker(cmp);
		        },
		        function (cmp) {
		        	this.verifyDatePickerPositioning(cmp);
		        }
		        ]
	},
	testDPPositioningAtPos7 : {
		browsers: ["-ANDROID_PHONE", "-ANDROID_TABLET", "-IPHONE", "-IPAD"],
		test : [
		        function(cmp) {
		        	this.setPosition(cmp, "7");
		        },
		        function(cmp) {
		        	this.verifyDatePickerIsClosed(cmp);
		        },
		        function (cmp) {
		        	this.openDatePicker(cmp);
		        },
		        function (cmp) {
		        	this.verifyDatePickerPositioning(cmp);
		        }
		        ]
	},
	testDPPositioningAtPos8 : {
		browsers: ["-ANDROID_PHONE", "-ANDROID_TABLET", "-IPHONE", "-IPAD"],
		test : [
		        function(cmp) {
		        	this.setPosition(cmp, "8");
		        },
		        function(cmp) {
		        	this.verifyDatePickerIsClosed(cmp);
		        },
		        function (cmp) {
		        	this.openDatePicker(cmp);
		        },
		        function (cmp) {
		        	this.verifyDatePickerPositioning(cmp);
		        }
		        ]
	},
	testDPPositioningAtPos9 : {
		browsers: ["-ANDROID_PHONE", "-ANDROID_TABLET", "-IPHONE", "-IPAD"],
		test : [
		        function(cmp) {
		        	this.setPosition(cmp, "9");
		        },
		        function(cmp) {
		        	this.verifyDatePickerIsClosed(cmp);
		        },
		        function (cmp) {
		        	this.openDatePicker(cmp);
		        },
		        function (cmp) {
		        	this.verifyDatePickerPositioning(cmp);
		        }
		        ]
	},

	setPosition : function(cmp, position) {
		 var newClass = "pos" + position;
		 var inputDateDiv = cmp.find('inputDateDiv').getElement();
		 cmp.find("pos1").set('v.value', "Position 1");

		 cmp.set('v.pos', position);
		 cmp.find(newClass).set('v.value', '');
		 $A.util.swapClass(inputDateDiv, "pos1", newClass);
	},

	verifyDatePickerIsClosed : function (cmp) {
		var datePicker = cmp.find('inputDate').find('datePicker').getElement();
		$A.test.addWaitForWithFailureMessage(false, function(){
			return $A.util.hasClass(datePicker,"visible");
		},"datePicker didn't close");
	},

	openDatePicker : function(cmp) {

		var calendarIcon = $A.test.select('.datePicker-openIcon')[0];
		$A.test.clickOrTouch(calendarIcon);

		$A.test.addWaitForWithFailureMessage(true, function(){
	        var datePicker = cmp.find('inputDate').find('datePicker').getElement();
		    if(($A.util.hasClass(datePicker,"visible"))) {
	          return true;
	        }
		    return false;
   		}, "Date Picker not visible or was not visible at the correct position");
	},

	verifyDatePickerPositioning : function(cmp) {

		var datePicker = cmp.find('inputDate').find('datePicker').getElement();
	    var datePickerRect = datePicker.getBoundingClientRect();
	    var inputDateRect = cmp.find('inputDate').getElement().getBoundingClientRect();

		$A.test.addWaitForWithFailureMessage(true, function(){
			//this is the accepted delta in the positioning of the datePicker with respect to the inputDate
			var epsilon = 15;

		    datePickerRect = datePicker.getBoundingClientRect();
		    inputDateRect = cmp.find('inputDate').getElement().getBoundingClientRect();

	        // check if datePicker is positioned immediately below inputDate and if its left margin is aligned to left margin of inputDate
	        if(((datePickerRect.top + epsilon) >= inputDateRect.bottom) && ((datePickerRect.top - epsilon) <= inputDateRect.bottom)
	         && (datePickerRect.left + epsilon >= 0)
	         && (datePickerRect.top + epsilon >= 0)
	         && (datePickerRect.left + epsilon >= inputDateRect.left) && (datePickerRect.left - epsilon <= inputDateRect.left)){
	            	return true;
	        	}
	        return false;

   		}, "Date Picker not visible or was not visible at the correct position. **DEBUG INFO**:\n datePickerTop=" + datePickerRect.top + "; inputDateBottom=" + inputDateRect.bottom + "; datePickerLeft=" + datePickerRect.left+ "; inputDateLeft=" + inputDateRect.left +"\n");
	}

})
<|endoftext|>