<commit_before>/*
 * Copyright 2011 Adobe Systems Incorporated. All Rights Reserved.
 */

/**
 * Responsible for coordinating file seletion between views by permitting only one view
 * to show the current file selection at a time. Currently, only WorkingSetView and
 * ProjectManager can show file selection and in general the WorkingSetView takes higher
 * priority until the user selects a file in the ProjectManager.
 *
 * - if user selects a file in WorkingSetView > select in WorkingSetView
 * - if user adds a file to the WorkingSetView > select in WorkingSetView
 * - if user selects a file in ProjectManager > select in ProjectManager
 *
 */

 define(function(require, exports, module) {

    // Load dependent modules
    var DocumentManager     = require("DocumentManager")
    ,   CommandManager      = require("CommandManager")
    ,   Commands            = require("Commands")
    ;

    /* Change the doc selection to the workign set when ever a new file
     * is added to the working set
     */
    $(DocumentManager).on("workingSetAdd", function(event, addedDoc) {
        _fileSelectionFocus = "WorkingSetView";
        $(exports).triggerHandler("documentSelectionFocusChange");
    });

    $(DocumentManager).on("currentDocumentChange",
    function(event) {

        // if the cause of the doc chagne didn't come through
        // openAndSelectDocument, so pick the best fileSelectionFocus
        if(!_curDocChangedDueToUs){
            var curDoc = DocumentManager.getCurrentDocument();
            if(DocumentManager.findInWorkingSet(curDoc.file.fullPath) != -1)
                _fileSelectionFocus = "WorkingSetView";
            else
                _fileSelectionFocus = "ProjectManager";
        }

        // reset since we have handled the doc change
        _curDocChangedDueToUs = false;

        $(exports).triggerHandler("documentSelectionFocusChange");
    });

    function addToWorkingSetAndSelect(fullPath) {
        CommandManager.execute(Commands.FILE_ADD_TO_WORKING_SET, {fullPath: fullPath});
        openAndSelectDocument(fullPath, "WorkingSetView");
    }

    var _curDocChangedDueToUs = false;

    /* Opens a document if not open and selects the file in the UI corresponding to
     * fileSelectionFocus
     * @param {!fullPath}
     * @param {string} - must be either "WorkingSetView" or "ProjectManager"
     * @returns {!Deferred}
     */
    function openAndSelectDocument(fullPath, fileSelectionFocus) {

        // Opening files are asynchronous and we want to know when this function caused a file
        // to open in order to properly set the fileSelectionFocus, so _curDocChangedDueToUs is
        // set to true here. The handler for currentDocumentChange well check this and reset it.
        _curDocChangedDueToUs = true;

        _fileSelectionFocus = fileSelectionFocus;

        var doc = DocumentManager.getDocumentForPath(fullPath);
        if(doc != null ) {
            $(exports).triggerHandler("documentSelectionFocusChange");
            DocumentManager.showInEditor(doc);
            _curDocChangedDueToUs = false;
            return (new $.Deferred()).resolve();
        }
        else {
            return CommandManager.execute(Commands.FILE_OPEN, {fullPath: fullPath})
        }

    }

    /**
     * @private
     * @see FileViewController.getFileSelectionFocus()
     */
    var _fileSelectionFocus = "ProjectManager";

    /**
     * returns either "WorkingSetView" or "ProjectManager"
     * @return {!String}
     */
    function getFileSelectionFocus() {
        return _fileSelectionFocus;
    }

        // Define public API
    exports.getFileSelectionFocus = getFileSelectionFocus;
    exports.openAndSelectDocument = openAndSelectDocument;
    exports.addToWorkingSetAndSelect = addToWorkingSetAndSelect;

});<commit_msg>Adding check for null doc<commit_after>/*
 * Copyright 2011 Adobe Systems Incorporated. All Rights Reserved.
 */

/**
 * Responsible for coordinating file seletion between views by permitting only one view
 * to show the current file selection at a time. Currently, only WorkingSetView and
 * ProjectManager can show file selection and in general the WorkingSetView takes higher
 * priority until the user selects a file in the ProjectManager.
 *
 * - if user selects a file in WorkingSetView > select in WorkingSetView
 * - if user adds a file to the WorkingSetView > select in WorkingSetView
 * - if user selects a file in ProjectManager > select in ProjectManager
 *
 */

 define(function(require, exports, module) {

    // Load dependent modules
    var DocumentManager     = require("DocumentManager")
    ,   CommandManager      = require("CommandManager")
    ,   Commands            = require("Commands")
    ;

    /* Change the doc selection to the workign set when ever a new file
     * is added to the working set
     */
    $(DocumentManager).on("workingSetAdd", function(event, addedDoc) {
        _fileSelectionFocus = "WorkingSetView";
        $(exports).triggerHandler("documentSelectionFocusChange");
    });

    $(DocumentManager).on("currentDocumentChange",
    function(event) {

        // if the cause of the doc chagne didn't come through
        // openAndSelectDocument, so pick the best fileSelectionFocus
        if(!_curDocChangedDueToUs){
            var curDoc = DocumentManager.getCurrentDocument();
            if(curDoc){
                if(DocumentManager.findInWorkingSet(curDoc.file.fullPath) != -1)
                    _fileSelectionFocus = "WorkingSetView";
                else
                    _fileSelectionFocus = "ProjectManager";
            }
        }

        // reset since we have handled the doc change
        _curDocChangedDueToUs = false;

        $(exports).triggerHandler("documentSelectionFocusChange");
    });

    function addToWorkingSetAndSelect(fullPath) {
        CommandManager.execute(Commands.FILE_ADD_TO_WORKING_SET, {fullPath: fullPath});
        openAndSelectDocument(fullPath, "WorkingSetView");
    }

    var _curDocChangedDueToUs = false;

    /* Opens a document if not open and selects the file in the UI corresponding to
     * fileSelectionFocus
     * @param {!fullPath}
     * @param {string} - must be either "WorkingSetView" or "ProjectManager"
     * @returns {!Deferred}
     */
    function openAndSelectDocument(fullPath, fileSelectionFocus) {

        // Opening files are asynchronous and we want to know when this function caused a file
        // to open in order to properly set the fileSelectionFocus, so _curDocChangedDueToUs is
        // set to true here. The handler for currentDocumentChange well check this and reset it.
        _curDocChangedDueToUs = true;

        _fileSelectionFocus = fileSelectionFocus;

        var doc = DocumentManager.getDocumentForPath(fullPath);
        if(doc != null ) {
            $(exports).triggerHandler("documentSelectionFocusChange");
            DocumentManager.showInEditor(doc);
            _curDocChangedDueToUs = false;
            return (new $.Deferred()).resolve();
        }
        else {
            return CommandManager.execute(Commands.FILE_OPEN, {fullPath: fullPath})
        }

    }

    /**
     * @private
     * @see FileViewController.getFileSelectionFocus()
     */
    var _fileSelectionFocus = "ProjectManager";

    /**
     * returns either "WorkingSetView" or "ProjectManager"
     * @return {!String}
     */
    function getFileSelectionFocus() {
        return _fileSelectionFocus;
    }

        // Define public API
    exports.getFileSelectionFocus = getFileSelectionFocus;
    exports.openAndSelectDocument = openAndSelectDocument;
    exports.addToWorkingSetAndSelect = addToWorkingSetAndSelect;

});<|endoftext|>


<commit_before>/*
 * DEFAULT Operators
 * OP - Operators
 * UOP - Unary operators
**/

export const RESERVED_KEYWORDS = new Set([
    'sqrt', 'cbrt', 'root',
    'sin', 'cos', 'tan',
    'acos', 'asin', 'atan',
    'log',
    'has',
    'floor', 'ceil', 'round',
    'len', 'reverse', 'abs', 'repr',
    'sign', 'print',
    'and', 'or', 'xor',
    // States
    'var', 'const',
    'if', 'for', 'while',
    'func', 'class',
    // Literals
    'true', 'false', 'nil'
]);

export const EXCLUDE_META_ASSIGNMENT = new Set(['==', '!=', '<=', '>=' ]);

export const OP = [
'**', '*', '/', '%', '+', '-', '<=', '>=', '<', '>', '==',
'&', '|', '^',
'&&', '||',
'!=', '=', '+=', '-=', '*=', '/=', '^=', '%=', '&=', '|=', '<<', '>>', '<<=', '>>=',
'|>', '::',
'@"', 'has',
'and', 'or', 'xor',
'log', 'sign',
'root'
];

// Unary operators
export const UOP = [
'-', '+',
'!',
'|>',
'sqrt', 'cbrt',
'sin', 'cos', 'tan',
'acos', 'asin', 'atan',
'floor', 'ceil', 'round',
'len', 'reverse', 'abs', 'repr',
'print',
'log', 'sign',
'new',
'@"'
];

// TODO: how will the user modify this? no idea
//TODO: fix precedence
export const UNARY_PRECEDENCE = new Map([
    ['new', 21000],
    ['!', 20000],
    ['-', 20000],
    ['+', 20000],
    ['@"', 17000],
    ['sqrt', 15000],
    ['cbrt', 15000],
    ['cos', 15000],
    ['sin', 15000],
    ['tan', 15000],
    ['acos', 15000],
    ['asin', 15000],
    ['atan', 15000],
    ['log', 15000],
    ['floor', 15000],
    ['ceil', 15000],
    ['abs', 15000],
    ['len', 15000],
    ['repr', 15000],
    ['reverse', 15000],
    ['round', 15000],
    ['sign', 15000],
    ['print', 0]
]);

export const PRECEDENCE = new Map([
    ['::', 15000],
    ['log', 14000],
    ['root', 14000],
    ['*', 13000],
    ['/', 13000],
    ['%', 13000],
    ['+', 12000],
    ['-', 12000],
    ['@"', 12000],
    ['<<', 11000],
    ['>>', 11000],
    ['<', 10000],
    ['>', 10000],
    ['<=', 10000],
    ['>=', 10000],
    ['sign', 10000],

    ['has', 90000],
    ['==', 9000],
    ['!=', 9000],

    ['&', 8000],
    ['xor', 7000],
    ['|', 6000],
    ['and', 5000],
    ['or', 4000],

    ['+=', 1000],
    ['-=', 1000],
    ['*=', 1000],
    ['/=', 1000],
    ['%=', 1000],
    ['&=', 1000],
    ['|=', 1000],
    ['^=', 1000],
    ['<<=', 1000],
    ['>>=', 1000]
]);

export const RA_PRECEDENCE = new Map([
    ['**', 14000],
    ['=', 1000]
]);

export const TYPE = {
    UNARY: Symbol('Unary Operator'),
    LTR: Symbol('LTR Operator'),
    RTL: Symbol('RTL Operator')
}
<commit_msg>fix [operator]: add missing operator precedences<commit_after>/*
 * DEFAULT Operators
 * OP - Operators
 * UOP - Unary operators
**/

export const RESERVED_KEYWORDS = new Set([
    'sqrt', 'cbrt', 'root',
    'sin', 'cos', 'tan',
    'acos', 'asin', 'atan',
    'log',
    'has',
    'floor', 'ceil', 'round',
    'len', 'reverse', 'abs', 'repr',
    'sign', 'print',
    'and', 'or', 'xor',
    // States
    'var', 'const',
    'if', 'for', 'while',
    'func', 'class',
    // Literals
    'true', 'false', 'nil'
]);

export const EXCLUDE_META_ASSIGNMENT = new Set(['==', '!=', '<=', '>=' ]);

export const OP = [
'**', '*', '/', '%', '+', '-', '<=', '>=', '<', '>', '==',
'&', '|', '^',
'&&', '||',
'!=', '=', '+=', '-=', '*=', '/=', '^=', '%=', '&=', '|=', '<<', '>>', '<<=', '>>=',
'|>', '::',
'@"', 'has',
'and', 'or', 'xor',
'log', 'sign',
'root'
];

// Unary operators
export const UOP = [
'-', '+',
'!',
'|>',
'sqrt', 'cbrt',
'sin', 'cos', 'tan',
'acos', 'asin', 'atan',
'floor', 'ceil', 'round',
'len', 'reverse', 'abs', 'repr',
'print',
'log', 'sign',
'new',
'@"'
];

// TODO: how will the user modify this? no idea
//TODO: fix precedence
export const UNARY_PRECEDENCE = new Map([
    ['new', 21000],
    ['!', 20000],
    ['-', 20000],
    ['+', 20000],
    ['@"', 17000],
    ['sqrt', 15000],
    ['cbrt', 15000],
    ['cos', 15000],
    ['sin', 15000],
    ['tan', 15000],
    ['acos', 15000],
    ['asin', 15000],
    ['atan', 15000],
    ['log', 15000],
    ['floor', 15000],
    ['ceil', 15000],
    ['abs', 15000],
    ['len', 15000],
    ['repr', 15000],
    ['reverse', 15000],
    ['round', 15000],
    ['sign', 15000],
    ['print', 0]
]);

export const PRECEDENCE = new Map([
    ['::', 15000],
    ['log', 14000],
    ['root', 14000],
    ['*', 13000],
    ['/', 13000],
    ['%', 13000],
    ['+', 12000],
    ['-', 12000],
    ['@"', 12000],
    ['<<', 11000],
    ['>>', 11000],
    ['<', 10000],
    ['>', 10000],
    ['<=', 10000],
    ['>=', 10000],
    ['sign', 10000],

    ['has', 90000],
    ['==', 9000],
    ['!=', 9000],

    ['&', 8000],
    ['xor', 7000],
    ['|', 6000],
    ['and', 5000],
    ['or', 4000],

    ['&&', 2001],
    ['||', 2000],

    ['+=', 1000],
    ['-=', 1000],
    ['*=', 1000],
    ['/=', 1000],
    ['%=', 1000],
    ['&=', 1000],
    ['|=', 1000],
    ['^=', 1000],
    ['<<=', 1000],
    ['>>=', 1000]
]);

export const RA_PRECEDENCE = new Map([
    ['**', 14000],
    ['=', 1000]
]);

export const TYPE = {
    UNARY: Symbol('Unary Operator'),
    LTR: Symbol('LTR Operator'),
    RTL: Symbol('RTL Operator')
}
<|endoftext|>


<commit_before>const focusableSelectors = [
  'input',
  'select',
  'a[href]',
  'textarea',
  'button',
  '[tabindex]'
];

const getFocusableNodesInElement = el => {
  const focusableNodes = Array.prototype.slice.call(el.querySelectorAll(focusableSelectors.join(',')));

  return focusableNodes && focusableNodes.length ? focusableNodes.filter(node => {
    const nodeTabIndexAttr = parseInt(node.getAttribute('tabindex'), 10);
    const nodeTabIndex = isNaN(nodeTabIndexAttr) ? 0 : nodeTabIndexAttr;
    const nodeAriaHiddenAttr = node.getAttribute('aria-hidden');

    return nodeTabIndex >= 0 && !nodeAriaHiddenAttr;
  }) : [];
};

const reconcileNodeArrays = (allFocusableNodes, childFocusableNodes) => {
  return allFocusableNodes.filter(node => {
    return childFocusableNodes.indexOf(node) === -1;
  });
};

const setNodeAttributes = (node, attributes) => {
  for (const key in attributes) {
    if (attributes.hasOwnProperty(key)) {
      node.setAttribute(key, attributes[key]);
    }
  }
};

module.exports = {
  focusableSelectors,
  getFocusableNodesInElement,
  reconcileNodeArrays,
  setNodeAttributes
};<commit_msg>Check for string true<commit_after>const focusableSelectors = [
  'input',
  'select',
  'a[href]',
  'textarea',
  'button',
  '[tabindex]'
];

const getFocusableNodesInElement = el => {
  const focusableNodes = Array.prototype.slice.call(el.querySelectorAll(focusableSelectors.join(',')));

  return focusableNodes && focusableNodes.length ? focusableNodes.filter(node => {
    const nodeTabIndexAttr = parseInt(node.getAttribute('tabindex'), 10);
    const nodeTabIndex = isNaN(nodeTabIndexAttr) ? 0 : nodeTabIndexAttr;
    const nodeAriaHiddenAttr = node.getAttribute('aria-hidden') === 'true';

    return nodeTabIndex >= 0 && !nodeAriaHiddenAttr;
  }) : [];
};

const reconcileNodeArrays = (allFocusableNodes, childFocusableNodes) => {
  return allFocusableNodes.filter(node => {
    return childFocusableNodes.indexOf(node) === -1;
  });
};

const setNodeAttributes = (node, attributes) => {
  for (const key in attributes) {
    if (attributes.hasOwnProperty(key)) {
      node.setAttribute(key, attributes[key]);
    }
  }
};

module.exports = {
  focusableSelectors,
  getFocusableNodesInElement,
  reconcileNodeArrays,
  setNodeAttributes
};<|endoftext|>


<commit_before>const focusableSelectors = [
  'input',
  'select',
  'a[href]',
  'textarea',
  'button',
  '[tabindex]'
];

const getFocusableNodesInElement = el => {
  const focusableNodes = el.querySelectorAll(focusableSelectors.join(','));

  return focusableNodes && focusableNodeslength ? focusableNodes.filter(node => {
    const nodeTabIndexAttr = parseInt(node.getAttribute('tabindex'), 10);
    const nodeTabIndex = isNaN(nodeTabIndexAttr) ? 0 : nodeTabIndexAttr;
    const nodeAriaHiddenAttr = node.getAttribute('aria-hidden');

    return nodeTabIndex >= 0 && !nodeAriaHiddenAttr;
  }) : [];
};

const reconcileNodeArrays = (allFocusableNodes, childFocusableNodes) => {
  return allFocusableNodes.filter(node => {
    return childFocusableNodes.indexOf(node) === -1;
  });
};

const toggleFocusAttributesForNode = (node, focusable) => {
  node.setAttribute('tabindex', focusable ? 0 : -1);
  node.setAttribute('aria-hidden', !focusable);
};

module.exports = {
  focusableSelectors,
  getFocusableNodesInElement,
  reconcileNodeArrays,
  toggleFocusAttributesForNode
};<commit_msg>Naming tweaks<commit_after>const focusableSelectors = [
  'input',
  'select',
  'a[href]',
  'textarea',
  'button',
  '[tabindex]'
];

const getFocusableNodesInElement = el => {
  const focusableNodes = el.querySelectorAll(focusableSelectors.join(','));

  return focusableNodes && focusableNodeslength ? focusableNodes.filter(node => {
    const nodeTabIndexAttr = parseInt(node.getAttribute('tabindex'), 10);
    const nodeTabIndex = isNaN(nodeTabIndexAttr) ? 0 : nodeTabIndexAttr;
    const nodeAriaHiddenAttr = node.getAttribute('aria-hidden');

    return nodeTabIndex >= 0 && !nodeAriaHiddenAttr;
  }) : [];
};

const hideNode = node => {
  node.setAttribute('tabindex', -1);
  node.setAttribute('aria-hidden', true);
};

const unHideNode = node => {
  node.setAttribute('tabindex', 0);
  node.setAttribute('aria-hidden', false);
};

const reconcileNodeArrays = (allFocusableNodes, childFocusableNodes) => {
  return allFocusableNodes.filter(node => {
    return childFocusableNodes.indexOf(node) === -1;
  });
};

module.exports = {
  focusableSelectors,
  getFocusableNodesInElement,
  hideNode,
  unHideNode,
  reconcileNodeArrays
};<|endoftext|>


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

(function(){

var HTMLElementElement = function(inElement) {
  inElement.register = HTMLElementElement.prototype.register;
  parseElementElement(inElement);
  return inElement;
};

HTMLElementElement.prototype = {
  register: function(inMore) {
    if (inMore) {
      this.options.lifecycle = inMore.lifecycle;
      if (inMore.prototype) {
        mixin(this.options.prototype, inMore.prototype);
      }
    }
  }
};

function parseElementElement(inElement) {
  // options to glean from inElement attributes
  var options = {
    name: '',
    extends: null
  };
  // glean them
  takeAttributes(inElement, options);
  // default base
  var base = HTMLElement.prototype;
  // optional specified base
  if (options.extends) {
    // build an instance of options.extends
    var archetype = document.createElement(options.extends);
    // acquire the prototype
    // TODO(sjmiles): __proto__ may be hinted by the custom element
    // system on platforms that don't support native __proto__
    // on those platforms the API is mixed into archetype and the
    // effective base is not archetype's real prototype
    base = archetype.__proto__ || Object.getPrototypeOf(archetype);
  }
  // extend base
  options.prototype = Object.create(base);
  // install options
  inElement.options = options;
  // locate user script
  var script = inElement.querySelector('script,scripts');
  if (script) {
    // execute user script in 'inElement' context
    executeComponentScript(script.textContent, inElement, options.name);
  };
  // register our new element
  var ctor = document.register(options.name, options);
  inElement.ctor = ctor;
  // store optional constructor reference
  var refName = inElement.getAttribute('constructor');
  if (refName) {
    window[refName] = ctor;
  }
}

// each property in inDictionary takes a value
// from the matching attribute in inElement, if any
function takeAttributes(inElement, inDictionary) {
  for (var n in inDictionary) {
    var a = inElement.attributes[n];
    if (a) {
      inDictionary[n] = a.value;
    }
  }
}

// invoke inScript in inContext scope
function executeComponentScript(inScript, inContext, inName) {
  // set (highlander) context
  context = inContext;
  // source location
  var owner = context.ownerDocument;
  var url = (owner._URL || owner.URL || owner.impl
      && (owner.impl._URL || owner.impl.URL));
  // ensure the component has a unique source map so it can be debugged
  // if the name matches the filename part of the owning document's url,
  // use this, otherwise, add ":<name>" to the document url.
  var match = url.match(/.*\/([^.]*)[.]?.*$/);
  if (match) {
    var name = match[1];
    url += name != inName ? ':' + inName : '';
  }
  // compose script
  var code = "__componentScript('"
    + inName
    + "', function(){"
    + inScript
    + "});"
    + "\n//# sourceURL=" + url + "\n"
  ;
  // inject script
  eval(code);
}

var context;

// global necessary for script injection
window.__componentScript = function(inName, inFunc) {
  inFunc.call(context);
};

// utility

// copy top level properties from props to obj
function mixin(obj, props) {
  obj = obj || {};
  try {
    Object.getOwnPropertyNames(props).forEach(function(n) {
      var pd = Object.getOwnPropertyDescriptor(props, n);
      if (pd) {
        Object.defineProperty(obj, n, pd);
      }
    });
  } catch(x) {
  }
  return obj;
}

// exports

window.HTMLElementElement = HTMLElementElement;

})();
<commit_msg>made script execution more specific to javascript<commit_after>/*
 * Copyright 2013 The Polymer Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style
 * license that can be found in the LICENSE file.
 */

(function(){

var HTMLElementElement = function(inElement) {
  inElement.register = HTMLElementElement.prototype.register;
  parseElementElement(inElement);
  return inElement;
};

HTMLElementElement.prototype = {
  register: function(inMore) {
    if (inMore) {
      this.options.lifecycle = inMore.lifecycle;
      if (inMore.prototype) {
        mixin(this.options.prototype, inMore.prototype);
      }
    }
  }
};

function parseElementElement(inElement) {
  // options to glean from inElement attributes
  var options = {
    name: '',
    extends: null
  };
  // glean them
  takeAttributes(inElement, options);
  // default base
  var base = HTMLElement.prototype;
  // optional specified base
  if (options.extends) {
    // build an instance of options.extends
    var archetype = document.createElement(options.extends);
    // acquire the prototype
    // TODO(sjmiles): __proto__ may be hinted by the custom element
    // system on platforms that don't support native __proto__
    // on those platforms the API is mixed into archetype and the
    // effective base is not archetype's real prototype
    base = archetype.__proto__ || Object.getPrototypeOf(archetype);
  }
  // extend base
  options.prototype = Object.create(base);
  // install options
  inElement.options = options;
  // locate user script
  var script = inElement.querySelector('script:not([type]),script[type="text/javascript"],scripts');
  if (script) {
    // execute user script in 'inElement' context
    executeComponentScript(script.textContent, inElement, options.name);
  };
  // register our new element
  var ctor = document.register(options.name, options);
  inElement.ctor = ctor;
  // store optional constructor reference
  var refName = inElement.getAttribute('constructor');
  if (refName) {
    window[refName] = ctor;
  }
}

// each property in inDictionary takes a value
// from the matching attribute in inElement, if any
function takeAttributes(inElement, inDictionary) {
  for (var n in inDictionary) {
    var a = inElement.attributes[n];
    if (a) {
      inDictionary[n] = a.value;
    }
  }
}

// invoke inScript in inContext scope
function executeComponentScript(inScript, inContext, inName) {
  // set (highlander) context
  context = inContext;
  // source location
  var owner = context.ownerDocument;
  var url = (owner._URL || owner.URL || owner.impl
      && (owner.impl._URL || owner.impl.URL));
  // ensure the component has a unique source map so it can be debugged
  // if the name matches the filename part of the owning document's url,
  // use this, otherwise, add ":<name>" to the document url.
  var match = url.match(/.*\/([^.]*)[.]?.*$/);
  if (match) {
    var name = match[1];
    url += name != inName ? ':' + inName : '';
  }
  // compose script
  var code = "__componentScript('"
    + inName
    + "', function(){"
    + inScript
    + "});"
    + "\n//# sourceURL=" + url + "\n"
  ;
  // inject script
  eval(code);
}

var context;

// global necessary for script injection
window.__componentScript = function(inName, inFunc) {
  inFunc.call(context);
};

// utility

// copy top level properties from props to obj
function mixin(obj, props) {
  obj = obj || {};
  try {
    Object.getOwnPropertyNames(props).forEach(function(n) {
      var pd = Object.getOwnPropertyDescriptor(props, n);
      if (pd) {
        Object.defineProperty(obj, n, pd);
      }
    });
  } catch(x) {
  }
  return obj;
}

// exports

window.HTMLElementElement = HTMLElementElement;

})();
<|endoftext|>


<commit_before>import path from 'path';
import webpack from 'webpack';
import AssetsPlugin from 'assets-webpack-plugin';
import nodeExternals from 'webpack-node-externals';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import appRootDir from 'app-root-dir';
import WebpackMd5Hash from 'webpack-md5-hash';
import { removeEmpty, ifElse, merge, happyPackPlugin } from '../utils';
import config, { clientConfig } from '../config';

/**
 * This function is responsible for creating the webpack configuration for
 * all of our bundles.
 *
 * It has been configured to support one "client/web" bundle, and any number of
 * additional "node" bundles (i.e. our "server").  You can define additional
 * node bundles by editing the config/project.js file.
 *
 * This factory does not and will not support building multiple web target
 * bundles.  We expect there to be only one web client representing the full
 * server side rendered single page application.  Code splitting negates any
 * need for you to create multiple web bundles.  Therefore we are avoiding this
 * level of abstraction to keep the config factory as simple as possible.
 */
export default function webpackConfigFactory(buildOptions) {
  const { target, mode, bundleConfig } = buildOptions;

  // mode
  const isDev = mode === 'development';
  const isProd = mode === 'production';
  const ifDev = ifElse(isDev);
  const ifProd = ifElse(isProd);

  // target
  const isClient = target === 'client';
  const isNode = target === 'server';
  const ifClient = ifElse(isClient);
  const ifNode = ifElse(isNode);

  // Preconfigure some ifElse helper instnaces. See the util docs for more
  // information on how this util works.
  const ifDevClient = ifElse(isDev && isClient);
  const ifDevServeClient = ifElse(isDev && isClient && bundleConfig.webPath);
  const ifProdClient = ifElse(isProd && isClient);

  let clientEnvVariables = {
    'process.env.NODE_ENV': JSON.stringify(mode),
    'process.env.IS_CLIENT': JSON.stringify(isClient),
    'process.env.IS_SERVER': JSON.stringify(isNode),
    'process.env.IS_NODE': JSON.stringify(isNode),
  };

  clientEnvVariables = config.plugins.envConfig(clientEnvVariables);

  if (!bundleConfig) {
    throw new Error('No bundle configuration exists for target:', target);
  }

  const webpackConfig = {
    target: isClient
      // Only our client bundle will target the web as a runtime.
      ? 'web'
      // Any other bundle (including the server) will target node as a runtime.
      : 'node',

    // Ensure that webpack polyfills the following node features for use
    // within any bundles that are targetting node as a runtime. This will be
    // ignored otherwise.
    node: {
      __dirname: true,
      __filename: true,
    },

    // We don't want our node_modules to be bundled with any bundle that is
    // targetting the node environment, prefering them to be resolved via
    // native node module system.
    // Therefore we use the `webpack-node-externals` library to help us generate
    // an  externals config that will ignore all node_modules.
    externals: removeEmpty([
      ifNode(
        () => nodeExternals(
          // Some of our node_modules may contain files that depend on webpack
          // loaders, e.g. CSS or SASS.
          // For these cases please make sure that the file extensions are
          // registered within the following configuration setting.
          { whitelist:
              // We always want the source-map-support excluded.
              ['source-map-support/register'].concat(
                // Then exclude any items specified in the config.
                config.nodeBundlesIncludeNodeModuleFileTypes || [],
              ),
          },
        ),
      ),
    ]),

    // Source map settings.
    devtool: ifElse(
        // Include source maps for ANY node bundle so that we can support
        // nice stack traces for errors (the source maps get consumed by
        // the `node-source-map-support` module to allow for this).
        isNode
        // Always include source maps for any development build.
        || isDev
        // Allow for the following flag to force source maps even for production
        // builds.
        || config.includeSourceMapsForProductionBuilds,
      )(
      // Produces an external source map (lives next to bundle output files).
      'source-map',
      // Produces no source map.
      'hidden-source-map',
    ),

    // Performance budget feature.
    // This enables checking of the output bundle size, which will result in
    // warnings/errors if the bundle sizes are too large.
    // We only want this enabled for our production client.  Please
    // see the webpack docs on how you can configure this to your own needs:
    // https://webpack.js.org/configuration/performance/
    performance: ifProdClient(
      // Enable webpack's performance hints for production client builds.
      { hints: 'warning' },
      // Else we have to set a value of "false" if we don't want the feature.
      false,
    ),

    // Define our entry chunks for our bundle.
    entry: {
      index: removeEmpty([
        // This grants us source map support, which combined with our webpack
        // source maps will give us nice stack traces for our node executed
        // bundles.
        ifNode('source-map-support/register'),
        // Required to support hot reloading of our client.
        ifDevServeClient('react-hot-loader/patch'),
        // Required to support hot reloading of our client.
        ifDevServeClient(() => `webpack-hot-middleware/client?reload=true&path=http://${config.host}:${config.clientDevServerPort}/__webpack_hmr`),
        // We are using polyfill.io instead of the very heavy babel-polyfill.
        // Therefore we need to add the regenerator-runtime as the babel-polyfill
        // included this, which polyfill.io doesn't include.
        ifClient('regenerator-runtime/runtime'),
        // The source entry file for the bundle.
        path.resolve(appRootDir.get(), bundleConfig.srcEntryFile),
      ]),
    },

    // Bundle output configuration.
    output: merge(
      {
        // The dir in which our bundle should be output.
        path: path.resolve(appRootDir.get(), bundleConfig.outputPath),
        // The filename format for our bundle's entries.
        filename: ifProdClient(
          // For our production client bundles we include a hash in the filename.
          // That way we won't hit any browser caching issues when our bundle
          // output changes.
          // Note: as we are using the WebpackMd5Hash plugin, the hashes will
          // only change when the file contents change. This means we can
          // set very aggressive caching strategies on our bundle output.
          '[name]-[chunkhash].js',
          // For any other bundle (typically a server/node) bundle we want a
          // determinable output name to allow for easier importing/execution
          // of the bundle by our scripts.
          '[name].js',
        ),
        // The name format for any additional chunks produced for the bundle.
        chunkFilename: '[name]-[chunkhash].js',
        // When in node mode we will output our bundle as a commonjs2 module.
        libraryTarget: ifNode('commonjs2', 'var'),
      },
      // This is the web path under which our webpack bundled client should
      // be considered as being served from.
      // We only need to set this for our server/client bundles as the server
      // bundle is the application that serves the client bundle.
      ifElse((isNode || isClient) && bundleConfig.webPath)(() => ({
        publicPath: ifDev(
          // As we run a seperate development server for our client and server
          // bundles we need to use an absolute http path for the public path.
          `http://${config.host}:${config.clientDevServerPort}${bundleConfig.webPath}`,
          // Otherwise we expect our bundled client to be served from this path.
          bundleConfig.webPath,
        ),
      })),
    ),

    resolve: {
      // These extensions are tried when resolving a file.
      extensions: config.bundleSrcTypes.map(ext => `.${ext}`),
      modules: [
        'src',
        'shared',
        'node_modules',
      ],
    },

    plugins: removeEmpty([
      // We use this so that our generated [chunkhash]'s are only different if
      // the content for our respective chunks have changed.  This optimises
      // our long term browser caching strategy for our client bundle, avoiding
      // cases where browsers end up having to download all the client chunks
      // even though 1 or 2 may have only changed.
      ifClient(() => new WebpackMd5Hash()),

      // The DefinePlugin is used by webpack to substitute any patterns that it
      // finds within the code with the respective value assigned below.
      new webpack.DefinePlugin(clientEnvVariables),

      // Generates a JSON file containing a map of all the output files for
      // our webpack bundle.  A necessisty for our server rendering process
      // as we need to interogate these files in order to know what JS/CSS
      // we need to inject into our HTML. We only need to know the assets for
      // our client bundle.
      ifClient(() =>
        new AssetsPlugin({
          filename: config.bundleAssetsFileName,
          path: path.resolve(appRootDir.get(), bundleConfig.outputPath),
        }),
      ),

      // We don't want webpack errors to occur during development as it will
      // kill our dev servers.
      ifDev(() => new webpack.NoEmitOnErrorsPlugin()),

      // We need this plugin to enable hot reloading of our client.
      ifDevClient(() => new webpack.HotModuleReplacementPlugin()),

      // For our production client we need to make sure we pass the required
      // configuration to ensure that the output is minimized/optimized.
      ifProdClient(
        () => new webpack.LoaderOptionsPlugin({
          minimize: config.optimizeProductionBuilds,
        }),
      ),

      // For our production client we need to make sure we pass the required
      // configuration to ensure that the output is minimized/optimized.
      ifProdClient(
        ifElse(config.optimizeProductionBuilds)(
          () => new webpack.optimize.UglifyJsPlugin({
            sourceMap: config.includeSourceMapsForProductionBuilds,
            compress: {
              screw_ie8: true,
              warnings: false,
            },
            mangle: {
              screw_ie8: true,
            },
            output: {
              comments: false,
              screw_ie8: true,
            },
          }),
        ),
      ),

      // For the production build of the client we need to extract the CSS into
      // CSS files.
      ifProdClient(
        () => new ExtractTextPlugin({
          filename: '[name]-[chunkhash].css', allChunks: true,
        }),
      ),

      // -----------------------------------------------------------------------
      // START: HAPPY PACK PLUGINS
      //
      // @see https://github.com/amireh/happypack/

      // HappyPack 'javascript' instance.
      happyPackPlugin({
        name: 'happypack-javascript',
        // We will use babel to do all our JS processing.
        loaders: [{
          path: 'babel-loader',
          // We will create a babel config and pass it through the plugin
          // defined in the project configuration, allowing additional
          // items to be added.
          query: config.plugins.babelConfig(
            // Our "standard" babel config.
            {
              // We need to ensure that we do this otherwise the babelrc will
              // get interpretted and for the current configuration this will mean
              // that it will kill our webpack treeshaking feature as the modules
              // transpilation has not been disabled within in.
              babelrc: false,

              presets: [
                'react',
                ifClient(['latest', { es2015: { modules: false } }]),
                'stage-0',
                ifNode(['env', { targets: { node: true }, modules: false }]),
              ].filter(x => x != null),

              plugins: [
                'transform-decorators-legacy',
                // Required to support react hot loader.
                ifDevServeClient('react-hot-loader/babel'),
                // This decorates our components with  __self prop to JSX elements,
                // which React will use to generate some runtime warnings.
                ifDev('transform-react-jsx-self'),
                // Adding this will give us the path to our components in the
                // react dev tools.
                ifDev('transform-react-jsx-source'),
              ].filter(x => x != null),
            },
            buildOptions,
          ),
        }],
      }),

      // HappyPack 'css' instance for development client.
      ifDevClient(
        () => happyPackPlugin({
          name: 'happypack-devclient-css',
          loaders: [
            'style-loader',
            {
              path: 'css-loader',
              // Include sourcemaps for dev experience++.
              query: {
                sourceMap: true,
                modules: true,
                importLoaders: 1,
                localIdentName: '[name]__[local]___[hash:base64:5]',
              },
            },
            'sass-loader',
          ],
        }),
      ),

      // END: HAPPY PACK PLUGINS
      // -----------------------------------------------------------------------

      // Client HTML
      ifElse(isClient && bundleConfig.htmlPage)(() => new HtmlWebpackPlugin({
        filename: 'index.html',
        template: path.resolve(__dirname, 'html-page'),
        minify: {
          removeComments: true,
          collapseWhitespace: true,
          removeRedundantAttributes: true,
          useShortDoctype: true,
          removeEmptyAttributes: true,
          removeStyleLinkTypeAttributes: true,
          keepClosingSlash: true,
          minifyJS: true,
          minifyCSS: true,
          minifyURLs: true,
        },
        inject: true,
        // We pass our config objects as values as they will be needed
        // by the template.
        custom: {
          config,
          bundleConfig,
          clientConfig,
        },
      })),
    ]),

    module: {
      rules: removeEmpty([
        // JAVASCRIPT
        {
          test: /\.jsx?$/,
          loader: 'happypack/loader?id=happypack-javascript',
          include: removeEmpty([
            ...bundleConfig.srcPaths.map(srcPath =>
              path.resolve(appRootDir.get(), srcPath),
            ),
          ]),
        },

        // CSS
        ifElse(isClient || isNode)(
          merge(
            {
              test: /\.(css|sass|scss)$/,
            },
            ifDevClient({
              loaders: ['happypack/loader?id=happypack-devclient-css'],
            }),
            ifProdClient(() => ({
              loader: ExtractTextPlugin.extract({
                fallback: 'style-loader',
                use: [
                  {
                    loader: 'css-loader',
                    options: {
                      sourceMap: false,
                      modules: true,
                      importLoaders: 1,
                      localIdentName: '[name]__[local]___[hash:base64:5]',
                    },
                  },
                  'sass-loader',
                ],
              }),
            })),
            ifNode({
              loaders: ['css-loader/locals'],
            }),
          ),
        ),

        // GraphQL
        {
          test: /\.(graphql|gql)$/,
          loaders: ['graphql-tag/loader'],
        },

        // ASSETS (Images/Fonts/etc)
        ifElse((isClient || isNode) && bundleConfig.webPath)(() => ({
          test: new RegExp(`\\.(${config.bundleAssetTypes.join('|')})$`, 'i'),
          loader: 'file-loader',
          query: {
            // What is the web path that the client bundle will be served from?
            // The same value has to be used for both the client and the
            // server bundles in order to ensure that SSR paths match the
            // paths used on the client.
            publicPath: isDev
              // When running in dev mode the client bundle runs on a
              // seperate port so we need to put an absolute path here.
              ? `http://${config.host}:${config.clientDevServerPort}${bundleConfig.webPath}`
              // Otherwise we just use the configured web path for the client.
              : bundleConfig.webPath,
            // We only emit files when building a web bundle, for the server
            // bundle we only care about the file loader being able to create
            // the correct asset URLs.
            emitFile: isClient,
          },
        })),
      ]),
    },
  };

  // Apply the configuration middleware.
  return config.plugins.webpackConfig(webpackConfig, buildOptions);
}
<commit_msg>config factory node options<commit_after>import path from 'path';
import webpack from 'webpack';
import AssetsPlugin from 'assets-webpack-plugin';
import nodeExternals from 'webpack-node-externals';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import appRootDir from 'app-root-dir';
import WebpackMd5Hash from 'webpack-md5-hash';
import { removeEmpty, ifElse, merge, happyPackPlugin } from '../utils';
import config, { clientConfig } from '../config';

/**
 * This function is responsible for creating the webpack configuration for
 * all of our bundles.
 *
 * It has been configured to support one "client/web" bundle, and any number of
 * additional "node" bundles (i.e. our "server").  You can define additional
 * node bundles by editing the config/project.js file.
 *
 * This factory does not and will not support building multiple web target
 * bundles.  We expect there to be only one web client representing the full
 * server side rendered single page application.  Code splitting negates any
 * need for you to create multiple web bundles.  Therefore we are avoiding this
 * level of abstraction to keep the config factory as simple as possible.
 */
export default function webpackConfigFactory(buildOptions) {
  const { target, mode, bundleConfig } = buildOptions;

  // mode
  const isDev = mode === 'development';
  const isProd = mode === 'production';
  const ifDev = ifElse(isDev);
  const ifProd = ifElse(isProd);

  // target
  const isClient = target === 'client';
  const isNode = target === 'server';
  const ifClient = ifElse(isClient);
  const ifNode = ifElse(isNode);

  // Preconfigure some ifElse helper instnaces. See the util docs for more
  // information on how this util works.
  const ifDevClient = ifElse(isDev && isClient);
  const ifDevServeClient = ifElse(isDev && isClient && bundleConfig.webPath);
  const ifProdClient = ifElse(isProd && isClient);

  let clientEnvVariables = {
    'process.env.NODE_ENV': JSON.stringify(mode),
    'process.env.IS_CLIENT': JSON.stringify(isClient),
    'process.env.IS_SERVER': JSON.stringify(isNode),
    'process.env.IS_NODE': JSON.stringify(isNode),
  };

  clientEnvVariables = config.plugins.envConfig(clientEnvVariables);

  if (!bundleConfig) {
    throw new Error('No bundle configuration exists for target:', target);
  }

  const webpackConfig = {
    target: isClient
      // Only our client bundle will target the web as a runtime.
      ? 'web'
      // Any other bundle (including the server) will target node as a runtime.
      : 'node',

    // Ensure that webpack polyfills the following node features for use
    // within any bundles that are targetting node as a runtime. This will be
    // ignored otherwise.
    node: Object.assign({
      __dirname: true,
      __filename: true,
    }, bundleConfig.node),

    // We don't want our node_modules to be bundled with any bundle that is
    // targetting the node environment, prefering them to be resolved via
    // native node module system.
    // Therefore we use the `webpack-node-externals` library to help us generate
    // an  externals config that will ignore all node_modules.
    externals: removeEmpty([
      ifNode(
        () => nodeExternals(
          // Some of our node_modules may contain files that depend on webpack
          // loaders, e.g. CSS or SASS.
          // For these cases please make sure that the file extensions are
          // registered within the following configuration setting.
          { whitelist:
              // We always want the source-map-support excluded.
              ['source-map-support/register'].concat(
                // Then exclude any items specified in the config.
                config.nodeBundlesIncludeNodeModuleFileTypes || [],
              ),
          },
        ),
      ),
    ]),

    // Source map settings.
    devtool: ifElse(
        // Include source maps for ANY node bundle so that we can support
        // nice stack traces for errors (the source maps get consumed by
        // the `node-source-map-support` module to allow for this).
        isNode
        // Always include source maps for any development build.
        || isDev
        // Allow for the following flag to force source maps even for production
        // builds.
        || config.includeSourceMapsForProductionBuilds,
      )(
      // Produces an external source map (lives next to bundle output files).
      'source-map',
      // Produces no source map.
      'hidden-source-map',
    ),

    // Performance budget feature.
    // This enables checking of the output bundle size, which will result in
    // warnings/errors if the bundle sizes are too large.
    // We only want this enabled for our production client.  Please
    // see the webpack docs on how you can configure this to your own needs:
    // https://webpack.js.org/configuration/performance/
    performance: ifProdClient(
      // Enable webpack's performance hints for production client builds.
      { hints: 'warning' },
      // Else we have to set a value of "false" if we don't want the feature.
      false,
    ),

    // Define our entry chunks for our bundle.
    entry: {
      index: removeEmpty([
        // This grants us source map support, which combined with our webpack
        // source maps will give us nice stack traces for our node executed
        // bundles.
        ifNode('source-map-support/register'),
        // Required to support hot reloading of our client.
        ifDevServeClient('react-hot-loader/patch'),
        // Required to support hot reloading of our client.
        ifDevServeClient(() => `webpack-hot-middleware/client?reload=true&path=http://${config.host}:${config.clientDevServerPort}/__webpack_hmr`),
        // We are using polyfill.io instead of the very heavy babel-polyfill.
        // Therefore we need to add the regenerator-runtime as the babel-polyfill
        // included this, which polyfill.io doesn't include.
        ifClient('regenerator-runtime/runtime'),
        // The source entry file for the bundle.
        path.resolve(appRootDir.get(), bundleConfig.srcEntryFile),
      ]),
    },

    // Bundle output configuration.
    output: merge(
      {
        // The dir in which our bundle should be output.
        path: path.resolve(appRootDir.get(), bundleConfig.outputPath),
        // The filename format for our bundle's entries.
        filename: ifProdClient(
          // For our production client bundles we include a hash in the filename.
          // That way we won't hit any browser caching issues when our bundle
          // output changes.
          // Note: as we are using the WebpackMd5Hash plugin, the hashes will
          // only change when the file contents change. This means we can
          // set very aggressive caching strategies on our bundle output.
          '[name]-[chunkhash].js',
          // For any other bundle (typically a server/node) bundle we want a
          // determinable output name to allow for easier importing/execution
          // of the bundle by our scripts.
          '[name].js',
        ),
        // The name format for any additional chunks produced for the bundle.
        chunkFilename: '[name]-[chunkhash].js',
        // When in node mode we will output our bundle as a commonjs2 module.
        libraryTarget: ifNode('commonjs2', 'var'),
      },
      // This is the web path under which our webpack bundled client should
      // be considered as being served from.
      // We only need to set this for our server/client bundles as the server
      // bundle is the application that serves the client bundle.
      ifElse((isNode || isClient) && bundleConfig.webPath)(() => ({
        publicPath: ifDev(
          // As we run a seperate development server for our client and server
          // bundles we need to use an absolute http path for the public path.
          `http://${config.host}:${config.clientDevServerPort}${bundleConfig.webPath}`,
          // Otherwise we expect our bundled client to be served from this path.
          bundleConfig.webPath,
        ),
      })),
    ),

    resolve: {
      // These extensions are tried when resolving a file.
      extensions: config.bundleSrcTypes.map(ext => `.${ext}`),
      modules: [
        'src',
        'shared',
        'node_modules',
      ],
    },

    plugins: removeEmpty([
      // We use this so that our generated [chunkhash]'s are only different if
      // the content for our respective chunks have changed.  This optimises
      // our long term browser caching strategy for our client bundle, avoiding
      // cases where browsers end up having to download all the client chunks
      // even though 1 or 2 may have only changed.
      ifClient(() => new WebpackMd5Hash()),

      // The DefinePlugin is used by webpack to substitute any patterns that it
      // finds within the code with the respective value assigned below.
      new webpack.DefinePlugin(clientEnvVariables),

      // Generates a JSON file containing a map of all the output files for
      // our webpack bundle.  A necessisty for our server rendering process
      // as we need to interogate these files in order to know what JS/CSS
      // we need to inject into our HTML. We only need to know the assets for
      // our client bundle.
      ifClient(() =>
        new AssetsPlugin({
          filename: config.bundleAssetsFileName,
          path: path.resolve(appRootDir.get(), bundleConfig.outputPath),
        }),
      ),

      // We don't want webpack errors to occur during development as it will
      // kill our dev servers.
      ifDev(() => new webpack.NoEmitOnErrorsPlugin()),

      // We need this plugin to enable hot reloading of our client.
      ifDevServeClient(() => new webpack.HotModuleReplacementPlugin()),

      // For our production client we need to make sure we pass the required
      // configuration to ensure that the output is minimized/optimized.
      ifProdClient(
        () => new webpack.LoaderOptionsPlugin({
          minimize: config.optimizeProductionBuilds,
        }),
      ),

      // For our production client we need to make sure we pass the required
      // configuration to ensure that the output is minimized/optimized.
      ifProdClient(
        ifElse(config.optimizeProductionBuilds)(
          () => new webpack.optimize.UglifyJsPlugin({
            sourceMap: config.includeSourceMapsForProductionBuilds,
            compress: {
              screw_ie8: true,
              warnings: false,
            },
            mangle: {
              screw_ie8: true,
            },
            output: {
              comments: false,
              screw_ie8: true,
            },
          }),
        ),
      ),

      // For the production build of the client we need to extract the CSS into
      // CSS files.
      ifProdClient(
        () => new ExtractTextPlugin({
          filename: '[name]-[chunkhash].css', allChunks: true,
        }),
      ),

      // -----------------------------------------------------------------------
      // START: HAPPY PACK PLUGINS
      //
      // @see https://github.com/amireh/happypack/

      // HappyPack 'javascript' instance.
      happyPackPlugin({
        name: 'happypack-javascript',
        // We will use babel to do all our JS processing.
        loaders: [{
          path: 'babel-loader',
          // We will create a babel config and pass it through the plugin
          // defined in the project configuration, allowing additional
          // items to be added.
          query: config.plugins.babelConfig(
            // Our "standard" babel config.
            {
              // We need to ensure that we do this otherwise the babelrc will
              // get interpretted and for the current configuration this will mean
              // that it will kill our webpack treeshaking feature as the modules
              // transpilation has not been disabled within in.
              babelrc: false,

              presets: [
                'react',
                ifClient(['latest', { es2015: { modules: false } }]),
                'stage-0',
                ifNode(['env', { targets: { node: true }, modules: false }]),
              ].filter(x => x != null),

              plugins: [
                'transform-decorators-legacy',
                // Required to support react hot loader.
                ifDevServeClient('react-hot-loader/babel'),
                // This decorates our components with  __self prop to JSX elements,
                // which React will use to generate some runtime warnings.
                ifDev('transform-react-jsx-self'),
                // Adding this will give us the path to our components in the
                // react dev tools.
                ifDev('transform-react-jsx-source'),
              ].filter(x => x != null),
            },
            buildOptions,
          ),
        }],
      }),

      // HappyPack 'css' instance for development client.
      ifDevClient(
        () => happyPackPlugin({
          name: 'happypack-devclient-css',
          loaders: [
            'style-loader',
            {
              path: 'css-loader',
              // Include sourcemaps for dev experience++.
              query: {
                sourceMap: true,
                modules: true,
                importLoaders: 1,
                localIdentName: '[name]__[local]___[hash:base64:5]',
              },
            },
            'sass-loader',
          ],
        }),
      ),

      // END: HAPPY PACK PLUGINS
      // -----------------------------------------------------------------------

      // Client HTML
      ifElse(isClient && bundleConfig.htmlPage)(() => new HtmlWebpackPlugin({
        filename: 'index.html',
        template: path.resolve(__dirname, 'html-page'),
        minify: {
          removeComments: true,
          collapseWhitespace: true,
          removeRedundantAttributes: true,
          useShortDoctype: true,
          removeEmptyAttributes: true,
          removeStyleLinkTypeAttributes: true,
          keepClosingSlash: true,
          minifyJS: true,
          minifyCSS: true,
          minifyURLs: true,
        },
        inject: true,
        // We pass our config objects as values as they will be needed
        // by the template.
        custom: {
          config,
          bundleConfig,
          clientConfig,
        },
      })),
    ]),

    module: {
      rules: removeEmpty([
        // JAVASCRIPT
        {
          test: /\.jsx?$/,
          loader: 'happypack/loader?id=happypack-javascript',
          include: removeEmpty([
            ...bundleConfig.srcPaths.map(srcPath =>
              path.resolve(appRootDir.get(), srcPath),
            ),
          ]),
        },

        // CSS
        ifElse(isClient || isNode)(
          merge(
            {
              test: /\.(css|sass|scss)$/,
            },
            ifDevClient({
              loaders: ['happypack/loader?id=happypack-devclient-css'],
            }),
            ifProdClient(() => ({
              loader: ExtractTextPlugin.extract({
                fallback: 'style-loader',
                use: [
                  {
                    loader: 'css-loader',
                    options: {
                      sourceMap: false,
                      modules: true,
                      importLoaders: 1,
                      localIdentName: '[name]__[local]___[hash:base64:5]',
                    },
                  },
                  'sass-loader',
                ],
              }),
            })),
            ifNode({
              loaders: ['css-loader/locals'],
            }),
          ),
        ),

        // GraphQL
        {
          test: /\.(graphql|gql)$/,
          loaders: ['graphql-tag/loader'],
        },

        // ASSETS (Images/Fonts/etc)
        ifElse((isClient || isNode) && bundleConfig.webPath)(() => ({
          test: new RegExp(`\\.(${config.bundleAssetTypes.join('|')})$`, 'i'),
          loader: 'file-loader',
          query: {
            // What is the web path that the client bundle will be served from?
            // The same value has to be used for both the client and the
            // server bundles in order to ensure that SSR paths match the
            // paths used on the client.
            publicPath: isDev
              // When running in dev mode the client bundle runs on a
              // seperate port so we need to put an absolute path here.
              ? `http://${config.host}:${config.clientDevServerPort}${bundleConfig.webPath}`
              // Otherwise we just use the configured web path for the client.
              : bundleConfig.webPath,
            // We only emit files when building a web bundle, for the server
            // bundle we only care about the file loader being able to create
            // the correct asset URLs.
            emitFile: isClient,
          },
        })),
      ]),
    },
  };

  // Apply the configuration middleware.
  return config.plugins.webpackConfig(webpackConfig, buildOptions);
}
<|endoftext|>


<commit_before>module.exports = function () {

    global.User = function (args) {
        this.text = args.text,
        this.addy = args.address
        this.isAgent = args.user.isStaff || false,
        this.lastActivity = args.timestamp,
        this.talkingToAgent = false
    };

    global.User.prototype.connectUserToAgent = function (moredata) {

    };
    global.User.prototype.getUser = function () {

    }

    global.users = [];

    global.agents = [];
}<commit_msg>did not take?<commit_after>module.exports = function () {

    global.User = function (args) {
        this.text = args.text,
        this.addy = args.address
        this.isAgent = args.user.isStaff || false,
        this.lastActivity = args.timestamp,
        this.talkingToAgent = false
    };

    global.User.prototype.connectUserToAgent = function (moredata) {

    };
    global.User.prototype.getUser = function () {

    }

    global.users = {};

    global.agents = {};
}<|endoftext|>


<commit_before>angular.module("app", ['ngAnimate'])
    .run(function() {
        FastClick.attach(document.body);

        //create a new instance of shake.js.
        var myShakeEvent = new Shake({
            threshold: 10 // optional shake strength threshold
        });
        myShakeEvent && myShakeEvent.start();
    })
    .controller("PokerController", function($scope) {

        $scope.numberSets = {
            'fib': ['?', 0, 1, 2, 3, 5, 8, 13, 21, 34, 55, '∞'],
            'tee': [' ? ', 'XS', 'S', 'M', 'L', 'XL']
        };

        $scope.numbers = $scope.numberSets['fib'];
//        $scope.numbers = $scope.numberSets['tee'];
        $scope.staged = false;
        $scope.revealed = false;
        $scope.selected = null;

        $scope.hasStandalone = typeof navigator.standalone === 'boolean';
        $scope.standalone = navigator.standalone === true;

        $scope.hasVibrate = 'vibrate' in navigator;

        $scope.onInit = function() {
            window.addEventListener('shake', function() {
                $scope.$apply(function() {
                    if($scope.staged && !$scope.revealed) {
                        $scope.revealClicked();
                        if($scope.hasVibrate) {
                            navigator.vibrate(100);
                        }
                    }
                });
            }, false);
        };

        $scope.clickNumber = function(number) {
            $scope.staged = true;
            $scope.selected = number;
        };

        $scope.revealClicked = function() {
            $scope.staged = false;
            $scope.revealed = true;
        };

        $scope.clearClicked = function() {
            $scope.revealed = false;
        };

        $scope.backgroundClick = function() {
            if($scope.staged && !$scope.revealed) {
                $scope.revealClicked();

            } else if($scope.revealed && !$scope.staged) {
                $scope.clearClicked();
            }
        };

        $scope.noPropogate = function($event) {
            $event.stopPropagation();
        };

        $scope.changeNumbers = function(s) {
            $scope.numbers = $scope.numberSets[s];
        };
    }
);<commit_msg>Remove commented code.<commit_after>angular.module("app", ['ngAnimate'])
    .run(function() {
        FastClick.attach(document.body);

        //create a new instance of shake.js.
        var myShakeEvent = new Shake({
            threshold: 10 // optional shake strength threshold
        });
        myShakeEvent && myShakeEvent.start();
    })
    .controller("PokerController", function($scope) {

        $scope.numberSets = {
            'fib': ['?', 0, 1, 2, 3, 5, 8, 13, 21, 34, 55, '∞'],
            'tee': [' ? ', 'XS', 'S', 'M', 'L', 'XL']
        };

        $scope.numbers = $scope.numberSets['fib'];
        $scope.staged = false;
        $scope.revealed = false;
        $scope.selected = null;

        $scope.hasStandalone = typeof navigator.standalone === 'boolean';
        $scope.standalone = navigator.standalone === true;

        $scope.hasVibrate = 'vibrate' in navigator;

        $scope.onInit = function() {
            window.addEventListener('shake', function() {
                $scope.$apply(function() {
                    if($scope.staged && !$scope.revealed) {
                        $scope.revealClicked();
                        if($scope.hasVibrate) {
                            navigator.vibrate(100);
                        }
                    }
                });
            }, false);
        };

        $scope.clickNumber = function(number) {
            $scope.staged = true;
            $scope.selected = number;
        };

        $scope.revealClicked = function() {
            $scope.staged = false;
            $scope.revealed = true;
        };

        $scope.clearClicked = function() {
            $scope.revealed = false;
        };

        $scope.backgroundClick = function() {
            if($scope.staged && !$scope.revealed) {
                $scope.revealClicked();

            } else if($scope.revealed && !$scope.staged) {
                $scope.clearClicked();
            }
        };

        $scope.noPropogate = function($event) {
            $event.stopPropagation();
        };

        $scope.changeNumbers = function(s) {
            $scope.numbers = $scope.numberSets[s];
        };
    }
);<|endoftext|>


<commit_before>/**
 * Subdomain setup Screen.
 *
 * UI for subdomain setup.
 *
 * 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/.
 */

'use strict';

const API = require('./api');
const fluent = require('./fluent');

function setupForm() {
  const subdomain = document.getElementById('subdomain');
  const email = document.getElementById('email');
  const optIn = document.getElementById('opt-in');
  const agree = document.getElementById('agree');
  const reclamationToken = document.getElementById('reclamation-token');
  const createDomainButton = document.getElementById('create-domain-button');
  const skipAnchor = document.getElementById('skip-subdomain-anchor');
  const errorMessage = document.getElementById('error-setup');
  const reclaimMessage = document.getElementById('error-reclaim');
  const validationMessage = document.getElementById('error-validation');
  const ntpMessage = document.getElementById('ntp-warning');

  function displayMessage(errorMsg, type) {
    reclaimMessage.classList.add('hidden');
    errorMessage.innerHTML = errorMsg;
    errorMessage.classList.remove('hidden');
    if (type === 'message') {
      errorMessage.classList.remove('error');
      errorMessage.classList.add('message');
    } else {
      errorMessage.classList.remove('message');
      errorMessage.classList.add('error');
    }
  }

  let haveRestartedNtp = false;
  function pollNtp() {
    API.getNtpStatus().then((body) => {
      if (body.statusImplemented) {
        if (body.synchronized) {
          ntpMessage.classList.add('hidden');
        } else {
          ntpMessage.classList.remove('hidden');

          if (!haveRestartedNtp) {
            API.restartNtpSync().catch((e) => {
              console.error('Failed to restart NTP sync:', e);
            });
            haveRestartedNtp = true;
          }

          // poll again in 5 seconds
          setTimeout(pollNtp, 5000);
        }
      }
    }).catch((e) => {
      console.error('Error polling NTP status:', e);

      // poll again in 5 seconds
      setTimeout(pollNtp, 5000);
    });
  }

  pollNtp();

  /**
   * Ensure that subdomain is valid:
   * - Contains only a-z, 0-9, and hyphens, but does not start or end with
   *   hyphen.
   * - Is not equal to "api", "www", or "ns\d*", as those are reserved.
   */
  function validateDomain() {
    const val = subdomain.value.toLowerCase();
    const re = new RegExp(/^\s*([a-z0-9]|[a-z0-9][a-z0-9-]*[a-z0-9])\s*$/);
    const nsRegex = new RegExp(/^ns\d*$/);
    if (!re.test(val) ||
        nsRegex.test(val) ||
        ['api', 'www'].includes(val) ||
        val.length > 63) {
      return false;
    }

    return true;
  }

  /**
   * Ensure that email is at least somewhat valid.
   */
  function validateEmail() {
    const val = email.value;
    // eslint-disable-next-line max-len
    const re = new RegExp(/^\s*[^@\s]+@(([a-z0-9]|[a-z0-9][a-z0-9-]*[a-z0-9])\.)+[a-z0-9][a-z0-9-]*[a-z0-9]\s*$/, 'i');
    return re.test(val) && val.length <= 254;
  }

  /**
   * Ensure that the reclamation token is valid.
   */
  function validateToken() {
    if (reclamationToken.offsetParent === null) {
      return true;
    }

    const val = reclamationToken.value;
    // eslint-disable-next-line max-len
    const re = new RegExp(/^\s*[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}\s*$/);
    return re.test(val);
  }

  /**
   * Ensure that all inputs are valid.
   */
  function validateInput() {
    if (!validateDomain()) {
      createDomainButton.disabled = true;
      validationMessage.innerText = fluent.getMessage('invalid-subdomain');
      validationMessage.classList.remove('hidden');
    } else if (!validateEmail()) {
      createDomainButton.disabled = true;
      validationMessage.innerText = fluent.getMessage('invalid-email');
      validationMessage.classList.remove('hidden');
    } else if (!validateToken()) {
      createDomainButton.disabled = true;
      validationMessage.innerText =
        fluent.getMessage('invalid-reclamation-token');
      validationMessage.classList.remove('hidden');
    } else {
      createDomainButton.disabled = !agree.checked;
      validationMessage.classList.add('hidden');
    }
  }

  /**
   * Submit the form if Enter was pressed in one of the inputs and all input is
   * valid.
   */
  function submitOnEnter(evt) {
    if (evt.key === 'Enter' && validateDomain() && validateEmail() &&
        validateToken()) {
      submitForm();
    }
  }

  /**
   * Submit the form.
   */
  function submitForm() {
    createDomainButton.disabled = true;
    displayMessage(fluent.getMessage('processing'), 'message');

    // Call the settings controller to subscribe the domain in the gateway.
    API.setupTunnel(
      email.value.trim(),
      subdomain.value.trim(),
      reclamationToken.value.trim(),
      !optIn.checked,
    ).then(([ok, body]) => {
      if (ok) {
        displayMessage(fluent.getMessage('domain-success'), 'message');
        setTimeout(() => {
          window.location.replace(body.url);
        }, 5000);
      } else {
        createDomainButton.disabled = false;

        if (body.indexOf('UnavailableName') > -1) {
          validateInput();

          if (body.indexOf('ReclamationPossible') > -1) {
            errorMessage.classList.add('hidden');
            reclaimMessage.classList.remove('hidden');
            reclaimMessage.querySelector('a').onclick = () => {
              document.getElementById('opt-in-group').style.display = 'none';
              reclamationToken.style.display = 'block';
              reclamationToken.focus();

              reclaimMessage.classList.add('hidden');
              errorMessage.textContent =
                fluent.getMessage('check-email-for-token');
              errorMessage.classList.remove('hidden');

              API.reclaimDomain(subdomain.value).catch(() => {
                displayMessage(fluent.getMessage('reclaim-failed'), 'error');
              });
            };
          } else {
            displayMessage(fluent.getMessage('subdomain-already-used'),
                           'error');
          }
        } else if (body.indexOf('ReclamationTokenMismatch') > -1) {
          displayMessage(fluent.getMessage('invalid-reclamation-token'),
                         'error');
        } else {
          displayMessage(fluent.getMessage('issuing-error'), 'error');
        }
      }
    }, () => {});
  }

  subdomain.addEventListener('input', validateInput);
  email.addEventListener('input', validateInput);
  reclamationToken.addEventListener('input', validateInput);
  agree.addEventListener('change', validateInput);

  subdomain.addEventListener('keydown', submitOnEnter);
  email.addEventListener('keydown', submitOnEnter);
  reclamationToken.addEventListener('keydown', submitOnEnter);

  createDomainButton.addEventListener('click', submitForm);

  skipAnchor.addEventListener('click', () => {
    createDomainButton.disabled = true;
    displayMessage(fluent.getMessage('processing'), 'message');

    // call the settings controller to skip the domain subscription
    API.skipTunnel().then(([ok, body]) => {
      if (ok) {
        displayMessage(fluent.getMessage('redirecting'), 'message');
        setTimeout(() => {
          window.location.replace(`http://${window.location.host}`);
        }, 1000);
      } else {
        displayMessage(body, 'error');
      }
    }).catch((error) => {
      displayMessage(error, 'error');
    });

    return false;
  });
}

window.addEventListener('load', function app_onLoad() {
  window.removeEventListener('load', app_onLoad);
  fluent.load().then(() => {
    fluent.init();
    setupForm();
  });
});
<commit_msg>Fix tunnel setup form. (#2667)<commit_after>/**
 * Subdomain setup Screen.
 *
 * UI for subdomain setup.
 *
 * 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/.
 */

'use strict';

const API = require('./api');
const fluent = require('./fluent');

function setupForm() {
  const subdomain = document.getElementById('subdomain');
  const email = document.getElementById('email');
  const optIn = document.getElementById('opt-in');
  const agree = document.getElementById('agree');
  const reclamationToken = document.getElementById('reclamation-token');
  const createDomainButton = document.getElementById('create-domain-button');
  const skipAnchor = document.getElementById('skip-subdomain-anchor');
  const errorMessage = document.getElementById('error-setup');
  const reclaimMessage = document.getElementById('error-reclaim');
  const validationMessage = document.getElementById('error-validation');
  const ntpMessage = document.getElementById('ntp-warning');

  function displayMessage(errorMsg, type) {
    reclaimMessage.classList.add('hidden');
    errorMessage.innerHTML = errorMsg;
    errorMessage.classList.remove('hidden');
    if (type === 'message') {
      errorMessage.classList.remove('error');
      errorMessage.classList.add('message');
    } else {
      errorMessage.classList.remove('message');
      errorMessage.classList.add('error');
    }
  }

  let haveRestartedNtp = false;
  function pollNtp() {
    API.getNtpStatus().then((body) => {
      if (body.statusImplemented) {
        if (body.synchronized) {
          ntpMessage.classList.add('hidden');
        } else {
          ntpMessage.classList.remove('hidden');

          if (!haveRestartedNtp) {
            API.restartNtpSync().catch((e) => {
              console.error('Failed to restart NTP sync:', e);
            });
            haveRestartedNtp = true;
          }

          // poll again in 5 seconds
          setTimeout(pollNtp, 5000);
        }
      }
    }).catch((e) => {
      console.error('Error polling NTP status:', e);

      // poll again in 5 seconds
      setTimeout(pollNtp, 5000);
    });
  }

  pollNtp();

  /**
   * Ensure that subdomain is valid:
   * - Contains only a-z, 0-9, and hyphens, but does not start or end with
   *   hyphen.
   * - Is not equal to "api", "www", or "ns\d*", as those are reserved.
   */
  function validateDomain() {
    const val = subdomain.value.toLowerCase();
    const re = new RegExp(/^\s*([a-z0-9]|[a-z0-9][a-z0-9-]*[a-z0-9])\s*$/);
    const nsRegex = new RegExp(/^ns\d*$/);
    if (!re.test(val) ||
        nsRegex.test(val) ||
        ['api', 'www'].includes(val) ||
        val.length > 63) {
      return false;
    }

    return true;
  }

  /**
   * Ensure that email is at least somewhat valid.
   */
  function validateEmail() {
    const val = email.value;
    // eslint-disable-next-line max-len
    const re = new RegExp(/^\s*[^@\s]+@(([a-z0-9]|[a-z0-9][a-z0-9-]*[a-z0-9])\.)+[a-z0-9][a-z0-9-]*[a-z0-9]\s*$/, 'i');
    return re.test(val) && val.length <= 254;
  }

  /**
   * Ensure that the reclamation token is valid.
   */
  function validateToken() {
    if (reclamationToken.offsetParent === null) {
      return true;
    }

    const val = reclamationToken.value;
    // eslint-disable-next-line max-len
    const re = new RegExp(/^\s*[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}\s*$/);
    return re.test(val);
  }

  /**
   * Ensure that all inputs are valid.
   */
  function validateInput() {
    if (!validateDomain()) {
      createDomainButton.disabled = true;
      validationMessage.innerText = fluent.getMessage('invalid-subdomain');
      validationMessage.classList.remove('hidden');
    } else if (!validateEmail()) {
      createDomainButton.disabled = true;
      validationMessage.innerText = fluent.getMessage('invalid-email');
      validationMessage.classList.remove('hidden');
    } else if (!validateToken()) {
      createDomainButton.disabled = true;
      validationMessage.innerText =
        fluent.getMessage('invalid-reclamation-token');
      validationMessage.classList.remove('hidden');
    } else {
      createDomainButton.disabled = !agree.checked;
      validationMessage.classList.add('hidden');
    }
  }

  /**
   * Submit the form if Enter was pressed in one of the inputs and all input is
   * valid.
   */
  function submitOnEnter(evt) {
    if (evt.key === 'Enter' && validateDomain() && validateEmail() &&
        validateToken()) {
      submitForm();
    }
  }

  /**
   * Submit the form.
   */
  function submitForm() {
    createDomainButton.disabled = true;
    displayMessage(fluent.getMessage('processing'), 'message');

    // Call the settings controller to subscribe the domain in the gateway.
    API.setupTunnel(
      email.value.trim(),
      subdomain.value.trim(),
      reclamationToken.value.trim(),
      !optIn.checked,
    ).then(([ok, body]) => {
      if (ok) {
        displayMessage(fluent.getMessage('domain-success'), 'message');
        setTimeout(() => {
          window.location.replace(body.url);
        }, 5000);
      } else {
        createDomainButton.disabled = false;

        if (body.indexOf('UnavailableName') > -1) {
          validateInput();

          if (body.indexOf('ReclamationPossible') > -1) {
            errorMessage.classList.add('hidden');
            reclaimMessage.classList.remove('hidden');
            reclaimMessage.querySelector('a').onclick = () => {
              document.getElementById('opt-in-group').style.display = 'none';
              document.getElementById('agree-group').style.display = 'none';
              reclamationToken.style.display = 'block';
              reclamationToken.focus();

              reclaimMessage.classList.add('hidden');
              errorMessage.textContent =
                fluent.getMessage('check-email-for-token');
              errorMessage.classList.remove('hidden');

              API.reclaimDomain(subdomain.value).catch(() => {
                displayMessage(fluent.getMessage('reclaim-failed'), 'error');
              });
            };
          } else {
            displayMessage(fluent.getMessage('subdomain-already-used'),
                           'error');
          }
        } else if (body.indexOf('ReclamationTokenMismatch') > -1) {
          displayMessage(fluent.getMessage('invalid-reclamation-token'),
                         'error');
        } else {
          displayMessage(fluent.getMessage('issuing-error'), 'error');
        }
      }
    }, () => {});
  }

  subdomain.addEventListener('input', validateInput);
  email.addEventListener('input', validateInput);
  reclamationToken.addEventListener('input', validateInput);
  agree.addEventListener('change', validateInput);

  subdomain.addEventListener('keydown', submitOnEnter);
  email.addEventListener('keydown', submitOnEnter);
  reclamationToken.addEventListener('keydown', submitOnEnter);

  createDomainButton.addEventListener('click', submitForm);

  skipAnchor.addEventListener('click', () => {
    createDomainButton.disabled = true;
    displayMessage(fluent.getMessage('processing'), 'message');

    // call the settings controller to skip the domain subscription
    API.skipTunnel().then(([ok, body]) => {
      if (ok) {
        displayMessage(fluent.getMessage('redirecting'), 'message');
        setTimeout(() => {
          window.location.replace(`http://${window.location.host}`);
        }, 1000);
      } else {
        displayMessage(body, 'error');
      }
    }).catch((error) => {
      displayMessage(error, 'error');
    });

    return false;
  });
}

window.addEventListener('load', function app_onLoad() {
  window.removeEventListener('load', app_onLoad);
  fluent.load().then(() => {
    fluent.init();
    setupForm();
  });
});
<|endoftext|>


<commit_before>define(['jquery', 'underscore', 'backbone', 'bootbox', 'views/dropbox', 'dropbox'], function ($, _, Backbone, bootbox, DropboxView) {

  console.log('CloudStore.');

  var CloudStore = {

    readFile: function () {
      console.log("CloudStore.readFile");
      return this.render('read');
    },

    saveFile: function () {
      console.log("CloudStore.saveFile");
      return this.render('save');
    },

    render: function (mode) {
      console.log("CloudStore.render: " + mode);

      var deferred = $.Deferred();

      var Dropbox = window.Dropbox;
      var client = new Dropbox.Client({ key: "dzdofhi3xrasyw8" });
      client.authDriver(new Dropbox.AuthDriver.Popup({receiverUrl: "https://quickencrypt.org/oauth/dropbox.html"}));

      client.authenticate( function( error, data ) {
        console.log("CloudStore.render/authenticate: error: " + error);
        if(error) {
          deferred.reject();
        } else {
          var dropboxView = new DropboxView();
          dropboxView.readDir(client, deferred, mode);
        }
      });

      console.log("CloudStore.render return deferred");
      return deferred;
    }
  };

  return CloudStore;

});
<commit_msg>Update cloudstore.js<commit_after>define(['jquery', 'underscore', 'backbone', 'bootbox', 'views/dropbox', 'dropbox'], function ($, _, Backbone, bootbox, DropboxView) {

  console.log('CloudStore.');

  var CloudStore = {

    readFile: function () {
      console.log("CloudStore.readFile");
      return this.render('read');
    },

    saveFile: function () {
      console.log("CloudStore.saveFile");
      return this.render('save');
    },

    render: function (mode) {
      console.log("CloudStore.render: " + mode);

      var deferred = $.Deferred();
      var dropboxView = new DropboxView();

      var Dropbox = window.Dropbox;
      var client = new Dropbox.Client({ key: "dzdofhi3xrasyw8" });
      client.authDriver(new Dropbox.AuthDriver.Popup({receiverUrl: "https://quickencrypt.org/oauth/dropbox.html"}));

      client.authenticate( function( error, data ) {
        console.log("CloudStore.render/authenticate: error: " + error);
        if(error) {
          deferred.reject();
        } else {
          dropboxView.readDir(client, deferred, mode);
        }
      });

      console.log("CloudStore.render return deferred");
      return deferred;
    }
  };

  return CloudStore;

});
<|endoftext|>


<commit_before>define(['jquery', 'underscore', 'backbone', 'bootbox', 'views/dropbox', 'dropbox'], function ($, _, Backbone, bootbox, DropboxView) {

  console.log('CloudStore.');

  var CloudStore = {

    readFile: function () {
      console.log("CloudStore.readFile");
      return this.render('read');
    },

    saveFile: function () {
      console.log("CloudStore.saveFile");
      return this.render('save');
    },

    render: function (mode) {
      console.log("CloudStore.render: " + mode);

      var deferred = $.Deferred();
      var dropboxView = new DropboxView();

      var Dropbox = window.Dropbox;
      var client = new Dropbox.Client({ key: "dzdofhi3xrasyw8" });
      client.authDriver(new Dropbox.AuthDriver.Popup({receiverUrl: "https://quickencrypt.org/oauth/dropbox.html"}));

      client.authenticate( function( error, data ) {
        console.log("CloudStore.render/authenticate: error: " + error);
        if(error) {
          deferred.reject();
        } else {
          dropboxView.readDir(client, deferred, mode);
        }
      });

      console.log("CloudStore.render return deferred");
      return deferred;
    }
  };

  return CloudStore;

});
<commit_msg>do not cache credentials<commit_after>define(['jquery', 'underscore', 'backbone', 'bootbox', 'views/dropbox', 'dropbox'], function ($, _, Backbone, bootbox, DropboxView) {

  console.log('CloudStore.');

  var CloudStore = {

    readFile: function () {
      console.log("CloudStore.readFile");
      return this.render('read');
    },

    saveFile: function () {
      console.log("CloudStore.saveFile");
      return this.render('save');
    },

    render: function (mode) {
      console.log("CloudStore.render: " + mode);

      var deferred = $.Deferred();
      var dropboxView = new DropboxView();

      var Dropbox = window.Dropbox;
      var client = new Dropbox.Client({ key: "dzdofhi3xrasyw8" });
      client.authDriver(new Dropbox.AuthDriver.Popup({rememberUser: false, receiverUrl: "https://quickencrypt.org/oauth/dropbox.html"}));

      client.authenticate( function( error, data ) {
        console.log("CloudStore.render/authenticate: error: " + error);
        if(error) {
          deferred.reject();
        } else {
          dropboxView.readDir(client, deferred, mode);
        }
      });

      console.log("CloudStore.render return deferred");
      return deferred;
    }
  };

  return CloudStore;

});
<|endoftext|>


<commit_before>/* This is a wrapper that represents a Stream of another Fantasy Land type T.
 * Depending on which methods of wrapper you want to use the inner type
 * T must implement certain FL specs. For example, if you want to use map(),
 * T must also have map(), and if you want to use chain(), T must have map(),
 * sequence(), and chain().
 *
 * This is somewhat similar to monad transformers, but not quite.
 */

import {map, chain, sequence, of, ap} from 'fantasy-land'
import {Stream} from './fantasy'

export class StreamT {

  constructor(stream) {
    this._stream = stream
  }

  [map](fn) {
    return new StreamT(
      this._stream[map](t => t[map](fn))
    )
  }

  [chain](fn) {
    return new StreamT(
      this._stream[chain](t => {
        const tst = t[map](fn)
        const stt = tst[sequence](Stream.of)
        const st = stt[map](tt => tt[chain](t => t))
        return st
      })
    )
  }

  [ap](s_t_x) {
    const s_t_fnxy = this
    const s_fntxy = s_t_fnxy._stream[map](t_fnxy => t_x => t_fnxy[ap](t_x))
    const s_t_y = s_fntxy[ap](s_t_x)
    return s_t_y
  }

  // Custom methods

  fromBasic(bs) {
    return new StreamT(new Stream(bs))
  }

  observe(fn) {
    // fn will get values of type T
    return this._stream.observe(fn)
  }

}

StreamT.genOf = innerOf => x => Stream[of](innerOf(x))
<commit_msg>fix fantasyT<commit_after>/* This is a wrapper that represents a Stream of another Fantasy Land type T.
 * Depending on which methods of wrapper you want to use the inner type
 * T must implement certain FL specs. For example, if you want to use map(),
 * T must also have map(), and if you want to use chain(), T must have map(),
 * sequence(), and chain().
 *
 * This is somewhat similar to monad transformers, but not quite.
 */

import {map, chain, sequence, of, ap} from 'fantasy-land'
import {Stream} from './fantasy'

export class StreamT {

  constructor(stream) {
    this._stream = stream
  }

  [map](fn) {
    return new StreamT(
      this._stream[map](t => t[map](fn))
    )
  }

  [chain](fn) {
    return new StreamT(
      this._stream[chain](t => {
        const tst = t[map](fn)
        const stt = tst[sequence](Stream.of)
        const st = stt[map](tt => tt[chain](t => t))
        return st
      })
    )
  }

  [ap](s_t_x) {
    const s_t_fnxy = this
    const s_fntxy = s_t_fnxy._stream[map](t_fnxy => t_x => t_fnxy[ap](t_x))
    const s_t_y = s_fntxy[ap](s_t_x)
    return s_t_y
  }

  // Custom methods

  observe(fn) {
    // fn will get values of type T
    return this._stream.observe(fn)
  }

}

StreamT.fromBasic = bs => new StreamT(new Stream(bs))

StreamT.genOf = innerOf => x => Stream[of](innerOf(x))
<|endoftext|>


<commit_before>// TODO: Shared configuration
var fileConfig = function($provide, picker, reader, dragger) { void 0; };
fileConfig.$inject = ['$provide']; //.concat(internalsProvider);

var fileProvider = function() {
  this.$get = function($rootScope, $q, picker) {
    return { pick: pick };

    function pick() {
      var files = $q.defer();
      var deregister = {};

      var fileCancel = function(e) {
        files.reject();
        deregister.cancel();
        deregister.receive();
        deregister.complete();
      };
      var fileReceive = function(e, data, name, file) {
        files.notify({
          data: data,
          name: name,
          file: file
        });
      };
      var fileComplete = function(e, log) {
        files.resolve(log);
        deregister.cancel();
        deregister.receive();
        deregister.complete();
      };

      picker.pick();
      // TODO: Emit this event
      deregister.cancel = $rootScope.$on('file:picker:canceled', fileCancel);
      deregister.receive = $rootScope.$on('file:reader:received', fileReceive);
      deregister.complete = $rootScope.$on('file:reader:complete', fileComplete);

      return files.promise;
    }
  };
  this.$get.$inject = ['$rootScope', '$q', 'file:picker'];
};

angular.module('file')
  .config(fileConfig)
  .provider('file', fileProvider)
;
<commit_msg>(fix) Propogate options to picker service.<commit_after>// TODO: Shared configuration
var fileConfig = function($provide, picker, reader, dragger) { void 0; };
fileConfig.$inject = ['$provide']; //.concat(internalsProvider);

var fileProvider = function() {
  this.$get = function($rootScope, $q, picker) {
    return { pick: pick };

    function pick(options) {
      var files = $q.defer();
      var deregister = {};

      var fileCancel = function(e) {
        files.reject();
        deregister.cancel();
        deregister.receive();
        deregister.complete();
      };
      var fileReceive = function(e, data, name, file) {
        files.notify({
          data: data,
          name: name,
          file: file
        });
      };
      var fileComplete = function(e, log) {
        files.resolve(log);
        deregister.cancel();
        deregister.receive();
        deregister.complete();
      };

      picker.pick(options);
      // TODO: Emit this event
      deregister.cancel = $rootScope.$on('file:picker:canceled', fileCancel);
      deregister.receive = $rootScope.$on('file:reader:received', fileReceive);
      deregister.complete = $rootScope.$on('file:reader:complete', fileComplete);

      return files.promise;
    }
  };
  this.$get.$inject = ['$rootScope', '$q', 'file:picker'];
};

angular.module('file')
  .config(fileConfig)
  .provider('file', fileProvider)
;
<|endoftext|>