<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

cr.define('options', function() {

  var OptionsPage = options.OptionsPage;

  // State variables.
  var syncEnabled = false;
  var syncSetupCompleted = false;

  /**
   * Encapsulated handling of personal options page.
   * @constructor
   */
  function PersonalOptions() {
    OptionsPage.call(this, 'personal',
                     templateData.personalPageTabTitle,
                     'personal-page');
  }

  cr.addSingletonGetter(PersonalOptions);

  PersonalOptions.prototype = {
    // Inherit PersonalOptions from OptionsPage.
    __proto__: options.OptionsPage.prototype,

    // Initialize PersonalOptions page.
    initializePage: function() {
      // Call base class implementation to start preference initialization.
      OptionsPage.prototype.initializePage.call(this);

      var self = this;
      $('sync-action-link').onclick = function(event) {
        SyncSetupOverlay.showErrorUI();
      };
      $('start-stop-sync').onclick = function(event) {
        if (self.syncSetupCompleted)
          SyncSetupOverlay.showStopSyncingUI();
        else
          SyncSetupOverlay.showSetupUI();
      };
      $('customize-sync').onclick = function(event) {
        SyncSetupOverlay.showSetupUI();
      };
      $('manage-passwords').onclick = function(event) {
        OptionsPage.navigateToPage('passwords');
        OptionsPage.showTab($('passwords-nav-tab'));
        chrome.send('coreOptionsUserMetricsAction',
            ['Options_ShowPasswordManager']);
      };
      $('autofill-settings').onclick = function(event) {
        OptionsPage.navigateToPage('autofill');
        chrome.send('coreOptionsUserMetricsAction',
            ['Options_ShowAutofillSettings']);
      };
      $('themes-reset').onclick = function(event) {
        chrome.send('themesReset');
      };

      if (!cr.isChromeOS) {
        $('import-data').onclick = function(event) {
          // Make sure that any previous import success message is hidden, and
          // we're showing the UI to import further data.
          $('import-data-configure').hidden = false;
          $('import-data-success').hidden = true;
          OptionsPage.navigateToPage('importData');
          chrome.send('coreOptionsUserMetricsAction', ['Import_ShowDlg']);
        };

        if ($('themes-GTK-button')) {
          $('themes-GTK-button').onclick = function(event) {
            chrome.send('themesSetGTK');
          };
        }
      } else {
        $('change-picture-button').onclick = function(event) {
          OptionsPage.navigateToPage('changePicture');
        };
        chrome.send('loadAccountPicture');

        if (cr.commandLine.options['--bwsi']) {
          // Disable the screen lock checkbox and change-picture-button in
          // guest mode.
          $('enable-screen-lock').disabled = true;
          $('change-picture-button').disabled = true;
        }
      }

      if (PersonalOptions.disablePasswordManagement()) {
        // Disable the Password Manager in guest mode.
        $('passwords-offersave').disabled = true;
        $('passwords-neversave').disabled = true;
        $('passwords-offersave').value = false;
        $('passwords-neversave').value = true;
        $('manage-passwords').disabled = true;
      } else {
        // Otherwise, follow the preference, which can be toggled at runtime.
        // TODO(joaodasilva): remove the radio controls toggles below, once a
        // generic fix for updateElementState_ in pref_ui.js is available.
        // The problem is that updateElementState_ disables controls when a
        // policy enforces the preference, but doesn't re-enable them when the
        // policy is changed or removed. That's because controls can also be
        // disabled for other reasons (e.g. Guest mode, in this case) and
        // removing the policy doesn't mean the control can be enabled again.
        Preferences.getInstance().addEventListener(
            'profile.password_manager_enabled',
            function(event) {
              var managed = event.value && event.value['managed'];
              var value = event.value && event.value['value'] != undefined ?
                  event.value['value'] : event.value;
              $('passwords-offersave').disabled = managed;
              $('passwords-neversave').disabled = managed;
              $('manage-passwords').disabled = managed && !value;
            });
      }

      if (PersonalOptions.disableAutofillManagement()) {
        $('autofill-settings').disabled = true;

        // Disable and turn off autofill.
        var autofillEnabled = $('autofill-enabled');
        autofillEnabled.disabled = true;
        autofillEnabled.checked = false;
        cr.dispatchSimpleEvent(autofillEnabled, 'change');
      }
    },

    setSyncEnabled_: function(enabled) {
      this.syncEnabled = enabled;
    },

    setSyncSetupCompleted_: function(completed) {
      this.syncSetupCompleted = completed;
      $('customize-sync').hidden = !completed;
    },

    setAccountPicture_: function(image) {
      $('account-picture').src = image;
    },

    setSyncStatus_: function(status) {
      var statusSet = status != '';
      $('sync-overview').hidden = statusSet;
      $('sync-status').hidden = !statusSet;
      $('sync-status-text').innerHTML = status;
    },

    setSyncStatusErrorVisible_: function(visible) {
      visible ? $('sync-status').classList.add('sync-error') :
                $('sync-status').classList.remove('sync-error');
    },

    setSyncActionLinkEnabled_: function(enabled) {
      $('sync-action-link').disabled = !enabled;
    },

    setSyncActionLinkLabel_: function(status) {
      $('sync-action-link').textContent = status;

      // link-button does is not zero-area when the contents of the button are
      // empty, so explicitly hide the element.
      $('sync-action-link').hidden = !status.length;
    },

    setProfilesSectionVisible_: function(visible) {
      $('profiles-create').hidden = !visible;
    },

    setNewProfileButtonEnabled_: function(enabled) {
      $('new-profile').disabled = !enabled;
      if (enabled)
        $('profiles-create').classList.remove('disabled');
      else
        $('profiles-create').classList.add('disabled');
    },

    setStartStopButtonVisible_: function(visible) {
      $('start-stop-sync').hidden = !visible;
    },

    setStartStopButtonEnabled_: function(enabled) {
      $('start-stop-sync').disabled = !enabled;
    },

    setStartStopButtonLabel_: function(label) {
      $('start-stop-sync').textContent = label;
    },

    setGtkThemeButtonEnabled_: function(enabled) {
      if (!cr.isChromeOS && navigator.platform.match(/linux|BSD/i)) {
        $('themes-GTK-button').disabled = !enabled;
      }
    },

    setThemesResetButtonEnabled_: function(enabled) {
      $('themes-reset').disabled = !enabled;
    },

    hideSyncSection_: function() {
      $('sync-section').hidden = true;
    },

    /**
     * Toggles the visibility of the data type checkboxes based on whether they
     * are enabled on not.
     * @param {Object} dict A mapping from data type to a boolean indicating
     *     whether it is enabled.
     * @private
     */
    setRegisteredDataTypes_: function(dict) {
      for (var type in dict) {
        if (type.match(/Registered$/) && !dict[type]) {
          node = $(type.replace(/([a-z]+)Registered$/i, '$1').toLowerCase()
                   + '-check');
          if (node)
            node.parentNode.style.display = 'none';
        }
      }
    },
  };

  /**
   * Returns whether the user should be able to manage (view and edit) their
   * stored passwords. Password management is disabled in guest mode.
   * @return {boolean} True if password management should be disabled.
   */
  PersonalOptions.disablePasswordManagement = function() {
    return cr.commandLine.options['--bwsi'];
  };

  /**
   * Returns whether the user should be able to manage autofill settings.
   * @return {boolean} True if password management should be disabled.
   */
  PersonalOptions.disableAutofillManagement = function() {
    return cr.commandLine.options['--bwsi'];
  };

  // Forward public APIs to private implementations.
  [
    'setSyncEnabled',
    'setSyncSetupCompleted',
    'setAccountPicture',
    'setSyncStatus',
    'setSyncStatusErrorVisible',
    'setSyncActionLinkEnabled',
    'setSyncActionLinkLabel',
    'setProfilesSectionVisible',
    'setNewProfileButtonEnabled',
    'setStartStopButtonVisible',
    'setStartStopButtonEnabled',
    'setStartStopButtonLabel',
    'setGtkThemeButtonEnabled',
    'setThemesResetButtonEnabled',
    'hideSyncSection',
    'setRegisteredDataTypes',
  ].forEach(function(name) {
    PersonalOptions[name] = function(value) {
      PersonalOptions.getInstance()[name + '_'](value);
    };
  });

  // Export
  return {
    PersonalOptions: PersonalOptions
  };

});
<commit_msg>Autofill button should get enabled and disabled according to the policy value.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

cr.define('options', function() {

  var OptionsPage = options.OptionsPage;

  // State variables.
  var syncEnabled = false;
  var syncSetupCompleted = false;

  /**
   * Encapsulated handling of personal options page.
   * @constructor
   */
  function PersonalOptions() {
    OptionsPage.call(this, 'personal',
                     templateData.personalPageTabTitle,
                     'personal-page');
  }

  cr.addSingletonGetter(PersonalOptions);

  PersonalOptions.prototype = {
    // Inherit PersonalOptions from OptionsPage.
    __proto__: options.OptionsPage.prototype,

    // Initialize PersonalOptions page.
    initializePage: function() {
      // Call base class implementation to start preference initialization.
      OptionsPage.prototype.initializePage.call(this);

      var self = this;
      $('sync-action-link').onclick = function(event) {
        SyncSetupOverlay.showErrorUI();
      };
      $('start-stop-sync').onclick = function(event) {
        if (self.syncSetupCompleted)
          SyncSetupOverlay.showStopSyncingUI();
        else
          SyncSetupOverlay.showSetupUI();
      };
      $('customize-sync').onclick = function(event) {
        SyncSetupOverlay.showSetupUI();
      };
      $('manage-passwords').onclick = function(event) {
        OptionsPage.navigateToPage('passwords');
        OptionsPage.showTab($('passwords-nav-tab'));
        chrome.send('coreOptionsUserMetricsAction',
            ['Options_ShowPasswordManager']);
      };
      $('autofill-settings').onclick = function(event) {
        OptionsPage.navigateToPage('autofill');
        chrome.send('coreOptionsUserMetricsAction',
            ['Options_ShowAutofillSettings']);
      };
      $('themes-reset').onclick = function(event) {
        chrome.send('themesReset');
      };

      if (!cr.isChromeOS) {
        $('import-data').onclick = function(event) {
          // Make sure that any previous import success message is hidden, and
          // we're showing the UI to import further data.
          $('import-data-configure').hidden = false;
          $('import-data-success').hidden = true;
          OptionsPage.navigateToPage('importData');
          chrome.send('coreOptionsUserMetricsAction', ['Import_ShowDlg']);
        };

        if ($('themes-GTK-button')) {
          $('themes-GTK-button').onclick = function(event) {
            chrome.send('themesSetGTK');
          };
        }
      } else {
        $('change-picture-button').onclick = function(event) {
          OptionsPage.navigateToPage('changePicture');
        };
        chrome.send('loadAccountPicture');

        if (cr.commandLine.options['--bwsi']) {
          // Disable the screen lock checkbox and change-picture-button in
          // guest mode.
          $('enable-screen-lock').disabled = true;
          $('change-picture-button').disabled = true;
        }
      }

      if (PersonalOptions.disablePasswordManagement()) {
        // Disable the Password Manager in guest mode.
        $('passwords-offersave').disabled = true;
        $('passwords-neversave').disabled = true;
        $('passwords-offersave').value = false;
        $('passwords-neversave').value = true;
        $('manage-passwords').disabled = true;
      } else {
        // Otherwise, follow the preference, which can be toggled at runtime.
        // TODO(joaodasilva): remove the radio controls toggles below, once a
        // generic fix for updateElementState_ in pref_ui.js is available.
        // The problem is that updateElementState_ disables controls when a
        // policy enforces the preference, but doesn't re-enable them when the
        // policy is changed or removed. That's because controls can also be
        // disabled for other reasons (e.g. Guest mode, in this case) and
        // removing the policy doesn't mean the control can be enabled again.
        Preferences.getInstance().addEventListener(
            'profile.password_manager_enabled',
            function(event) {
              var managed = event.value && event.value['managed'];
              var value = event.value && event.value['value'] != undefined ?
                  event.value['value'] : event.value;
              $('passwords-offersave').disabled = managed;
              $('passwords-neversave').disabled = managed;
              $('manage-passwords').disabled = managed && !value;
            });
      }

      if (PersonalOptions.disableAutofillManagement()) {
        $('autofill-settings').disabled = true;

        // Disable and turn off autofill.
        var autofillEnabled = $('autofill-enabled');
        autofillEnabled.disabled = true;
        autofillEnabled.checked = false;
        cr.dispatchSimpleEvent(autofillEnabled, 'change');
      } else {
        Preferences.getInstance().addEventListener(
            'autofill.enabled',
            function(event) {
              var managed = event.value && event.value['managed'];
              var value = event.value && event.value['value'] != undefined ?
                  event.value['value'] : event.value;
              $('autofill-settings').disabled = managed && !value;
            });
      }
    },

    setSyncEnabled_: function(enabled) {
      this.syncEnabled = enabled;
    },

    setSyncSetupCompleted_: function(completed) {
      this.syncSetupCompleted = completed;
      $('customize-sync').hidden = !completed;
    },

    setAccountPicture_: function(image) {
      $('account-picture').src = image;
    },

    setSyncStatus_: function(status) {
      var statusSet = status != '';
      $('sync-overview').hidden = statusSet;
      $('sync-status').hidden = !statusSet;
      $('sync-status-text').innerHTML = status;
    },

    setSyncStatusErrorVisible_: function(visible) {
      visible ? $('sync-status').classList.add('sync-error') :
                $('sync-status').classList.remove('sync-error');
    },

    setSyncActionLinkEnabled_: function(enabled) {
      $('sync-action-link').disabled = !enabled;
    },

    setSyncActionLinkLabel_: function(status) {
      $('sync-action-link').textContent = status;

      // link-button does is not zero-area when the contents of the button are
      // empty, so explicitly hide the element.
      $('sync-action-link').hidden = !status.length;
    },

    setProfilesSectionVisible_: function(visible) {
      $('profiles-create').hidden = !visible;
    },

    setNewProfileButtonEnabled_: function(enabled) {
      $('new-profile').disabled = !enabled;
      if (enabled)
        $('profiles-create').classList.remove('disabled');
      else
        $('profiles-create').classList.add('disabled');
    },

    setStartStopButtonVisible_: function(visible) {
      $('start-stop-sync').hidden = !visible;
    },

    setStartStopButtonEnabled_: function(enabled) {
      $('start-stop-sync').disabled = !enabled;
    },

    setStartStopButtonLabel_: function(label) {
      $('start-stop-sync').textContent = label;
    },

    setGtkThemeButtonEnabled_: function(enabled) {
      if (!cr.isChromeOS && navigator.platform.match(/linux|BSD/i)) {
        $('themes-GTK-button').disabled = !enabled;
      }
    },

    setThemesResetButtonEnabled_: function(enabled) {
      $('themes-reset').disabled = !enabled;
    },

    hideSyncSection_: function() {
      $('sync-section').hidden = true;
    },

    /**
     * Toggles the visibility of the data type checkboxes based on whether they
     * are enabled on not.
     * @param {Object} dict A mapping from data type to a boolean indicating
     *     whether it is enabled.
     * @private
     */
    setRegisteredDataTypes_: function(dict) {
      for (var type in dict) {
        if (type.match(/Registered$/) && !dict[type]) {
          node = $(type.replace(/([a-z]+)Registered$/i, '$1').toLowerCase()
                   + '-check');
          if (node)
            node.parentNode.style.display = 'none';
        }
      }
    },
  };

  /**
   * Returns whether the user should be able to manage (view and edit) their
   * stored passwords. Password management is disabled in guest mode.
   * @return {boolean} True if password management should be disabled.
   */
  PersonalOptions.disablePasswordManagement = function() {
    return cr.commandLine.options['--bwsi'];
  };

  /**
   * Returns whether the user should be able to manage autofill settings.
   * @return {boolean} True if password management should be disabled.
   */
  PersonalOptions.disableAutofillManagement = function() {
    return cr.commandLine.options['--bwsi'];
  };

  // Forward public APIs to private implementations.
  [
    'setSyncEnabled',
    'setSyncSetupCompleted',
    'setAccountPicture',
    'setSyncStatus',
    'setSyncStatusErrorVisible',
    'setSyncActionLinkEnabled',
    'setSyncActionLinkLabel',
    'setProfilesSectionVisible',
    'setNewProfileButtonEnabled',
    'setStartStopButtonVisible',
    'setStartStopButtonEnabled',
    'setStartStopButtonLabel',
    'setGtkThemeButtonEnabled',
    'setThemesResetButtonEnabled',
    'hideSyncSection',
    'setRegisteredDataTypes',
  ].forEach(function(name) {
    PersonalOptions[name] = function(value) {
      PersonalOptions.getInstance()[name + '_'](value);
    };
  });

  // Export
  return {
    PersonalOptions: PersonalOptions
  };

});
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012-2015 S-Core Co., Ltd.
 *
 * 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.
 */

define(['./plugin',
        'webida-lib/plugins/workbench/plugin',
        'webida-lib/app',
        'webida-lib/widgets/views/splitviewcontainer',
        'webida-lib/widgets/views/viewmanager',
        'dojo/dom-style',
        'dojo/dom-geometry',
        'dojo/topic',
        'other-lib/underscore/lodash.min'
       ], function (editors, workbench, ide, SplitViewContainer, vm, domStyle,
              geometry, topic, _) {
    'use strict';
    /* global timedLogger: true */

    function getPanel() {
        var docFrag = document.createDocumentFragment();
        docFrag.appendChild(editors.elem);
        return docFrag;
    }

    function onPanelAppended() {
        var $elemTab = $('

');
        $(editors.elem).append($elemTab);

        editors.splitViewContainer = new SplitViewContainer();
        editors.splitViewContainer.init({
            'splitCount': 2,
            'verticalSplit': false,
            'smartVisible': true,
            'rotatable': true
        }, 'editor-tab');
        vm.addToGroup(editors.splitViewContainer, 'editorView');

        topic.subscribe('editor-panel-resize', function () {
            var borderContainer = editors.splitViewContainer.widgetObject;
            var children = borderContainer.getChildren();
            var totalW = 0;
            var totalH = 0;
            var width, height;
            var child;
            var i;
            var ratioW, ratioH;
            for (i = 0; i < children.length; i++) {
                child = children[i];
                totalW += geometry.getMarginBox(child.domNode).w;
                totalH += geometry.getMarginBox(child.domNode).h;
            }

            for (i = 1; i < children.length; i++) {
                child = children[i];
                width = geometry.getMarginBox(child.domNode).w;
                height = geometry.getMarginBox(child.domNode).h;
                ratioW =  parseInt((width * 100 / totalW) + 0.5, 10) + '%';
                ratioH =  parseInt((height * 100 / totalH) + 0.5, 10) + '%';
                //console.log('total : ' +totalW+ ', content : '+ i  + ' : ' + width + ', ratio : '+ratioW);
                if (child.get('region') === 'right') {
                    if ($(child.domNode).css('width').split('%').length > 1) {
                        continue;
                    }
                    domStyle.set(child.domNode, 'width', ratioW);
                } else if (child.get('region') === 'bottom') {
                    if ($(child.domNode).css('height').split('%').length > 1) {
                        continue;
                    }
                    domStyle.set(child.domNode, 'height', ratioH);
                }
            }
        });

        /* viewcontainer supports 'dblclick' event
        var vcList = editors.splitViewContainer.getViewContainers();
        _.forEach(vcList, function (vc) {
            dojo.connect(vc.tabContainer, 'onDblClick', function (ev) {
                if (ev.currentTarget === vc.tabContainer.domNode) {
                    var parent = ev.srcElement.parentNode;
                    while (parent && parent.parentNode) {
                        if (parent === vc.tabContainer.domNode.firstElementChild) {
                            workbench.toggleFullScreen();
                            break;
                        }
                        parent = parent.parentNode;
                    }
                }
            });
        });
        */

        topic.subscribe('view.selected', function (event) {
            var view = event.view;
            var vc = event.viewContainer;
            if (!vc || (vc.getParent() !== editors.splitViewContainer)) {
                return;
            }

            var file = editors.getFileByViewId(view.getId());
            if (file) {
                var changed = editors.currentFile !== file;
                if (changed) {
                    if (editors.currentFile && editors.getPart(editors.currentFile)) {
                        editors.getPart(editors.currentFile).hide();
                    }
                    editors.setCurrentFile(file);
                }

                editors.ensureCreated(file, true);
            }

            /*
            //TODO FIXME --> #issue 11937. resolved in a different way
            var viewList = vc.getViewList();
            file = null;
            for (var i = viewList.length - 1; i >= 0; i--) {
                if (view === viewList[i]) {
                    if (i > 0) {
                        file = editors.getFileByViewId(viewList[i - 1].getId());
                    } else if (viewList.length > 1) {
                        file = editors.getFileByViewId(viewList[i + 1].getId());
                    }
                    break;
                }
            }
            if (file) {
                editors.ensureCreated(file, false);
            }
             */
        });

        topic.subscribe('view.focused', function (event) {
            var view = event.view;
            var vc = event.viewContainer;
            if (!vc || (vc.getParent() !== editors.splitViewContainer)) {
                return;
            }

            var file = editors.getFileByViewId(view.getId());
            if (file) {
                if (editors.currentFile !== file) {
                    editors.setCurrentFile(file);
                }

                topic.publish('editors.focused', file.path, file);
            }
        });

        topic.subscribe('view.close', function (event, close) {

            function closeFile() {
                if (event.closable) {
                	var editorPart = editors.getPart(file);
                    editorPart.hide();
                    editorPart.destroy();
                    editors.removeFile(file.path);

                    var i = editors.currentFiles.indexOf(file);
                    if (i >= 0) {
                        editors.currentFiles.splice(i, 1);
                    } else {
                        console.warn('unexpected');
                    }

                    if (editors.currentFile === file) {
                        editors.setCurrentFile(null);
                    }

                    workbench.unregistFromViewFocusList(view);

                    topic.publish('editors.closed', file.path);
                    close();
                }
            }

            var view = event.view;
            var vc = event.viewContainer;
            if (!vc || (vc.getParent() !== editors.splitViewContainer)) {
                return;
            }

            var file = editors.getFileByViewId(view.getId());

            editors.editorTabFocusController.unregisterView(view);

            if (!event.force && file.isModified()) {
                require(['webida-lib/widgets/dialogs/buttoned-dialog/ButtonedDialog'], function (ButtonedDialog) {
                    var dialog = new ButtonedDialog({
                        title: 'Unsaved Changes in the File to Close',
                        buttons: [
                            {
                                caption: 'Save and Close',
                                methodOnClick: 'saveAndClose'
                            },
                            {
                                caption: 'Close without Saving',
                                methodOnClick: 'closeWithoutSaving'
                            },
                            {
                                caption: 'Cancel',
                                methodOnClick: 'hide'
                            }
                        ],
                        methodOnEnter: 'saveAndClose',
                        saveAndClose: function () {
                            editors.saveFile({
                                path: file.path,
                                callback: function () {
                                    //event.closable = true;
                                    closeFile();
                                    dialog.hide();
                                }
                            });
                        },
                        closeWithoutSaving: function () {
                            //event.closable = true;
                            closeFile();
                            this.hide();
                        },

                        buttonsWidth: '140px',
                        onHide: function () {
                            dialog.destroyRecursive();
                        }
                    });
                    dialog.setContentArea(' File "' + file.name  + '" has unsaved changes. ' +
                                          ' Save and close this file? ');
                    dialog.show();
                });
            } else {
                closeFile();
            }

        });

        ide.registerBeforeUnloadChecker(function () {
            var keys = Object.keys(editors.files);
            var modifiedFileNames = [];
            var len = keys.length;
            for (var i = 0; i < len; i++) {
                var key = keys[i];
                var file = editors.files[key];
                //if (editors.isModifiedFile(file)) {
                if (file.isModified()) {
                    modifiedFileNames.push(file.name);
                }
            }
            if (modifiedFileNames.length > 0) {
                return 'You have unsaved changes in files: ' + modifiedFileNames.join(', ');
            }
        });

        var lastStatus = ide.registerStatusContributorAndGetLastStatus('editor-view', function () {
            var status = {};
            var cursorDefault = {col: 0, row: 0};
            var splitVc = editors.splitViewContainer;
            var viewContainers = splitVc.getViewContainers();
            var vc, i, j;
            var totalW = 0;
            var totalH = 0;
            for (i = 0; i < viewContainers.length; i++) {
                vc = viewContainers[i];
                if (vc.getViewList().length > 0) {
                    totalW += geometry.getContentBox(vc.topContainer.domNode).w;
                    totalH += geometry.getContentBox(vc.topContainer.domNode).h;
                }
            }

            // status.viewContainers
            status.viewContainers = [];
            for (i = 0; i < viewContainers.length; i++) {
                vc = viewContainers[i];
                var viewList = vc.getViewList();
                var tabs = [];
                var selfile;
                var width = 0;
                var height = 0;
                if (viewList.length > 0) {
                    for (j = 0; j < viewList.length; j++) {
                        var view = viewList[j];
                        var file = editors.getFileByViewId(view.getId());
                        var cursor = editors.getCursor(file) || cursorDefault;
                        var foldings = file.editorContext ? file.editorContext.getFoldings() : [];
                                // temporary solution
                                // TODO: see why file.editorContext sometimes is null.
                        tabs.push([cursor.col, cursor.row, file.path, foldings, file.editorName]);
                        console.log('--* path : ' + file.path);
                    }
                    selfile = editors.getFileByViewId(vc.getSelectedView().getId());
                    width = domStyle.get(vc.topContainer.domNode, 'width');
                    height = domStyle.get(vc.topContainer.domNode, 'height');

                    width = geometry.getContentBox(vc.topContainer.domNode).w;
                    height = geometry.getContentBox(vc.topContainer.domNode).h;
                    if (width > 0) {
                        width = parseInt((width * 100 / totalW), 10) + '%';
                    }
                    if (height > 0) {
                        height = parseInt((height * 100 / totalH), 10) + '%';
                    }
                }
                status.viewContainers.push({
                    tabs: tabs,
                    selected: selfile && selfile.path,
                    width: width,
                    height: height
                });
            }

            // status.viewLayout
            if (viewContainers.length > 0) {
                status.viewLayout = {
                    count: splitVc.get('splitCount'),
                    vertical: splitVc.get('verticalSplit')
                };
            }

            // status.recentFiles
            status.recentFiles = editors.recentFiles.exportToPlainArray();

            return status;
        });

        if (lastStatus && lastStatus.viewContainers) {
            setTimeout(function () {
                editors.onloadPendingFilesCount = _.reduce(lastStatus.viewContainers, function (memo, vc) {
                    return memo + vc.tabs.length;
                }, 0);

                var tab;
                var openFileWithNamespace = function (path, opt, pos, foldings) {
                    var t = timedLogger.getLoggerTime();
                    editors.openFile(path, opt, function (file) {
                        //console.log('hina: file opend. pos.col = ' + pos.col);
                        //console.log('hina: file opend. pos.row = ' + pos.row);

                        _.defer(function () {
                            if (file.editorContext && file.editorContext.setCursor) {
                                file.editorContext.setCursor(pos);
                            }
                            if (file.editorContext && foldings) {
                                _.each(foldings, function (fold) {
                                    file.editorContext.foldCode(fold);
                                });
                            }
                        });

                        timedLogger.log('opened file "' + path + '"', t);
                    });
                };

                var path = null;
                var opt = null;
                var pos = null;
                var vc;

                if (lastStatus.viewLayout && lastStatus.viewLayout.vertical) {
                    if (lastStatus.viewLayout.vertical === true) {
                        editors.splitViewContainer.set('verticalSplit', true);
                    } else {
                        editors.splitViewContainer.set('verticalSplit', false);
                    }
                }

                for (var i = 0; i < lastStatus.viewContainers.length; i++) {
                    vc = lastStatus.viewContainers[i];
                    var siblingList = [];
                    var j;
                    for (j = 0; j < vc.tabs.length; j++) {
                        siblingList.push(vc.tabs[j][2]);
                    }

                    for (j = 0; j < vc.tabs.length; j++) {
                        tab = vc.tabs[j];
                        opt = {};
                        path = tab[2];
                        if (path === vc.selected) {
                            opt.show = true;
                        } else {
                            opt.show = false;
                        }
                        opt.cellIndex = i;
                        opt.siblingList = siblingList;
                        opt.editorName = tab[4];
                        pos = {};
                        pos.col = tab[0];
                        pos.row = tab[1];
                        openFileWithNamespace(path, opt, pos, tab[3]);
                    }

                    var viewContainers = editors.splitViewContainer.getViewContainers();
                    //console.log($(viewContainers[i].topContainer.domNode).css('width'));
                    if (i > 0 && (vc.tabs.length > 0)) {
                        $(viewContainers[i].topContainer.domNode).css('width', vc.width);
                        $(viewContainers[i].topContainer.domNode).css('height', vc.height);
                    }
                }

                if (lastStatus.recentFiles) {
                    editors.recentFiles.importFromPlainArray(lastStatus.recentFiles);
                }
            }, 50);
        }
    }

    return {
        getPanel: getPanel,
        onPanelAppended: onPanelAppended
    };
});
<commit_msg>[BUGFIX] Correct computation of editor width/height ratio when resizing. (ODP-7) [desc] This patch fixes the problem of constantly moving editor splitter when we show and hide other view panels. Note that this is a temporal bug fix and an extensive redesign of IDE's view system will be done soon.<commit_after>/*
 * Copyright (c) 2012-2015 S-Core Co., Ltd.
 *
 * 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.
 */

define(['./plugin',
        'webida-lib/plugins/workbench/plugin',
        'webida-lib/app',
        'webida-lib/widgets/views/splitviewcontainer',
        'webida-lib/widgets/views/viewmanager',
        'dojo/dom-style',
        'dojo/dom-geometry',
        'dojo/topic',
        'other-lib/underscore/lodash.min'
       ], function (editors, workbench, ide, SplitViewContainer, vm, domStyle,
              geometry, topic, _) {
    'use strict';
    /* global timedLogger: true */

    function getPanel() {
        var docFrag = document.createDocumentFragment();
        docFrag.appendChild(editors.elem);
        return docFrag;
    }

    function onPanelAppended() {
        var $elemTab = $('

');
        $(editors.elem).append($elemTab);

        editors.splitViewContainer = new SplitViewContainer();
        editors.splitViewContainer.init({
            'splitCount': 2,
            'verticalSplit': false,
            'smartVisible': true,
            'rotatable': true
        }, 'editor-tab');
        vm.addToGroup(editors.splitViewContainer, 'editorView');

        topic.subscribe('editor-panel-resize', function () {
            var borderContainer = editors.splitViewContainer.widgetObject;
            var children = borderContainer.getChildren();
            var totalW = 5;  // including margin and splitter size
            var totalH = 5;  // including margin and splitter size
            var width, height;
            var child;
            var i;
            var ratioW, ratioH;
            for (i = 0; i < children.length; i++) {
                child = children[i];
                totalW += geometry.getMarginBox(child.domNode).w;
                totalH += geometry.getMarginBox(child.domNode).h;
            }

            for (i = 1; i < children.length; i++) {
                child = children[i];
                width = geometry.getMarginBox(child.domNode).w;
                height = geometry.getMarginBox(child.domNode).h;
                ratioW = ((width - 2) * 100 / totalW) + '%';
                ratioH = ((height - 2) * 100 / totalH) + '%';
                //console.log('total : ' +totalW+ ', content : '+ i  + ' : ' + width + ', ratio : '+ratioW);
                if (child.get('region') === 'right') {
                    if ($(child.domNode).css('width').split('%').length > 1) {
                        continue;
                    }
                    domStyle.set(child.domNode, 'width', ratioW);
                } else if (child.get('region') === 'bottom') {
                    if ($(child.domNode).css('height').split('%').length > 1) {
                        continue;
                    }
                    domStyle.set(child.domNode, 'height', ratioH);
                }
            }
        });

        /* viewcontainer supports 'dblclick' event
        var vcList = editors.splitViewContainer.getViewContainers();
        _.forEach(vcList, function (vc) {
            dojo.connect(vc.tabContainer, 'onDblClick', function (ev) {
                if (ev.currentTarget === vc.tabContainer.domNode) {
                    var parent = ev.srcElement.parentNode;
                    while (parent && parent.parentNode) {
                        if (parent === vc.tabContainer.domNode.firstElementChild) {
                            workbench.toggleFullScreen();
                            break;
                        }
                        parent = parent.parentNode;
                    }
                }
            });
        });
        */

        topic.subscribe('view.selected', function (event) {
            var view = event.view;
            var vc = event.viewContainer;
            if (!vc || (vc.getParent() !== editors.splitViewContainer)) {
                return;
            }

            var file = editors.getFileByViewId(view.getId());
            if (file) {
                var changed = editors.currentFile !== file;
                if (changed) {
                    if (editors.currentFile && editors.getPart(editors.currentFile)) {
                        editors.getPart(editors.currentFile).hide();
                    }
                    editors.setCurrentFile(file);
                }

                editors.ensureCreated(file, true);
            }

            /*
            //TODO FIXME --> #issue 11937. resolved in a different way
            var viewList = vc.getViewList();
            file = null;
            for (var i = viewList.length - 1; i >= 0; i--) {
                if (view === viewList[i]) {
                    if (i > 0) {
                        file = editors.getFileByViewId(viewList[i - 1].getId());
                    } else if (viewList.length > 1) {
                        file = editors.getFileByViewId(viewList[i + 1].getId());
                    }
                    break;
                }
            }
            if (file) {
                editors.ensureCreated(file, false);
            }
             */
        });

        topic.subscribe('view.focused', function (event) {
            var view = event.view;
            var vc = event.viewContainer;
            if (!vc || (vc.getParent() !== editors.splitViewContainer)) {
                return;
            }

            var file = editors.getFileByViewId(view.getId());
            if (file) {
                if (editors.currentFile !== file) {
                    editors.setCurrentFile(file);
                }

                topic.publish('editors.focused', file.path, file);
            }
        });

        topic.subscribe('view.close', function (event, close) {

            function closeFile() {
                if (event.closable) {
                	var editorPart = editors.getPart(file);
                    editorPart.hide();
                    editorPart.destroy();
                    editors.removeFile(file.path);

                    var i = editors.currentFiles.indexOf(file);
                    if (i >= 0) {
                        editors.currentFiles.splice(i, 1);
                    } else {
                        console.warn('unexpected');
                    }

                    if (editors.currentFile === file) {
                        editors.setCurrentFile(null);
                    }

                    workbench.unregistFromViewFocusList(view);

                    topic.publish('editors.closed', file.path);
                    close();
                }
            }

            var view = event.view;
            var vc = event.viewContainer;
            if (!vc || (vc.getParent() !== editors.splitViewContainer)) {
                return;
            }

            var file = editors.getFileByViewId(view.getId());

            editors.editorTabFocusController.unregisterView(view);

            if (!event.force && file.isModified()) {
                require(['webida-lib/widgets/dialogs/buttoned-dialog/ButtonedDialog'], function (ButtonedDialog) {
                    var dialog = new ButtonedDialog({
                        title: 'Unsaved Changes in the File to Close',
                        buttons: [
                            {
                                caption: 'Save and Close',
                                methodOnClick: 'saveAndClose'
                            },
                            {
                                caption: 'Close without Saving',
                                methodOnClick: 'closeWithoutSaving'
                            },
                            {
                                caption: 'Cancel',
                                methodOnClick: 'hide'
                            }
                        ],
                        methodOnEnter: 'saveAndClose',
                        saveAndClose: function () {
                            editors.saveFile({
                                path: file.path,
                                callback: function () {
                                    //event.closable = true;
                                    closeFile();
                                    dialog.hide();
                                }
                            });
                        },
                        closeWithoutSaving: function () {
                            //event.closable = true;
                            closeFile();
                            this.hide();
                        },

                        buttonsWidth: '140px',
                        onHide: function () {
                            dialog.destroyRecursive();
                        }
                    });
                    dialog.setContentArea(' File "' + file.name  + '" has unsaved changes. ' +
                                          ' Save and close this file? ');
                    dialog.show();
                });
            } else {
                closeFile();
            }

        });

        ide.registerBeforeUnloadChecker(function () {
            var keys = Object.keys(editors.files);
            var modifiedFileNames = [];
            var len = keys.length;
            for (var i = 0; i < len; i++) {
                var key = keys[i];
                var file = editors.files[key];
                //if (editors.isModifiedFile(file)) {
                if (file.isModified()) {
                    modifiedFileNames.push(file.name);
                }
            }
            if (modifiedFileNames.length > 0) {
                return 'You have unsaved changes in files: ' + modifiedFileNames.join(', ');
            }
        });

        var lastStatus = ide.registerStatusContributorAndGetLastStatus('editor-view', function () {
            var status = {};
            var cursorDefault = {col: 0, row: 0};
            var splitVc = editors.splitViewContainer;
            var viewContainers = splitVc.getViewContainers();
            var vc, i, j;
            var totalW = 0;
            var totalH = 0;
            for (i = 0; i < viewContainers.length; i++) {
                vc = viewContainers[i];
                if (vc.getViewList().length > 0) {
                    totalW += geometry.getContentBox(vc.topContainer.domNode).w;
                    totalH += geometry.getContentBox(vc.topContainer.domNode).h;
                }
            }

            // status.viewContainers
            status.viewContainers = [];
            for (i = 0; i < viewContainers.length; i++) {
                vc = viewContainers[i];
                var viewList = vc.getViewList();
                var tabs = [];
                var selfile;
                var width = 0;
                var height = 0;
                if (viewList.length > 0) {
                    for (j = 0; j < viewList.length; j++) {
                        var view = viewList[j];
                        var file = editors.getFileByViewId(view.getId());
                        var cursor = editors.getCursor(file) || cursorDefault;
                        var foldings = file.editorContext ? file.editorContext.getFoldings() : [];
                                // temporary solution
                                // TODO: see why file.editorContext sometimes is null.
                        tabs.push([cursor.col, cursor.row, file.path, foldings, file.editorName]);
                        console.log('--* path : ' + file.path);
                    }
                    selfile = editors.getFileByViewId(vc.getSelectedView().getId());
                    width = domStyle.get(vc.topContainer.domNode, 'width');
                    height = domStyle.get(vc.topContainer.domNode, 'height');

                    width = geometry.getContentBox(vc.topContainer.domNode).w;
                    height = geometry.getContentBox(vc.topContainer.domNode).h;
                    if (width > 0) {
                        width = parseInt((width * 100 / totalW), 10) + '%';
                    }
                    if (height > 0) {
                        height = parseInt((height * 100 / totalH), 10) + '%';
                    }
                }
                status.viewContainers.push({
                    tabs: tabs,
                    selected: selfile && selfile.path,
                    width: width,
                    height: height
                });
            }

            // status.viewLayout
            if (viewContainers.length > 0) {
                status.viewLayout = {
                    count: splitVc.get('splitCount'),
                    vertical: splitVc.get('verticalSplit')
                };
            }

            // status.recentFiles
            status.recentFiles = editors.recentFiles.exportToPlainArray();

            return status;
        });

        if (lastStatus && lastStatus.viewContainers) {
            setTimeout(function () {
                editors.onloadPendingFilesCount = _.reduce(lastStatus.viewContainers, function (memo, vc) {
                    return memo + vc.tabs.length;
                }, 0);

                var tab;
                var openFileWithNamespace = function (path, opt, pos, foldings) {
                    var t = timedLogger.getLoggerTime();
                    editors.openFile(path, opt, function (file) {
                        //console.log('hina: file opend. pos.col = ' + pos.col);
                        //console.log('hina: file opend. pos.row = ' + pos.row);

                        _.defer(function () {
                            if (file.editorContext && file.editorContext.setCursor) {
                                file.editorContext.setCursor(pos);
                            }
                            if (file.editorContext && foldings) {
                                _.each(foldings, function (fold) {
                                    file.editorContext.foldCode(fold);
                                });
                            }
                        });

                        timedLogger.log('opened file "' + path + '"', t);
                    });
                };

                var path = null;
                var opt = null;
                var pos = null;
                var vc;

                if (lastStatus.viewLayout && lastStatus.viewLayout.vertical) {
                    if (lastStatus.viewLayout.vertical === true) {
                        editors.splitViewContainer.set('verticalSplit', true);
                    } else {
                        editors.splitViewContainer.set('verticalSplit', false);
                    }
                }

                for (var i = 0; i < lastStatus.viewContainers.length; i++) {
                    vc = lastStatus.viewContainers[i];
                    var siblingList = [];
                    var j;
                    for (j = 0; j < vc.tabs.length; j++) {
                        siblingList.push(vc.tabs[j][2]);
                    }

                    for (j = 0; j < vc.tabs.length; j++) {
                        tab = vc.tabs[j];
                        opt = {};
                        path = tab[2];
                        if (path === vc.selected) {
                            opt.show = true;
                        } else {
                            opt.show = false;
                        }
                        opt.cellIndex = i;
                        opt.siblingList = siblingList;
                        opt.editorName = tab[4];
                        pos = {};
                        pos.col = tab[0];
                        pos.row = tab[1];
                        openFileWithNamespace(path, opt, pos, tab[3]);
                    }

                    var viewContainers = editors.splitViewContainer.getViewContainers();
                    //console.log($(viewContainers[i].topContainer.domNode).css('width'));
                    if (i > 0 && (vc.tabs.length > 0)) {
                        $(viewContainers[i].topContainer.domNode).css('width', vc.width);
                        $(viewContainers[i].topContainer.domNode).css('height', vc.height);
                    }
                }

                if (lastStatus.recentFiles) {
                    editors.recentFiles.importFromPlainArray(lastStatus.recentFiles);
                }
            }, 50);
        }
    }

    return {
        getPanel: getPanel,
        onPanelAppended: onPanelAppended
    };
});
<|endoftext|>


<commit_before>module.exports = [
    {
        id: 'clientconfig',
        description: "Pass config options from the server to your single page app.",
        tags: ['config']
    },
    {
        id: 'human-model',
        description: "Drop-in replacement for Backbone Models with more structure and features.",
        tags: ['model', 'backbone', 'mvc']
    },
    {
        id: 'human-view',
        description: 'A smart base view for Backbone apps, to make it easy to bind collections and properties to the DOM.',
        tags: ['backbone', 'view', 'mvc']
    },
    {
        id: 'moonboots',
        description: 'A set of tools and conventions for building/serving clientside apps with node.js.',
        repoType: 'server',
        tags: ['server', 'assets']
    },
    {
        id: 'simplewebrtc',
        description: "World's easiest WebRTC",
        tags: ['webrtc']
    },
    {
        id: 'getusermedia',
        description: 'Cross-browser getUserMedia shim with node.js style error-first API.',
        tags: ['webrtc', 'media']
    },
    {
        id: 'humanjs',
        github: 'humanjs-app-generator',
        description: 'Single page app scaffolding following http://humanjavascript.com conventions.',
        tags: ['tools', 'scaffolding']
    },
    {
        id: 'attachmediastream',
        description: 'Simple abstraction for handling differences between browsers for attaching a media stream to a video element',
        tags: ['webrtc', 'media', 'video', 'audio']
    },
    {
        id: 'mediastream-gain',
        description: 'A tiny browser module for creating a gain/volume controller for the audio channels in a MediaStream.',
        tags: ['webrtc', 'media', 'audio']
    },
    {
        id: 'domeventlogger',
        description: 'Inspects and logs out all events emitted by a DOM object. Useful for debugging.',
        tags: ['events']
    },
    {
        id: 'cookie-getter',
        description: 'Reads cookies. That\'s it!',
        tags: ['cookie']
    },
    {
        id: 'dummy-api',
        description: 'Simple REST-ful in memory API for express. Useful for testing clientside apps.',
        tags: ['server', 'development', 'api']
    },
    {
        id: 'emoji-images',
        description: 'Replace stuff like :smiley: in text with <img> tags of a corresponding image.',
        tags: ['emoji']
    },
    {
        id: 'favicon-setter',
        description: 'Super-simple tool for dynamically setting the favicon image on a page.',
        tags: ['favicon']
    },
    {
        id: 'image-to-data-uri',
        github: 'image-to-data-uri.js',
        description: 'Takes an image url, downloads the image and creates a data URI for caching, etc.',
        tags: ['image', 'data-uri', 'canvas']
    },
    {
        id: 'loading-stats',
        description: 'For tracking web app loading performance for single page apps.',
        tags: ['metrics', 'stats', 'performance']
    },
    {
        id: 'mockconsole',
        description: 'An object with all the same methods as console in the browser. But does nothing.',
        tags: ['console', 'debugging', 'logging']
    },
    {
        id: 'photograb',
        description: 'Browser module for capturing snapshots from a video (or other compatible) element.',
        tags: ['media', 'canvas', 'webrtc']
    },
    {
        id: 'reformer',
        description: 'Super customizable, Self-contained, self-rendering, self-validating forms that can only output valid data.',
        tags: ['forms', 'validation']
    },
    {
        id: 'reformer-username',
        description: 'Field plugin for reformer, that handles the annoying problem of username validataion in forms.',
        tags: ['forms', 'validation']
    },
    {
        id: 'rtcpeerconnection',
        description: 'A tiny browser module that gives normalizes and simplifies the API for WebRTC peer connections.',
        tags: ['webrtc', 'peerconnection']
    },
    {
        id: 'semi-static',
        description: "lazy way to serve a directory of semi-static pages in express.js. Handy for building quick 'static' pages inside an othewise 'dynamic' app.",
        tags: ['express', 'server', 'jade']
    },
    {
        id: 'slugger',
        description: "Takes a string, returns a url friendly string. Works in browser and node. Dead simple.",
        tags: ['url', 'slug']
    },
    {
        id: 'sound-effect-manager',
        description: 'Easy way to manage and play sound effects using HTML5 Web Audio API',
        tags: ['media', 'webaudio', 'sounds']
    },
    {
        id: 'system-requirements',
        github: 'system-requirements.js',
        description: "Boxed software has 'em, now the web does too. Specify minimum allowed browsers and versions.",
        tags: ['browsers']
    },
    {
        id: 'templatizer',
        description: "imple solution for compiling jade templates into vanilla JS functions for blazin' fast client-side use.",
        tags: ['templates', 'jade']
    },
    {
        id: 'time-counter',
        description: 'Simple time counter tracker. Create count-ups and count-downs. That can be rendered to the dom.',
        tags: ['counter', 'timer']
    },
    {
        id: 'video-recorder',
        description: 'Experimental browser module for recording the contents of a <video> tag.',
        tags: ['media', 'video', 'webrtc']
    },
    {
        id: 'wake-event',
        description: 'Detection for computer waking up from sleep.',
        tags: ['events']
    },
    {
        id: 'webrtc',
        github: 'webrtc.js',
        description: 'WebRTC abstraction for managing it simple to manage multiple peer connections of various types. Used by SimpleWebRTC',
        tags: ['webrtc', 'media']
    },
    {
        id: 'webrtcsupport',
        description: 'Browser module to detect support for webrtc and extract proper constructors.',
        tags: ['webrtc']
    },
    {
        id: 'wildemitter',
        description: "A super lightweight EventEmitter similar to what comes in Node.js, but with a support for wildcard events '*' and grouped handlers",
        tags: ['events']
    },
    {
        id: 'zepto-detect',
        description: 'The detect portion of zepto.js structured for use with browserify.',
        tags: ['detect', 'browser']
    },
    {
        id: 'hark',
        author: 'latentflip',
        description: 'Hark is a tiny browser/commonJS module that listens to an audio stream, and emits events indicating whether the user is speaking or not.',
        tags: ['webrtc', 'audio', 'media']
    },
    {
        id: 'bows',
        author: 'latentflip',
        description: 'Safe, production happy, colourful logging for chrome - makes reading your logs much easier.',
        tags: ['logging', 'debugging', 'development']
    },
    {
        id: 'andlog',
        description: 'Safely leave console statements in production',
        tags: ['logging', 'debugging', 'development']
    },
    {
        id: 'event-component',
        description: 'Event binding component for DOM events.',
        author: 'tjholowaychuk',
        githubUser: 'component',
        github: 'event',
        tags: ['events', 'dom']
    },
    {
        id: 'classes-component',
        description: 'Cross-browser element class manipulation.',
        author: 'tjholowaychuk',
        githubUser: 'component',
        github: 'event',
        tags: ['dom']
    },
    {
        id: 'query-param-getter',
        description: 'Module for grabbing query parameters by name from the URL. Result is purposely not cached since URL can change.',
        tags: ['query', 'param', 'url']
    },
    {
        id: 'raf-component',
        description: 'Request animation frame API with fallback and cancel support',
        author: 'tjholowaychuk',
        githubUser: 'component',
        github: 'raf',
        tags: ['animation', 'canvas', 'rendering']
    }
];
<commit_msg>adding transform/translatez libs<commit_after>module.exports = [
    {
        id: 'clientconfig',
        description: "Pass config options from the server to your single page app.",
        tags: ['config']
    },
    {
        id: 'human-model',
        description: "Drop-in replacement for Backbone Models with more structure and features.",
        tags: ['model', 'backbone', 'mvc']
    },
    {
        id: 'human-view',
        description: 'A smart base view for Backbone apps, to make it easy to bind collections and properties to the DOM.',
        tags: ['backbone', 'view', 'mvc']
    },
    {
        id: 'moonboots',
        description: 'A set of tools and conventions for building/serving clientside apps with node.js.',
        repoType: 'server',
        tags: ['server', 'assets']
    },
    {
        id: 'simplewebrtc',
        description: "World's easiest WebRTC",
        tags: ['webrtc']
    },
    {
        id: 'getusermedia',
        description: 'Cross-browser getUserMedia shim with node.js style error-first API.',
        tags: ['webrtc', 'media']
    },
    {
        id: 'humanjs',
        github: 'humanjs-app-generator',
        description: 'Single page app scaffolding following http://humanjavascript.com conventions.',
        tags: ['tools', 'scaffolding']
    },
    {
        id: 'attachmediastream',
        description: 'Simple abstraction for handling differences between browsers for attaching a media stream to a video element',
        tags: ['webrtc', 'media', 'video', 'audio']
    },
    {
        id: 'mediastream-gain',
        description: 'A tiny browser module for creating a gain/volume controller for the audio channels in a MediaStream.',
        tags: ['webrtc', 'media', 'audio']
    },
    {
        id: 'domeventlogger',
        description: 'Inspects and logs out all events emitted by a DOM object. Useful for debugging.',
        tags: ['events']
    },
    {
        id: 'cookie-getter',
        description: 'Reads cookies. That\'s it!',
        tags: ['cookie']
    },
    {
        id: 'dummy-api',
        description: 'Simple REST-ful in memory API for express. Useful for testing clientside apps.',
        tags: ['server', 'development', 'api']
    },
    {
        id: 'emoji-images',
        description: 'Replace stuff like :smiley: in text with <img> tags of a corresponding image.',
        tags: ['emoji']
    },
    {
        id: 'favicon-setter',
        description: 'Super-simple tool for dynamically setting the favicon image on a page.',
        tags: ['favicon']
    },
    {
        id: 'image-to-data-uri',
        github: 'image-to-data-uri.js',
        description: 'Takes an image url, downloads the image and creates a data URI for caching, etc.',
        tags: ['image', 'data-uri', 'canvas']
    },
    {
        id: 'loading-stats',
        description: 'For tracking web app loading performance for single page apps.',
        tags: ['metrics', 'stats', 'performance']
    },
    {
        id: 'mockconsole',
        description: 'An object with all the same methods as console in the browser. But does nothing.',
        tags: ['console', 'debugging', 'logging']
    },
    {
        id: 'photograb',
        description: 'Browser module for capturing snapshots from a video (or other compatible) element.',
        tags: ['media', 'canvas', 'webrtc']
    },
    {
        id: 'reformer',
        description: 'Super customizable, Self-contained, self-rendering, self-validating forms that can only output valid data.',
        tags: ['forms', 'validation']
    },
    {
        id: 'reformer-username',
        description: 'Field plugin for reformer, that handles the annoying problem of username validataion in forms.',
        tags: ['forms', 'validation']
    },
    {
        id: 'rtcpeerconnection',
        description: 'A tiny browser module that gives normalizes and simplifies the API for WebRTC peer connections.',
        tags: ['webrtc', 'peerconnection']
    },
    {
        id: 'semi-static',
        description: "lazy way to serve a directory of semi-static pages in express.js. Handy for building quick 'static' pages inside an othewise 'dynamic' app.",
        tags: ['express', 'server', 'jade']
    },
    {
        id: 'slugger',
        description: "Takes a string, returns a url friendly string. Works in browser and node. Dead simple.",
        tags: ['url', 'slug']
    },
    {
        id: 'sound-effect-manager',
        description: 'Easy way to manage and play sound effects using HTML5 Web Audio API',
        tags: ['media', 'webaudio', 'sounds']
    },
    {
        id: 'system-requirements',
        github: 'system-requirements.js',
        description: "Boxed software has 'em, now the web does too. Specify minimum allowed browsers and versions.",
        tags: ['browsers']
    },
    {
        id: 'templatizer',
        description: "imple solution for compiling jade templates into vanilla JS functions for blazin' fast client-side use.",
        tags: ['templates', 'jade']
    },
    {
        id: 'time-counter',
        description: 'Simple time counter tracker. Create count-ups and count-downs. That can be rendered to the dom.',
        tags: ['counter', 'timer']
    },
    {
        id: 'video-recorder',
        description: 'Experimental browser module for recording the contents of a <video> tag.',
        tags: ['media', 'video', 'webrtc']
    },
    {
        id: 'wake-event',
        description: 'Detection for computer waking up from sleep.',
        tags: ['events']
    },
    {
        id: 'webrtc',
        github: 'webrtc.js',
        description: 'WebRTC abstraction for managing it simple to manage multiple peer connections of various types. Used by SimpleWebRTC',
        tags: ['webrtc', 'media']
    },
    {
        id: 'webrtcsupport',
        description: 'Browser module to detect support for webrtc and extract proper constructors.',
        tags: ['webrtc']
    },
    {
        id: 'wildemitter',
        description: "A super lightweight EventEmitter similar to what comes in Node.js, but with a support for wildcard events '*' and grouped handlers",
        tags: ['events']
    },
    {
        id: 'zepto-detect',
        description: 'The detect portion of zepto.js structured for use with browserify.',
        tags: ['detect', 'browser']
    },
    {
        id: 'hark',
        author: 'latentflip',
        description: 'Hark is a tiny browser/commonJS module that listens to an audio stream, and emits events indicating whether the user is speaking or not.',
        tags: ['webrtc', 'audio', 'media']
    },
    {
        id: 'bows',
        author: 'latentflip',
        description: 'Safe, production happy, colourful logging for chrome - makes reading your logs much easier.',
        tags: ['logging', 'debugging', 'development']
    },
    {
        id: 'andlog',
        description: 'Safely leave console statements in production',
        tags: ['logging', 'debugging', 'development']
    },
    {
        id: 'event-component',
        description: 'Event binding component for DOM events.',
        author: 'tjholowaychuk',
        githubUser: 'component',
        github: 'event',
        tags: ['events', 'dom']
    },
    {
        id: 'classes-component',
        description: 'Cross-browser element class manipulation.',
        author: 'tjholowaychuk',
        githubUser: 'component',
        github: 'event',
        tags: ['dom']
    },
    {
        id: 'query-param-getter',
        description: 'Module for grabbing query parameters by name from the URL. Result is purposely not cached since URL can change.',
        tags: ['query', 'param', 'url']
    },
    {
        id: 'raf-component',
        description: 'Request animation frame API with fallback and cancel support',
        author: 'tjholowaychuk',
        githubUser: 'component',
        github: 'raf',
        tags: ['animation', 'canvas', 'rendering']
    },
    {
        id: 'transform-style',
        description: 'Apply transform style property with proper prefix to an element. For use with browserify / CommonJS.',
        tags: ['performance', 'dom', 'css', 'rendering']
    },
    {
        id: 'translatez-hack',
        description: 'Apply the translateZ hack in a cross-browser way',
        tags: ['performance', 'dom', 'css', 'rendering']
    }
];
<|endoftext|>


<commit_before>var config = {
  allScriptsTimeout: 30000,
  getPageTimeout: 30000,

  job_basename: require('path').basename(process.cwd()) + '_' + process.env.TRAVIS_JOB_ID,

  sauceSeleniumAddress: 'localhost:4445/wd/hub',
  sauceUser: process.env.SAUCE_USERNAME,
  sauceKey: process.env.SAUCE_ACCESS_KEY,

  browsers: [
    {browserName: 'chrome'},
    {browserName: 'firefox', version: '34.0'},
    {browserName: 'safari', version: 7, platform: 'OS X 10.9'},
    {browserName: 'safari', version: 6, platform: 'OS X 10.8'},
    {browserName: 'internet explorer', version: 11, platform: 'Windows 8.1'},
    {browserName: 'internet explorer', version: 10, platform: 'Windows 8'},
    {browserName: 'internet explorer', version: 9, platform: 'Windows 7'},
    {browserName: 'internet explorer', version: 8, platform: 'Windows XP'},
    {browserName: 'Android', version:'4.4', platform: 'Linux'},
    {browserName: 'Android', version:'4.1', platform: 'Linux'},
    {browserName: 'Android', version:'4.0', platform: 'Linux'},
    {browserName: 'iphone', deviceName: 'iPhone Simulator', version:'8.1', platform: 'OS X 10.9'},
    {browserName: 'iphone', deviceName: 'iPhone Simulator', version:'8.0', platform: 'OS X 10.9'},
    {browserName: 'iphone', deviceName: 'iPhone Simulator', version:'7.1', platform: 'OS X 10.9'},
    {browserName: 'iphone', deviceName: 'iPhone Simulator', version:'6.1', platform: 'OS X 10.8'},
    {browserName: 'ipad', deviceName: 'iPad Simulator', version:'8.1', platform: 'OS X 10.9'},
    {browserName: 'ipad', deviceName: 'iPad Simulator', version:'8.0', platform: 'OS X 10.9'},
    {browserName: 'ipad', deviceName: 'iPad Simulator', version:'7.1', platform: 'OS X 10.9'},
    {browserName: 'ipad', deviceName: 'iPad Simulator', version:'6.1', platform: 'OS X 10.8'}
  ],

  specs: [process.cwd() + '/spec.js'],

  baseUrl: 'http://localhost:3000/',

  // This enable testing on none angular pages without test code change.
  onPrepare: function () {
    element = browser.element;
    browser.ignoreSynchronization = true;
  },

  jasmineNodeOpts: {
    showColors: true,
    defaultTimeoutInterval: 20000
  }
};

config.multiCapabilities = config.browsers.map(function (cfg) {
  cfg.build = config.job_basename;
  cfg['tunnel-identifier'] = process.env.TRAVIS_JOB_NUMBER;
  cfg.name = 'FluxEx browser test for example: ' + config.job_basename;
  cfg.public = 'public';
  cfg.tags = [process.env.TRAVIS_JOB_ID, process.env.TRAVIS_COMMIT, 'fluxex'];
  return cfg;
});

module.exports.config = config;
<commit_msg>try win7<commit_after>var config = {
  allScriptsTimeout: 30000,
  getPageTimeout: 30000,

  job_basename: require('path').basename(process.cwd()) + '_' + process.env.TRAVIS_JOB_ID,

  sauceSeleniumAddress: 'localhost:4445/wd/hub',
  sauceUser: process.env.SAUCE_USERNAME,
  sauceKey: process.env.SAUCE_ACCESS_KEY,

  browsers: [
    {browserName: 'chrome'},
    {browserName: 'firefox', version: '34.0'},
    {browserName: 'safari', version: 7, platform: 'OS X 10.9'},
    {browserName: 'safari', version: 6, platform: 'OS X 10.8'},
    {browserName: 'internet explorer', version: 11, platform: 'Windows 8.1'},
    {browserName: 'internet explorer', version: 10, platform: 'Windows 8'},
    {browserName: 'internet explorer', version: 9, platform: 'Windows 7'},
    {browserName: 'internet explorer', version: 8, platform: 'Windows 7'},
    {browserName: 'Android', version:'4.4', platform: 'Linux'},
    {browserName: 'Android', version:'4.1', platform: 'Linux'},
    {browserName: 'Android', version:'4.0', platform: 'Linux'},
    {browserName: 'iphone', deviceName: 'iPhone Simulator', version:'8.1', platform: 'OS X 10.9'},
    {browserName: 'iphone', deviceName: 'iPhone Simulator', version:'8.0', platform: 'OS X 10.9'},
    {browserName: 'iphone', deviceName: 'iPhone Simulator', version:'7.1', platform: 'OS X 10.9'},
    {browserName: 'iphone', deviceName: 'iPhone Simulator', version:'6.1', platform: 'OS X 10.8'},
    {browserName: 'ipad', deviceName: 'iPad Simulator', version:'8.1', platform: 'OS X 10.9'},
    {browserName: 'ipad', deviceName: 'iPad Simulator', version:'8.0', platform: 'OS X 10.9'},
    {browserName: 'ipad', deviceName: 'iPad Simulator', version:'7.1', platform: 'OS X 10.9'},
    {browserName: 'ipad', deviceName: 'iPad Simulator', version:'6.1', platform: 'OS X 10.8'}
  ],

  specs: [process.cwd() + '/spec.js'],

  baseUrl: 'http://localhost:3000/',

  // This enable testing on none angular pages without test code change.
  onPrepare: function () {
    element = browser.element;
    browser.ignoreSynchronization = true;
  },

  jasmineNodeOpts: {
    showColors: true,
    defaultTimeoutInterval: 20000
  }
};

config.multiCapabilities = config.browsers.map(function (cfg) {
  cfg.build = config.job_basename;
  cfg['tunnel-identifier'] = process.env.TRAVIS_JOB_NUMBER;
  cfg.name = 'FluxEx browser test for example: ' + config.job_basename;
  cfg.public = 'public';
  cfg.tags = [process.env.TRAVIS_JOB_ID, process.env.TRAVIS_COMMIT, 'fluxex'];
  return cfg;
});

module.exports.config = config;
<|endoftext|>


<commit_before>/*jslint indent: 2, nomen: true, maxlen: 120 */
/*global module, require, exports */

////////////////////////////////////////////////////////////////////////////////
/// @brief Foxx Request Context
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2013 triagens GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Lucas Dohmen
/// @author Copyright 2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

var RequestContext,
  extend = require("underscore").extend,
  internal = require("org/arangodb/foxx/internals");

////////////////////////////////////////////////////////////////////////////////
/// @fn JSF_foxx_RequestContext_initializer
/// @brief Context of a Request Definition
///
/// Used for documenting and constraining the routes.
////////////////////////////////////////////////////////////////////////////////

RequestContext = function (route) {
  'use strict';
  this.route = route;
  this.typeToRegex = {
    "int": "/[0-9]+/",
    "string": "/.+/"
  };
  this.route.docs.nickname = internal.constructNickname(route.docs.httpMethod, route.url.match);
};

extend(RequestContext.prototype, {

////////////////////////////////////////////////////////////////////////////////
/// @fn JSF_foxx_RequestContext_pathParam
/// @brief Describe a path parameter
///
/// meow
////////////////////////////////////////////////////////////////////////////////

  pathParam: function (paramName, attributes) {
    'use strict';
    var url = this.route.url,
      docs = this.route.docs,
      constraint = url.constraint || {};

    constraint[paramName] = this.typeToRegex[attributes.dataType];
    this.route.url = internal.constructUrlObject(url.match, constraint, url.methods[0]);
    this.route.docs.parameters.push(internal.constructPathParamDoc(
      paramName,
      attributes.description,
      attributes.dataType
    ));
    return this;
  },

////////////////////////////////////////////////////////////////////////////////
/// @fn JSF_foxx_RequestContext_queryParam
/// @brief Describe a Query Parameter
///
/// @FUN{FoxxApplication::queryParam(@FA{id}, @FA{options})}
///
/// Describe a query parameter:
///
/// If you defined a route "/foxx", you can constrain which format a query
/// parameter (`/foxx?a=12`) can have by giving it a type.  We currently support
/// the following types:
///
/// * int
/// * string
///
/// You can also provide a description of this parameter, if it is required and
/// if you can provide the parameter multiple times.
///
/// @EXAMPLES
///
/// @code
///     app.get("/foxx", function {
///       // Do something
///     }).queryParam("id", {
///       description: "Id of the Foxx",
///       dataType: "int",
///       required: true,
///       allowMultiple: false
///     });
/// @endcode
////////////////////////////////////////////////////////////////////////////////

  queryParam: function (paramName, attributes) {
    'use strict';
    this.route.docs.parameters.push(internal.constructQueryParamDoc(
      paramName,
      attributes.description,
      attributes.dataType,
      attributes.required,
      attributes.allowMultiple
    ));
    return this;
  },

////////////////////////////////////////////////////////////////////////////////
/// @fn JSF_foxx_RequestContext_summary
/// @brief Set the summary for this route in the documentation
///
/// @FUN{FoxxApplication::summary(@FA{description})}
///
/// Set the summary for this route in the documentation. Can't be longer than 60.
/// characters
////////////////////////////////////////////////////////////////////////////////

  summary: function (summary) {
    'use strict';
    if (summary.length > 60) {
      throw new Error("Summary can't be longer than 60 characters");
    }
    this.route.docs.summary = summary;
    return this;
  },

////////////////////////////////////////////////////////////////////////////////
/// @fn JSF_foxx_RequestContext_notes
/// @brief Set the notes for this route in the documentation
///
/// @FUN{FoxxApplication::notes(@FA{description})}
///
/// Set the notes for this route in the documentation
////////////////////////////////////////////////////////////////////////////////

  notes: function (notes) {
    'use strict';
    this.route.docs.notes = notes;
    return this;
  },

////////////////////////////////////////////////////////////////////////////////
/// @fn JSF_foxx_RequestContext_errorResponse
/// @brief Document an error response
///
/// @FUN{FoxxApplication::errorResponse(@FA{code}, @FA{description})}
///
/// Document the error response for a given error @FA{code} with a reason for
/// the occurrence.
////////////////////////////////////////////////////////////////////////////////

  errorResponse: function (code, reason) {
    'use strict';
    this.route.docs.errorResponses.push(internal.constructErrorResponseDoc(code, reason));
    return this;
  }
});

exports.RequestContext = RequestContext;

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------

/// Local Variables:
/// mode: outline-minor
/// outline-regexp: "/// @brief\\|/// @addtogroup\\|/// @page\\|// --SECTION--\\|/// @\\}\\|/\\*jslint"
/// End:
<commit_msg>Foxx: Separated the idea of documentation and the concept of annotation<commit_after>/*jslint indent: 2, nomen: true, maxlen: 120 */
/*global module, require, exports */

////////////////////////////////////////////////////////////////////////////////
/// @brief Foxx Request Context
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2013 triagens GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Lucas Dohmen
/// @author Copyright 2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

var RequestContext,
  SwaggerDocs,
  extend = require("underscore").extend,
  internal = require("org/arangodb/foxx/internals");

// Wraps the docs object of a route to add swagger compatible documentation
SwaggerDocs = function (docs) {
  this.docs = docs;
};

extend(SwaggerDocs.prototype, {
  addNickname: function (httpMethod, match) {
    this.docs.nickname = internal.constructNickname(httpMethod, match);
  },

  addPathParam: function (paramName, description, dataType) {
    this.docs.parameters.push(internal.constructPathParamDoc(paramName, description, dataType));
  },

  addQueryParam: function (paramName, description, dataType, required, allowMultiple) {
    this.docs.parameters.push(internal.constructQueryParamDoc(
      paramName,
      description,
      dataType,
      required,
      allowMultiple
    ));
  },

  addSummary: function (summary) {
    this.docs.summary = summary;
  },

  addNotes: function (notes) {
    this.docs.notes = notes;
  }
});

////////////////////////////////////////////////////////////////////////////////
/// @fn JSF_foxx_RequestContext_initializer
/// @brief Context of a Request Definition
///
/// Used for documenting and constraining the routes.
////////////////////////////////////////////////////////////////////////////////

RequestContext = function (route) {
  'use strict';
  this.route = route;
  this.typeToRegex = {
    "int": "/[0-9]+/",
    "string": "/.+/"
  };
  this.docs = new SwaggerDocs(this.route.docs);
  this.docs.addNickname(route.docs.httpMethod, route.url.match);
};

extend(RequestContext.prototype, {

////////////////////////////////////////////////////////////////////////////////
/// @fn JSF_foxx_RequestContext_pathParam
/// @brief Describe a path parameter
///
/// meow
////////////////////////////////////////////////////////////////////////////////

  pathParam: function (paramName, attributes) {
    'use strict';
    var url = this.route.url,
      docs = this.route.docs,
      constraint = url.constraint || {};

    constraint[paramName] = this.typeToRegex[attributes.dataType];
    this.route.url = internal.constructUrlObject(url.match, constraint, url.methods[0]);
    this.docs.addPathParam(paramName, attributes.description, attributes.dataType);
    return this;
  },

////////////////////////////////////////////////////////////////////////////////
/// @fn JSF_foxx_RequestContext_queryParam
/// @brief Describe a Query Parameter
///
/// @FUN{FoxxApplication::queryParam(@FA{id}, @FA{options})}
///
/// Describe a query parameter:
///
/// If you defined a route "/foxx", you can constrain which format a query
/// parameter (`/foxx?a=12`) can have by giving it a type.  We currently support
/// the following types:
///
/// * int
/// * string
///
/// You can also provide a description of this parameter, if it is required and
/// if you can provide the parameter multiple times.
///
/// @EXAMPLES
///
/// @code
///     app.get("/foxx", function {
///       // Do something
///     }).queryParam("id", {
///       description: "Id of the Foxx",
///       dataType: "int",
///       required: true,
///       allowMultiple: false
///     });
/// @endcode
////////////////////////////////////////////////////////////////////////////////

  queryParam: function (paramName, attributes) {
    'use strict';
    this.docs.addQueryParam(
      paramName,
      attributes.description,
      attributes.dataType,
      attributes.required,
      attributes.allowMultiple
    );
    return this;
  },

////////////////////////////////////////////////////////////////////////////////
/// @fn JSF_foxx_RequestContext_summary
/// @brief Set the summary for this route in the documentation
///
/// @FUN{FoxxApplication::summary(@FA{description})}
///
/// Set the summary for this route in the documentation. Can't be longer than 60.
/// characters
////////////////////////////////////////////////////////////////////////////////

  summary: function (summary) {
    'use strict';
    if (summary.length > 60) {
      throw new Error("Summary can't be longer than 60 characters");
    }
    this.docs.addSummary(summary);
    return this;
  },

////////////////////////////////////////////////////////////////////////////////
/// @fn JSF_foxx_RequestContext_notes
/// @brief Set the notes for this route in the documentation
///
/// @FUN{FoxxApplication::notes(@FA{description})}
///
/// Set the notes for this route in the documentation
////////////////////////////////////////////////////////////////////////////////

  notes: function (notes) {
    'use strict';
    this.docs.addNotes(notes);
    return this;
  },

////////////////////////////////////////////////////////////////////////////////
/// @fn JSF_foxx_RequestContext_errorResponse
/// @brief Document an error response
///
/// @FUN{FoxxApplication::errorResponse(@FA{code}, @FA{description})}
///
/// Document the error response for a given error @FA{code} with a reason for
/// the occurrence.
////////////////////////////////////////////////////////////////////////////////

  errorResponse: function (code, reason) {
    'use strict';
    this.route.docs.errorResponses.push(internal.constructErrorResponseDoc(code, reason));
    return this;
  }
});

exports.RequestContext = RequestContext;

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------

/// Local Variables:
/// mode: outline-minor
/// outline-regexp: "/// @brief\\|/// @addtogroup\\|/// @page\\|// --SECTION--\\|/// @\\}\\|/\\*jslint"
/// End:
<|endoftext|>


<commit_before>'use strict'

const path = require('path')
const gulp = require('gulp')
const replace = require('gulp-replace')
const config = require('../config')
const NodeGitVersion = require('@hmrc/node-git-versioning')
let version = ''

const errorPages = (v) => {
  const nextMinorVersion = parseInt(NodeGitVersion().split('.')[1]) + 1

  if (process.env.JENKINS_URL === 'https://build.tax.service.gov.uk/') {
    version = [v.slice(1), nextMinorVersion, '0'].join('.')
  } else {
    version = path.parse(config.snapshotDir[v]).name
  }
  return gulp.src(config.errorPages.src)
    .pipe(replace('{{ assetsPath }}', `${config.errorPages.assetsBaseUri}${version}/`))
    .pipe(gulp.dest(config.snapshotDir[v]))
}

gulp.task('error-pages:v3', () => {
  return errorPages('v3')
})

gulp.task('error-pages:v4', () => {
  return errorPages('v4')
})
<commit_msg>Use a regex to test for build servers<commit_after>'use strict'

const path = require('path')
const gulp = require('gulp')
const replace = require('gulp-replace')
const config = require('../config')
const NodeGitVersion = require('@hmrc/node-git-versioning')
let version = ''

const errorPages = (v) => {
  const nextMinorVersion = parseInt(NodeGitVersion().split('.')[1]) + 1

  if (/https?:\/\/.*\.tax\.service\.gov\.uk\//.test(process.env.JENKINS_URL)) {
    version = [v.slice(1), nextMinorVersion, '0'].join('.')
  } else {
    version = path.parse(config.snapshotDir[v]).name
  }
  return gulp.src(config.errorPages.src)
    .pipe(replace('{{ assetsPath }}', `${config.errorPages.assetsBaseUri}${version}/`))
    .pipe(gulp.dest(config.snapshotDir[v]))
}

gulp.task('error-pages:v3', () => {
  return errorPages('v3')
})

gulp.task('error-pages:v4', () => {
  return errorPages('v4')
})
<|endoftext|>