<commit_before>/*
 *
 * (c) Copyright Ascensio System SIA 2010-2019
 *
 * This program is a free software product. You can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License (AGPL)
 * version 3 as published by the Free Software Foundation. In accordance with
 * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
 * that Ascensio System SIA expressly excludes the warranty of non-infringement
 * of any third-party rights.
 *
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR  PURPOSE. For
 * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
 *
 * You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha
 * street, Riga, Latvia, EU, LV-1050.
 *
 * The  interactive user interfaces in modified source and object code versions
 * of the Program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU AGPL version 3.
 *
 * Pursuant to Section 7(b) of the License you must retain the original Product
 * logo when distributing the program. Pursuant to Section 7(e) we decline to
 * grant you any rights under trademark law for use of our trademarks.
 *
 * All the Product's GUI elements, including illustrations and icon sets, as
 * well as technical writing content are licensed under the terms of the
 * Creative Commons Attribution-ShareAlike 4.0 International. See the License
 * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
 *
*/
/**
 * User: Julia.Radzhabova
 * Date: 14.12.17
 */

define([
    'core',
    'documenteditor/main/app/collection/Navigation',
    'documenteditor/main/app/view/Navigation'
], function () {
    'use strict';

    DE.Controllers.Navigation = Backbone.Controller.extend(_.extend({
        models: [],
        collections: [
            'Navigation'
        ],
        views: [
            'Navigation'
        ],

        initialize: function() {
            var me = this;
            this.addListeners({
                'Navigation': {
                    'show': function() {
                        if (!this.canUseViwerNavigation) {
                            me.api.asc_ShowDocumentOutline();
                        } else {
                            if (me.panelNavigation && me.panelNavigation.viewNavigationList && me.panelNavigation.viewNavigationList.scroller)
                                me.panelNavigation.viewNavigationList.scroller.update({alwaysVisibleY: true});
                        }
                        if (!me.mode.isEdit && !me.mode.isRestrictedEdit)
                            me.panelNavigation.viewNavigationList.focus();
                    },
                    'hide': function() {
                        if (!this.canUseViwerNavigation) {
                            me.api && me.api.asc_HideDocumentOutline();
                        }
                    }
                }
            });
        },

        events: function() {
        },

        onLaunch: function() {
            this.panelNavigation= this.createView('Navigation', {
                storeNavigation: this.getApplication().getCollection('Navigation')
            });
            this.panelNavigation.on('render:after', _.bind(this.onAfterRender, this));
            this._navigationObject = null;
            this._viewerNavigationObject = null;
            this._isDisabled = false;
        },

        setApi: function(api) {
            this.api = api;
            this.api.asc_registerCallback('asc_onDocumentOutlineUpdate', _.bind(this.updateNavigation, this));
            this.api.asc_registerCallback('asc_onDocumentOutlineCurrentPosition', _.bind(this.onChangeOutlinePosition, this));
            this.api.asc_registerCallback('asc_onDocumentOutlineUpdateAdd', _.bind(this.updateNavigation, this));
            this.api.asc_registerCallback('asc_onDocumentOutlineUpdateChange', _.bind(this.updateChangeNavigation, this));
            this.api.asc_registerCallback('asc_onDocumentOutlineUpdateRemove', _.bind(this.updateNavigation, this));

            this.api.asc_registerCallback('asc_onViewerBookmarksUpdate', _.bind(this.updateViewerNavigation, this));
            return this;
        },

        setMode: function(mode) {
            this.mode = mode;
            this.canUseViwerNavigation = this.mode.canUseViwerNavigation;
            if (this.panelNavigation && this.panelNavigation.viewNavigationList) {
                this.panelNavigation.viewNavigationList.setEmptyText(this.mode.isEdit ? this.panelNavigation.txtEmpty : this.panelNavigation.txtEmptyViewer);
                this.panelNavigation.viewNavigationList.enableKeyEvents = !this.mode.isEdit && !this.mode.isRestrictedEdit;
            }
            return this;
        },

        onAfterRender: function(panelNavigation) {
            panelNavigation.viewNavigationList.on('item:click', _.bind(this.onSelectItem, this));
            panelNavigation.viewNavigationList.on('item:contextmenu', _.bind(this.onItemContextMenu, this));
            panelNavigation.viewNavigationList.on('item:add', _.bind(this.onItemAdd, this));
            panelNavigation.navigationMenu.on('item:click',           _.bind(this.onMenuItemClick, this));
            panelNavigation.navigationMenu.items[11].menu.on('item:click', _.bind(this.onMenuLevelsItemClick, this));
            panelNavigation.btnSettingsMenu.on('item:click',           _.bind(this.onMenuSettingsItemClick, this));
            panelNavigation.btnSettingsMenu.items[2].menu.on('item:click', _.bind(this.onMenuLevelsItemClick, this));
            panelNavigation.btnSettingsMenu.items[4].menu.on('item:click', _.bind(this.onMenuFontSizeClick, this));
            panelNavigation.btnClose.on('click', _.bind(this.onClickClosePanel, this));

            var viewport = this.getApplication().getController('Viewport').getView('Viewport');
            viewport.hlayout.on('layout:resizedrag',  function () {
                if (panelNavigation.viewNavigationList && panelNavigation.viewNavigationList.scroller)
                    panelNavigation.viewNavigationList.scroller.update({alwaysVisibleY: true});
            });
        },

        updateNavigation: function() {
            if (!this._navigationObject)
                this._navigationObject = this.api.asc_GetDocumentOutlineManager();

            if (!this._navigationObject) return;

            var count = this._navigationObject.get_ElementsCount(),
                prev_level = -1,
                header_level = -1,
                first_header = !this._navigationObject.isFirstItemNotHeader(),
                arr = [];
            for (var i=0; i<count; i++) {
                var level = this._navigationObject.get_Level(i),
                    hasParent = true;
                if (level>prev_level && i>0)
                    arr[i-1].set('hasSubItems', true);
                if (header_level<0 || level<=header_level) {
                    if (i>0 || first_header)
                        header_level = level;
                    hasParent = false;
                }
                arr.push(new Common.UI.TreeViewModel({
                    name : this._navigationObject.get_Text(i),
                    level: level,
                    index: i,
                    hasParent: hasParent,
                    isEmptyItem: this._navigationObject.isEmptyItem(i)
                }));
                prev_level = level;
            }
            if (count>0 && !first_header) {
                arr[0].set('hasSubItems', false);
                arr[0].set('isNotHeader', true);
                arr[0].set('name', this.txtBeginning);
                arr[0].set('tip', this.txtGotoBeginning);
            }

            var me = this;
            var store = this.getApplication().getCollection('Navigation');//.reset(arr);
            store.reset(arr.splice(0, 50));

            this._currentPos = this._navigationObject.get_CurrentPosition();

            function addToPanel() {
                if (arr.length<1) {
                    me.panelNavigation.viewNavigationList.scroller && me.panelNavigation.viewNavigationList.scroller.update({alwaysVisibleY: true});
                    if (me._currentPos>-1 && me._currentPos<store.length)
                        me.onChangeOutlinePosition(me._currentPos);
                    me._currentPos = -1;
                    return;
                }
                setTimeout(function () {
                    store.add(arr.splice(0, 100));
                    if (me._currentPos>-1 && me._currentPos<store.length) {
                        me.onChangeOutlinePosition(me._currentPos);
                        me._currentPos = -1;
                    }
                    addToPanel();
                }, 1);
            }
            addToPanel();
        },

        updateChangeNavigation: function(index) {
            if (!this._navigationObject)
                this._navigationObject = this.api.asc_GetDocumentOutlineManager();

            if (!this._navigationObject) return;

            var item = this.getApplication().getCollection('Navigation').at(index);
            if (item.get('level') !== this._navigationObject.get_Level(index) ||
                index==0 && item.get('isNotHeader') !== this._navigationObject.isFirstItemNotHeader()) {
                this.updateNavigation();
            } else {
                item.set('name', this._navigationObject.get_Text(index));
                item.set('isEmptyItem', this._navigationObject.isEmptyItem(index));
                this.panelNavigation.viewNavigationList.updateTip(item.get('dataItem'));
            }
        },

        onChangeOutlinePosition: function(index) {
            if (index<this.panelNavigation.viewNavigationList.store.length)
                this.panelNavigation.viewNavigationList.scrollToRecord(this.panelNavigation.viewNavigationList.selectByIndex(index));
            else
                this._currentPos = index;
        },

        onItemContextMenu: function(picker, item, record, e){
            var showPoint;
            var menu = this.panelNavigation.navigationMenu;
            if (menu.isVisible()) {
                menu.hide();
            }

            var parentOffset = this.panelNavigation.$el.offset(),
                top = e.clientY*Common.Utils.zoom();
            showPoint = [e.clientX*Common.Utils.zoom() + 5, top - parentOffset.top + 5];

            for (var i=0; i<7; i++) {
                menu.items[i].setVisible(this.mode.isEdit);
            }

            menu.items[7].setVisible(!this.canUseViwerNavigation);
            menu.items[8].setVisible(!this.canUseViwerNavigation);

            var isNotHeader = record.get('isNotHeader');
            menu.items[0].setDisabled(isNotHeader || this._isDisabled);
            menu.items[1].setDisabled(isNotHeader || this._isDisabled);
            menu.items[3].setDisabled(isNotHeader || this._isDisabled);
            menu.items[4].setDisabled(this._isDisabled);
            menu.items[5].setDisabled(this._isDisabled);
            menu.items[7].setDisabled(isNotHeader);

            if (showPoint != undefined) {
                var menuContainer = this.panelNavigation.$el.find('#menu-navigation-container');
                if (!menu.rendered) {
                    if (menuContainer.length < 1) {
                        menuContainer = $('

', menu.id);
                        $(this.panelNavigation.$el).append(menuContainer);
                    }
                    menu.render(menuContainer);
                    menu.cmpEl.attr({tabindex: "-1"});
                }
                menu.cmpEl.attr('data-value', record.get('index'));
                menuContainer.css({
                    left: showPoint[0],
                    top: showPoint[1]
                });
                menu.show();
                _.delay(function() {
                    menu.cmpEl.focus();
                }, 10);
            }

        },

        onSelectItem: function(picker, item, record, e){
            if (this._navigationObject) {
                this._navigationObject.goto(record.get('index'));
            } else if (this._viewerNavigationObject) {
                this.api.asc_viewerNavigateTo(record.get('index'));
            }
            (this.mode.isEdit || this.mode.isRestrictedEdit) && Common.NotificationCenter.trigger('edit:complete', this.panelNavigation);
        },

        onItemAdd: function(picker, item, record, e){
            record.set('dataItem', item);
        },

        onMenuItemClick: function (menu, item) {
            if (!this._navigationObject && !this._viewerNavigationObject) return;
            var index = parseInt(menu.cmpEl.attr('data-value'));
            if (item.value == 'promote') {
                this._navigationObject.promote(index);
            } else if (item.value == 'demote') {
                this._navigationObject.demote(index);
            } else if (item.value == 'before') {
                this._navigationObject.insertHeader(index, true);
            } else if (item.value == 'after') {
                this._navigationObject.insertHeader(index, false);
            } else if (item.value == 'new') {
                this._navigationObject.insertSubHeader(index);
            } else if (item.value == 'select') {
                this._navigationObject.selectContent(index);
            } else if (item.value == 'expand') {
                this.panelNavigation.viewNavigationList.expandAll();
            } else  if (item.value == 'collapse') {
                this.panelNavigation.viewNavigationList.collapseAll();
            }
        },
        onClickClosePanel: function() {
            Common.NotificationCenter.trigger('leftmenu:change', 'hide');
        },

        onMenuSettingsItemClick: function (menu, item){
            switch (item.value){
                case 'expand':
                    this.panelNavigation.viewNavigationList.expandAll();
                    break;
                case 'collapse':
                    this.panelNavigation.viewNavigationList.collapseAll();
                    break;
                case 'wrap':
                    this.panelNavigation.changeWrapHeadings();
                    break;
            }
        },

        onMenuLevelsItemClick: function (menu, item) {
            this.panelNavigation.viewNavigationList.expandToLevel(item.value-1);
        },

        onMenuFontSizeClick: function (menu, item){
            this.panelNavigation.changeFontSize(item.value);
        },

        SetDisabled: function(state) {
            this._isDisabled = state;
        },

        updateViewerNavigation: function (bookmarks) {
            this._viewerNavigationObject = bookmarks.length > 0 ? bookmarks : null;
            if (this._viewerNavigationObject) {
                var count = this._viewerNavigationObject.length,
                    prev_level = -1,
                    header_level = -1,
                    first_header = true,//!this._navigationObject.isFirstItemNotHeader(),
                    arr = [];
                for (var i = 0; i < count; i++) {
                    var level = this._viewerNavigationObject[i].level - 1,
                        hasParent = true;
                    if (level > prev_level && i > 0)
                        arr[i - 1].set('hasSubItems', true);
                    if (header_level < 0 || level <= header_level) {
                        if (i > 0 || first_header)
                            header_level = level;
                        hasParent = false;
                    }
                    arr.push(new Common.UI.TreeViewModel({
                        name: this._viewerNavigationObject[i].description,
                        level: level,
                        index: i,
                        hasParent: hasParent,
                        isEmptyItem: !this._viewerNavigationObject[i].description
                    }));
                    prev_level = level;
                }
                if (count > 0 && !first_header) {
                    arr[0].set('hasSubItems', false);
                    arr[0].set('isNotHeader', true);
                    arr[0].set('name', this.txtBeginning);
                    arr[0].set('tip', this.txtGotoBeginning);
                }
                this.getApplication().getCollection('Navigation').reset(arr);
                if (this.panelNavigation && this.panelNavigation.viewNavigationList && this.panelNavigation.viewNavigationList.scroller)
                    this.panelNavigation.viewNavigationList.scroller.update({alwaysVisibleY: true});
            }
        },

        txtBeginning: 'Beginning of document',
        txtGotoBeginning: 'Go to the beginning of the document'

    }, DE.Controllers.Navigation || {}));
});
<commit_msg>Refactoring<commit_after>/*
 *
 * (c) Copyright Ascensio System SIA 2010-2019
 *
 * This program is a free software product. You can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License (AGPL)
 * version 3 as published by the Free Software Foundation. In accordance with
 * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
 * that Ascensio System SIA expressly excludes the warranty of non-infringement
 * of any third-party rights.
 *
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR  PURPOSE. For
 * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
 *
 * You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha
 * street, Riga, Latvia, EU, LV-1050.
 *
 * The  interactive user interfaces in modified source and object code versions
 * of the Program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU AGPL version 3.
 *
 * Pursuant to Section 7(b) of the License you must retain the original Product
 * logo when distributing the program. Pursuant to Section 7(e) we decline to
 * grant you any rights under trademark law for use of our trademarks.
 *
 * All the Product's GUI elements, including illustrations and icon sets, as
 * well as technical writing content are licensed under the terms of the
 * Creative Commons Attribution-ShareAlike 4.0 International. See the License
 * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
 *
*/
/**
 * User: Julia.Radzhabova
 * Date: 14.12.17
 */

define([
    'core',
    'documenteditor/main/app/collection/Navigation',
    'documenteditor/main/app/view/Navigation'
], function () {
    'use strict';

    DE.Controllers.Navigation = Backbone.Controller.extend(_.extend({
        models: [],
        collections: [
            'Navigation'
        ],
        views: [
            'Navigation'
        ],

        initialize: function() {
            var me = this;
            this.addListeners({
                'Navigation': {
                    'show': function() {
                        if (!this.canUseViwerNavigation) {
                            me.api.asc_ShowDocumentOutline();
                        } else {
                            if (me.panelNavigation && me.panelNavigation.viewNavigationList && me.panelNavigation.viewNavigationList.scroller)
                                me.panelNavigation.viewNavigationList.scroller.update({alwaysVisibleY: true});
                        }
                        if (!me.mode.isEdit && !me.mode.isRestrictedEdit)
                            me.panelNavigation.viewNavigationList.focus();
                    },
                    'hide': function() {
                        if (!this.canUseViwerNavigation) {
                            me.api && me.api.asc_HideDocumentOutline();
                        }
                    }
                }
            });
        },

        events: function() {
        },

        onLaunch: function() {
            this.panelNavigation= this.createView('Navigation', {
                storeNavigation: this.getApplication().getCollection('Navigation')
            });
            this.panelNavigation.on('render:after', _.bind(this.onAfterRender, this));
            this._navigationObject = null;
            this._viewerNavigationObject = null;
            this._isDisabled = false;
        },

        setApi: function(api) {
            this.api = api;
            this.api.asc_registerCallback('asc_onDocumentOutlineUpdate', _.bind(this.updateNavigation, this));
            this.api.asc_registerCallback('asc_onDocumentOutlineCurrentPosition', _.bind(this.onChangeOutlinePosition, this));
            this.api.asc_registerCallback('asc_onDocumentOutlineUpdateAdd', _.bind(this.updateNavigation, this));
            this.api.asc_registerCallback('asc_onDocumentOutlineUpdateChange', _.bind(this.updateChangeNavigation, this));
            this.api.asc_registerCallback('asc_onDocumentOutlineUpdateRemove', _.bind(this.updateNavigation, this));

            this.api.asc_registerCallback('asc_onViewerBookmarksUpdate', _.bind(this.updateViewerNavigation, this));
            return this;
        },

        setMode: function(mode) {
            this.mode = mode;
            this.canUseViwerNavigation = this.mode.canUseViwerNavigation;
            if (this.panelNavigation && this.panelNavigation.viewNavigationList) {
                this.panelNavigation.viewNavigationList.setEmptyText(this.mode.isEdit ? this.panelNavigation.txtEmpty : this.panelNavigation.txtEmptyViewer);
                this.panelNavigation.viewNavigationList.enableKeyEvents = !this.mode.isEdit && !this.mode.isRestrictedEdit;
            }
            return this;
        },

        onAfterRender: function(panelNavigation) {
            panelNavigation.viewNavigationList.on('item:click', _.bind(this.onSelectItem, this));
            panelNavigation.viewNavigationList.on('item:contextmenu', _.bind(this.onItemContextMenu, this));
            panelNavigation.viewNavigationList.on('item:add', _.bind(this.onItemAdd, this));
            panelNavigation.navigationMenu.on('item:click',           _.bind(this.onMenuItemClick, this));
            panelNavigation.navigationMenu.items[11].menu.on('item:click', _.bind(this.onMenuLevelsItemClick, this));
            panelNavigation.btnSettingsMenu.on('item:click',           _.bind(this.onMenuSettingsItemClick, this));
            panelNavigation.btnSettingsMenu.items[2].menu.on('item:click', _.bind(this.onMenuLevelsItemClick, this));
            panelNavigation.btnSettingsMenu.items[4].menu.on('item:click', _.bind(this.onMenuFontSizeClick, this));
            panelNavigation.btnClose.on('click', _.bind(this.onClickClosePanel, this));

            var viewport = this.getApplication().getController('Viewport').getView('Viewport');
            viewport.hlayout.on('layout:resizedrag',  function () {
                if (panelNavigation.viewNavigationList && panelNavigation.viewNavigationList.scroller)
                    panelNavigation.viewNavigationList.scroller.update({alwaysVisibleY: true});
            });
        },

        updateNavigation: function() {
            if (!this._navigationObject)
                this._navigationObject = this.api.asc_GetDocumentOutlineManager();

            if (!this._navigationObject) return;

            var count = this._navigationObject.get_ElementsCount(),
                prev_level = -1,
                header_level = -1,
                first_header = !this._navigationObject.isFirstItemNotHeader(),
                arr = [];
            for (var i=0; i<count; i++) {
                var level = this._navigationObject.get_Level(i),
                    hasParent = true;
                if (level>prev_level && i>0)
                    arr[i-1].set('hasSubItems', true);
                if (header_level<0 || level<=header_level) {
                    if (i>0 || first_header)
                        header_level = level;
                    hasParent = false;
                }
                arr.push(new Common.UI.TreeViewModel({
                    name : this._navigationObject.get_Text(i),
                    level: level,
                    index: i,
                    hasParent: hasParent,
                    isEmptyItem: this._navigationObject.isEmptyItem(i)
                }));
                prev_level = level;
            }
            if (count>0 && !first_header) {
                arr[0].set('hasSubItems', false);
                arr[0].set('isNotHeader', true);
                arr[0].set('name', this.txtBeginning);
                arr[0].set('tip', this.txtGotoBeginning);
            }

            var me = this;
            var store = this.getApplication().getCollection('Navigation');
            store.reset(arr.splice(0, 50));

            this._currentPos = this._navigationObject.get_CurrentPosition();

            function addToPanel() {
                if (arr.length<1) {
                    me.panelNavigation.viewNavigationList.scroller && me.panelNavigation.viewNavigationList.scroller.update({alwaysVisibleY: true});
                    if (me._currentPos>-1 && me._currentPos<store.length)
                        me.onChangeOutlinePosition(me._currentPos);
                    me._currentPos = -1;
                    return;
                }
                setTimeout(function () {
                    store.add(arr.splice(0, 100));
                    if (me._currentPos>-1 && me._currentPos<store.length) {
                        me.onChangeOutlinePosition(me._currentPos);
                        me._currentPos = -1;
                    }
                    addToPanel();
                }, 1);
            }
            addToPanel();
        },

        updateChangeNavigation: function(index) {
            if (!this._navigationObject)
                this._navigationObject = this.api.asc_GetDocumentOutlineManager();

            if (!this._navigationObject) return;

            var item = this.getApplication().getCollection('Navigation').at(index);
            if (item.get('level') !== this._navigationObject.get_Level(index) ||
                index==0 && item.get('isNotHeader') !== this._navigationObject.isFirstItemNotHeader()) {
                this.updateNavigation();
            } else {
                item.set('name', this._navigationObject.get_Text(index));
                item.set('isEmptyItem', this._navigationObject.isEmptyItem(index));
                this.panelNavigation.viewNavigationList.updateTip(item.get('dataItem'));
            }
        },

        onChangeOutlinePosition: function(index) {
            if (index<this.panelNavigation.viewNavigationList.store.length)
                this.panelNavigation.viewNavigationList.scrollToRecord(this.panelNavigation.viewNavigationList.selectByIndex(index));
            else
                this._currentPos = index;
        },

        onItemContextMenu: function(picker, item, record, e){
            var showPoint;
            var menu = this.panelNavigation.navigationMenu;
            if (menu.isVisible()) {
                menu.hide();
            }

            var parentOffset = this.panelNavigation.$el.offset(),
                top = e.clientY*Common.Utils.zoom();
            showPoint = [e.clientX*Common.Utils.zoom() + 5, top - parentOffset.top + 5];

            for (var i=0; i<7; i++) {
                menu.items[i].setVisible(this.mode.isEdit);
            }

            menu.items[7].setVisible(!this.canUseViwerNavigation);
            menu.items[8].setVisible(!this.canUseViwerNavigation);

            var isNotHeader = record.get('isNotHeader');
            menu.items[0].setDisabled(isNotHeader || this._isDisabled);
            menu.items[1].setDisabled(isNotHeader || this._isDisabled);
            menu.items[3].setDisabled(isNotHeader || this._isDisabled);
            menu.items[4].setDisabled(this._isDisabled);
            menu.items[5].setDisabled(this._isDisabled);
            menu.items[7].setDisabled(isNotHeader);

            if (showPoint != undefined) {
                var menuContainer = this.panelNavigation.$el.find('#menu-navigation-container');
                if (!menu.rendered) {
                    if (menuContainer.length < 1) {
                        menuContainer = $('

', menu.id);
                        $(this.panelNavigation.$el).append(menuContainer);
                    }
                    menu.render(menuContainer);
                    menu.cmpEl.attr({tabindex: "-1"});
                }
                menu.cmpEl.attr('data-value', record.get('index'));
                menuContainer.css({
                    left: showPoint[0],
                    top: showPoint[1]
                });
                menu.show();
                _.delay(function() {
                    menu.cmpEl.focus();
                }, 10);
            }

        },

        onSelectItem: function(picker, item, record, e){
            if (this._navigationObject) {
                this._navigationObject.goto(record.get('index'));
            } else if (this._viewerNavigationObject) {
                this.api.asc_viewerNavigateTo(record.get('index'));
            }
            (this.mode.isEdit || this.mode.isRestrictedEdit) && Common.NotificationCenter.trigger('edit:complete', this.panelNavigation);
        },

        onItemAdd: function(picker, item, record, e){
            record.set('dataItem', item);
        },

        onMenuItemClick: function (menu, item) {
            if (!this._navigationObject && !this._viewerNavigationObject) return;
            var index = parseInt(menu.cmpEl.attr('data-value'));
            if (item.value == 'promote') {
                this._navigationObject.promote(index);
            } else if (item.value == 'demote') {
                this._navigationObject.demote(index);
            } else if (item.value == 'before') {
                this._navigationObject.insertHeader(index, true);
            } else if (item.value == 'after') {
                this._navigationObject.insertHeader(index, false);
            } else if (item.value == 'new') {
                this._navigationObject.insertSubHeader(index);
            } else if (item.value == 'select') {
                this._navigationObject.selectContent(index);
            } else if (item.value == 'expand') {
                this.panelNavigation.viewNavigationList.expandAll();
            } else  if (item.value == 'collapse') {
                this.panelNavigation.viewNavigationList.collapseAll();
            }
        },
        onClickClosePanel: function() {
            Common.NotificationCenter.trigger('leftmenu:change', 'hide');
        },

        onMenuSettingsItemClick: function (menu, item){
            switch (item.value){
                case 'expand':
                    this.panelNavigation.viewNavigationList.expandAll();
                    break;
                case 'collapse':
                    this.panelNavigation.viewNavigationList.collapseAll();
                    break;
                case 'wrap':
                    this.panelNavigation.changeWrapHeadings();
                    break;
            }
        },

        onMenuLevelsItemClick: function (menu, item) {
            this.panelNavigation.viewNavigationList.expandToLevel(item.value-1);
        },

        onMenuFontSizeClick: function (menu, item){
            this.panelNavigation.changeFontSize(item.value);
        },

        SetDisabled: function(state) {
            this._isDisabled = state;
        },

        updateViewerNavigation: function (bookmarks) {
            this._viewerNavigationObject = bookmarks.length > 0 ? bookmarks : null;
            if (this._viewerNavigationObject) {
                var count = this._viewerNavigationObject.length,
                    prev_level = -1,
                    header_level = -1,
                    first_header = true,//!this._navigationObject.isFirstItemNotHeader(),
                    arr = [];
                for (var i = 0; i < count; i++) {
                    var level = this._viewerNavigationObject[i].level - 1,
                        hasParent = true;
                    if (level > prev_level && i > 0)
                        arr[i - 1].set('hasSubItems', true);
                    if (header_level < 0 || level <= header_level) {
                        if (i > 0 || first_header)
                            header_level = level;
                        hasParent = false;
                    }
                    arr.push(new Common.UI.TreeViewModel({
                        name: this._viewerNavigationObject[i].description,
                        level: level,
                        index: i,
                        hasParent: hasParent,
                        isEmptyItem: !this._viewerNavigationObject[i].description
                    }));
                    prev_level = level;
                }
                if (count > 0 && !first_header) {
                    arr[0].set('hasSubItems', false);
                    arr[0].set('isNotHeader', true);
                    arr[0].set('name', this.txtBeginning);
                    arr[0].set('tip', this.txtGotoBeginning);
                }
                this.getApplication().getCollection('Navigation').reset(arr);
                if (this.panelNavigation && this.panelNavigation.viewNavigationList && this.panelNavigation.viewNavigationList.scroller)
                    this.panelNavigation.viewNavigationList.scroller.update({alwaysVisibleY: true});
            }
        },

        txtBeginning: 'Beginning of document',
        txtGotoBeginning: 'Go to the beginning of the document'

    }, DE.Controllers.Navigation || {}));
});
<|endoftext|>


<commit_before>/**
@toc
2. load grunt plugins
3. init
4. setup variables
5. grunt.initConfig
6. register grunt tasks

*/

'use strict';

module.exports = function(grunt) {

	/**
	Load grunt plugins
	@toc 2.
	*/
	grunt.loadNpmTasks('grunt-contrib-concat');
	grunt.loadNpmTasks('grunt-contrib-less');
	grunt.loadNpmTasks('grunt-contrib-uglify');
	grunt.loadNpmTasks('grunt-contrib-cssmin');
	grunt.loadNpmTasks('grunt-contrib-jshint');
	grunt.loadNpmTasks('grunt-contrib-copy');
	grunt.loadNpmTasks('grunt-karma');

	/**
	Function that wraps everything to allow dynamically setting/changing grunt options and config later by grunt task. This init function is called once immediately (for using the default grunt options, config, and setup) and then may be called again AFTER updating grunt (command line) options.
	@toc 3.
	@method init
	*/
	function init(params) {
		/**
		Project configuration.
		@toc 5.
		*/
		grunt.initConfig({
			concat: {
				devCss: {
					src:    [],
					dest:   []
				}
			},
			jshint: {
				options: {
					//force:          true,
					globalstrict:   true,
					//sub:            true,
					node: true,
					loopfunc: true,
					browser:        true,
					devel:          true,
					globals: {
						angular:    false,
						$:          false,
						moment:		false,
						Pikaday: false,
						module: false,
						forge: false
					}
				},
				beforeconcat:   {
					options: {
						force:	false,
						ignores: ['**.min.js']
					},
					files: {
						src: []
					}
				},
				//quick version - will not fail entire grunt process if there are lint errors
				beforeconcatQ:   {
					options: {
						force:	true,
						ignores: ['**.min.js']
					},
					files: {
						src: ['**.js']
					}
				}
			},
			uglify: {
				options: {
					mangle: false
				},
				build: {
					files:  {},
					src:    'timeline.js',
					dest:   'dist/js/timeline.min.js'
				}
			},
			less: {
				development: {
					options: {
					},
					files: {
						"dist/styles/timeline.css": "timeline.less"
					}
				}
			},
			copy: {
				dist : {
					files : [{ expand: true, src: ['timeline.js'], dest: 'dist/js/' }]
				}
			},
			cssmin: {
				dev: {
					src: ['dist/styles/timeline.css'],
					dest: 'dist/styles/timeline.min.css'
				}
			}/*,
			karma: {
				unit: {
					configFile: publicPathRelativeRoot+'config/karma.conf.js',
					singleRun: true,
					browsers: ['PhantomJS']
				}
			}*/
		});

		/**
		register/define grunt tasks
		@toc 6.
		*/
		// Default task(s).
		// grunt.registerTask('default', ['jshint:beforeconcat', 'less:development', 'concat:devJs', 'concat:devCss']);
		grunt.registerTask('default', ['jshint:beforeconcatQ', 'less:development', 'cssmin', 'uglify:build', 'copy:dist']);

	}
	init({});		//initialize here for defaults (init may be called again later within a task)

};<commit_msg>Added install.sh script<commit_after>/**
@toc
2. load grunt plugins
3. init
4. setup variables
5. grunt.initConfig
6. register grunt tasks

*/

'use strict';

module.exports = function(grunt) {

	/**
	Load grunt plugins
	@toc 2.
	*/
	grunt.loadNpmTasks('grunt-contrib-concat');
	grunt.loadNpmTasks('grunt-contrib-less');
	grunt.loadNpmTasks('grunt-contrib-uglify');
	grunt.loadNpmTasks('grunt-contrib-cssmin');
	grunt.loadNpmTasks('grunt-contrib-jshint');
	grunt.loadNpmTasks('grunt-contrib-copy');
	grunt.loadNpmTasks('grunt-karma');

	/**
	Function that wraps everything to allow dynamically setting/changing grunt options and config later by grunt task. This init function is called once immediately (for using the default grunt options, config, and setup) and then may be called again AFTER updating grunt (command line) options.
	@toc 3.
	@method init
	*/
	function init(params) {
		/**
		Project configuration.
		@toc 5.
		*/
		grunt.initConfig({
			concat: {
				devCss: {
					src:    [],
					dest:   []
				}
			},
			jshint: {
				options: {
					//force:          true,
					globalstrict:   true,
					//sub:            true,
					node: true,
					loopfunc: true,
					browser:        true,
					devel:          true,
					globals: {
						angular:    false,
						$:          false,
						moment:		false,
						Pikaday: false,
						module: false,
						forge: false
					}
				},
				beforeconcat:   {
					options: {
						force:	false,
						ignores: ['**.min.js']
					},
					files: {
						src: []
					}
				},
				//quick version - will not fail entire grunt process if there are lint errors
				beforeconcatQ:   {
					options: {
						force:	true,
						ignores: ['**.min.js']
					},
					files: {
						src: ['**.js']
					}
				}
			},
			uglify: {
				options: {
					mangle: false
				},
				build: {
					files:  {},
					src:    'timeline.js',
					dest:   'dist/js/timeline.min.js'
				}
			},
			less: {
				development: {
					options: {
					},
					files: {
						"dist/styles/timeline.css": "timeline.less"
					}
				}
			},
			copy: {
				dist : {
					files : [{ expand: true, src: ['timeline.js'], dest: 'dist/js/' }]
				}
			},
			cssmin: {
				dev: {
					src: ['dist/styles/timeline.css'],
					dest: 'dist/styles/timeline.min.css'
				}
			}/*,
			karma: {
				unit: {
					configFile: publicPathRelativeRoot+'config/karma.conf.js',
					singleRun: true,
					browsers: ['PhantomJS']
				}
			}*/
		});

		/**
		register/define grunt tasks
		@toc 6.
		*/
		// Default task(s).
		// grunt.registerTask('default', ['jshint:beforeconcat', 'less:development', 'concat:devJs', 'concat:devCss']);
		grunt.registerTask('package', ['less:development', 'cssmin', 'uglify:build', 'copy:dist']);
		grunt.registerTask('default', ['jshint:beforeconcatQ', 'less:development', 'cssmin', 'uglify:build', 'copy:dist']);

	}
	init({});		//initialize here for defaults (init may be called again later within a task)

};<|endoftext|>


<commit_before>/* jshint node: true */

var semver = require('semver'),
    format = require('util').format;

module.exports = function(grunt) {
    'use strict';

    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),

        version: grunt.file.readJSON('package.json').version,

        banner: [
            ' /* ----------------------------------------------------------------------------',
            ' // <%= pkg.title || pkg.name %>',
            ' // v<%= pkg.version %> - released <%= grunt.template.today("yyyy-mm-dd HH:MM") %>',
            ' // Licensed under the MIT license.',
            ' // <%= pkg.homepage %>',
            ' // ----------------------------------------------------------------------------',
            ' // Copyright (C) <%= grunt.template.today("yyyy") %> Jay Salvat',
            ' // http://jaysalvat.com/',
            ' // ---------------------------------------------------------------------------*/',
            '\n'
        ].join('\n'),

        clean: {
          dist: ['dist'],
          tmp: ['tmp']
        },

        sed: {
            version: {
                pattern: '%VERSION%',
                replacement: '<%= version %>',
                path: [ 'dist/*' ]
            },
            copyright: {
                pattern: /\(c\) \d{4} /,
                replacement: '(c) <%= grunt.template.today("yyyy") %> ',
                path: [ 'README.md', 'MIT-LICENSE' ]
            }
        },

        concat: {
            options: {
                banner: '<%= banner %>',
                stripBanners: true
            },
            js: {
                src: [ 'src/jquery.ezdz.js' ],
                dest: 'dist/jquery.ezdz.js'
            },
            css: {
                src: [ 'src/jquery.ezdz.css' ],
                dest: 'dist/jquery.ezdz.css'
            }
        },

        jshint: {
            options: {
                jshintrc: '.jshintrc'
            },
            files: [
                'Gruntfile.js',
                'src/*.js',
                'test/*.js'
            ]
        },

        uglify: {
            min: {
                options: {
                    banner: '<%= banner %>',
                    report: 'min',
                    mangle: true,
                    compress: true
                },
                src: 'src/jquery.ezdz.js',
                dest: 'dist/jquery.ezdz.min.js'
            }
        },

        qunit: {
            src: [ 'test/index.html' ],
            dist: [ 'test/index.min.html' ]
        },

        recess: {
            min: {
                options: {
                    compress: true,
                    compile: true,
                    banner: '<%= banner %>'
                },
                src: [ 'src/jquery.ezdz.css' ],
                dest: 'dist/jquery.ezdz.min.css'
            }
        },

        compress: {
            main: {
                options: {
                    archive: 'tmp/jquery.ezdz.zip'
                },
                files: [
                    { flatten: true, expand: true, src: [ 'dist/*' ], dest: 'tmp/' }
                ]
            }
        },

        copy: {
            main: {
                files: [
                    { flatten: true, expand: true, src: [ 'dist/*' ], dest: 'tmp/' }
                ]
            }
        },

        exec: {
            gitIsClean: {
                cmd: 'test -z "$(git status --porcelain)"'
            },
            gitIsOnMaster: {
                cmd: 'test $(git symbolic-ref -q HEAD) = refs/heads/master'
            },
            gitAdd: {
                cmd: 'git add .'
            },
            gitCommit: {
                cmd: function(message) {
                    return format('git commit -m "Build v%s"', message);
                }
            },
            gitTag: {
                cmd: function(version) {
                    return format('git tag v%s -am "%s"', version, version);
                }
            },
            gitPush: {
                cmd: [
                    'git push',
                    'git push --tags'
                ].join(' && ')
            },
            publish: {
                cmd: [
                    'git checkout gh-pages',
                    'mkdir -p releases',
                    'rm -rf releases/latest',
                    'cp -r tmp releases/<%= version %>',
                    'cp -r tmp releases/latest',
                    'git add releases/<%= version %> releases/latest',
                    'git commit -m "Add assets for v<%= version %>."',
                    'git push',
                    'git checkout -'
                ].join(' && ')
            }
        }
    });

    grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-contrib-compress');
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-qunit');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-exec');
    grunt.loadNpmTasks('grunt-sed');
    grunt.loadNpmTasks('grunt-recess');
    grunt.loadNpmTasks('semver');

    grunt.registerTask('default', 'Default task', [ 'qunit:src', 'build' ]);
    grunt.registerTask('test', 'Run tests.', [ 'jshint', 'qunit:src' ]);
    grunt.registerTask('build', 'Build.', [ 'clean:dist', 'concat', 'uglify', 'recess', 'qunit:dist' ]);
    grunt.registerTask('tmp', 'Build tmp folder.', [ 'clean:tmp', 'copy', 'compress', 'metadata' ]);

    /**
     * Publish and release a new version
     * @param  {string} version semver version number
     * @param  {bool}   force   force the bump even if the version is lower
     */
    grunt.registerTask('release', 'Release.', function(version, force) {
        var currentVersion = grunt.config.get('version');

        version = semver.inc(currentVersion, version) || version;

        if (!semver.valid(version) || (!force && semver.lte(version, currentVersion))) {
            grunt.fatal('Invalid version dummy.');
        }

        grunt.config.set('version', version);

        grunt.task.run([
            'exec:gitIsOnMaster',           // Check if it is on Master
            'exec:gitIsClean',              // Check if everything has been committed
            'test',                         // Run test
            'manifests:' + version,         // Update manifests
            'build',                        // Build the disttib
            'exec:gitAdd',                  // Git add it
            'exec:gitCommit:' + version,    // Git commit it
            'exec:gitTag:' + version,       // Git add a new tag
            'exec:gitPush',                 // Git push it th Github
            'publish'                       // Publish assets
        ]);
    });

    /**
     * Publish the assets
     */
    grunt.registerTask('publish', 'Publish file.', function() {
        grunt.task.run([
            'tmp',           // Build the tmp folder from dist
            'exec:publish',  // Publish assets
            'clean:tmp'      // Remove the tmp folder
        ]);
    });

    /**
     * Create a metadata json file
     * @param  {string} version numeric version
     */
    grunt.registerTask('metadata', 'Create metadata file.', function(version) {
        version = version || grunt.config.get('version');

        var metadata = {
            'date': grunt.template.today("yyyy-mm-dd HH:MM:ss"),
            'version': version
        };

        grunt.file.write('tmp/metadata.json', JSON.stringify(metadata, null, 4));
    });

    /**
     * Bump manifests and build
     * @param  {string} version semver version number
     * @param  {bool}   force   force the bump even if the version is lower
     */
    grunt.registerTask('bump', 'Bump version.', function(version, force) {
        var currentVersion = grunt.config.get('version');

        version = semver.inc(currentVersion, version) || version;

        if (!semver.valid(version) || (!force && semver.lte(version, currentVersion))) {
            grunt.fatal('Invalid version dummy.');
        }

        grunt.config.set('version', version);

        grunt.task.run([
            'manifests:' + version,
            'build'
        ]);
    });

    /**
     * Update manifests
     * @param  {string} version semver version number
     */
    grunt.registerTask('manifests', 'Update manifests.', function(version) {
        var _     = grunt.util._,
            pkg   = grunt.file.readJSON('package.json'),
            bower = grunt.file.readJSON('bower.json'),
            jqry  = grunt.file.readJSON('ezdz.jquery.json');

        bower = JSON.stringify(_.extend(bower, {
            version: version
        }), null, 4);

        jqry = JSON.stringify(_.extend(jqry, {
            version: version,
            description: pkg.description
        }), null, 4);

        pkg = JSON.stringify(_.extend(pkg, {
            version: version
        }), null, 4);

        grunt.config.data.pkg = JSON.parse(pkg);

        grunt.file.write('package.json', pkg);
        grunt.file.write('bower.json', bower);
        grunt.file.write('ezdz.jquery.json', jqry);

        grunt.task.run([
            'sed:copyright'
        ]);
    });
};
<commit_msg>Update Gruntfile<commit_after>/* jshint node: true */

var semver = require('semver'),
    format = require('util').format;

module.exports = function(grunt) {
    'use strict';

    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),

        version: grunt.file.readJSON('package.json').version,

        banner: [
            ' /* ----------------------------------------------------------------------------',
            ' // <%= pkg.title || pkg.name %>',
            ' // v<%= pkg.version %> - released <%= grunt.template.today("yyyy-mm-dd HH:MM") %>',
            ' // Licensed under the MIT license.',
            ' // <%= pkg.homepage %>',
            ' // ----------------------------------------------------------------------------',
            ' // Copyright (C) <%= grunt.template.today("yyyy") %> Jay Salvat',
            ' // http://jaysalvat.com/',
            ' // ---------------------------------------------------------------------------*/',
            '\n'
        ].join('\n'),

        clean: {
          dist: ['dist'],
          tmp: ['tmp']
        },

        sed: {
            version: {
                pattern: '%VERSION%',
                replacement: '<%= version %>',
                path: [ 'dist/*' ]
            },
            copyright: {
                pattern: /\(c\) \d{4} /,
                replacement: '(c) <%= grunt.template.today("yyyy") %> ',
                path: [ 'README.md', 'MIT-LICENSE' ]
            }
        },

        concat: {
            options: {
                banner: '<%= banner %>',
                stripBanners: true
            },
            js: {
                src: [ 'src/jquery.ezdz.js' ],
                dest: 'dist/jquery.ezdz.js'
            },
            css: {
                src: [ 'src/jquery.ezdz.css' ],
                dest: 'dist/jquery.ezdz.css'
            }
        },

        jshint: {
            options: {
                jshintrc: '.jshintrc'
            },
            files: [
                'Gruntfile.js',
                'src/*.js',
                'test/*.js'
            ]
        },

        uglify: {
            min: {
                options: {
                    banner: '<%= banner %>',
                    report: 'min',
                    mangle: true,
                    compress: true
                },
                src: 'src/jquery.ezdz.js',
                dest: 'dist/jquery.ezdz.min.js'
            }
        },

        qunit: {
            src: [ 'test/index.html' ],
            dist: [ 'test/index.min.html' ]
        },

        recess: {
            min: {
                options: {
                    compress: true,
                    compile: true,
                    banner: '<%= banner %>'
                },
                src: [ 'src/jquery.ezdz.css' ],
                dest: 'dist/jquery.ezdz.min.css'
            }
        },

        compress: {
            main: {
                options: {
                    archive: 'tmp/jquery.ezdz.zip'
                },
                files: [
                    { flatten: true, expand: true, src: [ 'dist/*' ], dest: 'tmp/' }
                ]
            }
        },

        copy: {
            main: {
                files: [
                    { flatten: true, expand: true, src: [ 'dist/*' ], dest: 'tmp/' }
                ]
            }
        },

        exec: {
            gitIsClean: {
                cmd: 'test -z "$(git status --porcelain)"'
            },
            gitIsOnMaster: {
                cmd: 'test $(git symbolic-ref -q HEAD) = refs/heads/master'
            },
            gitAdd: {
                cmd: 'git add .'
            },
            gitCommit: {
                cmd: function(message) {
                    return format('git commit -m "Build v%s"', message);
                }
            },
            gitTag: {
                cmd: function(version) {
                    return format('git tag v%s -am "%s"', version, version);
                }
            },
            gitPush: {
                cmd: [
                    'git push',
                    'git push --tags'
                ].join(' && ')
            },
            publish: {
                cmd: [
                    'git checkout gh-pages',
                    'mkdir -p releases',
                    'rm -rf releases/latest',
                    'cp -r tmp releases/<%= version %>',
                    'cp -r tmp releases/latest',
                    'git add releases/<%= version %> releases/latest',
                    'git commit -m "Add assets for v<%= version %>."',
                    'git push',
                    'git checkout -'
                ].join(' && ')
            }
        }
    });

    grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-contrib-compress');
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-qunit');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-exec');
    grunt.loadNpmTasks('grunt-sed');
    grunt.loadNpmTasks('grunt-recess');

    grunt.registerTask('default', 'Default task', [ 'qunit:src', 'build' ]);
    grunt.registerTask('test', 'Run tests.', [ 'jshint', 'qunit:src' ]);
    grunt.registerTask('build', 'Build.', [ 'clean:dist', 'concat', 'uglify', 'recess', 'qunit:dist' ]);
    grunt.registerTask('tmp', 'Build tmp folder.', [ 'clean:tmp', 'copy', 'compress', 'metadata' ]);

    /**
     * Publish and release a new version
     * @param  {string} version semver version number
     * @param  {bool}   force   force the bump even if the version is lower
     */
    grunt.registerTask('release', 'Release.', function(version, force) {
        var currentVersion = grunt.config.get('version');

        version = semver.inc(currentVersion, version) || version;

        if (!semver.valid(version) || (!force && semver.lte(version, currentVersion))) {
            grunt.fatal('Invalid version dummy.');
        }

        grunt.config.set('version', version);

        grunt.task.run([
            'exec:gitIsOnMaster',           // Check if it is on Master
            'exec:gitIsClean',              // Check if everything has been committed
            'test',                         // Run test
            'manifests:' + version,         // Update manifests
            'build',                        // Build the disttib
            'exec:gitAdd',                  // Git add it
            'exec:gitCommit:' + version,    // Git commit it
            'exec:gitTag:' + version,       // Git add a new tag
            'exec:gitPush',                 // Git push it th Github
            'publish'                       // Publish assets
        ]);
    });

    /**
     * Publish the assets
     */
    grunt.registerTask('publish', 'Publish file.', function() {
        grunt.task.run([
            'tmp',           // Build the tmp folder from dist
            'exec:publish',  // Publish assets
            'clean:tmp'      // Remove the tmp folder
        ]);
    });

    /**
     * Create a metadata json file
     * @param  {string} version numeric version
     */
    grunt.registerTask('metadata', 'Create metadata file.', function(version) {
        version = version || grunt.config.get('version');

        var metadata = {
            'date': grunt.template.today("yyyy-mm-dd HH:MM:ss"),
            'version': version
        };

        grunt.file.write('tmp/metadata.json', JSON.stringify(metadata, null, 4));
    });

    /**
     * Bump manifests and build
     * @param  {string} version semver version number
     * @param  {bool}   force   force the bump even if the version is lower
     */
    grunt.registerTask('bump', 'Bump version.', function(version, force) {
        var currentVersion = grunt.config.get('version');

        version = semver.inc(currentVersion, version) || version;

        if (!semver.valid(version) || (!force && semver.lte(version, currentVersion))) {
            grunt.fatal('Invalid version dummy.');
        }

        grunt.config.set('version', version);

        grunt.task.run([
            'manifests:' + version,
            'build'
        ]);
    });

    /**
     * Update manifests
     * @param  {string} version semver version number
     */
    grunt.registerTask('manifests', 'Update manifests.', function(version) {
        var _     = grunt.util._,
            pkg   = grunt.file.readJSON('package.json'),
            bower = grunt.file.readJSON('bower.json'),
            jqry  = grunt.file.readJSON('ezdz.jquery.json');

        bower = JSON.stringify(_.extend(bower, {
            version: version
        }), null, 4);

        jqry = JSON.stringify(_.extend(jqry, {
            version: version,
            description: pkg.description
        }), null, 4);

        pkg = JSON.stringify(_.extend(pkg, {
            version: version
        }), null, 4);

        grunt.config.data.pkg = JSON.parse(pkg);

        grunt.file.write('package.json', pkg);
        grunt.file.write('bower.json', bower);
        grunt.file.write('ezdz.jquery.json', jqry);

        grunt.task.run([
            'sed:copyright'
        ]);
    });
};
<|endoftext|>


<commit_before>module.exports = function(grunt) {
  require('matchdep').
    filterDev('grunt-*').
    filter(function(name){ return name !== 'grunt-cli'; }).
      forEach(grunt.loadNpmTasks);

  grunt.loadTasks('tasks');

  function config(configFileName) {
    return require('./configurations/' + configFileName);
  }

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    env: process.env,

    connect: config('connect'),
    watch: config('watch'),
    transpile: config('transpile'),
    copy: config('copy'),
    qunit: config('qunit'),
    ember_handlebars: config('ember_handlebars'),
    concat: config('concat'),
    sass: config('sass'),
    shell: config('shell'),
    s3: config('s3'),
    jshint: config('jshint'),
    clean: ["tmp"],
    md5: config('md5'),
    uglify: config('uglify')
  });

  grunt.registerTask("prod", function(){
    process.env.GLAZIER_ENV = 'prod';
  });

  grunt.registerTask('build', ['clean', 'ember_handlebars', 'transpile', 'jshint', 'copy_glazier', 'sass', 'concat', 'shell:buildCards', 'copy:cards']);
  grunt.registerTask('copy_glazier', ['copy:main', 'copy:test', 'copy:fixtures', 'copy:vendor']);

  grunt.registerTask('assets', ['build', /*'uglify:all',*/ 'md5', 'index.html']);

  grunt.registerTask('ingest', ['assets', 'shell:ingest']);
  grunt.registerTask('deploy', ['assets', 's3:dev']);

  grunt.registerTask('ingestCards', ['build', 'shell:ingestCardManifests']);

  grunt.registerTask('preview', ['build', /*'uglify:all',*/ 'md5', 'index.html', 'shell:ingest', 'connect', 'watch']);
  grunt.registerTask('preview:cdn', ['prod', 'deploy', 'shell:ingest', 'connect', 'watch']);

  grunt.registerTask('test', ['shell:npmInstallForCards', 'build',  'connect', 'qunit:all']);
  grunt.registerTask('default', ['shell:npmInstallForCards','build', 'index.html', 'connect', 'watch']);
};
<commit_msg>ingestCards should run npm for the cards<commit_after>module.exports = function(grunt) {
  require('matchdep').
    filterDev('grunt-*').
    filter(function(name){ return name !== 'grunt-cli'; }).
      forEach(grunt.loadNpmTasks);

  grunt.loadTasks('tasks');

  function config(configFileName) {
    return require('./configurations/' + configFileName);
  }

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    env: process.env,

    connect: config('connect'),
    watch: config('watch'),
    transpile: config('transpile'),
    copy: config('copy'),
    qunit: config('qunit'),
    ember_handlebars: config('ember_handlebars'),
    concat: config('concat'),
    sass: config('sass'),
    shell: config('shell'),
    s3: config('s3'),
    jshint: config('jshint'),
    clean: ["tmp"],
    md5: config('md5'),
    uglify: config('uglify')
  });

  grunt.registerTask("prod", function(){
    process.env.GLAZIER_ENV = 'prod';
  });

  grunt.registerTask('build', ['clean', 'ember_handlebars', 'transpile', 'jshint', 'copy_glazier', 'sass', 'concat', 'shell:buildCards', 'copy:cards']);
  grunt.registerTask('copy_glazier', ['copy:main', 'copy:test', 'copy:fixtures', 'copy:vendor']);

  grunt.registerTask('assets', ['build', /*'uglify:all',*/ 'md5', 'index.html']);

  grunt.registerTask('ingest', ['assets', 'shell:ingest']);
  grunt.registerTask('deploy', ['assets', 's3:dev']);

  grunt.registerTask('ingestCards', ['build', 'shell:npmInstallForCards', 'shell:ingestCardManifests']);

  grunt.registerTask('preview', ['build', /*'uglify:all',*/ 'md5', 'index.html', 'shell:ingest', 'connect', 'watch']);
  grunt.registerTask('preview:cdn', ['prod', 'deploy', 'shell:ingest', 'connect', 'watch']);

  grunt.registerTask('test', ['shell:npmInstallForCards', 'build',  'connect', 'qunit:all']);
  grunt.registerTask('default', ['shell:npmInstallForCards','build', 'index.html', 'connect', 'watch']);
};
<|endoftext|>


<commit_before>/*
 * Copyright 2013 Mozilla Foundation
 *
 * 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.
 */

var homePath;
var release;

var jsBuildPath = homePath + "src/";
var tsBuildPath = homePath + "build/ts/";

load(tsBuildPath + "utilities.js");

assert(homePath, "Host compartment needs to initialize homePath.");

load(jsBuildPath + "avm2/avm2Util.js");
load(tsBuildPath + "dataBuffer.js");
load(tsBuildPath + "options.js");
load(tsBuildPath + "settings.js");
load(tsBuildPath + "metrics.js");

var ArgumentParser = Shumway.Options.ArgumentParser;
var Option = Shumway.Options.Option;
var OptionSet = Shumway.Options.OptionSet;

var systemOptions = new OptionSet("System Options");
var shumwayOptions = systemOptions.register(new OptionSet("Shumway Options"));
load(tsBuildPath + "avm2/options.js");
var shellOptions = systemOptions.register(new OptionSet("AVM2 Shell Options"));
var traceWarnings = shellOptions.register(new Option("tw", "traceWarnings", "boolean", false, "prints warnings"));

Timer.start("Loading VM");

load(jsBuildPath + "avm2/constants.js");
load(tsBuildPath + "avm2/errors.js");
load(tsBuildPath + "avm2/parser.js");
load(tsBuildPath + "avm2/bytecode.js");
load(jsBuildPath + "avm2/disassembler.js");

Timer.start("Loading Compiler");
load(tsBuildPath + "avm2/compiler/verifier.js");
load(tsBuildPath + "avm2/compiler/c4/ir.js");
load(tsBuildPath + "avm2/compiler/c4/as.ir.js");
load(tsBuildPath + "avm2/compiler/c4/ast.js");
load(tsBuildPath + "avm2/compiler/c4/optimizer.js");
load(tsBuildPath + "avm2/compiler/c4/looper.js");
load(tsBuildPath + "avm2/compiler/c4/backend.js");
load(tsBuildPath + "avm2/compiler/builder.js");
load(jsBuildPath + "avm2/compiler/aot.js");
Timer.stop();

Timer.start("Loading Runtime");
load(tsBuildPath + "avm2/trampoline.js");
load(tsBuildPath + "avm2/bindings.js");
load(tsBuildPath + "avm2/scope.js");

load(tsBuildPath + "avm2/domain.js");
load(jsBuildPath + "avm2/xregexp.js");
load(tsBuildPath + "avm2/runtime.js");
load(jsBuildPath + "avm2/runtime-exports.js");
load(tsBuildPath + "avm2/interpreter.js");

load(tsBuildPath + "avm2/natives/int32Vector.js");
load(tsBuildPath + "avm2/natives/uint32Vector.js");
load(tsBuildPath + "avm2/natives/float64Vector.js");
load(tsBuildPath + "avm2/native.js");
load(tsBuildPath + "avm2/natives/GenericVector.js");
load(tsBuildPath + "avm2/natives/dictionary.js");
load(tsBuildPath + "avm2/natives/proxy.js");
load(tsBuildPath + "avm2/natives/xml.js");
load(tsBuildPath + "avm2/natives/system.js");
load(tsBuildPath + "avm2/natives/byteArray.js");

Timer.stop();
Timer.stop();

function grabAbc(fileOrBuffer) {
  if (isString(fileOrBuffer)) {
//    var buffer = snarf(fileOrBuffer, "binary");
//    for (var i = 0; i < 10; i++) {
//      var start = performance.now();
//      new AbcFile(buffer, "file");
//      print("Parsed: " + fileOrBuffer + " in " + (performance.now() - start).toFixed(4));
//    }
    return new AbcFile(snarf(fileOrBuffer, "binary"), fileOrBuffer);
  } else {
    var buffer = new Uint8Array(fileOrBuffer); // Copy into local compartment.
    return new AbcFile(buffer);
  }
}
<commit_msg>Add assert to shell compartment.<commit_after>/*
 * Copyright 2013 Mozilla Foundation
 *
 * 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.
 */

var homePath;
var release;

var jsBuildPath = homePath + "src/";
var tsBuildPath = homePath + "build/ts/";

load(tsBuildPath + "utilities.js");

Shumway.Debug.assert(homePath, "Host compartment needs to initialize homePath.");

load(jsBuildPath + "avm2/avm2Util.js");
load(tsBuildPath + "dataBuffer.js");
load(tsBuildPath + "options.js");
load(tsBuildPath + "settings.js");
load(tsBuildPath + "metrics.js");

var ArgumentParser = Shumway.Options.ArgumentParser;
var Timer = new Shumway.Metrics.Timer();
var Option = Shumway.Options.Option;
var OptionSet = Shumway.Options.OptionSet;

var systemOptions = new OptionSet("System Options");
var shumwayOptions = systemOptions.register(new OptionSet("Shumway Options"));
load(tsBuildPath + "avm2/options.js");
var shellOptions = systemOptions.register(new OptionSet("AVM2 Shell Options"));
var traceWarnings = shellOptions.register(new Option("tw", "traceWarnings", "boolean", false, "prints warnings"));

Timer.start("Loading VM");

load(jsBuildPath + "avm2/constants.js");
load(tsBuildPath + "avm2/errors.js");
load(tsBuildPath + "avm2/parser.js");
load(tsBuildPath + "avm2/bytecode.js");
load(jsBuildPath + "avm2/disassembler.js");

Timer.start("Loading Compiler");
load(tsBuildPath + "avm2/compiler/verifier.js");
load(tsBuildPath + "avm2/compiler/c4/ir.js");
load(tsBuildPath + "avm2/compiler/c4/as.ir.js");
load(tsBuildPath + "avm2/compiler/c4/ast.js");
load(tsBuildPath + "avm2/compiler/c4/optimizer.js");
load(tsBuildPath + "avm2/compiler/c4/looper.js");
load(tsBuildPath + "avm2/compiler/c4/backend.js");
load(tsBuildPath + "avm2/compiler/builder.js");
load(jsBuildPath + "avm2/compiler/aot.js");
Timer.stop();

Timer.start("Loading Runtime");
load(tsBuildPath + "avm2/trampoline.js");
load(tsBuildPath + "avm2/bindings.js");
load(tsBuildPath + "avm2/scope.js");

load(tsBuildPath + "avm2/domain.js");
load(jsBuildPath + "avm2/xregexp.js");
load(tsBuildPath + "avm2/runtime.js");
load(jsBuildPath + "avm2/runtime-exports.js");
load(tsBuildPath + "avm2/interpreter.js");

load(tsBuildPath + "avm2/natives/int32Vector.js");
load(tsBuildPath + "avm2/natives/uint32Vector.js");
load(tsBuildPath + "avm2/natives/float64Vector.js");
load(tsBuildPath + "avm2/native.js");
load(tsBuildPath + "avm2/natives/GenericVector.js");
load(tsBuildPath + "avm2/natives/dictionary.js");
load(tsBuildPath + "avm2/natives/proxy.js");
load(tsBuildPath + "avm2/natives/xml.js");
load(tsBuildPath + "avm2/natives/system.js");
load(tsBuildPath + "avm2/natives/byteArray.js");

Timer.stop();
Timer.stop();

function grabAbc(fileOrBuffer) {
  if (isString(fileOrBuffer)) {
//    var buffer = snarf(fileOrBuffer, "binary");
//    for (var i = 0; i < 10; i++) {
//      var start = performance.now();
//      new AbcFile(buffer, "file");
//      print("Parsed: " + fileOrBuffer + " in " + (performance.now() - start).toFixed(4));
//    }
    return new AbcFile(snarf(fileOrBuffer, "binary"), fileOrBuffer);
  } else {
    var buffer = new Uint8Array(fileOrBuffer); // Copy into local compartment.
    return new AbcFile(buffer);
  }
}
<|endoftext|>


<commit_before>/*global module:false*/
module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({

    // Metadata.
    pkg: grunt.file.readJSON('package.json'),
    banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' +
      '<%= grunt.template.today("yyyy-mm-dd") %>\n' +
      '<%= pkg.homepage ? "* " + pkg.homepage + "\\n" : "" %>' +
      '* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' +
      ' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */\n',

    // Custome Paths
    srcFiles: ['src/js/*.js'], // source files
    componentsDir: 'bower_components', // bower components
    testFiles: ['spec/*.spec.js'], // test files (jasmine specs)

    // Task configuration.
    jscs: { // check javascript style
      options: {
        config: '.jscsrc',  // configuration file
        fix: true,
        force: true
      },
      source: {
        src: '<%= srcFiles %>'
      },
      gruntfile: {
        src: 'Gruntfile.js'
      },
      test: {
        src: '<%= testFiles %>'
      }
    },

    jshint: { // check javascript syntax and errors
      options: {
        jshintrc: true // configuration file
      },
      source: {
        src: '<%= jscs.source.src %>'
      },
      gruntfile: {
        src: '<%= jscs.gruntfile.src %>'
      },
      test: {
        src: '<%= jscs.test.src %>'
      }
    },

    connect: {
      test: {
        options: {
          hostname: 'localhost',
          port: 8001,
          base: ['.']
        }
      }
    },

    jasmine: { // run tests, source files are first copied within componentsDir
      test: {
        options: {
          host: 'http://<%= connect.test.options.hostname %>:<%= connect.test.options.port %>/',
          src: '<%= componentsDir %>/<%= pkg.name %>/src/js/*.js',
          specs: '<%= jshint.test.src %>',
          template: require('grunt-template-jasmine-requirejs'),
          templateOptions: {
            version: '<%= componentsDir %>/requirejs/require.js',
            requireConfigFile: 'demo/config.js', // requireJS's config file
            /*requireConfig: {
              baseUrl: '.' // change base url to execute tests from local FS
            }*/
          }
        }
      }
    },

    requirejs: { // concat and minimize AMD modules
      compile: {
        options: {
          baseUrl: '<%= componentsDir %>',
          paths: {
            jquery: 'empty:', // does not include jquery in the output
            jquery_ui: 'empty:', // does not include jquery_ui in the output
          },
          name: '<%= pkg.name %>Package',
          mainConfigFile: 'demo/config.js',
          out: 'dist/<%= pkg.name %>.min.js'
        }
      }
    },

    cssmin: { // concat and minimize css
      dist: {
        files: {
          'dist/styles/<%= pkg.name %>.css': ['src/styles/**/*.css']
        }
      }
    },

    copy: {
      components: { // copy the bower components that were not concat to dist/
        files: [
          {
            expand: true,
            cwd: '<%= componentsDir %>',
            src: ['requirejs/require.js', 'jquery/dist/jquery.min.js',
                         'jquery-ui/jquery-ui.min.js', 'jquery-ui/themes/**'],
            dest: 'dist/dependencies'}]
      },
      module: { // copy the module as a bower component to <%= componentsDir %>
        files: [
          {
            expand: true,
            src: 'src/**/*',
            dest: '<%= componentsDir %>/<%= pkg.name %>/'
          }]
      }
    },

    watch: {
      source: {
        files: '<%= jshint.source.src %>',
        tasks: ['jscs:source', 'jshint:source', 'copy:module']
      },
      gruntfile: {
        files: '<%= jshint.gruntfile.src %>',
        tasks: ['jscs:source', 'jshint:gruntfile']
      },
      test: {
        files: '<%= jshint.test.src %>',
        tasks: ['jscs:source', 'jshint:test', 'jasmine']
      }
    },

    browserSync: {
      dev: {
        bsFiles: {
          src: [
              'demo/**/*.js',
              'demo/**/*.css',
              'demo/**/*.html',
              'src/**/*.js',
              'src/**/*.css',
              'src/**/*.html'
          ]
        },
        options: {
          watchTask: true,
          // serve base dir
          // AND
          // bower_components
          // AT SAME LEVEL
          server: ['.'],
          startPath: '/demo'
        }
      }
    }

  });

  // These plugins provide necessary tasks.
  grunt.loadNpmTasks('grunt-contrib-connect');
  grunt.loadNpmTasks('grunt-contrib-cssmin');
  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-contrib-jasmine');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-jscs');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-connect');
  grunt.loadNpmTasks('grunt-browser-sync');
  grunt.loadNpmTasks('grunt-contrib-requirejs');

  // Serve task.
  grunt.registerTask('serve', function(/*target*/) {

    grunt.task.run([
      'browserSync:dev',
      'watch'
    ]);
  });

  // Test task.
  grunt.registerTask('test', ['jscs', 'jshint', 'copy:module', 'connect', 'jasmine']);

  // Build task.
  grunt.registerTask('build', ['cssmin', 'test', 'requirejs', 'copy']);

  // Default task.
  grunt.registerTask('default', ['build']);

};
<commit_msg>main module is now copied at the beggining of grunt serve<commit_after>/*global module:false*/
module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({

    // Metadata.
    pkg: grunt.file.readJSON('package.json'),
    banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' +
      '<%= grunt.template.today("yyyy-mm-dd") %>\n' +
      '<%= pkg.homepage ? "* " + pkg.homepage + "\\n" : "" %>' +
      '* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' +
      ' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */\n',

    // Custome Paths
    srcFiles: ['src/js/*.js'], // source files
    componentsDir: 'bower_components', // bower components
    testFiles: ['spec/*.spec.js'], // test files (jasmine specs)

    // Task configuration.
    jscs: { // check javascript style
      options: {
        config: '.jscsrc',  // configuration file
        fix: true,
        force: true
      },
      source: {
        src: '<%= srcFiles %>'
      },
      gruntfile: {
        src: 'Gruntfile.js'
      },
      test: {
        src: '<%= testFiles %>'
      }
    },

    jshint: { // check javascript syntax and errors
      options: {
        jshintrc: true // configuration file
      },
      source: {
        src: '<%= jscs.source.src %>'
      },
      gruntfile: {
        src: '<%= jscs.gruntfile.src %>'
      },
      test: {
        src: '<%= jscs.test.src %>'
      }
    },

    connect: {
      test: {
        options: {
          hostname: 'localhost',
          port: 8001,
          base: ['.']
        }
      }
    },

    jasmine: { // run tests, source files are first copied within componentsDir
      test: {
        options: {
          host: 'http://<%= connect.test.options.hostname %>:<%= connect.test.options.port %>/',
          src: '<%= componentsDir %>/<%= pkg.name %>/src/js/*.js',
          specs: '<%= jshint.test.src %>',
          template: require('grunt-template-jasmine-requirejs'),
          templateOptions: {
            version: '<%= componentsDir %>/requirejs/require.js',
            requireConfigFile: 'demo/config.js', // requireJS's config file
            /*requireConfig: {
              baseUrl: '.' // change base url to execute tests from local FS
            }*/
          }
        }
      }
    },

    requirejs: { // concat and minimize AMD modules
      compile: {
        options: {
          baseUrl: '<%= componentsDir %>',
          paths: {
            jquery: 'empty:', // does not include jquery in the output
            jquery_ui: 'empty:', // does not include jquery_ui in the output
          },
          name: '<%= pkg.name %>Package',
          mainConfigFile: 'demo/config.js',
          out: 'dist/<%= pkg.name %>.min.js'
        }
      }
    },

    cssmin: { // concat and minimize css
      dist: {
        files: {
          'dist/styles/<%= pkg.name %>.css': ['src/styles/**/*.css']
        }
      }
    },

    copy: {
      components: { // copy the bower components that were not concat to dist/
        files: [
          {
            expand: true,
            cwd: '<%= componentsDir %>',
            src: ['requirejs/require.js', 'jquery/dist/jquery.min.js',
                         'jquery-ui/jquery-ui.min.js', 'jquery-ui/themes/**'],
            dest: 'dist/dependencies'}]
      },
      module: { // copy the module as a bower component to <%= componentsDir %>
        files: [
          {
            expand: true,
            src: 'src/**/*',
            dest: '<%= componentsDir %>/<%= pkg.name %>/'
          }]
      }
    },

    watch: {
      source: {
        files: '<%= jshint.source.src %>',
        tasks: ['jscs:source', 'jshint:source', 'copy:module']
      },
      gruntfile: {
        files: '<%= jshint.gruntfile.src %>',
        tasks: ['jscs:source', 'jshint:gruntfile']
      },
      test: {
        files: '<%= jshint.test.src %>',
        tasks: ['jscs:source', 'jshint:test', 'jasmine']
      }
    },

    browserSync: {
      dev: {
        bsFiles: {
          src: [
              'demo/**/*.js',
              'demo/**/*.css',
              'demo/**/*.html',
              'src/**/*.js',
              'src/**/*.css',
              'src/**/*.html'
          ]
        },
        options: {
          watchTask: true,
          // serve base dir
          server: ['.'],
          startPath: '/demo'
        }
      }
    }

  });

  // These plugins provide necessary tasks.
  grunt.loadNpmTasks('grunt-contrib-connect');
  grunt.loadNpmTasks('grunt-contrib-cssmin');
  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-contrib-jasmine');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-jscs');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-connect');
  grunt.loadNpmTasks('grunt-browser-sync');
  grunt.loadNpmTasks('grunt-contrib-requirejs');

  // Serve task.
  grunt.registerTask('serve', function(/*target*/) {

    grunt.task.run([
      'copy:module',
      'browserSync:dev',
      'watch'
    ]);
  });

  // Test task.
  grunt.registerTask('test', ['jscs', 'jshint', 'copy:module', 'connect', 'jasmine']);

  // Build task.
  grunt.registerTask('build', ['cssmin', 'test', 'requirejs', 'copy']);

  // Default task.
  grunt.registerTask('default', ['build']);

};
<|endoftext|>


<commit_before>module.exports = function(grunt) {
  var pkg_data = grunt.file.readJSON('package.json');

  // Interpolates pkg variables into files during browserification
  function addPackageVars(file) {
    var through = require('through'), data = "";
    function write(buf) { data += grunt.template.process(buf, { pkg: pkg_data }); }
    function end() { this.queue(data); this.queue(null); }
    return through(write, end);
  }

  grunt.initConfig({
    pkg: pkg_data,
    copy: {
      build: { files: [{ expand: true, src: ['src/**'], dest: 'tmp/' }] }
    },
    bower: {
      dist: {
        dest: 'tmp/components'
      }
    },
    browserify: {
      options: { transform: [ addPackageVars ] },
      tracekit: {
        src: ['tmp/src/main-tracekit.js'],
        dest: 'dist/<%= pkg.name %>-tracekit.js'
      },
      fallback: {
        src: ['tmp/src/main-fallback.js'],
        dest: 'dist/<%= pkg.name %>-fallback.js'
      },
      'tracekit-sourcemap': {
        src: ['tmp/src/main-tracekit-sourcemaps.js'],
        dest: 'dist/<%= pkg.name %>-tracekit-sourcemap.js'
      },
      'fallback-sourcemap': {
        src: ['tmp/src/main-fallback-sourcemaps.js'],
        dest: 'dist/<%= pkg.name %>-fallback-sourcemap.js'
      }
    },
    uglify: {
      options: {
        banner: '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n'
      },
      dist: {
        files: {
          'dist/<%= pkg.name %>-tracekit.min.js':             ['dist/<%= pkg.name %>-tracekit.js'],
          'dist/<%= pkg.name %>-tracekit-sourcemaps.min.js':  ['dist/<%= pkg.name %>-tracekit-sourcemaps.js'],
          'dist/<%= pkg.name %>-fallback.min.js':             ['dist/<%= pkg.name %>-fallback.js'],
          'dist/<%= pkg.name %>-fallback-sourcemaps.min.js':  ['dist/<%= pkg.name %>-fallback-sourcemaps.js']
        }
      }
    },
    jshint: {
      files: ['gruntfile.js', 'src/**/*.js', '!src/lib/**/*.js'],
      options: {
        // options here to override JSHint defaults
        globals: {
          console: true,
          module: true,
          document: true
        }
      }
    },
    watch: {
      test_only: {
        files: ['test/*.coffee', 'test/**/*.coffee'],
        tasks: ['test'],
        options: { interrupt: true }
      },
      build_and_test: {
        files: ['<%= jshint.files %>'],
        tasks: ['build', 'test'],
        options: { interrupt: true }
      }
    },
    connect: {
      integration_test: {
        options: {
          hostname: '*',
          port: 9001,
          base: '.',
          keepalive: true
        }
      }
    },
    mochacli: {
      all: ['test/**/*.coffee'],
      options: {
        compilers: ['coffee:coffee-script'],
        files: 'test/**/*.coffee',
        bail: true,
        reporter: 'spec'
      }
    },
    jasmine: {
      tracekit_processor: {
        src: 'test/examples/dist/<%= pkg.name %>-tracekit.js',
        options: {
          keepRunner: false,
          outfile: 'test/examples/tracekit_runner.html',
          specs: 'test/integration/spec/**/*.js'
        }
      },
      fallback_processor: {
        src: 'test/examples/dist/<%= pkg.name %>-fallback.js',
        options: {
          keepRunner: false,
          outfile: 'test/examples/fallback_runner.html',
          specs: 'test/integration/spec/**/*.js'
        }
      }
    }
  });

  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-bower');
  grunt.loadNpmTasks('grunt-browserify');
  grunt.loadNpmTasks('grunt-template');
  grunt.loadNpmTasks('grunt-contrib-uglify');

  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-connect');
  grunt.loadNpmTasks('grunt-mocha-cli');
  grunt.loadNpmTasks('grunt-contrib-jasmine');

  grunt.registerTask('test', ['mochacli', 'jshint']);

  // Running the `serve` command starts up a webserver
  grunt.registerTask('serve', ['connect']);

  grunt.registerTask('build', ['copy', 'bower', 'browserify']);
  grunt.registerTask('minify', ['uglify']);
  grunt.registerTask('default', ['build', 'minify']);

  // Push distribution libraries to CDN
  // Build and publish distribution site
  grunt.registerTask('publish', []);
};
<commit_msg>Correct minification source filenames<commit_after>module.exports = function(grunt) {
  var pkg_data = grunt.file.readJSON('package.json');

  // Interpolates pkg variables into files during browserification
  function addPackageVars(file) {
    var through = require('through'), data = "";
    function write(buf) { data += grunt.template.process(buf, { pkg: pkg_data }); }
    function end() { this.queue(data); this.queue(null); }
    return through(write, end);
  }

  grunt.initConfig({
    pkg: pkg_data,
    copy: {
      build: { files: [{ expand: true, src: ['src/**'], dest: 'tmp/' }] }
    },
    bower: {
      dist: {
        dest: 'tmp/components'
      }
    },
    browserify: {
      options: { transform: [ addPackageVars ] },
      tracekit: {
        src: ['tmp/src/main-tracekit.js'],
        dest: 'dist/<%= pkg.name %>-tracekit.js'
      },
      fallback: {
        src: ['tmp/src/main-fallback.js'],
        dest: 'dist/<%= pkg.name %>-fallback.js'
      },
      'tracekit-sourcemap': {
        src: ['tmp/src/main-tracekit-sourcemaps.js'],
        dest: 'dist/<%= pkg.name %>-tracekit-sourcemap.js'
      },
      'fallback-sourcemap': {
        src: ['tmp/src/main-fallback-sourcemaps.js'],
        dest: 'dist/<%= pkg.name %>-fallback-sourcemap.js'
      }
    },
    uglify: {
      options: {
        banner: '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n'
      },
      dist: {
        files: {
          'dist/<%= pkg.name %>-tracekit.min.js':             ['dist/<%= pkg.name %>-tracekit.js'],
          'dist/<%= pkg.name %>-tracekit-sourcemap.min.js':   ['dist/<%= pkg.name %>-tracekit-sourcemap.js'],
          'dist/<%= pkg.name %>-fallback.min.js':             ['dist/<%= pkg.name %>-fallback.js'],
          'dist/<%= pkg.name %>-fallback-sourcemap.min.js':   ['dist/<%= pkg.name %>-fallback-sourcemap.js']
        }
      }
    },
    jshint: {
      files: ['gruntfile.js', 'src/**/*.js', '!src/lib/**/*.js'],
      options: {
        // options here to override JSHint defaults
        globals: {
          console: true,
          module: true,
          document: true
        }
      }
    },
    watch: {
      test_only: {
        files: ['test/*.coffee', 'test/**/*.coffee'],
        tasks: ['test'],
        options: { interrupt: true }
      },
      build_and_test: {
        files: ['<%= jshint.files %>'],
        tasks: ['build', 'test'],
        options: { interrupt: true }
      }
    },
    connect: {
      integration_test: {
        options: {
          hostname: '*',
          port: 9001,
          base: '.',
          keepalive: true
        }
      }
    },
    mochacli: {
      all: ['test/**/*.coffee'],
      options: {
        compilers: ['coffee:coffee-script'],
        files: 'test/**/*.coffee',
        bail: true,
        reporter: 'spec'
      }
    },
    jasmine: {
      tracekit_processor: {
        src: 'test/examples/dist/<%= pkg.name %>-tracekit.js',
        options: {
          keepRunner: false,
          outfile: 'test/examples/tracekit_runner.html',
          specs: 'test/integration/spec/**/*.js'
        }
      },
      fallback_processor: {
        src: 'test/examples/dist/<%= pkg.name %>-fallback.js',
        options: {
          keepRunner: false,
          outfile: 'test/examples/fallback_runner.html',
          specs: 'test/integration/spec/**/*.js'
        }
      }
    }
  });

  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-bower');
  grunt.loadNpmTasks('grunt-browserify');
  grunt.loadNpmTasks('grunt-template');
  grunt.loadNpmTasks('grunt-contrib-uglify');

  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-connect');
  grunt.loadNpmTasks('grunt-mocha-cli');
  grunt.loadNpmTasks('grunt-contrib-jasmine');

  grunt.registerTask('test', ['mochacli', 'jshint']);

  // Running the `serve` command starts up a webserver
  grunt.registerTask('serve', ['connect']);

  grunt.registerTask('build', ['copy', 'bower', 'browserify']);
  grunt.registerTask('minify', ['uglify']);
  grunt.registerTask('default', ['build', 'minify']);

  // Push distribution libraries to CDN
  // Build and publish distribution site
  grunt.registerTask('publish', []);
};
<|endoftext|>


<commit_before>/*global module:false*/
module.exports = function(grunt) {
  require('jit-grunt')(grunt, {
    useminPrepare: 'grunt-usemin'
  });
  require('time-grunt')(grunt);

  // Project configuration.
  grunt.initConfig({
    // Project settings
    pkg: grunt.file.readJSON('package.json'),

    config: {
      dist: 'dist',
      client: 'public'
    },

    app: {
      public: 'public',
      server: 'server',
      dist: 'dist'
    },

    dir: {
      public: 'public',
      server: 'server',
      dist: 'dist'
    },

    express: {
      options: {
        port: process.env.PORT || 4000,
        livereload: true
      },
      dev: {
        options: {
          script: '<%=app.server%>/app.js'
        }
      },
      prod: {
        options: {
          script: '<%=app.dist%>/server/app.js'
        }
      }
    },

    watch: {
      gruntfile: {
        files: ['Gruntfile.js']
      },
      livereload: {
        files: [
          '<%=app.public%>/**/*.js',
          '<%=app.public%>/**/*.html'
        ],
        options: {
          livereload: true
        }
      },

      express: {
        files: [
          '<%=app.server%>/**/*.{js,json}'
        ],
        tasks: ['express:dev', 'wait'],
        options: {
          livereload: true,
          nospawn: true //Without this option specified express won't be reloaded
        }
      }
    },

    open: {
      all: {
        path: 'http://localhost:<%=express.options.port%>'
      }
    },

    jshint: {
      options: {
        reporter: require('jshint-stylish'),
        jshintrc: '.jshintrc'
      },
      public: {
        src: [
          '<%=app.public%>/js/**/*.js',
          '!<%=app.public%>/js/**/*.spec.js'
        ]
      },
      public_test: {
        src: [
          '<%=app.public%>/js/**/*.spec.js'
        ]
      },
      server: {
        src: [
          '<%=app.server%>/**/*.js'
        ]
      }
    },

    clean: {
      dist: {
        files: [{
          dot: true,
          src: [
            '.tmp',
            '<%=app.dist%>/*'
          ]
        }]
      },
      server: '.tmp'
    },

    copy: {
      dist: {
        files: [
          {
            expand: true,
            cwd: '<%=app.public%>',
            src: [
              '*.{ico,png.txt}',
              'index.html'
            ],
            dest: '<%=app.dist%>/public'
          },
          {
            expand: true,
            src: ['server/**/*', 'package.json'],
            dest: '<%=app.dist%>'
          }

        ]
      }
    },

    injector: {
      bower_dependencies: {
        options: {
          bowerPrefix: 'bower:',
          relative: true,
          ignorePath: '<%=app.public%>/'
        },
        files: {
          '<%=app.public%>/index.html': [
            'bower.json'
          ]
        }
      },
      local_dependencies: {
        options: {
          relative: true,
          ignorePath: '<%=app.public%>/'
        },
        files: {
          '<%=app.public%>/index.html': [
            '<%=app.public%>/js/**/*.js',
            '<%=app.public%>/css/**/*.css'
          ]
        }
      }
    },

    useminPrepare: {
      html: ['<%=app.public%>/index.html'],
      options: {
        dest: '<%=app.dist%>/public'
      }
    },

    usemin: {
      html: ['<%=app.dist%>/public/**/*.html'],
      options: {
        dirs: [
          '<%=app.dist%>/public'
        ]
      }
    },

    karma: {
      unit: {
        configFile: 'karma.conf.js',
        singleRun: true
      }
    }
  });

  grunt.registerTask('wait', function () {
    grunt.log.ok('Waiting for server reload...');

    var done = this.async();

    setTimeout(function () {
      grunt.log.writeln('Done waiting!');
      done();
    }, 1500);
  });

  grunt.registerTask('serve', [
    'injector',
    'express:dev',
    'wait',
    'open',
    'watch'
  ]);

  grunt.registerTask('test', function(target) {
    if (target === 'client') {
      return grunt.task.run([
        'karma'
      ]);
    } else {
      return grunt.task.run([
        'test:client'
      ]);
    }
  });

  grunt.registerTask('build', [
    'clean:dist',
    'injector',
    'copy',
    'useminPrepare',
    'concat',
    'uglify',
    'cssmin',
    'usemin'
  ]);

  // Default task.
  grunt.registerTask('default', [
    'jshint',
    'test',
    'build'
  ]);
};
<commit_msg>update Gruntfile.js<commit_after>/*global module:false*/
module.exports = function(grunt) {
  require('jit-grunt')(grunt, {
    express: 'grunt-express-server',
    useminPrepare: 'grunt-usemin'
  });
  require('time-grunt')(grunt);

  // Project configuration.
  grunt.initConfig({
    // Project settings
    pkg: grunt.file.readJSON('package.json'),

    config: {
      dist: 'dist',
      client: 'public'
    },

    app: {
      public: 'public',
      server: 'server',
      dist: 'dist'
    },

    dir: {
      public: 'public',
      server: 'server',
      dist: 'dist'
    },

    express: {
      options: {
        port: process.env.PORT || 4000,
        livereload: true
      },
      dev: {
        options: {
          script: '<%=app.server%>/app.js'
        }
      },
      prod: {
        options: {
          script: '<%=app.dist%>/server/app.js'
        }
      }
    },

    watch: {
      gruntfile: {
        files: ['Gruntfile.js']
      },
      livereload: {
        files: [
          '<%=app.public%>/**/*.js',
          '<%=app.public%>/**/*.html'
        ],
        options: {
          livereload: true
        }
      },

      express: {
        files: [
          '<%=app.server%>/**/*.{js,json}'
        ],
        tasks: ['express:dev', 'wait'],
        options: {
          livereload: true,
          nospawn: true //Without this option specified express won't be reloaded
        }
      }
    },

    open: {
      all: {
        path: 'http://localhost:<%=express.options.port%>'
      }
    },

    jshint: {
      options: {
        reporter: require('jshint-stylish'),
        jshintrc: '.jshintrc'
      },
      public: {
        src: [
          '<%=app.public%>/js/**/*.js',
          '!<%=app.public%>/js/**/*.spec.js'
        ]
      },
      public_test: {
        src: [
          '<%=app.public%>/js/**/*.spec.js'
        ]
      },
      server: {
        src: [
          '<%=app.server%>/**/*.js'
        ]
      }
    },

    clean: {
      dist: {
        files: [{
          dot: true,
          src: [
            '.tmp',
            '<%=app.dist%>/*'
          ]
        }]
      },
      server: '.tmp'
    },

    copy: {
      dist: {
        files: [
          {
            expand: true,
            cwd: '<%=app.public%>',
            src: [
              '*.{ico,png.txt}',
              'index.html'
            ],
            dest: '<%=app.dist%>/public'
          },
          {
            expand: true,
            src: ['server/**/*', 'package.json'],
            dest: '<%=app.dist%>'
          }

        ]
      }
    },

    injector: {
      bower_dependencies: {
        options: {
          bowerPrefix: 'bower:',
          relative: true,
          ignorePath: '<%=app.public%>/'
        },
        files: {
          '<%=app.public%>/index.html': [
            'bower.json'
          ]
        }
      },
      local_dependencies: {
        options: {
          relative: true,
          ignorePath: '<%=app.public%>/'
        },
        files: {
          '<%=app.public%>/index.html': [
            '<%=app.public%>/js/**/*.js',
            '<%=app.public%>/css/**/*.css'
          ]
        }
      }
    },

    useminPrepare: {
      html: ['<%=app.public%>/index.html'],
      options: {
        dest: '<%=app.dist%>/public'
      }
    },

    usemin: {
      html: ['<%=app.dist%>/public/**/*.html'],
      options: {
        dirs: [
          '<%=app.dist%>/public'
        ]
      }
    },

    karma: {
      unit: {
        configFile: 'karma.conf.js',
        singleRun: true
      }
    }
  });

  grunt.registerTask('wait', function () {
    grunt.log.ok('Waiting for server reload...');

    var done = this.async();

    setTimeout(function () {
      grunt.log.writeln('Done waiting!');
      done();
    }, 1500);
  });

  grunt.registerTask('serve', [
    'injector',
    'express:dev',
    'wait',
    'open',
    'watch'
  ]);

  grunt.registerTask('test', function(target) {
    if (target === 'client') {
      return grunt.task.run([
        'karma'
      ]);
    } else {
      return grunt.task.run([
        'test:client'
      ]);
    }
  });

  grunt.registerTask('build', [
    'clean:dist',
    'injector',
    'copy',
    'useminPrepare',
    'concat',
    'uglify',
    'cssmin',
    'usemin'
  ]);

  // Default task.
  grunt.registerTask('default', [
    'jshint',
    'test',
    'build'
  ]);
};
<|endoftext|>


<commit_before>module.exports = function(grunt) {
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        browserify: {
            all: {
                src: 'src/main.js',
                dest: 'dist/j29n.js'
            },
            options: {
                browserifyOptions: {
                    standalone: 'j29n'
                }
            }
        },
        uglify: {
            build: {
                src: 'dist/j29n.js',
                dest: 'dist/j29n.min.js'
            }
        }
    });

    grunt.loadNpmTasks('grunt-browserify');
    grunt.loadNpmTasks('grunt-contrib-uglify');

    grunt.registerTask('default', ['browserify', 'uglify']);
};<commit_msg>Added grunt browser task.<commit_after>module.exports = function(grunt) {
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        browserify: {
            all: {
                src: 'src/main.js',
                dest: 'dist/j29n.js'
            },
            options: {
                browserifyOptions: {
                    standalone: 'j29n'
                }
            }
        },
        uglify: {
            build: {
                src: 'dist/j29n.js',
                dest: 'dist/j29n.min.js'
            }
        }
    });

    grunt.loadNpmTasks('grunt-browserify');
    grunt.loadNpmTasks('grunt-contrib-uglify');

    grunt.registerTask('browser', ['browserify', 'uglify']);
    grunt.registerTask('default', 'browser');
};<|endoftext|>