<commit_before>/* 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.
 */
'use strict';

var flowableApp = angular.module('flowableApp', [
    'ngCookies',
    'ngResource',
    'ngSanitize',
    'ngRoute',
    'ngDragDrop',
    'mgcrea.ngStrap',
    'ngFileUpload',
    'ngAnimate',
    'pascalprecht.translate',
    'ui.grid',
    'ui.grid.edit',
    'ui.grid.selection',
    'ui.grid.autoResize',
    'angular-loading-bar',
    'cfp.hotkeys'
]);

var flowableModule = flowableApp;

flowableApp

  // Initialize routes
   .config(['$provide', '$routeProvider', '$selectProvider', '$datepickerProvider', '$translateProvider', 'cfpLoadingBarProvider',
   function ($provide, $routeProvider, $selectProvider, $datepickerProvider, $translateProvider, cfpLoadingBarProvider) {

   var appName = 'workflow';
   $provide.value('appName', appName);
   var appResourceRoot = FLOWABLE.CONFIG.webContextRoot + (FLOWABLE.CONFIG.webContextRoot ? '/' + appName + '/' : '');
   $provide.value('appResourceRoot', appResourceRoot);

    // Override caret for bs-select directive
    angular.extend($selectProvider.defaults, {
        caretHtml: ' '
    });

    // Override carets for bs-datepicker directive
    angular.extend($datepickerProvider.defaults, {
        iconLeft: 'icon icon-caret-left',
        iconRight: 'icon icon-caret-right'
    });

    $routeProvider
        .when('/start-process', {
            templateUrl: appResourceRoot + 'views/start-process.html',
            controller: 'StartProcessController'
        })
        .when('/apps/:deploymentKey/start-process', {
            templateUrl: appResourceRoot + 'views/start-process.html',
            controller: 'StartProcessController'
        })
        .when('/tasks', {
            templateUrl: appResourceRoot + 'views/tasks.html',
            controller: 'TasksController'
        })
        .when('/apps/:deploymentKey/tasks', {
            templateUrl: appResourceRoot + 'views/tasks.html',
            controller: 'TasksController'
        })
        .when('/task/:taskId', {
            templateUrl: appResourceRoot + 'views/task.html',
            controller: 'TaskController'
        })
        .when('/apps/:deploymentKey/task/:taskId', {
            templateUrl: appResourceRoot + 'views/task.html',
            controller: 'TaskController'
        })
        .when('/processes', {
            templateUrl: appResourceRoot + 'views/processes.html',
            controller: 'ProcessesController'
        })
        .when('/apps/:deploymentKey/processes', {
            templateUrl: appResourceRoot + 'views/processes.html',
            controller: 'ProcessesController'
        })
        .when('/process/:processId', {
            templateUrl: appResourceRoot + 'views/process.html',
            controller: 'ProcessController'
        })
        .when('/apps/:deploymentKey/process/:processId', {
            templateUrl: appResourceRoot + 'views/process.html',
            controller: 'ProcessController'
        })
        .otherwise({
            redirectTo: FLOWABLE.CONFIG.appDefaultRoute || '/tasks'
        });

        // Initialize angular-translate
        $translateProvider.useStaticFilesLoader({
           prefix: './i18n/',
           suffix: '.json'
        })
        /*
        This can be used to map multiple browser language keys to a
        angular translate language key.
        */
        // .registerAvailableLanguageKeys(['en'], {
        //     'en-*': 'en'
        // })
        .useSanitizeValueStrategy('sanitizeParameters')
        .uniformLanguageTag('bcp47')
        .determinePreferredLanguage();

       // turn loading bar spinner off (angular-loading-bar lib)
       cfpLoadingBarProvider.includeSpinner = false;
    }])
    .run(['$rootScope', '$routeParams', '$timeout', '$translate', '$location', '$http', '$window', 'appResourceRoot', 'AppDefinitionService', 'ProcessService',
        function($rootScope, $routeParams, $timeout, $translate, $location, $http, $window, appResourceRoot, AppDefinitionService, ProcessService) {

        // set angular translate fallback language
        $translate.fallbackLanguage(['en']);

        $rootScope.restRootUrl = function() {
            return FLOWABLE.CONFIG.contextRoot;
        };

        $rootScope.config = FLOWABLE.CONFIG;
        $rootScope.appResourceRoot = appResourceRoot;
        $rootScope.activitiFieldIdPrefix = 'activiti-';

        $rootScope.window = {};
        var updateWindowSize = function() {
            $rootScope.window.width = $window.innerWidth;
            $rootScope.window.height  = $window.innerHeight;
        };

        // Window resize hook
        angular.element($window).bind('resize', function() {
            $rootScope.$apply(updateWindowSize());
        });

        $rootScope.$watch('window.forceRefresh', function(newValue) {
            if(newValue) {
                $timeout(function() {
                    updateWindowSize();
                    $rootScope.window.forceRefresh = false;
                });
            }
        });

        updateWindowSize();

        // Main navigation
        $rootScope.mainNavigation = [
            {
                'id': 'tasks',
                'title': 'GENERAL.NAVIGATION.TASKS',
                'path': '/tasks'
            },
            {
                'id': 'processes',
                'title': 'GENERAL.NAVIGATION.PROCESSES',
                'path': '/processes'
            }
        ];

        $rootScope.mainPage = $rootScope.mainNavigation[0];

        // Empty object to hold cached app-definitions
        $rootScope.appDefinitions = {

        };

        /*
         * Set the current main page, using the page object. If the page is already active,
         * this is a no-op.
         */
        $rootScope.setMainPage = function(mainPage) {
            $rootScope.mainPage = mainPage;

            var path;
            if($rootScope.activeAppDefinition) {
                path = "/apps/" + $rootScope.activeAppDefinition.id + mainPage.path;
            } else {
                path = $rootScope.mainPage.path;
            }
            $location.path(path);
        };

        /*
         * Set the current main page, using the page ID. If the page is already active,
         * this is a no-op.
         */
        $rootScope.setMainPageById = function(mainPageId) {
            for (var i=0; i<$rootScope.mainNavigation.length; i++) {
                if (mainPageId == $rootScope.mainNavigation[i].id) {
                    $rootScope.mainPage = $rootScope.mainNavigation[i];
                    break;
                }
            }
        };

        // Alerts
        $rootScope.alerts = {
            queue: []
        };

        $rootScope.showAlert = function(alert) {
            if(alert.queue.length > 0) {
                alert.current = alert.queue.shift();
                // Start timout for message-pruning
                alert.timeout = $timeout(function() {
                    if(alert.queue.length == 0) {
                        alert.current = undefined;
                        alert.timeout = undefined;
                    } else {
                        $rootScope.showAlert(alert);
                    }
                }, (alert.current.type == 'error' ? 5000 : 1000));
            } else {
                $rootScope.alerts.current = undefined;
            }
        };

        $rootScope.addAlert = function(message, type) {
            var newAlert = {message: message, type: type};
            if(!$rootScope.alerts.timeout) {
                // Timeout for message queue is not running, start one
                $rootScope.alerts.queue.push(newAlert);
                $rootScope.showAlert($rootScope.alerts);
            } else {
                $rootScope.alerts.queue.push(newAlert);
            }
        };

        $rootScope.dismissAlert = function() {
            if(!$rootScope.alerts.timeout) {
                $rootScope.alerts.current = undefined;
            } else {
                $timeout.cancel($rootScope.alerts.timeout);
                $rootScope.alerts.timeout = undefined;
                $rootScope.showAlert($rootScope.alerts);
            }
        };

        $rootScope.addAlertPromise = function(promise, type) {
            if(promise) {
                promise.then(function(data) {
                    $rootScope.addAlert(data, type);
                });
            }
        };

        $http.get(FLOWABLE.CONFIG.contextRoot + '/app/rest/account')
        	.success(function (data, status, headers, config) {
              	$rootScope.account = data;
               	$rootScope.invalidCredentials = false;
 				$rootScope.authenticated = true;
          	});

        $rootScope.model = {};
        // TODO: remove proc-def from rootscope or make smarter
        $rootScope.root = {};

        $rootScope.loadProcessDefinitions = function(deploymentKey) {
        	ProcessService.getProcessDefinitions(deploymentKey).then(function(response) {
        		$rootScope.root.processDefinitions = response.data;
        	});
        };

        $rootScope.$on("$locationChangeStart",
            function (event, newUrl, oldUrl) {
                if(newUrl.indexOf("headless") >= 0) {
                    $rootScope.root.headless = true;
                } else {
                    $rootScope.root.headless = false;
                }
            }
        );

        /**
         * A 'safer' apply that avoids concurrent updates (which $apply allows).
         */
        $rootScope.safeApply = function(fn) {
            var phase = this.$root.$$phase;
            if(phase == '$apply' || phase == '$digest') {
                if(fn && (typeof(fn) === 'function')) {
                    fn();
                }
            } else {
                this.$apply(fn);
            }
        };

        $rootScope.logout = function () {
            $rootScope.authenticated = false;
            $rootScope.authenticationError = false;
            $http.get(FLOWABLE.CONFIG.contextRoot + '/app/logout')
                .success(function (data, status, headers, config) {
                    $rootScope.login = null;
                    $rootScope.authenticated = false;
                    $window.location.href = '/';
                    $window.location.reload();
                });
        };

    }
  ])
  .run(['$rootScope', '$location', '$window', '$translate', 'appName', '$modal',
        function($rootScope, $location, $window, $translate, appName , $modal) {

        var fixedUrlPart = '/' + appName + '/';

        $rootScope.backToLanding = function() {
            var baseUrl = $location.absUrl();
            var index = baseUrl.indexOf(fixedUrlPart);
            if (index >= 0) {
                baseUrl = baseUrl.substring(0, index) + '/';
            }
            $window.location.href = baseUrl;
        }
    }])

    // Moment-JS date-formatting filter
    .filter('dateformat', function() {
        return function(date, format) {
            if (date) {
                if(format == 'fromNow') {
                    return moment(date).fromNow();
                } else if(format == 'fromNowFull') {
                    return moment(date).fromNow() + ' (' + moment(date).format('MMMM Do YYYY') + ')';
                } else if (format) {
                    return moment(date).format(format);
                } else {
                    return moment(date).calendar();
                }
            }
            return '';
        };
    })
    .filter('duration', ['$translate', function($translate) {
        return function(millis) {
            if (millis) {
                var duration = moment.duration(millis);
                var result = '';
                var hours = duration.hours();
                if (hours > 0) {
                    result = result + hours + ' ' + $translate.instant('GENERAL.TIME.HOURS') + ' ';
                }
                var mins = duration.minutes();
                if (mins > 0) {
                    result = result + mins + ' ' + $translate.instant('GENERAL.TIME.MINUTES');
                }

                if (hours == 0 && mins == 0) {
                    result = duration.seconds() + ' ' + $translate.instant('GENERAL.TIME.SECONDS');

                }

                return result;
            }
            return millis;
        };
    }])
    .filter('username', function() {
        return function(user) {
            if (user) {
               if(user.firstName) {
                   return user.firstName + " " + user.lastName;
               } else if(user.lastName) {
                   return user.lastName;
               } else {
			       if (user != undefined && user != null){
				       var _user = user.split(".");
					   if (_user.length > 1){
					       user = _user[0].charAt(0).toUpperCase() + _user[0].slice(1) +" "+ _user[1].charAt(0).toUpperCase() + _user[1].slice(1);
					   } else {
						   user = _user[0].charAt(0).toUpperCase() + _user[0].slice(1);
					   }
					   return user;

				   } else {
					   return "??";
			       }
			   }
            }
            return '';
        };
    });
<commit_msg>Update workflow-app.js<commit_after>/* 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.
 */
'use strict';

var flowableApp = angular.module('flowableApp', [
    'ngCookies',
    'ngResource',
    'ngSanitize',
    'ngRoute',
    'ngDragDrop',
    'mgcrea.ngStrap',
    'ngFileUpload',
    'ngAnimate',
    'pascalprecht.translate',
    'ui.grid',
    'ui.grid.edit',
    'ui.grid.selection',
    'ui.grid.autoResize',
    'angular-loading-bar',
    'cfp.hotkeys',
    'ui.mask'
]);

var flowableModule = flowableApp;

flowableApp

  // Initialize routes
   .config(['$provide', '$routeProvider', '$selectProvider', '$datepickerProvider', '$translateProvider', 'cfpLoadingBarProvider',
   function ($provide, $routeProvider, $selectProvider, $datepickerProvider, $translateProvider, cfpLoadingBarProvider) {

   var appName = 'workflow';
   $provide.value('appName', appName);
   var appResourceRoot = FLOWABLE.CONFIG.webContextRoot + (FLOWABLE.CONFIG.webContextRoot ? '/' + appName + '/' : '');
   $provide.value('appResourceRoot', appResourceRoot);

    // Override caret for bs-select directive
    angular.extend($selectProvider.defaults, {
        caretHtml: ' '
    });

    // Override carets for bs-datepicker directive
    angular.extend($datepickerProvider.defaults, {
        iconLeft: 'icon icon-caret-left',
        iconRight: 'icon icon-caret-right'
    });

    $routeProvider
        .when('/start-process', {
            templateUrl: appResourceRoot + 'views/start-process.html',
            controller: 'StartProcessController'
        })
        .when('/apps/:deploymentKey/start-process', {
            templateUrl: appResourceRoot + 'views/start-process.html',
            controller: 'StartProcessController'
        })
        .when('/tasks', {
            templateUrl: appResourceRoot + 'views/tasks.html',
            controller: 'TasksController'
        })
        .when('/apps/:deploymentKey/tasks', {
            templateUrl: appResourceRoot + 'views/tasks.html',
            controller: 'TasksController'
        })
        .when('/task/:taskId', {
            templateUrl: appResourceRoot + 'views/task.html',
            controller: 'TaskController'
        })
        .when('/apps/:deploymentKey/task/:taskId', {
            templateUrl: appResourceRoot + 'views/task.html',
            controller: 'TaskController'
        })
        .when('/processes', {
            templateUrl: appResourceRoot + 'views/processes.html',
            controller: 'ProcessesController'
        })
        .when('/apps/:deploymentKey/processes', {
            templateUrl: appResourceRoot + 'views/processes.html',
            controller: 'ProcessesController'
        })
        .when('/process/:processId', {
            templateUrl: appResourceRoot + 'views/process.html',
            controller: 'ProcessController'
        })
        .when('/apps/:deploymentKey/process/:processId', {
            templateUrl: appResourceRoot + 'views/process.html',
            controller: 'ProcessController'
        })
        .otherwise({
            redirectTo: FLOWABLE.CONFIG.appDefaultRoute || '/tasks'
        });

        // Initialize angular-translate
        $translateProvider.useStaticFilesLoader({
           prefix: './i18n/',
           suffix: '.json'
        })
        /*
        This can be used to map multiple browser language keys to a
        angular translate language key.
        */
        // .registerAvailableLanguageKeys(['en'], {
        //     'en-*': 'en'
        // })
        .useSanitizeValueStrategy('sanitizeParameters')
        .uniformLanguageTag('bcp47')
        .determinePreferredLanguage();

       // turn loading bar spinner off (angular-loading-bar lib)
       cfpLoadingBarProvider.includeSpinner = false;
    }])
    .run(['$rootScope', '$routeParams', '$timeout', '$translate', '$location', '$http', '$window', 'appResourceRoot', 'AppDefinitionService', 'ProcessService',
        function($rootScope, $routeParams, $timeout, $translate, $location, $http, $window, appResourceRoot, AppDefinitionService, ProcessService) {

        // set angular translate fallback language
        $translate.fallbackLanguage(['en']);

        $rootScope.restRootUrl = function() {
            return FLOWABLE.CONFIG.contextRoot;
        };

        $rootScope.config = FLOWABLE.CONFIG;
        $rootScope.appResourceRoot = appResourceRoot;
        $rootScope.activitiFieldIdPrefix = 'activiti-';

        $rootScope.window = {};
        var updateWindowSize = function() {
            $rootScope.window.width = $window.innerWidth;
            $rootScope.window.height  = $window.innerHeight;
        };

        // Window resize hook
        angular.element($window).bind('resize', function() {
            $rootScope.$apply(updateWindowSize());
        });

        $rootScope.$watch('window.forceRefresh', function(newValue) {
            if(newValue) {
                $timeout(function() {
                    updateWindowSize();
                    $rootScope.window.forceRefresh = false;
                });
            }
        });

        updateWindowSize();

        // Main navigation
        $rootScope.mainNavigation = [
            {
                'id': 'tasks',
                'title': 'GENERAL.NAVIGATION.TASKS',
                'path': '/tasks'
            },
            {
                'id': 'processes',
                'title': 'GENERAL.NAVIGATION.PROCESSES',
                'path': '/processes'
            }
        ];

        $rootScope.mainPage = $rootScope.mainNavigation[0];

        // Empty object to hold cached app-definitions
        $rootScope.appDefinitions = {

        };

        /*
         * Set the current main page, using the page object. If the page is already active,
         * this is a no-op.
         */
        $rootScope.setMainPage = function(mainPage) {
            $rootScope.mainPage = mainPage;

            var path;
            if($rootScope.activeAppDefinition) {
                path = "/apps/" + $rootScope.activeAppDefinition.id + mainPage.path;
            } else {
                path = $rootScope.mainPage.path;
            }
            $location.path(path);
        };

        /*
         * Set the current main page, using the page ID. If the page is already active,
         * this is a no-op.
         */
        $rootScope.setMainPageById = function(mainPageId) {
            for (var i=0; i<$rootScope.mainNavigation.length; i++) {
                if (mainPageId == $rootScope.mainNavigation[i].id) {
                    $rootScope.mainPage = $rootScope.mainNavigation[i];
                    break;
                }
            }
        };

        // Alerts
        $rootScope.alerts = {
            queue: []
        };

        $rootScope.showAlert = function(alert) {
            if(alert.queue.length > 0) {
                alert.current = alert.queue.shift();
                // Start timout for message-pruning
                alert.timeout = $timeout(function() {
                    if(alert.queue.length == 0) {
                        alert.current = undefined;
                        alert.timeout = undefined;
                    } else {
                        $rootScope.showAlert(alert);
                    }
                }, (alert.current.type == 'error' ? 5000 : 1000));
            } else {
                $rootScope.alerts.current = undefined;
            }
        };

        $rootScope.addAlert = function(message, type) {
            var newAlert = {message: message, type: type};
            if(!$rootScope.alerts.timeout) {
                // Timeout for message queue is not running, start one
                $rootScope.alerts.queue.push(newAlert);
                $rootScope.showAlert($rootScope.alerts);
            } else {
                $rootScope.alerts.queue.push(newAlert);
            }
        };

        $rootScope.dismissAlert = function() {
            if(!$rootScope.alerts.timeout) {
                $rootScope.alerts.current = undefined;
            } else {
                $timeout.cancel($rootScope.alerts.timeout);
                $rootScope.alerts.timeout = undefined;
                $rootScope.showAlert($rootScope.alerts);
            }
        };

        $rootScope.addAlertPromise = function(promise, type) {
            if(promise) {
                promise.then(function(data) {
                    $rootScope.addAlert(data, type);
                });
            }
        };

        $http.get(FLOWABLE.CONFIG.contextRoot + '/app/rest/account')
        	.success(function (data, status, headers, config) {
              	$rootScope.account = data;
               	$rootScope.invalidCredentials = false;
 				$rootScope.authenticated = true;
          	});

        $rootScope.model = {};
        // TODO: remove proc-def from rootscope or make smarter
        $rootScope.root = {};

        $rootScope.loadProcessDefinitions = function(deploymentKey) {
        	ProcessService.getProcessDefinitions(deploymentKey).then(function(response) {
        		$rootScope.root.processDefinitions = response.data;
        	});
        };

        $rootScope.$on("$locationChangeStart",
            function (event, newUrl, oldUrl) {
                if(newUrl.indexOf("headless") >= 0) {
                    $rootScope.root.headless = true;
                } else {
                    $rootScope.root.headless = false;
                }
            }
        );

        /**
         * A 'safer' apply that avoids concurrent updates (which $apply allows).
         */
        $rootScope.safeApply = function(fn) {
            var phase = this.$root.$$phase;
            if(phase == '$apply' || phase == '$digest') {
                if(fn && (typeof(fn) === 'function')) {
                    fn();
                }
            } else {
                this.$apply(fn);
            }
        };

        $rootScope.logout = function () {
            $rootScope.authenticated = false;
            $rootScope.authenticationError = false;
            $http.get(FLOWABLE.CONFIG.contextRoot + '/app/logout')
                .success(function (data, status, headers, config) {
                    $rootScope.login = null;
                    $rootScope.authenticated = false;
                    $window.location.href = '/';
                    $window.location.reload();
                });
        };

    }
  ])
  .run(['$rootScope', '$location', '$window', '$translate', 'appName', '$modal',
        function($rootScope, $location, $window, $translate, appName , $modal) {

        var fixedUrlPart = '/' + appName + '/';

        $rootScope.backToLanding = function() {
            var baseUrl = $location.absUrl();
            var index = baseUrl.indexOf(fixedUrlPart);
            if (index >= 0) {
                baseUrl = baseUrl.substring(0, index) + '/';
            }
            $window.location.href = baseUrl;
        }
    }])

    // Moment-JS date-formatting filter
    .filter('dateformat', function() {
        return function(date, format) {
            if (date) {
                if(format == 'fromNow') {
                    return moment(date).fromNow();
                } else if(format == 'fromNowFull') {
                    return moment(date).fromNow() + ' (' + moment(date).format('MMMM Do YYYY') + ')';
                } else if (format) {
                    return moment(date).format(format);
                } else {
                    return moment(date).calendar();
                }
            }
            return '';
        };
    })
    .filter('duration', ['$translate', function($translate) {
        return function(millis) {
            if (millis) {
                var duration = moment.duration(millis);
                var result = '';
                var hours = duration.hours();
                if (hours > 0) {
                    result = result + hours + ' ' + $translate.instant('GENERAL.TIME.HOURS') + ' ';
                }
                var mins = duration.minutes();
                if (mins > 0) {
                    result = result + mins + ' ' + $translate.instant('GENERAL.TIME.MINUTES');
                }

                if (hours == 0 && mins == 0) {
                    result = duration.seconds() + ' ' + $translate.instant('GENERAL.TIME.SECONDS');

                }

                return result;
            }
            return millis;
        };
    }])
    .filter('username', function() {
        return function(user) {
            if (user) {
               if(user.firstName) {
                   return user.firstName + " " + user.lastName;
               } else if(user.lastName) {
                   return user.lastName;
               } else {
			       if (user != undefined && user != null){
				       var _user = user.split(".");
					   if (_user.length > 1){
					       user = _user[0].charAt(0).toUpperCase() + _user[0].slice(1) +" "+ _user[1].charAt(0).toUpperCase() + _user[1].slice(1);
					   } else {
						   user = _user[0].charAt(0).toUpperCase() + _user[0].slice(1);
					   }
					   return user;

				   } else {
					   return "??";
			       }
			   }
            }
            return '';
        };
    });
<|endoftext|>


<commit_before>/* Copyright Théo Zimmermann 2014
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

define(["app/dom", "app/i18n", "app/utils", "he", "diff_match_patch"], function($, i18n, utils, he) {

    "use strict";

    // ATTRIBUTES

    // mode can take values "reading", "reading_modification" and "commenting"
    var mode = "reading";
    // if mode is "reading_modification", currently_showing stores id of comment
    var currently_showing;

    // there must be only one
 on the page
    var article = $("article");
    // but there can be many blocks in an article
    var blocks = $(".block", article, false);
    // in the case there is no block, current_block will always represent the full article
    var current_block = article;

    // we will also save the comment html elements and their associated block
    var comments = [];

    var original_content, new_content;

    // button to show the original version
    var original_button;
    var create_original_button = function() {
        if (typeof original_button === "undefined") {
            original_button = $.htmlify(
                '<button type="button">' +
                i18n.translate("show-original") +
                '</button>'
            );
            original_button.on("click", show_original);
            original_button.style.visibility = "hidden";
        }
        return original_button;
    };

    // remember some of the DOM elements
    var cancel_button, comment_field;

    // the block slider is used to choose which block is currently selected
    var current_position;
    (function() {
        // having a slider makes no sense with no blocks
        if (blocks === null) { return null; }

        var slider = $.htmlify('

');
        // slider position
        slider.style.left =
            ((article.getBoundingClientRect().right
              + $("#isso-thread").getBoundingClientRect().left) / 2
             - 10) + "px";
        article.insertAfter(slider);

        var cursor = $.htmlify('

');
        slider.append(cursor);
        // cursor position
        var set_cursor_position = function(y) {
            var slider_rect = slider.getBoundingClientRect();
            var slider_height = slider_rect.bottom - slider_rect.top;
            var raw_position = y - slider_rect.top - 10;
            var corrected_position =
                (raw_position < 0) ?
                0 : ((raw_position > slider_height - 20) ?
                     slider_height - 20 : raw_position);
            cursor.style.top = corrected_position + "px";
            // current_position is useful to determine the current block
            current_position = y + slider_rect.top + 10;
        };

        var first_block = blocks[0].getBoundingClientRect();
        setTimeout(function() {
            set_cursor_position((first_block.top + first_block.bottom) / 2);
        }, 0);

        // define events on slider
        var follow_mouse = function(e) {
            set_cursor_position(e.clientY);
        };
        cursor.addEventListener("mousedown", function(e) {
            document.addEventListener("mousemove", follow_mouse);
            e.preventDefault();
        });
        document.addEventListener("mouseup", function() {
            document.removeEventListener("mousemove", follow_mouse);
            show_block_comments();
        });
    })();

    // INITIALIZE LIBRARIES

    // make a diff_match_patch object once and for all
    var dmp = new diff_match_patch();

    // CKEDITOR is not required thus we must check if it is available
    if (typeof CKEDITOR !== "undefined") {
        // turn off automatic editor creation once and for all
        CKEDITOR.disableAutoInline = true;
    }
    var editor;

    // AUXILIARY FUNCTIONS

    var highlight_current_block = function() {
        for (var i = 0; i < blocks.length; i++) {
            blocks[i].style.background = "transparent";
        }
        current_block.style.background = "rgba(211,211,211,0.5)";
    };

    // content after CKEditor reformatting
    // after decoding html entities
    // and after removing extra whitespace and new lines
    var getEditorContent = function() {
        return utils.clean_html(editor.getData());
    };

    var getBlockContent = function() {
        return utils.clean_html(current_block.innerHTML);
    }

    // FUNCTIONS WHICH ENABLE COMMENTING AND EDITING

    var init = function(comment_postbox) {
        comment_field = $(".textarea", comment_postbox);
        // let's curry!
        return function() {
            show_original();
            if (mode === "reading" && comment_field.innerHTML !== "") {
                mode = "commenting";
                original_content = getBlockContent();
                new_content = null;
                current_block.setAttribute("contenteditable", true);
                if (typeof CKEDITOR !== "undefined") {
                    editor = CKEDITOR.inline(current_block);
                    editor.on("instanceReady", function() {
                        editor.dataProcessor.writer.setRules("p", {
                            ident: false,
                            breakBeforeOpen: false,
                            breakAfterOpen: false,
                            breakBeforeClose: false,
                            breakAfterClose: false
                        });
                        original_content = getEditorContent();
                    });
                    editor.on("change", maybe_article_just_changed);
                }
                // first time : create cancel button and associate event
                if (!cancel_button) {
                    cancel_button = $(".post-action", comment_postbox).prepend(
                      '<input type="reset" value="' + i18n.translate("postbox-cancel") + '"></input>');
                    cancel_button.on("click", function(e) {
                        if (new_content === null ||
                            confirm(i18n.translate("postbox-confirm-cancel"))) {
                            comment_field.innerHTML = "";
                            cancel();
                        }
                    });
                }
                else {
                  cancel_button.style.display = "inline";
                }
            }
            else if (mode === "commenting" && comment_field.innerHTML === ""
                                           && new_content === null) {
                cancel();
            }
        };
    };

    var maybe_article_just_changed = function() {
        var current = typeof CKEDITOR === "undefined" ?
                        getBlockContent() :
                        getEditorContent();
        if (current !== original_content) {
            new_content = current;
        }
        else {
            new_content = null;
            if (comment_field.innerHTML === i18n.translate("postbox-text") ||
                comment_field.innerHTML === "") {
                current_block.blur();
                cancel();
            }
        }
    };

    var cancel = function() {
        if (mode === "commenting") {
            if (typeof editor !== "undefined") {
                editor.destroy();
            }
            current_block.setAttribute("contenteditable", false);
            if (new_content !== null) {
                current_block.innerHTML = original_content;
                new_content = null;
            }
            cancel_button.hide();
            mode = "reading";
        }
    };

    // FUNCTIONS TO SHOW COMMENTS / EDITS

    var save_comment = function(el, block_id) {
        comments.push({el: el, block: block_id});
    };

    var show_block_comments = function() {
        // when showing an edit or commenting, the current block is locked
        // this function is useless if there are no blocks
        if (mode == "reading" && blocks !== null) {
            // current block = block at current_position
            var i = 0;
            while (i < blocks.length &&
                   blocks[i].getBoundingClientRect().top <= current_position) {
                i++;
            }
            current_block = blocks[i - 1];
            highlight_current_block();
            // mask all comments that are not associated with the current block
            for (var i = 0 ; i < comments.length ; i++ ) {
                comments[i].el.style.display =
                    (comments[i].block === current_block.id) ?
                    "block" :
                    "none";
            }
        }
    };

    var show_edit = function(el, comment) {
        // let's curry!
        return function() {
            if (mode === "reading" || mode === "reading_modification") {
                if (currently_showing === comment.id) {
                    show_original();
                }
                else {
                    var previous_block = current_block;

                    // first check that the block associated with the comment
                    // exists or that there is no associated block simply
                    // because the page has no blocks
                    if (comment.block === "") {
                        if (blocks !== null) { return; }
                    }
                    else {
                        if (blocks === null) { return; }
                        var i = 0;
                        while (
                            i < blocks.length &&
                            blocks[i].id !== comment.block
                        ) { i++; }
                        if (i === blocks.length) { return; }
                        current_block = blocks[i];
                        highlight_current_block();
                    }

                    // save original content for later if it was not already
                    if (mode === "reading") {
                        original_content = getBlockContent();
                    }
                    else if (previous_block !== current_block) {
                        // restore original content for previous block
                        previous_block.innerHTML = original_content;
                        original_content = getBlockContent();
                    }

                    mode = "reading_modification";
                    currently_showing = comment.id;

                    // print diffs
                    var array = JSON.parse(he.decode(comment.edit));
                    var html = dmp.diff_prettyHtml(array);
                    current_block.innerHTML = html;

                    // add button to go back to standard reading mode
                    original_button.style.visibility = "visible";

                    // display selected comment in green and all others are set back to default
                    var comments = $(".isso-comment", null, false);
                    for (var i = 0; i < comments.length; i++) {
                        comments[i].classList.remove("selected");
                    }
                    el.classList.add("selected");

                    // scroll to block then to first change
                    var edit_top = $("#edit");
                    if (!edit_top.topIsVisible()) {
                        current_block.scrollIntoView();
                    }
                    if (!edit_top.topIsVisible()) {
                        edit_top.scrollIntoView();
                    }
                }
            }
        };
    };

    var show_original = function() {
        if (mode === "reading_modification") {
            // restore original display
            current_block.innerHTML = original_content;
            original_button.style.visibility = "hidden";
            var comments = $(".isso-comment", null, false);
            for (var i = 0; i < comments.length; i++) {
                comments[i].classList.remove("selected");
            }
            mode = "reading";
            currently_showing = null;
            // now show the current block like if we had just scrolled
            show_block_comments();
        }
    };

    // DEFINE EVENTS

    // fallback if we cannot use CKEditor change event
    if (typeof CKEDITOR === "undefined") {
        article.on("keyup", maybe_article_just_changed);
    }

    document.addEventListener("keydown", function(e) {
        if (e.keyCode === 27) {
            show_original();
        }
    });

    window.addEventListener("scroll", show_block_comments);

    // PUBLIC METHODS

    return {
        init: init,
        new_content: function() {
            if (new_content === null) {
                return null;
            }
            // otherwise we apply some pre-treatment before returning
            var splitted = dmp.diff_wordsToChars_(original_content, new_content);
            var diffs = dmp.diff_main(splitted.chars1, splitted.chars2);
            dmp.diff_cleanupSemantic(diffs);
            dmp.diff_charsToLines_(diffs, splitted.wordArray);
            return JSON.stringify(diffs);
        },
        block_id: function() { return current_block.id; },
        save_comment: save_comment,
        show_block_comments: show_block_comments,
        cancel: cancel,
        show: show_edit,
        original_button: create_original_button,
        show_original: show_original
    };
});

<commit_msg>start listening to scroll event<commit_after>/* Copyright Théo Zimmermann 2014
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

define(["app/dom", "app/i18n", "app/utils", "he", "diff_match_patch"], function($, i18n, utils, he) {

    "use strict";

    // ATTRIBUTES

    // mode can take values "reading", "reading_modification" and "commenting"
    var mode = "reading";
    // if mode is "reading_modification", currently_showing stores id of comment
    var currently_showing;

    // there must be only one
 on the page
    var article = $("article");
    // but there can be many blocks in an article
    var blocks = $(".block", article, false);
    // in the case there is no block, current_block will always represent the full article
    var current_block = article;

    // we will also save the comment html elements and their associated block
    var comments = [];

    var original_content, new_content;

    // button to show the original version
    var original_button;
    var create_original_button = function() {
        if (typeof original_button === "undefined") {
            original_button = $.htmlify(
                '<button type="button">' +
                i18n.translate("show-original") +
                '</button>'
            );
            original_button.on("click", show_original);
            original_button.style.visibility = "hidden";
        }
        return original_button;
    };

    // remember some of the DOM elements
    var cancel_button, comment_field;

    // the block slider is used to choose which block is currently selected
    var current_position;
    (function() {
        // having a slider makes no sense with no blocks
        if (blocks === null) { return null; }

        var slider = $.htmlify('

');
        // slider position
        slider.style.left =
            ((article.getBoundingClientRect().right
              + $("#isso-thread").getBoundingClientRect().left) / 2
             - 10) + "px";
        article.insertAfter(slider);

        var cursor = $.htmlify('

');
        slider.append(cursor);
        // cursor position
        var set_cursor_position = function(y) {
            var slider_rect = slider.getBoundingClientRect();
            var slider_height = slider_rect.bottom - slider_rect.top;
            var raw_position = y - slider_rect.top - 10;
            var corrected_position =
                (raw_position < 0) ?
                0 : ((raw_position > slider_height - 20) ?
                     slider_height - 20 : raw_position);
            cursor.style.top = corrected_position + "px";
            // current_position is useful to determine the current block
            current_position = y + slider_rect.top + 10;
        };

        var first_block = blocks[0].getBoundingClientRect();
        setTimeout(function() {
            set_cursor_position((first_block.top + first_block.bottom) / 2);
        }, 0);

        // define events on slider
        var follow_mouse = function(e) {
            set_cursor_position(e.clientY);
        };
        cursor.addEventListener("mousedown", function(e) {
            document.addEventListener("mousemove", follow_mouse);
            e.preventDefault();
        });
        document.addEventListener("mouseup", function() {
            document.removeEventListener("mousemove", follow_mouse);
            show_block_comments();
        });

        // move cursor when scrolling to the top at the top or to the bottom
        // at the bottom
        // ie. when we are already at top or bottom AND scrolling had no effect
        var previous_position = window.pageYOffset;
        document.addEventListener("scroll", function() {
            var new_position = window.pageYOffset;
            if (new_position === previous_position) {
                var max = document.documentElement.scrollHeight
                          - window.innerHeight;
                if (new_position >= max) {
                    // we are at the bottom
                    alert("bottom");
                } else if (new_position <= 0) {
                    // we are at the top
                    alert("top");
                }
            }
            previous_position = new_position;
        });
    })();

    // INITIALIZE LIBRARIES

    // make a diff_match_patch object once and for all
    var dmp = new diff_match_patch();

    // CKEDITOR is not required thus we must check if it is available
    if (typeof CKEDITOR !== "undefined") {
        // turn off automatic editor creation once and for all
        CKEDITOR.disableAutoInline = true;
    }
    var editor;

    // AUXILIARY FUNCTIONS

    var highlight_current_block = function() {
        for (var i = 0; i < blocks.length; i++) {
            blocks[i].style.background = "transparent";
        }
        current_block.style.background = "rgba(211,211,211,0.5)";
    };

    // content after CKEditor reformatting
    // after decoding html entities
    // and after removing extra whitespace and new lines
    var getEditorContent = function() {
        return utils.clean_html(editor.getData());
    };

    var getBlockContent = function() {
        return utils.clean_html(current_block.innerHTML);
    }

    // FUNCTIONS WHICH ENABLE COMMENTING AND EDITING

    var init = function(comment_postbox) {
        comment_field = $(".textarea", comment_postbox);
        // let's curry!
        return function() {
            show_original();
            if (mode === "reading" && comment_field.innerHTML !== "") {
                mode = "commenting";
                original_content = getBlockContent();
                new_content = null;
                current_block.setAttribute("contenteditable", true);
                if (typeof CKEDITOR !== "undefined") {
                    editor = CKEDITOR.inline(current_block);
                    editor.on("instanceReady", function() {
                        editor.dataProcessor.writer.setRules("p", {
                            ident: false,
                            breakBeforeOpen: false,
                            breakAfterOpen: false,
                            breakBeforeClose: false,
                            breakAfterClose: false
                        });
                        original_content = getEditorContent();
                    });
                    editor.on("change", maybe_article_just_changed);
                }
                // first time : create cancel button and associate event
                if (!cancel_button) {
                    cancel_button = $(".post-action", comment_postbox).prepend(
                      '<input type="reset" value="' + i18n.translate("postbox-cancel") + '"></input>');
                    cancel_button.on("click", function(e) {
                        if (new_content === null ||
                            confirm(i18n.translate("postbox-confirm-cancel"))) {
                            comment_field.innerHTML = "";
                            cancel();
                        }
                    });
                }
                else {
                  cancel_button.style.display = "inline";
                }
            }
            else if (mode === "commenting" && comment_field.innerHTML === ""
                                           && new_content === null) {
                cancel();
            }
        };
    };

    var maybe_article_just_changed = function() {
        var current = typeof CKEDITOR === "undefined" ?
                        getBlockContent() :
                        getEditorContent();
        if (current !== original_content) {
            new_content = current;
        }
        else {
            new_content = null;
            if (comment_field.innerHTML === i18n.translate("postbox-text") ||
                comment_field.innerHTML === "") {
                current_block.blur();
                cancel();
            }
        }
    };

    var cancel = function() {
        if (mode === "commenting") {
            if (typeof editor !== "undefined") {
                editor.destroy();
            }
            current_block.setAttribute("contenteditable", false);
            if (new_content !== null) {
                current_block.innerHTML = original_content;
                new_content = null;
            }
            cancel_button.hide();
            mode = "reading";
        }
    };

    // FUNCTIONS TO SHOW COMMENTS / EDITS

    var save_comment = function(el, block_id) {
        comments.push({el: el, block: block_id});
    };

    var show_block_comments = function() {
        // when showing an edit or commenting, the current block is locked
        // this function is useless if there are no blocks
        if (mode == "reading" && blocks !== null) {
            // current block = block at current_position
            var i = 0;
            while (i < blocks.length &&
                   blocks[i].getBoundingClientRect().top <= current_position) {
                i++;
            }
            current_block = blocks[i - 1];
            highlight_current_block();
            // mask all comments that are not associated with the current block
            for (var i = 0 ; i < comments.length ; i++ ) {
                comments[i].el.style.display =
                    (comments[i].block === current_block.id) ?
                    "block" :
                    "none";
            }
        }
    };

    var show_edit = function(el, comment) {
        // let's curry!
        return function() {
            if (mode === "reading" || mode === "reading_modification") {
                if (currently_showing === comment.id) {
                    show_original();
                }
                else {
                    var previous_block = current_block;

                    // first check that the block associated with the comment
                    // exists or that there is no associated block simply
                    // because the page has no blocks
                    if (comment.block === "") {
                        if (blocks !== null) { return; }
                    }
                    else {
                        if (blocks === null) { return; }
                        var i = 0;
                        while (
                            i < blocks.length &&
                            blocks[i].id !== comment.block
                        ) { i++; }
                        if (i === blocks.length) { return; }
                        current_block = blocks[i];
                        highlight_current_block();
                    }

                    // save original content for later if it was not already
                    if (mode === "reading") {
                        original_content = getBlockContent();
                    }
                    else if (previous_block !== current_block) {
                        // restore original content for previous block
                        previous_block.innerHTML = original_content;
                        original_content = getBlockContent();
                    }

                    mode = "reading_modification";
                    currently_showing = comment.id;

                    // print diffs
                    var array = JSON.parse(he.decode(comment.edit));
                    var html = dmp.diff_prettyHtml(array);
                    current_block.innerHTML = html;

                    // add button to go back to standard reading mode
                    original_button.style.visibility = "visible";

                    // display selected comment in green and all others are set back to default
                    var comments = $(".isso-comment", null, false);
                    for (var i = 0; i < comments.length; i++) {
                        comments[i].classList.remove("selected");
                    }
                    el.classList.add("selected");

                    // scroll to block then to first change
                    var edit_top = $("#edit");
                    if (!edit_top.topIsVisible()) {
                        current_block.scrollIntoView();
                    }
                    if (!edit_top.topIsVisible()) {
                        edit_top.scrollIntoView();
                    }
                }
            }
        };
    };

    var show_original = function() {
        if (mode === "reading_modification") {
            // restore original display
            current_block.innerHTML = original_content;
            original_button.style.visibility = "hidden";
            var comments = $(".isso-comment", null, false);
            for (var i = 0; i < comments.length; i++) {
                comments[i].classList.remove("selected");
            }
            mode = "reading";
            currently_showing = null;
            // now show the current block like if we had just scrolled
            show_block_comments();
        }
    };

    // DEFINE EVENTS

    // fallback if we cannot use CKEditor change event
    if (typeof CKEDITOR === "undefined") {
        article.on("keyup", maybe_article_just_changed);
    }

    document.addEventListener("keydown", function(e) {
        if (e.keyCode === 27) {
            show_original();
        }
    });

    window.addEventListener("scroll", show_block_comments);

    // PUBLIC METHODS

    return {
        init: init,
        new_content: function() {
            if (new_content === null) {
                return null;
            }
            // otherwise we apply some pre-treatment before returning
            var splitted = dmp.diff_wordsToChars_(original_content, new_content);
            var diffs = dmp.diff_main(splitted.chars1, splitted.chars2);
            dmp.diff_cleanupSemantic(diffs);
            dmp.diff_charsToLines_(diffs, splitted.wordArray);
            return JSON.stringify(diffs);
        },
        block_id: function() { return current_block.id; },
        save_comment: save_comment,
        show_block_comments: show_block_comments,
        cancel: cancel,
        show: show_edit,
        original_button: create_original_button,
        show_original: show_original
    };
});

<|endoftext|>


<commit_before>//
// JavaScript Notes code
// Created by Miguel Rentes on 2015-11-03.
// This code is free under the MIT license

// Chapter 1. Object Creation

var car = {
    brand: "Volvo",  // Properties listing
    model: "XC 90",
    used: false
};

console.log(car);

function Car(brand, model, used) {
    this.brand = brand;
    this.model = model;
    this.used = used;
};

// Notice the "new" keyword to create object instances
var another_car = new Car("Volvo", "XC 90", false);

console.log(another_car);<commit_msg>Eliminates unnecessary comments<commit_after>// JavaScript Notes code
// Created by Miguel Rentes on 2015-11-03.
// This code is free under the MIT license

// 1. Object Creation

var car = {
    brand: "Volvo",  // Properties listing
    model: "XC 90",
    used: false
};

console.log(car);

function Car(brand, model, used) {
    this.brand = brand;
    this.model = model;
    this.used = used;
};

// Notice the "new" keyword to create object instances
var another_car = new Car("Volvo", "XC 90", false);

console.log(another_car);
<|endoftext|>


<commit_before>$('html').toggleClass('no-js js');

$(document).ready(function() {

	/**
     * Create delete links for each delete form (forms are hidden by CSS)
     */
	$("td.actions form").each(function() {
	    $(this).after('Delete');
	});

    /**
     * Display warning message when clicking "delete" links
     * @return {boolean}     false
     */
	$('.delete').click(function(){
        $('td.actions a').css('visibility', 'hidden'); // hide all action links
        var formname = '#'+$(this).data("formname");
        var cells = $("table tr:nth-child(2) td").length;
        $(this).parent().parent().addClass('delete_selected').after(
            '
Do you really want to delete this? ' +
            'No ' +
                'Yes' +
                '
');
        $("#confirm_delete").click( function() {
            var formid = $(this).data("form");
            $(formid).submit();
            return false;
        });
        $("#cancel_delete").click( function() {
            $('#delete_choices').remove();
            $('tr.delete_selected').removeClass('delete_selected');
            $('td.actions a').removeAttr('style'); // show all action links
        });
        return false;
    });

	/**
     * Fade out flash messages
     */
	var success = $('.message');
	if(success.length) {
		success.animate({opacity: 1.0}, 2000).fadeOut();
		success.fadeOut(3000);
	}

    /**
     * enable responsive main navigation menu, see responsive-nav.js
     */
    var nav = responsiveNav(".nav-collapse", {
    open: function(){
        // when opening the menu, close the user menu, if it's open.
        var subnav = $('.sub-nav');
        if (subnav.is(':visible')) {
            subnav.hide();
        }
    }
    });

    if(window.getComputedStyle) {
        /**
         * Determine screen width based on generated content.
         * Generated content is added to the body within a media query.
         * see http://adactio.com/journal/5429/
         * @return {Boolean}
         */
        function isNarrowScreen() {
            var size = window.getComputedStyle(document.body,':after').getPropertyValue('content');
            if (size.indexOf("smallscreen") !=-1
            || size.indexOf("mediumscreen") !=-1
            || size.indexOf("widescreen") !=-1 ) {
                return false;
            } else {
                return true;
            }
        }
    }

    /**
     * Show user nav menu on click (shows on hover without Javascript).
     */
    $('.parent').click(function(e) {
        $('.sub-nav').slideToggle(200);
        var narrow = isNarrowScreen();
        if( narrow ) {
          nav.close(); // close the main nav menu
        }
    }).find('.sub-nav a').click(function(e) {
        // http://stackoverflow.com/questions/2457246/jquery-click-function-exclude-children
        e.stopPropagation(); // don't slide up when user-nav-menu links are clicked
    });

    /**
     * close the user menu if you click anywhere else on the page
     */
    $(document).click(function(e) {
        var subnav = $('.sub-nav');
        if( !$(e.target).closest('.parent').length ) {
            if (subnav.is(':visible')) {
                subnav.slideUp();
            }
        }
    });
});
<commit_msg>indentation<commit_after>$('html').toggleClass('no-js js');

$(document).ready(function() {

    /**
     * Create delete links for each delete form (forms are hidden by CSS)
     */
	$("td.actions form").each(function() {
	    $(this).after('Delete');
	});

    /**
     * Display warning message when clicking "delete" links
     * @return {boolean}     false
     */
	$('.delete').click(function(){
        $('td.actions a').css('visibility', 'hidden'); // hide all action links
        var formname = '#'+$(this).data("formname");
        var cells = $("table tr:nth-child(2) td").length;
        $(this).parent().parent().addClass('delete_selected').after(
            '
Do you really want to delete this? ' +
            'No ' +
            'Yes' +
            '
');
        $("#confirm_delete").click( function() {
            var formid = $(this).data("form");
            $(formid).submit();
            return false;
        });
        $("#cancel_delete").click( function() {
            $('#delete_choices').remove();
            $('tr.delete_selected').removeClass('delete_selected');
            $('td.actions a').removeAttr('style'); // show all action links
        });
        return false;
    });

	/**
     * Fade out flash messages
     */
	var success = $('.message');
	if(success.length) {
		success.animate({opacity: 1.0}, 2000).fadeOut();
		success.fadeOut(3000);
	}

    /**
     * enable responsive main navigation menu, see responsive-nav.js
     */
    var nav = responsiveNav(".nav-collapse", {
    open: function(){
        // when opening the menu, close the user menu, if it's open.
        var subnav = $('.sub-nav');
        if (subnav.is(':visible')) {
            subnav.hide();
        }
    }
    });

    if(window.getComputedStyle) {
        /**
         * Determine screen width based on generated content.
         * Generated content is added to the body within a media query.
         * see http://adactio.com/journal/5429/
         * @return {Boolean}
         */
        function isNarrowScreen() {
            var size = window.getComputedStyle(document.body,':after').getPropertyValue('content');
            if (size.indexOf("smallscreen") !=-1
            || size.indexOf("mediumscreen") !=-1
            || size.indexOf("widescreen") !=-1 ) {
                return false;
            } else {
                return true;
            }
        }
    }

    /**
     * Show user nav menu on click (shows on hover without Javascript).
     */
    $('.parent').click(function(e) {
        $('.sub-nav').slideToggle(200);
        var narrow = isNarrowScreen();
        if( narrow ) {
          nav.close(); // close the main nav menu
        }
    }).find('.sub-nav a').click(function(e) {
        // http://stackoverflow.com/questions/2457246/jquery-click-function-exclude-children
        e.stopPropagation(); // don't slide up when user-nav-menu links are clicked
    });

    /**
     * close the user menu if you click anywhere else on the page
     */
    $(document).click(function(e) {
        var subnav = $('.sub-nav');
        if( !$(e.target).closest('.parent').length ) {
            if (subnav.is(':visible')) {
                subnav.slideUp();
            }
        }
    });
});
<|endoftext|>


<commit_before>
    /* Playa written by Evan Short 2009  *
     *          ,,,=^_^=,,,              */

/* available at http://github.com/whtevn/playa */

/* distributed under the mit standard license  */

/************ Sharing is Caring ****************/
//                                             //
// if you have changes to make to this project //
//    fork it on github,                       //
//        and the whole world will love you    //
//                            forever and ever.//
//                                             //
/***********************************************/

// really need to get together an api reference
// and a changelog
// yuck.
var Playa =
  {
    init: function(name){
      var instance =
        {
          name: "",
          playlist:{},
          currentTrack: 0,
          totalTracks: 0,
          playhead: 0,
          playing: false,
          id3Info: {},
          trackTime: 0,
          setTrackTime: function(time) {
            time =time.toFixed(0)
            if(time != NaN && time > this.trackTime){
              this.trackTime = time.toFixed(0);
            }
          },
          setPlayState: function(state){ this.playing = state; },
          setPlayhead: function(time){ this.playhead = time.toFixed(0); },
          updatePlayhead: function() { this.setPlayhead(this.app.playheadPosition()); },
          setCurrentTrack: function(track){
            if(!track){
              track = this.currentTrack;
            }

            try {
              this.trackTime = this.playlist[this.currentTrack].tracktime;
            } catch(err) { }
            this.executeCallback("activateTrack");
          },
          gotoNext: function(){
            this.setPlayhead(0);

            if(this.currentTrack != this.totalTracks-1){
              this.setCurrentTrack(this.currentTrack += 1);
              this.executeCallback("gotoNext");
            }

            return(this.currentTrack);
          },
          gotoPrevious: function(){
            this.setPlayhead(0);

            if(this.currentTrack != 0){
              this.setCurrentTrack(this.currentTrack -= 1);
              this.executeCallback("gotoPrevious");
            }

            return(this.currentTrack);
          },
          playNext: function(){
            this.stop();
            if(this.currentTrack != this.gotoNext()){
              this.play();
              this.executeCallback("playNext");
            }
          },
          playPrevious: function(){
            this.stop();
            if(this.currentTrac != this.gotoPrevious()){
               this.play();
               this.executeCallback("playPrevious");
            }
          },
          currentTrackUrl: function(){
            var item = this.playlist[this.currentTrack];

            if(typeof item != 'string'){
              item = item.url;
            }

            return(item);
          },
          play: function(url, time){
            if(!url){
              url = this.currentTrackUrl();
           }

            if(!time){
              time = this.playhead;
            }

            if(this.playing == false){
              if(this.app.play(this.name, url, time)==true){
                this.executeCallback("play");
                this.startDoingWhilePlaying();
              }
            }
          },
          pause: function(){
            if(this.playing==true && this.app.pause(this.name)==true){
              this.executeCallback("pause");
              this.stopDoingWhilePlaying();
            }
          },
          stop: function(){
            if(this.app.stop(this.name)==true){
              this.stopDoingWhilePlaying();
            }

            this.executeCallback("stop");
          },
          playIntervalId: '',
          playheadUpdater: function(){
            /*
             * setInterval re-scopes everything to window
             * Playa only has a .current because of that
             * it is very disspointing to me that these
             * functions have to be called this way.
             * very dissapointing, indeed.
             */
            Playa.current.updatePlayhead(Playa.current);
            Playa.current.executeCallback("playing", Playa.current);
          },
          doOn: Playa.callbackDefault,
          executeCallback: function(name, playa){
            if(!playa){
              playa = this;
            }

            try {
              this.doOn[name](playa);
            } catch(err){ try { Playa.callbackDefault[name](playa);
              } catch(err){ }
            }
          },
          startDoingWhilePlaying: function(){
            this.playIntervalId = setInterval(this.playheadUpdater, 100);
          },
          stopDoingWhilePlaying: function(){
            clearInterval(this.playIntervalId);
          },

        };
      instance.name = name;
      return(instance);
    },

    setup: function(name, playlist) {
      if(typeof playlist == "string"){
        playlist = eval('('+playlist+')');
      }

      // need to go through the playlist
      // and make a track instance for each member
      // and then store it in the playlist as a track

      // need to pull all track logic out of here
      // and put it in there

      instance = Playa.init(name);
      instance.playlist = playlist;

      // this should be a method that actually returns
      // the length of the playlist
      instance.totalTracks = Playa.countTracks(playlist);

      instance.setCurrentTrack(0);
      instance['app'] = FlashInterface.get('Playa');
      Playa.add(name, instance);

      return(instance)
    },

    countTracks: function(playlist){ return(playlist.length) },
    add: function(name, instance) { this.get[name] = instance; },
    get: {},
    current: {},
    setCurrent: function(name){ this.current = this.get[name]; },
    callbackDefault: {}
  };

// this needs to be extracted into something worthwhile
// like a module with functions to get what is needed

// i think this is what is meant as "self-documenting code"

$(document).ready(function(){
  $(".playa").each(function(i){
    var element = this;
    var playa;
    $(this).find(".playlist").each(function(){
      if(!this.value){
        var playlist = []
        $(this).find(".track").each(function(i){
          var href;
          var time;
          if(!this.href){
            $(this).find("a").each(function(i){
              if(i==0)
                href = this.href
            });
          }else{
            href = this.href;
          }

          $(this).find(".tracktime").each(function(){
            if(this.value){
              time = parseInt(this.value);
            }else{
              time = $(this).text().split(":");
              time = parseInt(time[0])*60 + parseInt(time[1])
            }
          });
          if(!time){ time = 0}
          playlist.push({url: href, tracktime: time})
        });
        playa = Playa.setup(element.id, playlist);
          $(this).find(".track").each(function(i){
            $(this).bind("click", function(e){
              playa.stop();
              playa.currentTrack = i;
              playa.play(this.href);
              e.preventDefault()
            });
        });
      }else{
        playa = Playa.setup(element.id, this.value);
      }
    });
    $(this).find(".play").each(function(){
      $(this).bind("click", function(e){
        playa.play();
      });
    });
    $(this).find(".pause").each(function(){
      $(this).bind("click", function(e){
        playa.pause();
      });
    });
    $(this).find(".stop").each(function(){
      $(this).bind("click", function(e){
        playa.stop();
      });
    });
    $(this).find(".next").each(function(){
      $(this).bind("click", function(e){
        if(playa.playing==true){
          playa.playNext();
        }else{
          playa.gotoNext();
        }
      });
    });
    $(this).find(".previous").each(function(){
      $(this).bind("click", function(e){
        if(playa.playing==true){
          playa.playPrevious();
        }else{
          playa.gotoPrevious();
        }
      });
    });
  });
  FlashInterface.pageInit();
});

<commit_msg>fixing play timer problem for json playlists<commit_after>
    /* Playa written by Evan Short 2009  *
     *          ,,,=^_^=,,,              */

/* available at http://github.com/whtevn/playa */

/* distributed under the mit standard license  */

/************ Sharing is Caring ****************/
//                                             //
// if you have changes to make to this project //
//    fork it on github,                       //
//        and the whole world will love you    //
//                            forever and ever.//
//                                             //
/***********************************************/

// really need to get together an api reference
// and a changelog
// yuck.
var Playa =
  {
    init: function(name){
      var instance =
        {
          name: "",
          playlist:{},
          currentTrack: 0,
          totalTracks: 0,
          playhead: 0,
          playing: false,
          id3Info: {},
          trackTime: 0,
          setTrackTime: function(time) {
            time =time.toFixed(0)
            if(time != NaN && time > this.trackTime){
              this['trackTime'] = parseInt(time).toFixed(0);
            }
          },
          setPlayState: function(state){ this.playing = state; },
          setPlayhead: function(time){ this.playhead = time.toFixed(0); },
          updatePlayhead: function() { this.setPlayhead(this.app.playheadPosition()); },
          setCurrentTrack: function(track){
            if(!track){
              track = this.currentTrack;
            }

            if(this.playlist[this.currentTrack].tracktime){
              this.trackTime = this.playlist[this.currentTrack].tracktime;
            }else{
              this.trackTime = 0;
            }
            this.executeCallback("activateTrack");
          },
          gotoNext: function(){
            this.setPlayhead(0);

            if(this.currentTrack != this.totalTracks-1){
              this.setCurrentTrack(this.currentTrack += 1);
              this.executeCallback("gotoNext");
            }

            return(this.currentTrack);
          },
          gotoPrevious: function(){
            this.setPlayhead(0);

            if(this.currentTrack != 0){
              this.setCurrentTrack(this.currentTrack -= 1);
              this.executeCallback("gotoPrevious");
            }

            return(this.currentTrack);
          },
          playNext: function(){
            this.stop();
            if(this.currentTrack != this.gotoNext()){
              this.play();
              this.executeCallback("playNext");
            }
          },
          playPrevious: function(){
            this.stop();
            if(this.currentTrac != this.gotoPrevious()){
               this.play();
               this.executeCallback("playPrevious");
            }
          },
          currentTrackUrl: function(){
            var item = this.playlist[this.currentTrack];

            if(typeof item != 'string'){
              item = item.url;
            }

            return(item);
          },
          play: function(url, time){
            if(!url){
              url = this.currentTrackUrl();
           }

            if(!time){
              time = this.playhead;
            }

            if(this.playing == false){
              if(this.app.play(this.name, url, time)==true){
                this.executeCallback("play");
                this.startDoingWhilePlaying();
              }
            }
          },
          pause: function(){
            if(this.playing==true && this.app.pause(this.name)==true){
              this.executeCallback("pause");
              this.stopDoingWhilePlaying();
            }
          },
          stop: function(){
            if(this.app.stop(this.name)==true){
              this.stopDoingWhilePlaying();
            }

            this.executeCallback("stop");
          },
          playIntervalId: '',
          playheadUpdater: function(){
            /*
             * setInterval re-scopes everything to window
             * Playa only has a .current because of that
             * it is very disspointing to me that these
             * functions have to be called this way.
             * very dissapointing, indeed.
             */
            Playa.current.updatePlayhead(Playa.current);
            Playa.current.executeCallback("playing", Playa.current);
          },
          doOn: Playa.callbackDefault,
          executeCallback: function(name, playa){
            if(!playa){
              playa = this;
            }

            try {
              this.doOn[name](playa);
            } catch(err){ try { Playa.callbackDefault[name](playa);
              } catch(err){ }
            }
          },
          startDoingWhilePlaying: function(){
            this.playIntervalId = setInterval(this.playheadUpdater, 100);
          },
          stopDoingWhilePlaying: function(){
            clearInterval(this.playIntervalId);
          },

        };
      instance.name = name;
      return(instance);
    },

    setup: function(name, playlist) {
      if(typeof playlist == "string"){
        playlist = eval('('+playlist+')');
      }

      // need to go through the playlist
      // and make a track instance for each member
      // and then store it in the playlist as a track

      // need to pull all track logic out of here
      // and put it in there

      instance = Playa.init(name);
      instance.playlist = playlist;

      // this should be a method that actually returns
      // the length of the playlist
      instance.totalTracks = Playa.countTracks(playlist);

      instance.setCurrentTrack(0);
      instance['app'] = FlashInterface.get('Playa');
      Playa.add(name, instance);

      return(instance)
    },

    countTracks: function(playlist){ return(playlist.length) },
    add: function(name, instance) { this.get[name] = instance; },
    get: {},
    current: {},
    setCurrent: function(name){ this.current = this.get[name]; },
    callbackDefault: {}
  };

// this needs to be extracted into something worthwhile
// like a module with functions to get what is needed

// i think this is what is meant as "self-documenting code"

$(document).ready(function(){
  $(".playa").each(function(i){
    var element = this;
    var playa;
    $(this).find(".playlist").each(function(){
      if(this.value){
        playa = Playa.setup(element.id, this.value);
      }else{
        var playlist = []
        $(this).find(".track").each(function(i){
          var href;
          var time;
          if(this.href){
            href = this.href;
          }else{
            $(this).find("a").each(function(i){
              if(i==0)
                href = this.href
            });
          }

          $(this).find(".tracktime").each(function(){
            if(this.value){
              time = parseInt(this.value);
            }else{
              time = $(this).text().split(":");
              time = parseInt(time[0])*60 + parseInt(time[1])
            }
          });
          playlist.push({url: href, tracktime: time})
        });
        playa = Playa.setup(element.id, playlist);
          $(this).find(".track").each(function(i){
            $(this).bind("click", function(e){
              playa.stop();
              playa.currentTrack = i;
              playa.play(this.href);
              e.preventDefault()
            });
        });
      }
    });
    $(this).find(".play").each(function(){
      $(this).bind("click", function(e){
        playa.play();
      });
    });
    $(this).find(".pause").each(function(){
      $(this).bind("click", function(e){
        playa.pause();
      });
    });
    $(this).find(".stop").each(function(){
      $(this).bind("click", function(e){
        playa.stop();
      });
    });
    $(this).find(".next").each(function(){
      $(this).bind("click", function(e){
        if(playa.playing==true){
          playa.playNext();
        }else{
          playa.gotoNext();
        }
      });
    });
    $(this).find(".previous").each(function(){
      $(this).bind("click", function(e){
        if(playa.playing==true){
          playa.playPrevious();
        }else{
          playa.gotoPrevious();
        }
      });
    });
  });
  FlashInterface.pageInit();
});

<|endoftext|>


<commit_before>!function(e){var n={};function t(o){if(n[o])return n[o].exports;var r=n[o]={i:o,l:!1,exports:{}};return e[o].call(r.exports,r,r.exports,t),r.l=!0,r.exports}t.m=e,t.c=n,t.d=function(e,n,o){t.o(e,n)||Object.defineProperty(e,n,{enumerable:!0,get:o})},t.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},t.t=function(e,n){if(1&n&&(e=t(e)),8&n)return e;if(4&n&&"object"==typeof e&&e&&e.__esModule)return e;var o=Object.create(null);if(t.r(o),Object.defineProperty(o,"default",{enumerable:!0,value:e}),2&n&&"string"!=typeof e)for(var r in e)t.d(o,r,function(n){return e[n]}.bind(null,r));return o},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,n){return Object.prototype.hasOwnProperty.call(e,n)},t.p="",t(t.s=1)}([function(e,n,t){},function(e,n,t){"use strict";t.r(n);t(0);new class{constructor(){$(".group-custom-forms.edit").length&&($("#field-do-send-thankyou").on("toggle",(e,n)=>{this.fieldDoSendThankYou(n)}),this.fieldDoSendThankYou($("#field-do-send-thankyou input[type=checkbox]").is(":checked")))}fieldDoSendThankYou(e){e?$("#send-thankyou-options").show():$("#send-thankyou-options").hide(),"object"==typeof window._nails&&window._nails.addStripes()}}}]);<commit_msg>Compiling JS<commit_after>!function(i){var t={};function e(n){if(t[n])return t[n].exports;var o=t[n]={i:n,l:!1,exports:{}};return i[n].call(o.exports,o,o.exports,e),o.l=!0,o.exports}e.m=i,e.c=t,e.d=function(i,t,n){e.o(i,t)||Object.defineProperty(i,t,{enumerable:!0,get:n})},e.r=function(i){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(i,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(i,"__esModule",{value:!0})},e.t=function(i,t){if(1&t&&(i=e(i)),8&t)return i;if(4&t&&"object"==typeof i&&i&&i.__esModule)return i;var n=Object.create(null);if(e.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:i}),2&t&&"string"!=typeof i)for(var o in i)e.d(n,o,function(t){return i[t]}.bind(null,o));return n},e.n=function(i){var t=i&&i.__esModule?function(){return i.default}:function(){return i};return e.d(t,"a",t),t},e.o=function(i,t){return Object.prototype.hasOwnProperty.call(i,t)},e.p="",e(e.s=1)}([function(i,t,e){},function(i,t,e){"use strict";e.r(t);e(0);new class{constructor(){this.dom={},this.dom.$container=$(".group-custom-forms.edit"),this.dom.$container.length&&(this.dom.thankyou={$container:$("#field-do-send-thankyou"),$checked:$("#field-do-send-thankyou input[type=checkbox]"),$options:$("#send-thankyou-options")},this.dom.fields={$container:$("#custom-form-fields")},this.dom.notification={$container:$("#field-custom-form-notifications")},this.bindEvents(),this.initialStates())}bindEvents(){this.dom.thankyou.$container.on("toggle",(i,t)=>{this.fieldDoSendThankYou(t)}),this.dom.fields.$container.on("click",".js-remove-field",i=>{setTimeout(()=>{this.refreshNotifyConditionals(!0)},50)}).on("blur",".form-builder__field__label",()=>{this.refreshNotifyConditionals()}).find(".js-add-field").on("click",()=>{this.refreshNotifyConditionals()}),this.dom.notification.$container.on("dynamic-table:add",(i,t)=>{t.find("select.js-notification-condition-enabled").trigger("change"),this.refreshNotifyConditionals()}).on("change","select.js-notification-condition-enabled",i=>{this.toggleNotifyConditionals("1"===i.currentTarget.value,$(i.currentTarget).closest("td"))})}initialStates(){this.fieldDoSendThankYou(this.dom.thankyou.$checked.is(":checked")),this.dom.notification.$container.find("select.js-notification-condition-enabled").trigger("change"),this.refreshNotifyConditionals(),this.dom.notification.$container.find("select.js-notification-condition-field-id").each((i,t)=>{let e=$(t);if(e[0].hasAttribute("data-dynamic-table-value")){let i=e.data("dynamic-table-value");$('option[value="'+i+'"]',e).prop("selected",!0),e.trigger("change")}})}fieldDoSendThankYou(i){i?this.dom.thankyou.$options.show():this.dom.thankyou.$options.hide(),"object"==typeof window._nails&&window._nails.addStripes()}toggleNotifyConditionals(i,t){t.find([".js-notification-condition-field-id",".js-notification-condition-operator",".js-notification-condition-value"].join(", ")).prop("disabled",!i).parent().css({opacity:i?1:.5,"pointer-events":i?"auto":"none"})}refreshNotifyConditionals(i){let t=[];this.dom.fields.$container.find(".form-builder__field").each((i,e)=>{let n=$(e);t.push({id:n.find(".form-builder__field__id").val(),fieldNumber:n.find(".form-builder__field__field-number").val(),label:n.find(".form-builder__field__label").val()})});let e=[];if(this.dom.notification.$container.find("select.js-notification-condition-field-id").each((n,o)=>{let d=$(o),a=d.closest("tr"),l=d.val();d.find("option").remove(),$.each(t,(i,t)=>{let e=$("<option>").attr("value",t.id||"fieldNumber:"+t.fieldNumber).html(t.label);d.append(e)});let r=d.find('option[value="'+l+'"]');if(r.length)r.prop("selected",!0);else if(i){a.find(".js-notification-condition-enabled").val(0).trigger("change");let i=a.find(".js-notification-email").val();e.push(i||"The item at position "+(n+1))}d.trigger("change")}),e.length){let i='The following notifications have been set to "Always" as their condition can no longer be satisfied:
';for(let t=0;t<e.length;t++)i+="
– "+e[t];$("
").html(i).dialog({modal:!0,resizable:!1,draggable:!1,title:"Notification conditions changed",width:500,buttons:{OK:function(){$(this).dialog("close")}}}).show()}}}}]);<|endoftext|>


<commit_before>const Schema = require("truffle-contract-schema");
const fs = require("fs-extra");
const path = require("path");
const _ = require("lodash");
const debug = require("debug")("artifactor");

class Artifactor {
  constructor(destination) {
    this.destination = destination;
  }

  async save(artifactObject) {
    const normalizedArtifact = Schema.normalize(artifactObject);
    const contractName = normalizedArtifact.contractName;

    if (!contractName) throw new Error("You must specify a contract name.");

    const output_path = path.join(this.destination, `${contractName}.json`);
    let completeArtifact = {};

    // private helper for writing artifacts
    const writeArtifact = _completeArtifact => {
      _completeArtifact.updatedAt = new Date().toISOString();
      fs.writeFileSync(
        output_path,
        JSON.stringify(_completeArtifact, null, 2),
        "utf8"
      );
    };

    try {
      const existingArtifact = fs.readFileSync(output_path, "utf8"); // check if artifact already exists
      const existingArtifactObject = JSON.parse(existingArtifact); // parse existing artifact
      const normalizedExistingArtifact = Schema.normalize(
        existingArtifactObject
      );
      _.assign(
        completeArtifact,
        normalizedExistingArtifact,
        normalizedArtifact
      );
      writeArtifact(completeArtifact);
    } catch (e) {
      // if artifact doesn't already exist, write new file
      if (e.code === "ENOENT") return writeArtifact(normalizedArtifact);
      else if (e instanceof SyntaxError) throw new Error(e); // catches improperly formatted artifact json
      throw new Error(e); // catch all other errors
    }
  }

  async saveAll(artifactObjects) {
    let newArtifactObjects = {};

    if (Array.isArray(artifactObjects)) {
      const tmpArtifactArray = artifactObjects;

      tmpArtifactArray.forEach(artifactObj => {
        newArtifactObjects[artifactObj.contract_name] = artifactObj;
      });
    } else {
      newArtifactObjects = artifactObjects;
    }

    try {
      fs.statSync(this.destination); // check if destination exists
    } catch (e) {
      if (e.code === "ENOENT")
        // if destination doesn't exist, throw error
        throw new Error(`Destination "${this.destination}" doesn't exist!`);
      throw new Error(e); // throw on all other errors
    }

    Object.keys(newArtifactObjects).forEach(contractName => {
      let artifactObject = newArtifactObjects[contractName];
      this.save(artifactObject);
    });
  }
}

module.exports = Artifactor;
<commit_msg>keep error context<commit_after>const Schema = require("truffle-contract-schema");
const fs = require("fs-extra");
const path = require("path");
const _ = require("lodash");
const debug = require("debug")("artifactor");

class Artifactor {
  constructor(destination) {
    this.destination = destination;
  }

  async save(artifactObject) {
    const normalizedArtifact = Schema.normalize(artifactObject);
    const contractName = normalizedArtifact.contractName;

    if (!contractName) throw new Error("You must specify a contract name.");

    const output_path = path.join(this.destination, `${contractName}.json`);
    let completeArtifact = {};

    // private helper for writing artifacts
    const writeArtifact = _completeArtifact => {
      _completeArtifact.updatedAt = new Date().toISOString();
      fs.writeFileSync(
        output_path,
        JSON.stringify(_completeArtifact, null, 2),
        "utf8"
      );
    };

    try {
      const existingArtifact = fs.readFileSync(output_path, "utf8"); // check if artifact already exists
      const existingArtifactObject = JSON.parse(existingArtifact); // parse existing artifact
      const normalizedExistingArtifact = Schema.normalize(
        existingArtifactObject
      );
      _.assign(
        completeArtifact,
        normalizedExistingArtifact,
        normalizedArtifact
      );
      writeArtifact(completeArtifact);
    } catch (e) {
      // if artifact doesn't already exist, write new file
      if (e.code === "ENOENT") return writeArtifact(normalizedArtifact);
      else if (e instanceof SyntaxError) throw e; // catches improperly formatted artifact json
      throw e; // catch all other errors
    }
  }

  async saveAll(artifactObjects) {
    let newArtifactObjects = {};

    if (Array.isArray(artifactObjects)) {
      const tmpArtifactArray = artifactObjects;

      tmpArtifactArray.forEach(artifactObj => {
        newArtifactObjects[artifactObj.contract_name] = artifactObj;
      });
    } else {
      newArtifactObjects = artifactObjects;
    }

    try {
      fs.statSync(this.destination); // check if destination exists
    } catch (e) {
      if (e.code === "ENOENT")
        // if destination doesn't exist, throw error
        throw new Error(`Destination "${this.destination}" doesn't exist!`);
      throw e; // throw on all other errors
    }

    Object.keys(newArtifactObjects).forEach(contractName => {
      let artifactObject = newArtifactObjects[contractName];
      this.save(artifactObject);
    });
  }
}

module.exports = Artifactor;
<|endoftext|>


<commit_before>(function ($) {
    skel.breakpoints({
        xlarge: '(max-width: 1680px)',
        large: '(max-width: 1280px)',
        medium: '(max-width: 980px)',
        small: '(max-width: 736px)',
        xsmall: '(max-width: 480px)'
    });

    $(function () {

        var $window = $(window),
            $body = $('body'),
            $wrapper = $('#page-wrapper'),
            $banner = $('#banner'),
            $header = $('#header');

        // Disable animations/transitions until the page has loaded.
        $body.addClass('is-loading');

        $window.on('load', function () {
            window.setTimeout(function () {
                $body.removeClass('is-loading');
            }, 100);
        });

        // Mobile?
        if (skel.vars.mobile)
            $body.addClass('is-mobile');
        else
            skel
                .on('-medium !medium', function () {
                    $body.removeClass('is-mobile');
                })
                .on('+medium', function () {
                    $body.addClass('is-mobile');
                });

        // Fix: Placeholder polyfill.
        $('form').placeholder();

        // Prioritize "important" elements on medium.
        skel.on('+medium -medium', function () {
            $.prioritize(
                '.important\\28 medium\\29',
                skel.breakpoint('medium').active
            );
        });

        // Scrolly.
        $('.scrolly')
            .scrolly({
                speed: 1500,
                offset: $header.outerHeight()
            });

        // Menu.
        $('#menu')
            .append('')
            .appendTo($body)
            .panel({
                delay: 500,
                hideOnClick: true,
                hideOnSwipe: true,
                resetScroll: true,
                resetForms: true,
                side: 'right',
                target: $body,
                visibleClass: 'is-menu-visible'
            });

        // Header.
        if (skel.vars.IEVersion < 9)
            $header.removeClass('alt');

        if ($banner.length > 0
            && $header.hasClass('alt')) {

            $window.on('resize', function () {
                $window.trigger('scroll');
            });

            $banner.scrollex({
                bottom: $header.outerHeight() + 1,
                terminate: function () {
                    $header.removeClass('alt');
                },
                enter: function () {
                    $header.addClass('alt');
                },
                leave: function () {
                    $header.removeClass('alt');
                }
            });

        }

    });

})(jQuery);
<commit_msg>reformat<commit_after>(function ($) {
    skel.breakpoints({
        xlarge: '(max-width: 1680px)',
        large: '(max-width: 1280px)',
        medium: '(max-width: 980px)',
        small: '(max-width: 736px)',
        xsmall: '(max-width: 480px)'
    });

    $(function () {

        var $window = $(window),
            $body = $('body'),
            $wrapper = $('#page-wrapper'),
            $banner = $('#banner'),
            $header = $('#header');

        // Disable animations/transitions until the page has loaded.
        $body.addClass('is-loading');

        $window.on('load', function () {
            window.setTimeout(function () {
                $body.removeClass('is-loading');
            }, 100);
        });

        // Mobile?
        if (skel.vars.mobile)
            $body.addClass('is-mobile');
        else
            skel.on('-medium !medium', function () {
                $body.removeClass('is-mobile');
            }).on('+medium', function () {
                $body.addClass('is-mobile');
            });

        // Fix: Placeholder polyfill.
        $('form').placeholder();

        // Prioritize "important" elements on medium.
        skel.on('+medium -medium', function () {
            $.prioritize(
                '.important\\28 medium\\29',
                skel.breakpoint('medium').active
            );
        });

        // Scrolly.
        $('.scrolly')
            .scrolly({
                speed: 1500,
                offset: $header.outerHeight()
            });

        // Menu.
        $('#menu')
            .append('')
            .appendTo($body)
            .panel({
                delay: 500,
                hideOnClick: true,
                hideOnSwipe: true,
                resetScroll: true,
                resetForms: true,
                side: 'right',
                target: $body,
                visibleClass: 'is-menu-visible'
            });

        // Header.
        if (skel.vars.IEVersion < 9)
            $header.removeClass('alt');

        if ($banner.length > 0 && $header.hasClass('alt')) {

            $window.on('resize', function () {
                $window.trigger('scroll');
            });

            $banner.scrollex({
                bottom: $header.outerHeight() + 1,
                terminate: function () {
                    $header.removeClass('alt');
                },
                enter: function () {
                    $header.addClass('alt');
                },
                leave: function () {
                    $header.removeClass('alt');
                }
            });

        }

    });

})(jQuery);
<|endoftext|>