<commit_before>import errors from 'feathers-errors';
import fp from 'mostly-func';
import mongose from 'mongoose';
import { getHookData, isSelected, setHookData } from '../helpers';

const defaultOptions = {
  idField: 'id'
};

const mergeField = function (prop, data, options) {
  let value = fp.prop(prop, data);
  if (fp.isNil(value) || fp.isIdLike(value)) {
    value = { [options.idField]: value };
  }
  // merge left except the idField, and keep populated object
  return fp.mergeWithKey((k, l, r) => {
    if (k === options.idField) return l;
    return fp.isObjLike(l)? l : r;
  }, fp.omit(prop, data), value);
};

const mergeData = function (field, data, options) {
  const path = fp.init(field.split('.'));
  const prop = fp.last(field.split('.'));
  const merge = data => {
    const fieldData = path.length? fp.path(path, data) : data;
    if (fieldData) {
      const result = fp.isArray(fieldData)
      ? fp.map(item => mergeField(prop, item, options), fieldData)
      : mergeField(prop, fieldData, options);
      return path.length? fp.assocPath(path, result, data) : result;
    } else {
      return data;
    }
  };
  if (Array.isArray(data)) {
    let results = fp.map(merge, data);
    if (results && options.sort) {
      results = fp.sortBy(fp.prop(options.sort), results);
    }
    return results;
  } else {
    return merge(data);
  }
};

export default function flatMerge (field, opts) {

  return async context => {
    let options = fp.assignAll(defaultOptions, opts);

    if (context.type !== 'after') {
      throw new errors.GeneralError('Can not merge on before hook.');
    }

    if (context.result) {
      const data = getHookData(context);
      const result = mergeData(field, data, options);
      setHookData(context, result);
    }
    return context;
  };
}<commit_msg>Fix merge to keep populated object<commit_after>import errors from 'feathers-errors';
import fp from 'mostly-func';
import mongose from 'mongoose';
import { getHookData, isSelected, setHookData } from '../helpers';

const defaultOptions = {
  idField: 'id'
};

const mergeField = function (prop, data, options) {
  let value = fp.prop(prop, data);
  if (fp.isNil(value) || fp.isIdLike(value)) {
    value = { [options.idField]: value };
  }
  // merge left except the idField, and keep populated object
  return fp.mergeWithKey((k, l, r) => {
    if (k === options.idField) return r;
    return fp.isIdLike(r)? l : r;
  }, fp.omit(prop, data), value);
};

const mergeData = function (field, data, options) {
  const path = fp.init(field.split('.'));
  const prop = fp.last(field.split('.'));
  const merge = data => {
    const fieldData = path.length? fp.path(path, data) : data;
    if (fieldData) {
      const result = fp.isArray(fieldData)
      ? fp.map(item => mergeField(prop, item, options), fieldData)
      : mergeField(prop, fieldData, options);
      return path.length? fp.assocPath(path, result, data) : result;
    } else {
      return data;
    }
  };
  if (Array.isArray(data)) {
    let results = fp.map(merge, data);
    if (results && options.sort) {
      results = fp.sortBy(fp.prop(options.sort), results);
    }
    return results;
  } else {
    return merge(data);
  }
};

export default function flatMerge (field, opts) {

  return async context => {
    let options = fp.assignAll(defaultOptions, opts);

    if (context.type !== 'after') {
      throw new errors.GeneralError('Can not merge on before hook.');
    }

    if (context.result) {
      const data = getHookData(context);
      const result = mergeData(field, data, options);
      setHookData(context, result);
    }
    return context;
  };
}<|endoftext|>


<commit_before>Kwf.enableOnReadyConsoleProfile = false;

/* fn: fn,
 * scope: scope,
 * options: options || {},
 * type: [jquery|ext],
 * num: unique number, //used to mark in initDone
 * selector: selector, // null if onContentReady
 * */
Kwf._readyHandlers = []; //for onContentReady
Kwf._readyElHandlers = []; //for onElement*
Kwf._skipDeferred; //if callOnContentReady should skip 'defer' callbacks or execute only 'defer' callbacks
                   //used on initial ready
Kwf._deferredStart = null; //used for timing deferred, required here because of multiple chunks
Kwf._onReadyIsCalling = false; //true while callOnContentReady is processing onReadyElQueue and we can add more to queue
Kwf._onReadyCallQueue = []; //queue for onContentReady to avoid recursions
Kwf._onReadyElQueue = []; //queue for onElementReady/Show/Hide/WidthChange calls
Kwf._elCacheBySelector = {};

if (!Kwf.isApp) {
    $(document).ready(function() {
        if (!document.body) {
            //this happens if a redirect by changing location in JS is done
            //in that case no contentReady needs to be called
            return;
        }
        var t = Kwf.Utils.BenchmarkBox.now();
        if (Kwf.enableOnReadyConsoleProfile) console.profile("callOnContentReady body");
        Kwf._skipDeferred = true;
        Kwf.callOnContentReady(document.body, { action: 'render' });
        delete Kwf._skipDeferred;
        if (Kwf.enableOnReadyConsoleProfile) console.profileEnd();
        Kwf.Utils.BenchmarkBox.time('time', Kwf.Utils.BenchmarkBox.now()-t);
        Kwf.Utils.BenchmarkBox.create({
            counters: Kwf._onReadyStats,
            type: 'onReady'
        });
        (function() {
            Kwf._deferredStart = Kwf.Utils.BenchmarkBox.now();
            if (Kwf.enableOnReadyConsoleProfile) console.profile("callOnContentReady body deferred");
            Kwf._skipDeferred = false;
            Kwf.callOnContentReady(document.body, { action: 'render' });
            delete Kwf._skipDeferred;
        }).defer(10);

        Ext.fly(window).on('resize', function() {
            Kwf.callOnContentReady(document.body, { action: 'widthChange' } );
        }, this, { buffer: 100 });
    });
}

Kwf._addReadyHandler = function(type, onAction, selector, fn, options)
{
    Kwf._readyElHandlers.push({
        selector: selector,
        fn: fn,
        options: options || {},
        num: Kwf._readyElHandlers.length, //unique number
        type: type,
        onAction: onAction
    });
};

/**
 * @param element the added/changed dom element
 * @param options newRender (bool): if new elements have been added to the dom or just visiblity/width changed
 */
Kwf.callOnContentReady = function(renderedEl, options)
{
    Kwf.Utils.BenchmarkBox.count('callOnContentReady');
    if (!options) options = {};
    if (typeof options.newRender != 'undefined') {
        //backwards compatibility, for callOnContentReady call
        options.action = options.newRender ? 'render' : 'show';
        delete options.newRender;
    }
    if (!options.action) {
        if (console && console.warn) console.warn('Please set option action on callOnContentReady');
        options.action = 'render';
    }
    if (!renderedEl) {
        if (console && console && console.warn) console.warn('Please pass element argument on callOnContentReady');
        renderedEl = document.body;
    }
    if (Ext.Element && renderedEl instanceof Ext.Element) renderedEl = renderedEl.dom;
    if (jQuery && renderedEl instanceof jQuery) renderedEl = renderedEl.get();
    options.newRender = options.action == 'render'; //backwards compatibility, for onContentReady callback

    Kwf._onReadyCallQueue.push({
        renderedEl: renderedEl,
        options: options
    });

    if (options.action == 'render') {
        //new elements rendered, clear cache
        Kwf._elCacheBySelector = {};

        var t = Kwf.Utils.BenchmarkBox.now();
        var html = renderedEl.innerHTML;
        Kwf.Utils.BenchmarkBox.time('innerHTML', Kwf.Utils.BenchmarkBox.now()-t);
    }

    //add entries to _onReadyElQueue, depending on renderedEl
    var onActions;
    if (options.action == 'render') {
        onActions = ['render', 'show', 'widthChange'];
    } else if (options.action == 'show') {
        onActions = ['show', 'widthChange'];
    } else if (options.action == 'hide') {
        onActions = ['hide'];
    } else if (options.action == 'widthChange') {
        onActions = ['widthChange'];
    }

    for (var i = 0; i < Kwf._readyElHandlers.length; i++) {
        var hndl = Kwf._readyElHandlers[i];

        //Kwf._skipDeferred gets set before callOnContentReady(body)
        //can not be part of options as it would be missing in recursive calls
        if (Kwf._skipDeferred === true) {
            if (hndl.options.defer) {
                continue;
            }
        } else if (Kwf._skipDeferred === false) {
            if (!hndl.options.defer) {
                continue;
            }
        }

        if (hndl.options.checkVisibility) {
            if (renderedEl != document.body && !Kwf.Utils.Element.isVisible(renderedEl)) {
                continue;
            }
            //if checkVisibility is activated, don't skip based on onActions as
            //even a widthChange action could make an element visible (media queries)
        } else {
            if (onActions.indexOf(hndl.onAction) == -1) {
                continue;
            }
        }

        if (options.action == 'render' && !Kwf._elCacheBySelector[hndl.selector]) {
            var t = Kwf.Utils.BenchmarkBox.now();
            var m = hndl.selector.match(/^[a-z]*\.([a-z]+)/i)
            if (m) {
                //do a stupid text search on the selector, using that we can skip query for many selectors that don't exist in the current el
                if (html.indexOf(m[1]) == -1) {
                    Kwf._elCacheBySelector[hndl.selector] = [];
                }
            }
            Kwf.Utils.BenchmarkBox.time('checkInnerHtml', Kwf.Utils.BenchmarkBox.now()-t);
        }

        if (Kwf._elCacheBySelector[hndl.selector]) {
            if (Kwf._elCacheBySelector[hndl.selector].length === 0) {
                //Optimize: if we never got element by that selector, skip query
                Kwf.Utils.BenchmarkBox.count('querySkip');
                continue;
            }
            Kwf.Utils.BenchmarkBox.count('queryCache');
            var els = [];
            for (var j=0; j<Kwf._elCacheBySelector[hndl.selector].length; j++) {
                if (renderedEl == document.body || $.contains(renderedEl, Kwf._elCacheBySelector[hndl.selector][j])) {
                    els.push(Kwf._elCacheBySelector[hndl.selector][j]);
                }
            }
        } else {
            var t = Kwf.Utils.BenchmarkBox.now();
            var els = $.makeArray($(renderedEl).find(hndl.selector));
            Kwf.Utils.BenchmarkBox.time('query', Kwf.Utils.BenchmarkBox.now() - t);
            if (options.action == 'render' && renderedEl == document.body) {
                Kwf._elCacheBySelector[hndl.selector] = els;
            }
        }
        for (var j = 0; j< els.length; ++j) {

            if (!els[j].onReadyQueue) els[j].onReadyQueue = [];
            var alreadyInQueue = els[j].onReadyQueue.indexOf(hndl.num) != -1;

            if (!alreadyInQueue) {
                els[j].onReadyQueue.push(hndl.num);
                var parentsCount = 0;
                var n = els[j];
                while (n = n.parentNode) {
                    parentsCount++;
                }
                Kwf.Utils.BenchmarkBox.count('readyEl');
                Kwf._onReadyElQueue.push({
                    el: els[j],
                    fn: hndl.fn,
                    options: hndl.options,
                    num: hndl.num,
                    type: hndl.type,
                    onAction: hndl.onAction,
                    selector: hndl.selector,
                    priority: hndl.options.priority || 0,
                    parentsCount: parentsCount
                });
            }
        }
    }

    //sort _onReadyElQueue
    var t = Kwf.Utils.BenchmarkBox.now();
    Kwf._onReadyElQueue.sort(function sortOnReadyElQueue(a, b) {
        if (a.priority != b.priority) {
            return a.priority - b.priority;
        } else {
            if (a.parentsCount != b.parentsCount) {
                return a.parentsCount - b.parentsCount;
            } else {
                return a.num - b.num;
            }
        }
    });
    Kwf.Utils.BenchmarkBox.time('sort', Kwf.Utils.BenchmarkBox.now() - t);

    if (Kwf._onReadyIsCalling) {
        return;
    }

    Kwf._onReadyIsCalling = true;

    //process onContentReady handlers
    while (Kwf._onReadyCallQueue.length) {
        var queueEntry = Kwf._onReadyCallQueue.pop();

        Kwf._readyHandlers.sort(function(a, b) {
            return (a.options.priority || 0) - (b.options.priority || 0);
        });
        for (var i = 0; i < Kwf._readyHandlers.length; i++) {
            var hndl = Kwf._readyHandlers[i];
            var t = Kwf.Utils.BenchmarkBox.now();
            hndl.fn.call(hndl.options.scope || window, queueEntry.renderedEl, queueEntry.options);
            var fnName = hndl.fn.name;
            if (!fnName) {
                fnName = 'unknown';
            }
            Kwf.Utils.BenchmarkBox.subTime('onContentReady', 'fn: '+fnName, Kwf.Utils.BenchmarkBox.now()-t);
        }
    }

    //call the callback of an element ready handler
    function callQueueFn(queueEntry, config)
    {
        var t = Kwf.Utils.BenchmarkBox.now();
        var el = queueEntry.el;
        el = queueEntry.type == 'ext' ? Ext.get(el) : $(el);
        queueEntry.fn.call(queueEntry.options.scope || window, el, config);
        var fnName = queueEntry.fn.name;
        if (!fnName) {
            fnName = 'unknown';
        }

        Kwf.Utils.BenchmarkBox.subTime(
            'on'+queueEntry.onAction.charAt(0).toUpperCase() + queueEntry.onAction.slice(1),
            'fn: '+fnName,
            Kwf.Utils.BenchmarkBox.now()-t
        );
    };

    //process one entry of the readyElQueue
    //own function so it can be called in sync or in deferred chunks
    function processOnReadyElQueueEntry()
    {
        var queueEntry = Kwf._onReadyElQueue.shift();
        var el = queueEntry.el;
        el.onReadyQueue.splice(el.onReadyQueue.indexOf(queueEntry.num), 1);
        if (queueEntry.onAction == 'render') {
            if (queueEntry.options.checkVisibility && !Kwf.Utils.Element.isVisible(el)) {
                return;
            }
            if (!el.initDone) el.initDone = {};
            if (el.initDone[queueEntry.num]) {
                return;
            }
            el.initDone[queueEntry.num] = true;
            var config = {};
            var configEl = $(el).find('> input[type="hidden"]');
            if (configEl.length) {
                try {
                    var v = configEl.get(0).value;
                    if (v.substr(0, 1) == '{') {
                        config = $.parseJSON(v);
                    }
                } catch (err) {}
            }
            callQueueFn(queueEntry, config);
        } else {
            if (queueEntry.onAction == 'show') {
                if (Kwf.Utils.Element.isVisible(el)) {
                    callQueueFn(queueEntry);
                }
            } else if (queueEntry.onAction == 'hide') {
                if (!Kwf.Utils.Element.isVisible(el)) {
                    callQueueFn(queueEntry);
                }
            } else if (queueEntry.onAction == 'widthChange') {
                if (!queueEntry.options.checkVisibility || Kwf.Utils.Element.isVisible(el)) {
                    callQueueFn(queueEntry);
                }
            }

        }
    }

    if (Kwf._skipDeferred === false) {
        var processNext = function processNext() {
            Kwf.Utils.BenchmarkBox.count('chunks');
            var t = Kwf.Utils.BenchmarkBox.now();
            while (Kwf._onReadyElQueue.length && Kwf.Utils.BenchmarkBox.now()-t < 50) {
                processOnReadyElQueueEntry();
            }
            if (Kwf._onReadyElQueue.length) {
                processNext.defer(this, 1);
            } else {
                Kwf._onReadyIsCalling = false;
                Kwf.Utils.BenchmarkBox.time('time', Kwf.Utils.BenchmarkBox.now()-Kwf._deferredStart);
                if (Kwf.enableOnReadyConsoleProfile) console.profileEnd();
                Kwf.Utils.BenchmarkBox.create({
                    counters: Kwf._onReadyStats,
                    type: 'onReady defer'
                });
            }
        };
        processNext();
    } else {
        while (Kwf._onReadyElQueue.length) {
            processOnReadyElQueueEntry();
        }
        Kwf._onReadyIsCalling = false;
    }

};

/**
 * Register a function that will be called when content is loaded or shown
 * @param callback function (passed arguments: el, options (newRender=bool))
 * @param options supported are: priority (integer, higher number means it's called after all with lower number, default 0)
 */
Kwf.onContentReady = function(fn, options) {
    if (arguments.length == 3) {
        var scope = arguments[1];
        var options = arguments[2];
        options.scope = scope;
    }
    Kwf._readyHandlers.push({
        fn: fn,
        options: options || {}
    });
};
<commit_msg>Optimize callOnContentReady<commit_after>Kwf.enableOnReadyConsoleProfile = false;

/* fn: fn,
 * scope: scope,
 * options: options || {},
 * type: [jquery|ext],
 * num: unique number, //used to mark in initDone
 * selector: selector, // null if onContentReady
 * */
Kwf._readyHandlers = []; //for onContentReady
Kwf._readyElHandlers = []; //for onElement*
Kwf._skipDeferred; //if callOnContentReady should skip 'defer' callbacks or execute only 'defer' callbacks
                   //used on initial ready
Kwf._deferredStart = null; //used for timing deferred, required here because of multiple chunks
Kwf._onReadyIsCalling = false; //true while callOnContentReady is processing onReadyElQueue and we can add more to queue
Kwf._onReadyCallQueue = []; //queue for onContentReady to avoid recursions
Kwf._onReadyElQueue = []; //queue for onElementReady/Show/Hide/WidthChange calls
Kwf._elCacheBySelector = {};

if (!Kwf.isApp) {
    $(document).ready(function() {
        if (!document.body) {
            //this happens if a redirect by changing location in JS is done
            //in that case no contentReady needs to be called
            return;
        }
        var t = Kwf.Utils.BenchmarkBox.now();
        if (Kwf.enableOnReadyConsoleProfile) console.profile("callOnContentReady body");
        Kwf._skipDeferred = true;
        Kwf.callOnContentReady(document.body, { action: 'render' });
        delete Kwf._skipDeferred;
        if (Kwf.enableOnReadyConsoleProfile) console.profileEnd();
        Kwf.Utils.BenchmarkBox.time('time', Kwf.Utils.BenchmarkBox.now()-t);
        Kwf.Utils.BenchmarkBox.create({
            counters: Kwf._onReadyStats,
            type: 'onReady'
        });
        (function() {
            Kwf._deferredStart = Kwf.Utils.BenchmarkBox.now();
            if (Kwf.enableOnReadyConsoleProfile) console.profile("callOnContentReady body deferred");
            Kwf._skipDeferred = false;
            Kwf.callOnContentReady(document.body, { action: 'render' });
            delete Kwf._skipDeferred;
        }).defer(10);

        Ext.fly(window).on('resize', function() {
            Kwf.callOnContentReady(document.body, { action: 'widthChange' } );
        }, this, { buffer: 100 });
    });
}

Kwf._addReadyHandler = function(type, onAction, selector, fn, options)
{
    Kwf._readyElHandlers.push({
        selector: selector,
        fn: fn,
        options: options || {},
        num: Kwf._readyElHandlers.length, //unique number
        type: type,
        onAction: onAction
    });
};

/**
 * @param element the added/changed dom element
 * @param options newRender (bool): if new elements have been added to the dom or just visiblity/width changed
 */
Kwf.callOnContentReady = function(renderedEl, options)
{
    Kwf.Utils.BenchmarkBox.count('callOnContentReady');
    if (!options) options = {};
    if (typeof options.newRender != 'undefined') {
        //backwards compatibility, for callOnContentReady call
        options.action = options.newRender ? 'render' : 'show';
        delete options.newRender;
    }
    if (!options.action) {
        if (console && console.warn) console.warn('Please set option action on callOnContentReady');
        options.action = 'render';
    }
    if (!renderedEl) {
        if (console && console && console.warn) console.warn('Please pass element argument on callOnContentReady');
        renderedEl = document.body;
    }
    if (Ext.Element && renderedEl instanceof Ext.Element) renderedEl = renderedEl.dom;
    if (jQuery && renderedEl instanceof jQuery) renderedEl = renderedEl.get();
    options.newRender = options.action == 'render'; //backwards compatibility, for onContentReady callback

    Kwf._onReadyCallQueue.push({
        renderedEl: renderedEl,
        options: options
    });

    //add entries to _onReadyElQueue, depending on renderedEl
    var onActions;
    if (options.action == 'render') {
        onActions = ['render', 'show', 'widthChange'];
    } else if (options.action == 'show') {
        onActions = ['show', 'widthChange'];
    } else if (options.action == 'hide') {
        onActions = ['hide'];
    } else if (options.action == 'widthChange') {
        onActions = ['widthChange'];
    }

    var html = false;
    for (var i = 0; i < Kwf._readyElHandlers.length; i++) {
        var hndl = Kwf._readyElHandlers[i];

        //Kwf._skipDeferred gets set before callOnContentReady(body)
        //can not be part of options as it would be missing in recursive calls
        if (Kwf._skipDeferred === true) {
            if (hndl.options.defer) {
                continue;
            }
        } else if (Kwf._skipDeferred === false) {
            if (!hndl.options.defer) {
                continue;
            }
        }

        if (hndl.options.checkVisibility) {
            if (renderedEl != document.body && !Kwf.Utils.Element.isVisible(renderedEl)) {
                continue;
            }
            //if checkVisibility is activated, don't skip based on onActions as
            //even a widthChange action could make an element visible (media queries)
        } else {
            if (onActions.indexOf(hndl.onAction) == -1) {
                continue;
            }
        }

        if (options.action == 'render' && !html) {
            var t = Kwf.Utils.BenchmarkBox.now();
            html = renderedEl.innerHTML;
            Kwf.Utils.BenchmarkBox.time('innerHTML', Kwf.Utils.BenchmarkBox.now()-t);
        }

        var useSelectorCache;
        if (options.action != 'render') {
            useSelectorCache = true;
        } else {
            if (Kwf._skipDeferred === false && Kwf._elCacheBySelector[hndl.selector]) {
                useSelectorCache = true;
            } else {
                var t = Kwf.Utils.BenchmarkBox.now();
                var m = hndl.selector.match(/^[a-z]*\.([a-z]+)/i);
                //do a stupid text search on the selector, using that we can skip query for many selectors that don't exist in the current el
                if (m && html.indexOf(m[1]) == -1) {
                    useSelectorCache = true;
                    if (!Kwf._elCacheBySelector[hndl.selector]) {
                        Kwf._elCacheBySelector[hndl.selector] = [];
                    }
                } else {
                    useSelectorCache = false;
                }
                Kwf.Utils.BenchmarkBox.time('checkInnerHtml', Kwf.Utils.BenchmarkBox.now()-t);
            }
        }

        if (useSelectorCache && Kwf._elCacheBySelector[hndl.selector]) {
            Kwf.Utils.BenchmarkBox.count('queryCache');
            var els = [];
            for (var j=0; j<Kwf._elCacheBySelector[hndl.selector].length; j++) {
                if (renderedEl == document.body || $.contains(renderedEl, Kwf._elCacheBySelector[hndl.selector][j])) {
                    els.push(Kwf._elCacheBySelector[hndl.selector][j]);
                }
            }
        } else {
            var t = Kwf.Utils.BenchmarkBox.now();
            var els = $.makeArray($(renderedEl).find(hndl.selector));
            Kwf.Utils.BenchmarkBox.time('query', Kwf.Utils.BenchmarkBox.now() - t);
            if (!Kwf._elCacheBySelector[hndl.selector]) {
                Kwf._elCacheBySelector[hndl.selector] = els;
            } else {
                els.each(function(i) {
                    if (Kwf._elCacheBySelector[hndl.selector].indexOf(i) == -1) {
                        Kwf._elCacheBySelector[hndl.selector].push(i);
                    }
                }, this);
            }
        }
        for (var j = 0; j< els.length; ++j) {

            if (!els[j].onReadyQueue) els[j].onReadyQueue = [];
            var alreadyInQueue = els[j].onReadyQueue.indexOf(hndl.num) != -1;

            if (!alreadyInQueue) {
                els[j].onReadyQueue.push(hndl.num);
                var parentsCount = 0;
                var n = els[j];
                while (n = n.parentNode) {
                    parentsCount++;
                }
                Kwf.Utils.BenchmarkBox.count('readyEl');
                Kwf._onReadyElQueue.push({
                    el: els[j],
                    fn: hndl.fn,
                    options: hndl.options,
                    num: hndl.num,
                    type: hndl.type,
                    onAction: hndl.onAction,
                    selector: hndl.selector,
                    priority: hndl.options.priority || 0,
                    parentsCount: parentsCount
                });
            }
        }
    }

    //sort _onReadyElQueue
    var t = Kwf.Utils.BenchmarkBox.now();
    Kwf._onReadyElQueue.sort(function sortOnReadyElQueue(a, b) {
        if (a.priority != b.priority) {
            return a.priority - b.priority;
        } else {
            if (a.parentsCount != b.parentsCount) {
                return a.parentsCount - b.parentsCount;
            } else {
                return a.num - b.num;
            }
        }
    });
    Kwf.Utils.BenchmarkBox.time('sort', Kwf.Utils.BenchmarkBox.now() - t);

    if (Kwf._onReadyIsCalling) {
        return;
    }

    Kwf._onReadyIsCalling = true;

    //process onContentReady handlers
    while (Kwf._onReadyCallQueue.length) {
        var queueEntry = Kwf._onReadyCallQueue.pop();

        Kwf._readyHandlers.sort(function(a, b) {
            return (a.options.priority || 0) - (b.options.priority || 0);
        });
        for (var i = 0; i < Kwf._readyHandlers.length; i++) {
            var hndl = Kwf._readyHandlers[i];
            var t = Kwf.Utils.BenchmarkBox.now();
            hndl.fn.call(hndl.options.scope || window, queueEntry.renderedEl, queueEntry.options);
            var fnName = hndl.fn.name;
            if (!fnName) {
                fnName = 'unknown';
            }
            Kwf.Utils.BenchmarkBox.subTime('onContentReady', 'fn: '+fnName, Kwf.Utils.BenchmarkBox.now()-t);
        }
    }

    //call the callback of an element ready handler
    function callQueueFn(queueEntry, config)
    {
        var t = Kwf.Utils.BenchmarkBox.now();
        var el = queueEntry.el;
        el = queueEntry.type == 'ext' ? Ext.get(el) : $(el);
        queueEntry.fn.call(queueEntry.options.scope || window, el, config);
        var fnName = queueEntry.fn.name;
        if (!fnName) {
            fnName = 'unknown';
        }

        Kwf.Utils.BenchmarkBox.subTime(
            'on'+queueEntry.onAction.charAt(0).toUpperCase() + queueEntry.onAction.slice(1),
            'fn: '+fnName,
            Kwf.Utils.BenchmarkBox.now()-t
        );
    };

    //process one entry of the readyElQueue
    //own function so it can be called in sync or in deferred chunks
    function processOnReadyElQueueEntry()
    {
        var queueEntry = Kwf._onReadyElQueue.shift();
        var el = queueEntry.el;
        el.onReadyQueue.splice(el.onReadyQueue.indexOf(queueEntry.num), 1);
        if (queueEntry.onAction == 'render') {
            if (queueEntry.options.checkVisibility && !Kwf.Utils.Element.isVisible(el)) {
                return;
            }
            if (!el.initDone) el.initDone = {};
            if (el.initDone[queueEntry.num]) {
                return;
            }
            el.initDone[queueEntry.num] = true;
            var config = {};
            var configEl = $(el).find('> input[type="hidden"]');
            if (configEl.length) {
                try {
                    var v = configEl.get(0).value;
                    if (v.substr(0, 1) == '{') {
                        config = $.parseJSON(v);
                    }
                } catch (err) {}
            }
            callQueueFn(queueEntry, config);
        } else {
            if (queueEntry.onAction == 'show') {
                if (Kwf.Utils.Element.isVisible(el)) {
                    callQueueFn(queueEntry);
                }
            } else if (queueEntry.onAction == 'hide') {
                if (!Kwf.Utils.Element.isVisible(el)) {
                    callQueueFn(queueEntry);
                }
            } else if (queueEntry.onAction == 'widthChange') {
                if (!queueEntry.options.checkVisibility || Kwf.Utils.Element.isVisible(el)) {
                    callQueueFn(queueEntry);
                }
            }

        }
    }

    if (Kwf._skipDeferred === false) {
        var processNext = function processNext() {
            Kwf.Utils.BenchmarkBox.count('chunks');
            var t = Kwf.Utils.BenchmarkBox.now();
            while (Kwf._onReadyElQueue.length && Kwf.Utils.BenchmarkBox.now()-t < 50) {
                processOnReadyElQueueEntry();
            }
            if (Kwf._onReadyElQueue.length) {
                processNext.defer(this, 1);
            } else {
                Kwf._onReadyIsCalling = false;
                Kwf.Utils.BenchmarkBox.time('time', Kwf.Utils.BenchmarkBox.now()-Kwf._deferredStart);
                if (Kwf.enableOnReadyConsoleProfile) console.profileEnd();
                Kwf.Utils.BenchmarkBox.create({
                    counters: Kwf._onReadyStats,
                    type: 'onReady defer'
                });
            }
        };
        processNext();
    } else {
        while (Kwf._onReadyElQueue.length) {
            processOnReadyElQueueEntry();
        }
        Kwf._onReadyIsCalling = false;
    }

};

/**
 * Register a function that will be called when content is loaded or shown
 * @param callback function (passed arguments: el, options (newRender=bool))
 * @param options supported are: priority (integer, higher number means it's called after all with lower number, default 0)
 */
Kwf.onContentReady = function(fn, options) {
    if (arguments.length == 3) {
        var scope = arguments[1];
        var options = arguments[2];
        options.scope = scope;
    }
    Kwf._readyHandlers.push({
        fn: fn,
        options: options || {}
    });
};
<|endoftext|>


<commit_before>import { $$, Component } from '../dom'
import { Form, FormRow, Modal, MultiSelect } from '../ui'

export default class CitationModal extends Component {
  getInitialState () {
    const { mode, node } = this.props
    const value = mode === 'edit' ? node.target : []
    return { value }
  }

  render () {
    const { document, mode } = this.props
    const { value } = this.state
    const confirmLabel = mode === 'edit' ? 'Update' : 'Create'
    const title = mode === 'edit' ? 'Edit Citation' : 'Create Citation'

    const root = document.root
    const referencesList = root.resolve('references')
    const disableConfirm = value.length === 0

    const modalProps = { title, cancelLabel: 'Cancel', confirmLabel, disableConfirm, size: 'large' }
    return $$(Modal, modalProps,
      $$(Form, {},
        $$(FormRow, {},
          $$(MultiSelect, {
            options: referencesList.map(ref => {
              return { value: ref.id, label: ref.content }
            }),
            value,
            label: 'Add Reference',
            placeholder: 'Please select one or more references',
            onchange: this._updateReferencess
          }).ref('references')
        )
      )
    )
  }

  _updateReferencess () {
    const value = this.refs.references.val()
    this.extendState({ value })
  }
}
<commit_msg>Repair CitationModal opening.<commit_after>import { $$, Component } from '../dom'
import { Form, FormRow, Modal, MultiSelect } from '../ui'

export default class CitationModal extends Component {
  getInitialState () {
    const { mode, node } = this.props
    const value = mode === 'edit' ? node.references : []
    return { value }
  }

  render () {
    const { document, mode } = this.props
    const { value } = this.state
    const confirmLabel = mode === 'edit' ? 'Update' : 'Create'
    const title = mode === 'edit' ? 'Edit Citation' : 'Create Citation'

    const root = document.root
    const referencesList = root.resolve('references')
    const disableConfirm = value.length === 0

    const modalProps = { title, cancelLabel: 'Cancel', confirmLabel, disableConfirm, size: 'large' }
    return $$(Modal, modalProps,
      $$(Form, {},
        $$(FormRow, {},
          $$(MultiSelect, {
            options: referencesList.map(ref => {
              return { value: ref.id, label: ref.content }
            }),
            value,
            label: 'Add Reference',
            placeholder: 'Please select one or more references',
            onchange: this._updateReferencess
          }).ref('references')
        )
      )
    )
  }

  _updateReferencess () {
    const value = this.refs.references.val()
    this.extendState({ value })
  }
}
<|endoftext|>


<commit_before>'use strict';

// Customers controller
angular.module('customers').controller('CustomersController', ['$scope', '$stateParams', '$location', 'Authentication', 'Customers',
	function($scope, $stateParams, $location, Authentication, Customers ) {
		$scope.authentication = Authentication;

		// Create new Customer
		$scope.create = function() {
			var personalDetails = {forename:''};
			// Create new Customer object
			var customer = new Customers ({
//				name: this.name
				personalDetails : {
					forename : this.forename,
					surname : this.surname,
					dob : this.dob
								  },
				addressDetails : {
					firstLine : this.firstLine,
					city : this.city,
					postCode : this.postCode
				},
				phoneDetails : {
					office : this.office,
					home : this.home,
					mobile : this.mobile
				}
			});

			// Redirect after save
			customer.$save(function(response) {
				$location.path('customers/' + response._id);

				// Clear form fields
				$scope.forename = '';
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Remove existing Customer
		$scope.remove = function( customer ) {
			if ( customer ) { customer.$remove();

				for (var i in $scope.customers ) {
					if ($scope.customers [i] === customer ) {
						$scope.customers.splice(i, 1);
					}
				}
			} else {
				$scope.customer.$remove(function() {
					$location.path('customers');
				});
			}
		};

		// Update existing Customer
		$scope.update = function() {
			var customer = $scope.customer ;

			customer.$update(function() {
				$location.path('customers/' + customer._id);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Find a list of Customers
		$scope.find = function() {
			$scope.customers = Customers.query();
		};

		// Find existing Customer
		$scope.findOne = function() {
			$scope.customer = Customers.get({
				customerId: $stateParams.customerId
			});
		};
	}
]);
//=========================================================================
// Customers controller
angular.module('customers').controller('OrdersController', ['$scope', '$stateParams', '$location', 'Authentication', 'Customers', 'Items', 'Orders',
	function($scope, $stateParams, $location, Authentication, Customers, Items, Orders ) {
		$scope.authentication = Authentication;

		console.log('[OrdersController : orderId = ' + $stateParams.orderId);
		if($stateParams.orderId) { // this kicks in when we land on the edit-order.client.view.html page
			var customerId = $stateParams.customerId;

			//retrieve order items
			var orderId = $stateParams.orderId;

			console.log('OrderController#initialise....customer: ' + customerId + ' order: ' + orderId);

			//generates following http request
			//http://localhost:3000/customers/54b8ead1dd050becddbc6360/orders/54b8eae3dd050becddbc6361

			$scope.order = Orders.get({customerId:customerId, orderId:orderId}, function(err){
				console.log('retrived order: ' + JSON.stringify($scope.order));
				$scope.orderItems = $scope.order.orderItems;
			});

		} else { // this kicks in when we land on any other page ie. create-order.client.view.html
			$scope.orderItems = [];
		}
		/**
		 * Find all items that can be purchased. display this in the view
		 * and user can make selections using addORderItem/removeOrderItem
		 */
		$scope.findAllItems = function() {
			console.log('{create order1 : customer = ' + $stateParams.customerId);

			$scope.customer = Customers.get({
				customerId : $stateParams.customerId
			}, function(){
				console.log('{create order2 : customer = ' + $stateParams.customerId);
				$scope.items = Items.query();
				console.log('{create order : items = ' + JSON.stringify($scope.items));
			});

		};

		/**
		 * called by add OrderItem button in view
		 * @param selectedItem The item selected by the user to be added to the cart
		 */
		$scope.addOrderItem = function(selectedItem) {

			//var jsObjects = [{a: 1, b: 2}, {a: 3, b: 4}, {a: 5, b: 6}, {a: 7, b: 8}];
			//var result = jsObjects.filter(function( obj ) {
			//	return obj.b === 6;
			//});
			//console.log('TEST: res = ' + JSON.stringify(result));

			if(!Array.prototype.filter) {
				console.log('WARNING:::: filter not supported');
			}
			//find element in array that matches the 'selectedItem'
			var orderItem = $scope.orderItems.filter(function(obj){
//				return obj.itemId === selectedItem._id;
//				return obj._id === selectedItem._id;
//				return obj.item === selectedItem._id;
				return obj.item._id === selectedItem._id;

			});

			console.log(' found item : ' + JSON.stringify(orderItem));
			if(orderItem[0]) {
				console.log('found item will increment quantity');
				orderItem[0].quantity += 1;
			} else {
//				var newOrderItem = { itemId: this.item._id, name: this.item.name, price : this.item.price, quantity : 1 };
//				var newOrderItem = { _id: this.item._id, price : this.item.price, quantity : 1 };
//				var newOrderItem = { item: this.item._id, name: this.item.name, price : this.item.price, quantity : 1 };
//				var newOrderItem = { item: this.item, name: this.item.name, price : this.item.price, quantity : 1 };
				var newOrderItem = { item: this.item, quantity : 1 };
				$scope.orderItems.push(newOrderItem);
			}

			console.log('[CCC] selected Items : ' + JSON.stringify($scope.orderItems));
		};

		/**
		 * called by remove OrderItem button in view
		 * @param selectedOrderItem The item the user wants to remove from the order.
		 */
		$scope.removeOrderItem = function(selectedOrderItem) {

			if(!Array.prototype.filter) {
				console.log('WARNING:::: filter not supported');
			}
			//find element in array that needs to be removed
			var orderItem = $scope.orderItems.filter(function(obj){
				return obj.id === selectedOrderItem.id;
			});

			console.log(' selected item : ' + JSON.stringify(selectedOrderItem));
			console.log(' found item : ' + JSON.stringify(orderItem));
			if(orderItem[0]) {
				console.log('found item will decrement quantity');
				orderItem[0].quantity -= 1;
				if(orderItem[0].quantity <= 0){
					console.log('will remove OrderItem');
					var index = $scope.orderItems.indexOf(orderItem[0]);
					$scope.orderItems.splice(index,1);
				}
			}
			console.log('selected Items : ' + JSON.stringify($scope.orderItems));

		};

		// Create new Order
		$scope.create = function() {

			console.log('XXXX');
			if($scope.orderItems.length > 0) {
				//use $resource to create Order for Customer

				var total = 0.0;
				$scope.orderItems.forEach(function(entry){
					total += (entry.price * entry.quantity);
				});

				//var order = {orderItems : $scope.orderItems, orderTotal : total};
                //
				//console.log('Will create an Order for : ' + JSON.stringify(order));
				console.log('about to persist new Order');

				var persistedOrder = new Orders({
					customerId: $stateParams.customerId, orderItems : $scope.orderItems, total : total
				});

				persistedOrder.$save(function(response) {
					$location.path('customers/' + response._id);
					console.log('successfully persisted order..');
					// Clear form fields
//					$scope.forename = '';
				}, function(errorResponse) {
					$scope.error = errorResponse.data.message;
				});
			}
		};

		// Remove existing Order
		$scope.remove = function( orderId) {
			console.log('about to delete - ' + orderId);
			//if ( customer ) { customer.$remove();
            //
			//	for (var i in $scope.customers ) {
			//		if ($scope.customers [i] === customer ) {
			//			$scope.customers.splice(i, 1);
			//		}
			//	}
			//} else {
			//	$scope.customer.$remove(function() {
			//		$location.path('customers');
			//	});
			//}
				Orders.remove({customerId : $stateParams.customerId, orderId:orderId}, function(err) {
					if(err) console.log('Error experienced deleting orderId: ' + JSON.stringify(err));
//					$location.path('customers/' + response._id);
//					$location.path('/customers/'+$stateParams.customerId+'/order/list');
					$location.path('/customers/'+$stateParams.customerId);
				});
		};

		/**
		 * Update existing Order
		 * Note that this is called from the edit-order.view.html page where
		 * the findOne has already been called and so $scope.order is correctly
		 * populated with the updated order.
		 */
		$scope.update = function() {

			console.log('Updating order - ' + JSON.stringify($scope.order) );

			if($scope.order) {

				var total = 0.0;
				$scope.order.orderItems.forEach(function(entry){
					total += (entry.item.price * entry.quantity);

					//TODO : perform depopluation() at the server and not the client
					//replace item definition with just the item._id. The schema defines item to be of type ObjectId
					//however when we pulled the Customer object from the database, we used 'populate' to repopulate
					//with the item object. So change item value to it's id.
					console.log('[A] item: ' + entry.item);
					console.log('[B] item: ' + entry.item._id);
//					entry.item = entry.item._id;
				});

				console.log('about to persist updated Order');

				$scope.order.total = total;
				var persistedOrder = new Orders({
					customerId: $stateParams.customerId, orderId : $stateParams.orderId, order : $scope.order
				});

				persistedOrder.$update(function(response) {
					console.log('successfully persisted order..Now navigateing to /customers/' + response._id);

					$location.path('customers/' + response._id);
					// Clear form fields
//					$scope.forename = '';
				}, function(errorResponse) {
					$scope.error = errorResponse.data.message;
				});

			}
			/*
			if($scope.orderItems.length > 0) {
				//use $resource to create Order for Customer

				var total = 0.0;
				$scope.orderItems.forEach(function(entry){
					total += (entry.price * entry.quantity);
				});

				//var order = {orderItems : $scope.orderItems, orderTotal : total};
				//
				//console.log('Will create an Order for : ' + JSON.stringify(order));
				console.log('about to persist updated Order');

				var persistedOrder = new Orders({
					customerId: $stateParams.customerId, orderId : $stateParams.orderId, orderItems : $scope.orderItems, total : total
				});

				persistedOrder.$update(function(response) {
					$location.path('customers/' + response._id);
					console.log('successfully persisted order..');
					// Clear form fields
//					$scope.forename = '';
				}, function(errorResponse) {
					$scope.error = errorResponse.data.message;
				});
			}
			*/

			//var customer = $scope.customer ;
            //
			//customer.$update(function() {
			//	$location.path('customers/' + customer._id);
			//}, function(errorResponse) {
			//	$scope.error = errorResponse.data.message;
			//});
		};

		// Find a list of Orders
		$scope.find = function() {

			console.log('OrderController#find()....');
			$scope.customerId= $stateParams.customerId;

			////first get Customer - will need to display some info about customer
			//$scope.customer = Customers.get({
			//	customerId: $stateParams.customerId
			//}, function(err){

				//now query for orders
				$scope.orders = Orders.query({customerId:$stateParams.customerId}, function(err, data){
					console.log('retrieved orders for customer: ' + $stateParams.customerId);
					console.log('results: ' + JSON.stringify(data));
				});

			//});

			//$scope.orders = Orders.query({customerId:$stateParams.customerId}, function(err, data){
			//	console.log('retrieved orders for customer: ' + $stateParams.customerId);
			//	console.log('results: ' + JSON.stringify(data));
			//});
		};

		// Find existing Order
		$scope.findOne = function() {
			var customerId = $stateParams.customerId;
			var orderId = $stateParams.orderId;

			console.log('OrderController#findOne()....customer: ' + customerId + ' order: ' + orderId);

			//generates following http request
			//http://localhost:3000/customers/54b8ead1dd050becddbc6360/orders/54b8eae3dd050becddbc6361

			$scope.order = Orders.get({customerId:customerId, orderId:orderId}, function(err){
				console.log('retrived order: ' + JSON.stringify($scope.order));
			});
			//$scope.customer = Customers.get({
			//	customerId: $stateParams.customerId
			//});
		};
	}
]);
<commit_msg>fixed defect to do with removing items from shopping list<commit_after>'use strict';

// Customers controller
angular.module('customers').controller('CustomersController', ['$scope', '$stateParams', '$location', 'Authentication', 'Customers',
	function($scope, $stateParams, $location, Authentication, Customers ) {
		$scope.authentication = Authentication;

		// Create new Customer
		$scope.create = function() {
			var personalDetails = {forename:''};
			// Create new Customer object
			var customer = new Customers ({
//				name: this.name
				personalDetails : {
					forename : this.forename,
					surname : this.surname,
					dob : this.dob
								  },
				addressDetails : {
					firstLine : this.firstLine,
					city : this.city,
					postCode : this.postCode
				},
				phoneDetails : {
					office : this.office,
					home : this.home,
					mobile : this.mobile
				}
			});

			// Redirect after save
			customer.$save(function(response) {
				$location.path('customers/' + response._id);

				// Clear form fields
				$scope.forename = '';
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Remove existing Customer
		$scope.remove = function( customer ) {
			if ( customer ) { customer.$remove();

				for (var i in $scope.customers ) {
					if ($scope.customers [i] === customer ) {
						$scope.customers.splice(i, 1);
					}
				}
			} else {
				$scope.customer.$remove(function() {
					$location.path('customers');
				});
			}
		};

		// Update existing Customer
		$scope.update = function() {
			var customer = $scope.customer ;

			customer.$update(function() {
				$location.path('customers/' + customer._id);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Find a list of Customers
		$scope.find = function() {
			$scope.customers = Customers.query();
		};

		// Find existing Customer
		$scope.findOne = function() {
			$scope.customer = Customers.get({
				customerId: $stateParams.customerId
			});
		};
	}
]);
//=========================================================================
// Customers controller
angular.module('customers').controller('OrdersController', ['$scope', '$stateParams', '$location', 'Authentication', 'Customers', 'Items', 'Orders',
	function($scope, $stateParams, $location, Authentication, Customers, Items, Orders ) {
		$scope.authentication = Authentication;

		console.log('[OrdersController : orderId = ' + $stateParams.orderId);
		if($stateParams.orderId) { // this kicks in when we land on the edit-order.client.view.html page
			var customerId = $stateParams.customerId;

			//retrieve order items
			var orderId = $stateParams.orderId;

			console.log('OrderController#initialise....customer: ' + customerId + ' order: ' + orderId);

			//generates following http request
			//http://localhost:3000/customers/54b8ead1dd050becddbc6360/orders/54b8eae3dd050becddbc6361

			$scope.order = Orders.get({customerId:customerId, orderId:orderId}, function(err){
				console.log('retrived order: ' + JSON.stringify($scope.order));
				$scope.orderItems = $scope.order.orderItems;
			});

		} else { // this kicks in when we land on any other page ie. create-order.client.view.html
			$scope.orderItems = [];
		}
		/**
		 * Find all items that can be purchased. display this in the view
		 * and user can make selections using addORderItem/removeOrderItem
		 */
		$scope.findAllItems = function() {
			console.log('{create order1 : customer = ' + $stateParams.customerId);

			$scope.customer = Customers.get({
				customerId : $stateParams.customerId
			}, function(){
				console.log('{create order2 : customer = ' + $stateParams.customerId);
				$scope.items = Items.query();
				console.log('{create order : items = ' + JSON.stringify($scope.items));
			});

		};

		/**
		 * called by add OrderItem button in view
		 * @param selectedItem The item selected by the user to be added to the cart
		 */
		$scope.addOrderItem = function(selectedItem) {

			if(!Array.prototype.filter) {
				console.log('WARNING:::: filter not supported');
			}
			//find element in array that matches the 'selectedItem'
			var orderItem = $scope.orderItems.filter(function(obj){
				return obj.item._id === selectedItem._id;
			});

			console.log(' found item : ' + JSON.stringify(orderItem));
			if(orderItem[0]) {
				console.log('found item will increment quantity');
				orderItem[0].quantity += 1;
			} else {
				var newOrderItem = { item: this.item, quantity : 1 };
				$scope.orderItems.push(newOrderItem);
			}

			console.log('[CCC] selected Items : ' + JSON.stringify($scope.orderItems));
		};

		/**
		 * called by remove OrderItem button in view
		 * @param selectedOrderItem The item the user wants to remove from the order.
		 */
		$scope.removeOrderItem = function(selectedOrderItem) {

			if(!Array.prototype.filter) {
				console.log('WARNING:::: filter not supported');
			}
			//find element in array that needs to be removed
			var orderItem = $scope.orderItems.filter(function(obj){
//				return obj.id === selectedOrderItem.id;
				return obj.item._id === selectedOrderItem.item._id;
			});

			//console.log(' selected item : ' + JSON.stringify(selectedOrderItem));
			//console.log(' found item : ' + JSON.stringify(orderItem));
			console.log('[X] selected item : ' + JSON.stringify(selectedOrderItem));
			console.log('[Y] found item : ' + JSON.stringify(orderItem));
//			console.log('[Y] found item : ' + JSON.stringify(orderItem));

			if(orderItem[0]) {
				console.log('found item will decrement quantity');
				orderItem[0].quantity -= 1;
				if(orderItem[0].quantity <= 0){
					console.log('will remove OrderItem');
					var index = $scope.orderItems.indexOf(orderItem[0]);
					$scope.orderItems.splice(index,1);
				}
			}
			console.log('selected Items : ' + JSON.stringify($scope.orderItems));

		};

		// Create new Order
		$scope.create = function() {

			console.log('XXXX');
			if($scope.orderItems.length > 0) {
				//use $resource to create Order for Customer

				var total = 0.0;
				$scope.orderItems.forEach(function(entry){
					total += (entry.price * entry.quantity);
				});

				//var order = {orderItems : $scope.orderItems, orderTotal : total};
                //
				//console.log('Will create an Order for : ' + JSON.stringify(order));
				console.log('about to persist new Order');

				var persistedOrder = new Orders({
					customerId: $stateParams.customerId, orderItems : $scope.orderItems, total : total
				});

				persistedOrder.$save(function(response) {
					$location.path('customers/' + response._id);
					console.log('successfully persisted order..');
					// Clear form fields
//					$scope.forename = '';
				}, function(errorResponse) {
					$scope.error = errorResponse.data.message;
				});
			}
		};

		// Remove existing Order
		$scope.remove = function( orderId) {
			console.log('about to delete - ' + orderId);
			//if ( customer ) { customer.$remove();
            //
			//	for (var i in $scope.customers ) {
			//		if ($scope.customers [i] === customer ) {
			//			$scope.customers.splice(i, 1);
			//		}
			//	}
			//} else {
			//	$scope.customer.$remove(function() {
			//		$location.path('customers');
			//	});
			//}
				Orders.remove({customerId : $stateParams.customerId, orderId:orderId}, function(err) {
					if(err) console.log('Error experienced deleting orderId: ' + JSON.stringify(err));
//					$location.path('customers/' + response._id);
//					$location.path('/customers/'+$stateParams.customerId+'/order/list');
					$location.path('/customers/'+$stateParams.customerId);
				});
		};

		/**
		 * Update existing Order
		 * Note that this is called from the edit-order.view.html page where
		 * the findOne has already been called and so $scope.order is correctly
		 * populated with the updated order.
		 */
		$scope.update = function() {

			console.log('Updating order - ' + JSON.stringify($scope.order) );

			if($scope.order) {

				var total = 0.0;
				$scope.order.orderItems.forEach(function(entry){
					total += (entry.item.price * entry.quantity);

					//TODO : perform depopluation() at the server and not the client
					//replace item definition with just the item._id. The schema defines item to be of type ObjectId
					//however when we pulled the Customer object from the database, we used 'populate' to repopulate
					//with the item object. So change item value to it's id.
					console.log('[A] item: ' + entry.item);
					console.log('[B] item: ' + entry.item._id);
//					entry.item = entry.item._id;
				});

				console.log('about to persist updated Order');

				$scope.order.total = total;
				var persistedOrder = new Orders({
					customerId: $stateParams.customerId, orderId : $stateParams.orderId, order : $scope.order
				});

				persistedOrder.$update(function(response) {
					console.log('successfully persisted order..Now navigateing to /customers/' + response._id);

					$location.path('customers/' + response._id);
					// Clear form fields
//					$scope.forename = '';
				}, function(errorResponse) {
					$scope.error = errorResponse.data.message;
				});

			}
			/*
			if($scope.orderItems.length > 0) {
				//use $resource to create Order for Customer

				var total = 0.0;
				$scope.orderItems.forEach(function(entry){
					total += (entry.price * entry.quantity);
				});

				//var order = {orderItems : $scope.orderItems, orderTotal : total};
				//
				//console.log('Will create an Order for : ' + JSON.stringify(order));
				console.log('about to persist updated Order');

				var persistedOrder = new Orders({
					customerId: $stateParams.customerId, orderId : $stateParams.orderId, orderItems : $scope.orderItems, total : total
				});

				persistedOrder.$update(function(response) {
					$location.path('customers/' + response._id);
					console.log('successfully persisted order..');
					// Clear form fields
//					$scope.forename = '';
				}, function(errorResponse) {
					$scope.error = errorResponse.data.message;
				});
			}
			*/

			//var customer = $scope.customer ;
            //
			//customer.$update(function() {
			//	$location.path('customers/' + customer._id);
			//}, function(errorResponse) {
			//	$scope.error = errorResponse.data.message;
			//});
		};

		// Find a list of Orders
		$scope.find = function() {

			console.log('OrderController#find()....');
			$scope.customerId= $stateParams.customerId;

			////first get Customer - will need to display some info about customer
			//$scope.customer = Customers.get({
			//	customerId: $stateParams.customerId
			//}, function(err){

				//now query for orders
				$scope.orders = Orders.query({customerId:$stateParams.customerId}, function(err, data){
					console.log('retrieved orders for customer: ' + $stateParams.customerId);
					console.log('results: ' + JSON.stringify(data));
				});

			//});

			//$scope.orders = Orders.query({customerId:$stateParams.customerId}, function(err, data){
			//	console.log('retrieved orders for customer: ' + $stateParams.customerId);
			//	console.log('results: ' + JSON.stringify(data));
			//});
		};

		// Find existing Order
		$scope.findOne = function() {
			var customerId = $stateParams.customerId;
			var orderId = $stateParams.orderId;

			console.log('OrderController#findOne()....customer: ' + customerId + ' order: ' + orderId);

			//generates following http request
			//http://localhost:3000/customers/54b8ead1dd050becddbc6360/orders/54b8eae3dd050becddbc6361

			$scope.order = Orders.get({customerId:customerId, orderId:orderId}, function(err){
				console.log('retrived order: ' + JSON.stringify($scope.order));
			});
			//$scope.customer = Customers.get({
			//	customerId: $stateParams.customerId
			//});
		};
	}
]);
<|endoftext|>


<commit_before>System.config({
  "transpiler": "babel",
  "babelOptions": {
    "optional": [
      "runtime"
    ]
  },
  "paths": {
    "*": "*.js",
    "github:*": "jspm_packages/github/*.js",
    "npm:*": "jspm_packages/npm/*.js"
  },
  "separateCSS": true
});

System.config({
  "map": {
    "angular": "npm:angular@1.4.1",
    "angular-animate": "npm:angular-animate@1.4.1",
    "angular-formly": "npm:angular-formly@6.15.2",
    "angular-hy-res": "npm:angular-hy-res@0.0.23",
    "angular-mocks": "github:angular/bower-angular-mocks@1.4.1",
    "api-check": "npm:api-check@7.5.0",
    "babel": "npm:babel-core@5.6.5",
    "babel-runtime": "npm:babel-runtime@5.6.5",
    "clean-css": "npm:clean-css@3.3.4",
    "core-js": "npm:core-js@0.9.18",
    "css": "github:systemjs/plugin-css@0.1.13",
    "es6-promise": "npm:es6-promise@2.3.0",
    "lodash": "npm:lodash@3.9.3",
    "ng-promise-status": "npm:ng-promise-status@0.1.2",
    "text": "github:systemjs/plugin-text@0.0.2",
    "github:angular/bower-angular-mocks@1.4.1": {
      "angular": "github:angular/bower-angular@1.4.1"
    },
    "github:jspm/nodelibs-assert@0.1.0": {
      "assert": "npm:assert@1.3.0"
    },
    "github:jspm/nodelibs-buffer@0.1.0": {
      "buffer": "npm:buffer@3.2.2"
    },
    "github:jspm/nodelibs-events@0.1.1": {
      "events": "npm:events@1.0.2"
    },
    "github:jspm/nodelibs-http@1.7.1": {
      "Base64": "npm:Base64@0.2.1",
      "events": "github:jspm/nodelibs-events@0.1.1",
      "inherits": "npm:inherits@2.0.1",
      "stream": "github:jspm/nodelibs-stream@0.1.0",
      "url": "github:jspm/nodelibs-url@0.1.0",
      "util": "github:jspm/nodelibs-util@0.1.0"
    },
    "github:jspm/nodelibs-https@0.1.0": {
      "https-browserify": "npm:https-browserify@0.0.0"
    },
    "github:jspm/nodelibs-os@0.1.0": {
      "os-browserify": "npm:os-browserify@0.1.2"
    },
    "github:jspm/nodelibs-path@0.1.0": {
      "path-browserify": "npm:path-browserify@0.0.0"
    },
    "github:jspm/nodelibs-process@0.1.1": {
      "process": "npm:process@0.10.1"
    },
    "github:jspm/nodelibs-stream@0.1.0": {
      "stream-browserify": "npm:stream-browserify@1.0.0"
    },
    "github:jspm/nodelibs-url@0.1.0": {
      "url": "npm:url@0.10.3"
    },
    "github:jspm/nodelibs-util@0.1.0": {
      "util": "npm:util@0.10.3"
    },
    "github:systemjs/plugin-css@0.1.12": {
      "clean-css": "npm:clean-css@3.1.9",
      "fs": "github:jspm/nodelibs-fs@0.1.2",
      "path": "github:jspm/nodelibs-path@0.1.0"
    },
    "npm:URIjs@1.15.1": {
      "process": "github:jspm/nodelibs-process@0.1.1"
    },
    "npm:amdefine@0.1.1": {
      "fs": "github:jspm/nodelibs-fs@0.1.2",
      "module": "github:jspm/nodelibs-module@0.1.0",
      "path": "github:jspm/nodelibs-path@0.1.0",
      "process": "github:jspm/nodelibs-process@0.1.1"
    },
    "npm:angular-formly@6.15.1": {
      "angular": "npm:angular@1.4.1",
      "path": "github:jspm/nodelibs-path@0.1.0"
    },
    "npm:angular-formly@6.15.2": {
      "angular": "npm:angular@1.4.1",
      "path": "github:jspm/nodelibs-path@0.1.0"
    },
    "npm:angular-hy-res@0.0.23": {
      "angular": "npm:angular@1.4.1",
      "hy-res": "npm:hy-res@0.0.16",
      "process": "github:jspm/nodelibs-process@0.1.1",
      "systemjs-json": "github:systemjs/plugin-json@0.1.0"
    },
    "npm:angular@1.4.1": {
      "process": "github:jspm/nodelibs-process@0.1.1"
    },
    "npm:assert@1.3.0": {
      "util": "npm:util@0.10.3"
    },
    "npm:babel-runtime@5.5.8": {
      "process": "github:jspm/nodelibs-process@0.1.1"
    },
    "npm:babel-runtime@5.6.3": {
      "process": "github:jspm/nodelibs-process@0.1.1"
    },
    "npm:babel-runtime@5.6.5": {
      "process": "github:jspm/nodelibs-process@0.1.1"
    },
    "npm:buffer@3.2.2": {
      "base64-js": "npm:base64-js@0.0.8",
      "ieee754": "npm:ieee754@1.1.6",
      "is-array": "npm:is-array@1.0.1"
    },
    "npm:clean-css@3.1.9": {
      "buffer": "github:jspm/nodelibs-buffer@0.1.0",
      "commander": "npm:commander@2.6.0",
      "fs": "github:jspm/nodelibs-fs@0.1.2",
      "http": "github:jspm/nodelibs-http@1.7.1",
      "https": "github:jspm/nodelibs-https@0.1.0",
      "os": "github:jspm/nodelibs-os@0.1.0",
      "path": "github:jspm/nodelibs-path@0.1.0",
      "process": "github:jspm/nodelibs-process@0.1.1",
      "source-map": "npm:source-map@0.1.43",
      "url": "github:jspm/nodelibs-url@0.1.0",
      "util": "github:jspm/nodelibs-util@0.1.0"
    },
    "npm:clean-css@3.3.4": {
      "buffer": "github:jspm/nodelibs-buffer@0.1.0",
      "commander": "npm:commander@2.8.1",
      "fs": "github:jspm/nodelibs-fs@0.1.2",
      "http": "github:jspm/nodelibs-http@1.7.1",
      "https": "github:jspm/nodelibs-https@0.1.0",
      "os": "github:jspm/nodelibs-os@0.1.0",
      "path": "github:jspm/nodelibs-path@0.1.0",
      "process": "github:jspm/nodelibs-process@0.1.1",
      "source-map": "npm:source-map@0.4.2",
      "url": "github:jspm/nodelibs-url@0.1.0",
      "util": "github:jspm/nodelibs-util@0.1.0"
    },
    "npm:commander@2.6.0": {
      "child_process": "github:jspm/nodelibs-child_process@0.1.0",
      "events": "github:jspm/nodelibs-events@0.1.1",
      "path": "github:jspm/nodelibs-path@0.1.0",
      "process": "github:jspm/nodelibs-process@0.1.1"
    },
    "npm:commander@2.8.1": {
      "child_process": "github:jspm/nodelibs-child_process@0.1.0",
      "events": "github:jspm/nodelibs-events@0.1.1",
      "fs": "github:jspm/nodelibs-fs@0.1.2",
      "graceful-readlink": "npm:graceful-readlink@1.0.1",
      "path": "github:jspm/nodelibs-path@0.1.0",
      "process": "github:jspm/nodelibs-process@0.1.1"
    },
    "npm:core-js@0.9.18": {
      "fs": "github:jspm/nodelibs-fs@0.1.2",
      "process": "github:jspm/nodelibs-process@0.1.1"
    },
    "npm:core-util-is@1.0.1": {
      "buffer": "github:jspm/nodelibs-buffer@0.1.0"
    },
    "npm:es6-promise@2.3.0": {
      "assert": "github:jspm/nodelibs-assert@0.1.0",
      "process": "github:jspm/nodelibs-process@0.1.1",
      "util": "github:jspm/nodelibs-util@0.1.0"
    },
    "npm:graceful-readlink@1.0.1": {
      "fs": "github:jspm/nodelibs-fs@0.1.2"
    },
    "npm:https-browserify@0.0.0": {
      "http": "github:jspm/nodelibs-http@1.7.1"
    },
    "npm:hy-res@0.0.16": {
      "URIjs": "npm:URIjs@1.15.1",
      "form-urlencoded": "npm:form-urlencoded@0.0.7",
      "http-link": "npm:http-link@0.3.0",
      "lodash": "npm:lodash@3.9.3",
      "process": "github:jspm/nodelibs-process@0.1.1",
      "systemjs-json": "github:systemjs/plugin-json@0.1.0"
    },
    "npm:inherits@2.0.1": {
      "util": "github:jspm/nodelibs-util@0.1.0"
    },
    "npm:lodash@3.9.3": {
      "process": "github:jspm/nodelibs-process@0.1.1"
    },
    "npm:ng-promise-status@0.1.2": {
      "fs": "github:jspm/nodelibs-fs@0.1.2",
      "process": "github:jspm/nodelibs-process@0.1.1"
    },
    "npm:os-browserify@0.1.2": {
      "os": "github:jspm/nodelibs-os@0.1.0"
    },
    "npm:path-browserify@0.0.0": {
      "process": "github:jspm/nodelibs-process@0.1.1"
    },
    "npm:punycode@1.3.2": {
      "process": "github:jspm/nodelibs-process@0.1.1"
    },
    "npm:readable-stream@1.1.13": {
      "buffer": "github:jspm/nodelibs-buffer@0.1.0",
      "core-util-is": "npm:core-util-is@1.0.1",
      "events": "github:jspm/nodelibs-events@0.1.1",
      "inherits": "npm:inherits@2.0.1",
      "isarray": "npm:isarray@0.0.1",
      "process": "github:jspm/nodelibs-process@0.1.1",
      "stream": "github:jspm/nodelibs-stream@0.1.0",
      "stream-browserify": "npm:stream-browserify@1.0.0",
      "string_decoder": "npm:string_decoder@0.10.31",
      "util": "github:jspm/nodelibs-util@0.1.0"
    },
    "npm:source-map@0.1.43": {
      "amdefine": "npm:amdefine@0.1.1",
      "fs": "github:jspm/nodelibs-fs@0.1.2",
      "path": "github:jspm/nodelibs-path@0.1.0",
      "process": "github:jspm/nodelibs-process@0.1.1"
    },
    "npm:source-map@0.4.2": {
      "amdefine": "npm:amdefine@0.1.1",
      "fs": "github:jspm/nodelibs-fs@0.1.2",
      "path": "github:jspm/nodelibs-path@0.1.0",
      "process": "github:jspm/nodelibs-process@0.1.1"
    },
    "npm:stream-browserify@1.0.0": {
      "events": "github:jspm/nodelibs-events@0.1.1",
      "inherits": "npm:inherits@2.0.1",
      "readable-stream": "npm:readable-stream@1.1.13"
    },
    "npm:string_decoder@0.10.31": {
      "buffer": "github:jspm/nodelibs-buffer@0.1.0"
    },
    "npm:url@0.10.3": {
      "assert": "github:jspm/nodelibs-assert@0.1.0",
      "punycode": "npm:punycode@1.3.2",
      "querystring": "npm:querystring@0.2.0",
      "util": "github:jspm/nodelibs-util@0.1.0"
    },
    "npm:util@0.10.3": {
      "inherits": "npm:inherits@2.0.1",
      "process": "github:jspm/nodelibs-process@0.1.1"
    }
  }
});

<commit_msg>dl-loader update<commit_after>System.config({
  "transpiler": "babel",
  "babelOptions": {
    "optional": [
      "runtime"
    ]
  },
  "paths": {
    "*": "*.js",
    "github:*": "jspm_packages/github/*.js",
    "npm:*": "jspm_packages/npm/*.js"
  },
  "separateCSS": true
});

System.config({
  "map": {
    "angular": "npm:angular@1.4.1",
    "angular-animate": "npm:angular-animate@1.4.1",
    "angular-formly": "npm:angular-formly@6.16.0",
    "angular-hy-res": "npm:angular-hy-res@0.0.23",
    "angular-mocks": "github:angular/bower-angular-mocks@1.4.1",
    "api-check": "npm:api-check@7.5.0",
    "babel": "npm:babel-core@5.6.11",
    "babel-runtime": "npm:babel-runtime@5.6.11",
    "clean-css": "npm:clean-css@3.3.4",
    "core-js": "npm:core-js@0.9.18",
    "css": "github:systemjs/plugin-css@0.1.13",
    "es6-promise": "npm:es6-promise@2.3.0",
    "lodash": "npm:lodash@3.9.3",
    "ng-promise-status": "npm:ng-promise-status@0.1.2",
    "text": "github:systemjs/plugin-text@0.0.2",
    "github:angular/bower-angular-mocks@1.4.1": {
      "angular": "github:angular/bower-angular@1.4.1"
    },
    "github:jspm/nodelibs-assert@0.1.0": {
      "assert": "npm:assert@1.3.0"
    },
    "github:jspm/nodelibs-buffer@0.1.0": {
      "buffer": "npm:buffer@3.2.2"
    },
    "github:jspm/nodelibs-events@0.1.1": {
      "events": "npm:events@1.0.2"
    },
    "github:jspm/nodelibs-http@1.7.1": {
      "Base64": "npm:Base64@0.2.1",
      "events": "github:jspm/nodelibs-events@0.1.1",
      "inherits": "npm:inherits@2.0.1",
      "stream": "github:jspm/nodelibs-stream@0.1.0",
      "url": "github:jspm/nodelibs-url@0.1.0",
      "util": "github:jspm/nodelibs-util@0.1.0"
    },
    "github:jspm/nodelibs-https@0.1.0": {
      "https-browserify": "npm:https-browserify@0.0.0"
    },
    "github:jspm/nodelibs-os@0.1.0": {
      "os-browserify": "npm:os-browserify@0.1.2"
    },
    "github:jspm/nodelibs-path@0.1.0": {
      "path-browserify": "npm:path-browserify@0.0.0"
    },
    "github:jspm/nodelibs-process@0.1.1": {
      "process": "npm:process@0.10.1"
    },
    "github:jspm/nodelibs-stream@0.1.0": {
      "stream-browserify": "npm:stream-browserify@1.0.0"
    },
    "github:jspm/nodelibs-url@0.1.0": {
      "url": "npm:url@0.10.3"
    },
    "github:jspm/nodelibs-util@0.1.0": {
      "util": "npm:util@0.10.3"
    },
    "github:systemjs/plugin-css@0.1.12": {
      "clean-css": "npm:clean-css@3.1.9",
      "fs": "github:jspm/nodelibs-fs@0.1.2",
      "path": "github:jspm/nodelibs-path@0.1.0"
    },
    "npm:URIjs@1.15.1": {
      "process": "github:jspm/nodelibs-process@0.1.1"
    },
    "npm:amdefine@0.1.1": {
      "fs": "github:jspm/nodelibs-fs@0.1.2",
      "module": "github:jspm/nodelibs-module@0.1.0",
      "path": "github:jspm/nodelibs-path@0.1.0",
      "process": "github:jspm/nodelibs-process@0.1.1"
    },
    "npm:angular-formly@6.15.1": {
      "angular": "npm:angular@1.4.1",
      "path": "github:jspm/nodelibs-path@0.1.0"
    },
    "npm:angular-formly@6.15.2": {
      "angular": "npm:angular@1.4.1",
      "path": "github:jspm/nodelibs-path@0.1.0"
    },
    "npm:angular-formly@6.16.0": {
      "angular": "npm:angular@1.4.1",
      "path": "github:jspm/nodelibs-path@0.1.0"
    },
    "npm:angular-hy-res@0.0.23": {
      "angular": "npm:angular@1.4.1",
      "hy-res": "npm:hy-res@0.0.16",
      "process": "github:jspm/nodelibs-process@0.1.1",
      "systemjs-json": "github:systemjs/plugin-json@0.1.0"
    },
    "npm:angular@1.4.1": {
      "process": "github:jspm/nodelibs-process@0.1.1"
    },
    "npm:assert@1.3.0": {
      "util": "npm:util@0.10.3"
    },
    "npm:babel-runtime@5.5.8": {
      "process": "github:jspm/nodelibs-process@0.1.1"
    },
    "npm:babel-runtime@5.6.11": {
      "process": "github:jspm/nodelibs-process@0.1.1"
    },
    "npm:babel-runtime@5.6.3": {
      "process": "github:jspm/nodelibs-process@0.1.1"
    },
    "npm:babel-runtime@5.6.5": {
      "process": "github:jspm/nodelibs-process@0.1.1"
    },
    "npm:buffer@3.2.2": {
      "base64-js": "npm:base64-js@0.0.8",
      "ieee754": "npm:ieee754@1.1.6",
      "is-array": "npm:is-array@1.0.1"
    },
    "npm:clean-css@3.1.9": {
      "buffer": "github:jspm/nodelibs-buffer@0.1.0",
      "commander": "npm:commander@2.6.0",
      "fs": "github:jspm/nodelibs-fs@0.1.2",
      "http": "github:jspm/nodelibs-http@1.7.1",
      "https": "github:jspm/nodelibs-https@0.1.0",
      "os": "github:jspm/nodelibs-os@0.1.0",
      "path": "github:jspm/nodelibs-path@0.1.0",
      "process": "github:jspm/nodelibs-process@0.1.1",
      "source-map": "npm:source-map@0.1.43",
      "url": "github:jspm/nodelibs-url@0.1.0",
      "util": "github:jspm/nodelibs-util@0.1.0"
    },
    "npm:clean-css@3.3.4": {
      "buffer": "github:jspm/nodelibs-buffer@0.1.0",
      "commander": "npm:commander@2.8.1",
      "fs": "github:jspm/nodelibs-fs@0.1.2",
      "http": "github:jspm/nodelibs-http@1.7.1",
      "https": "github:jspm/nodelibs-https@0.1.0",
      "os": "github:jspm/nodelibs-os@0.1.0",
      "path": "github:jspm/nodelibs-path@0.1.0",
      "process": "github:jspm/nodelibs-process@0.1.1",
      "source-map": "npm:source-map@0.4.2",
      "url": "github:jspm/nodelibs-url@0.1.0",
      "util": "github:jspm/nodelibs-util@0.1.0"
    },
    "npm:commander@2.6.0": {
      "child_process": "github:jspm/nodelibs-child_process@0.1.0",
      "events": "github:jspm/nodelibs-events@0.1.1",
      "path": "github:jspm/nodelibs-path@0.1.0",
      "process": "github:jspm/nodelibs-process@0.1.1"
    },
    "npm:commander@2.8.1": {
      "child_process": "github:jspm/nodelibs-child_process@0.1.0",
      "events": "github:jspm/nodelibs-events@0.1.1",
      "fs": "github:jspm/nodelibs-fs@0.1.2",
      "graceful-readlink": "npm:graceful-readlink@1.0.1",
      "path": "github:jspm/nodelibs-path@0.1.0",
      "process": "github:jspm/nodelibs-process@0.1.1"
    },
    "npm:core-js@0.9.18": {
      "fs": "github:jspm/nodelibs-fs@0.1.2",
      "process": "github:jspm/nodelibs-process@0.1.1"
    },
    "npm:core-util-is@1.0.1": {
      "buffer": "github:jspm/nodelibs-buffer@0.1.0"
    },
    "npm:es6-promise@2.3.0": {
      "assert": "github:jspm/nodelibs-assert@0.1.0",
      "process": "github:jspm/nodelibs-process@0.1.1",
      "util": "github:jspm/nodelibs-util@0.1.0"
    },
    "npm:graceful-readlink@1.0.1": {
      "fs": "github:jspm/nodelibs-fs@0.1.2"
    },
    "npm:https-browserify@0.0.0": {
      "http": "github:jspm/nodelibs-http@1.7.1"
    },
    "npm:hy-res@0.0.16": {
      "URIjs": "npm:URIjs@1.15.1",
      "form-urlencoded": "npm:form-urlencoded@0.0.7",
      "http-link": "npm:http-link@0.3.0",
      "lodash": "npm:lodash@3.9.3",
      "process": "github:jspm/nodelibs-process@0.1.1",
      "systemjs-json": "github:systemjs/plugin-json@0.1.0"
    },
    "npm:inherits@2.0.1": {
      "util": "github:jspm/nodelibs-util@0.1.0"
    },
    "npm:lodash@3.9.3": {
      "process": "github:jspm/nodelibs-process@0.1.1"
    },
    "npm:ng-promise-status@0.1.2": {
      "fs": "github:jspm/nodelibs-fs@0.1.2",
      "process": "github:jspm/nodelibs-process@0.1.1"
    },
    "npm:os-browserify@0.1.2": {
      "os": "github:jspm/nodelibs-os@0.1.0"
    },
    "npm:path-browserify@0.0.0": {
      "process": "github:jspm/nodelibs-process@0.1.1"
    },
    "npm:punycode@1.3.2": {
      "process": "github:jspm/nodelibs-process@0.1.1"
    },
    "npm:readable-stream@1.1.13": {
      "buffer": "github:jspm/nodelibs-buffer@0.1.0",
      "core-util-is": "npm:core-util-is@1.0.1",
      "events": "github:jspm/nodelibs-events@0.1.1",
      "inherits": "npm:inherits@2.0.1",
      "isarray": "npm:isarray@0.0.1",
      "process": "github:jspm/nodelibs-process@0.1.1",
      "stream": "github:jspm/nodelibs-stream@0.1.0",
      "stream-browserify": "npm:stream-browserify@1.0.0",
      "string_decoder": "npm:string_decoder@0.10.31",
      "util": "github:jspm/nodelibs-util@0.1.0"
    },
    "npm:source-map@0.1.43": {
      "amdefine": "npm:amdefine@0.1.1",
      "fs": "github:jspm/nodelibs-fs@0.1.2",
      "path": "github:jspm/nodelibs-path@0.1.0",
      "process": "github:jspm/nodelibs-process@0.1.1"
    },
    "npm:source-map@0.4.2": {
      "amdefine": "npm:amdefine@0.1.1",
      "fs": "github:jspm/nodelibs-fs@0.1.2",
      "path": "github:jspm/nodelibs-path@0.1.0",
      "process": "github:jspm/nodelibs-process@0.1.1"
    },
    "npm:stream-browserify@1.0.0": {
      "events": "github:jspm/nodelibs-events@0.1.1",
      "inherits": "npm:inherits@2.0.1",
      "readable-stream": "npm:readable-stream@1.1.13"
    },
    "npm:string_decoder@0.10.31": {
      "buffer": "github:jspm/nodelibs-buffer@0.1.0"
    },
    "npm:url@0.10.3": {
      "assert": "github:jspm/nodelibs-assert@0.1.0",
      "punycode": "npm:punycode@1.3.2",
      "querystring": "npm:querystring@0.2.0",
      "util": "github:jspm/nodelibs-util@0.1.0"
    },
    "npm:util@0.10.3": {
      "inherits": "npm:inherits@2.0.1",
      "process": "github:jspm/nodelibs-process@0.1.1"
    }
  }
});

<|endoftext|>


<commit_before>// @flow

import React, { Component, type Element } from 'react';
import styled from 'react-emotion';
import { createPortal } from 'react-dom';

import { borderRadius, gridSize } from '../../theme';
import FocusTrap from './FocusTrap';
import { SlideDown } from './transitions';
import withModalHandlers, { type CloseType } from './withModalHandlers';

const ARROW_WIDTH = 8;
const CHROME_GUTTER = 30;

const Wrapper = styled.div(({ left, top, width }) => {
  const placementStyles = { left, top, width };

  return {
    backgroundColor: 'white',
    borderRadius: borderRadius,
    boxShadow: '0 0 0 1px rgba(0, 0, 0, 0.175), 0 3px 8px rgba(0, 0, 0, 0.175)',
    marginTop: gridSize * 2,
    maxHeight: '100%',
    width: width,
    position: 'absolute',
    ...placementStyles,
  };
});
const WrapperInner = styled.div({
  padding: 1,
  position: 'relative',
});
const Arrow = styled.div`
  left: ${p => p.left};
  margin-left: -${ARROW_WIDTH}px;
  margin-top: -${ARROW_WIDTH + 1}px;
  position: absolute;

  &::before,
  &::after {
    border-left: ${ARROW_WIDTH}px solid transparent;
    border-right: ${ARROW_WIDTH}px solid transparent;
    border-bottom: ${ARROW_WIDTH}px dashed;
    content: '';
    display: inline-block;
    height: 0;
    left: 0;
    position: absolute;
    top: 0;
    width: 0;
  }

  &::before {
    border-bottom-color: rgba(0, 0, 0, 0.2);
    top: -1px;
  }

  &::after {
    border-bottom-color: white;
  }
`;

type Props = {
  children: Element<*>,
  close: CloseType,
  defaultIsOpen: boolean,
  getModalRef: HTMLElement => void,
  style: Object,
  target: Element<*>,
  targetNode: HTMLElement,
  width: number,
};

type State = { leftOffset: number, topOffset: number, arrowLeftOffset: string };

class Popout extends Component<Props, State> {
  wrapperNode: HTMLElement;
  state = { leftOffset: 0, topOffset: 0, arrowLeftOffset: '0' };
  static defaultProps = {
    width: 320,
  };

  componentDidMount() {
    window.addEventListener('resize', this.calculatePosition);
    this.calculatePosition();
  }
  componentWillUnmount() {
    window.removeEventListener('resize', this.calculatePosition);
  }

  calculatePosition = () => {
    const { targetNode, width } = this.props;

    if (!targetNode || !document.body) return;

    // prepare common values
    const bodyRect = document.body.getBoundingClientRect();
    const targetRect = targetNode.getBoundingClientRect();

    const targetCenter = targetRect.left + targetRect.width / 2;
    let leftOffset = Math.max(targetCenter - width / 2, CHROME_GUTTER);
    let topOffset = targetRect.bottom - bodyRect.top;
    let isAlignedRight = false;

    // handle right aligned
    const spaceOnRight =
      window.innerWidth - (leftOffset + width + CHROME_GUTTER);
    if (spaceOnRight < 0) {
      leftOffset = leftOffset + spaceOnRight;
      isAlignedRight = true;
    }

    // get arrow offset
    let arrowLeftOffset = '50%';
    if (leftOffset === CHROME_GUTTER) {
      arrowLeftOffset = `${targetCenter - ARROW_WIDTH / 2 - CHROME_GUTTER}px`;
    }
    if (isAlignedRight) {
      arrowLeftOffset = `${targetCenter - leftOffset}px`;
    }

    // avoid state thrashing
    const newStateAvaliable =
      this.state.leftOffset !== leftOffset ||
      this.state.topOffset !== topOffset ||
      this.state.arrowLeftOffset !== arrowLeftOffset;

    if (newStateAvaliable) {
      this.setState({ leftOffset, topOffset, arrowLeftOffset });
    }
  };

  render() {
    const { children, getModalRef, style, width } = this.props;
    let { leftOffset, topOffset, arrowLeftOffset } = this.state;

    return document.body
      ? createPortal(
          <Wrapper
            innerRef={getModalRef}
            left={leftOffset}
            top={topOffset}
            width={width}
            style={style} // style comes from Transition
          >
            <FocusTrap options={{ clickOutsideDeactivates: true }}>
              <WrapperInner>
                <Arrow left={arrowLeftOffset} />
                {children}
              </WrapperInner>
            </FocusTrap>
          </Wrapper>,
          document.body
        )
      : null;
  }
}

export default withModalHandlers(Popout, { Transition: SlideDown });
<commit_msg>fix popout layering<commit_after>// @flow

import React, { Component, type Element } from 'react';
import styled from 'react-emotion';
import { createPortal } from 'react-dom';

import { borderRadius, gridSize } from '../../theme';
import FocusTrap from './FocusTrap';
import { SlideDown } from './transitions';
import withModalHandlers, { type CloseType } from './withModalHandlers';

const ARROW_WIDTH = 8;
const CHROME_GUTTER = 30;

const Wrapper = styled.div(({ left, top, width }) => {
  const placementStyles = { left, top, width };

  return {
    backgroundColor: 'white',
    borderRadius: borderRadius,
    boxShadow: '0 0 0 1px rgba(0, 0, 0, 0.175), 0 3px 8px rgba(0, 0, 0, 0.175)',
    marginTop: gridSize * 2,
    maxHeight: '100%',
    width: width,
    position: 'absolute',
    zIndex: 2,
    ...placementStyles,
  };
});
const WrapperInner = styled.div({
  padding: 1,
  position: 'relative',
});
const Arrow = styled.div`
  left: ${p => p.left};
  margin-left: -${ARROW_WIDTH}px;
  margin-top: -${ARROW_WIDTH + 1}px;
  position: absolute;

  &::before,
  &::after {
    border-left: ${ARROW_WIDTH}px solid transparent;
    border-right: ${ARROW_WIDTH}px solid transparent;
    border-bottom: ${ARROW_WIDTH}px dashed;
    content: '';
    display: inline-block;
    height: 0;
    left: 0;
    position: absolute;
    top: 0;
    width: 0;
  }

  &::before {
    border-bottom-color: rgba(0, 0, 0, 0.2);
    top: -1px;
  }

  &::after {
    border-bottom-color: white;
  }
`;

type Props = {
  children: Element<*>,
  close: CloseType,
  defaultIsOpen: boolean,
  getModalRef: HTMLElement => void,
  style: Object,
  target: Element<*>,
  targetNode: HTMLElement,
  width: number,
};

type State = { leftOffset: number, topOffset: number, arrowLeftOffset: string };

class Popout extends Component<Props, State> {
  wrapperNode: HTMLElement;
  state = { leftOffset: 0, topOffset: 0, arrowLeftOffset: '0' };
  static defaultProps = {
    width: 320,
  };

  componentDidMount() {
    window.addEventListener('resize', this.calculatePosition);
    this.calculatePosition();
  }
  componentWillUnmount() {
    window.removeEventListener('resize', this.calculatePosition);
  }

  calculatePosition = () => {
    const { targetNode, width } = this.props;

    if (!targetNode || !document.body) return;

    // prepare common values
    const bodyRect = document.body.getBoundingClientRect();
    const targetRect = targetNode.getBoundingClientRect();

    const targetCenter = targetRect.left + targetRect.width / 2;
    let leftOffset = Math.max(targetCenter - width / 2, CHROME_GUTTER);
    let topOffset = targetRect.bottom - bodyRect.top;
    let isAlignedRight = false;

    // handle right aligned
    const spaceOnRight =
      window.innerWidth - (leftOffset + width + CHROME_GUTTER);
    if (spaceOnRight < 0) {
      leftOffset = leftOffset + spaceOnRight;
      isAlignedRight = true;
    }

    // get arrow offset
    let arrowLeftOffset = '50%';
    if (leftOffset === CHROME_GUTTER) {
      arrowLeftOffset = `${targetCenter - ARROW_WIDTH / 2 - CHROME_GUTTER}px`;
    }
    if (isAlignedRight) {
      arrowLeftOffset = `${targetCenter - leftOffset}px`;
    }

    // avoid state thrashing
    const newStateAvaliable =
      this.state.leftOffset !== leftOffset ||
      this.state.topOffset !== topOffset ||
      this.state.arrowLeftOffset !== arrowLeftOffset;

    if (newStateAvaliable) {
      this.setState({ leftOffset, topOffset, arrowLeftOffset });
    }
  };

  render() {
    const { children, getModalRef, style, width } = this.props;
    let { leftOffset, topOffset, arrowLeftOffset } = this.state;

    return document.body
      ? createPortal(
          <Wrapper
            innerRef={getModalRef}
            left={leftOffset}
            top={topOffset}
            width={width}
            style={style} // style comes from Transition
          >
            <FocusTrap options={{ clickOutsideDeactivates: true }}>
              <WrapperInner>
                <Arrow left={arrowLeftOffset} />
                {children}
              </WrapperInner>
            </FocusTrap>
          </Wrapper>,
          document.body
        )
      : null;
  }
}

export default withModalHandlers(Popout, { Transition: SlideDown });
<|endoftext|>


<commit_before>// # Ghost Configuration

var path = require('path');
var env = require('common-env')();

var config = env.getOrElseAll({
    production: {
        url: {
         $aliases: ['BLOG_URL']
        },
        mail: {
            transport: 'SMTP',
            options: {
                service: 'Mailgun',
                auth: {
                    user: {
                        $aliases: ['MAILGUN_SMTP_LOGIN']
                    },
                    pass: {
                        $aliases: ['MAILGUN_SMTP_PASSWORD']
                    }
                }
            }
        },
        database: {
            client: 'pg',
            connection: {
                host     : {
                    $aliases: ['POSTGRESQL_ADDON_HOST']
                },
                user     : {
                    $aliases: ['POSTGRESQL_ADDON_USER']
                },
                password : {
                    $aliases: ['POSTGRESQL_ADDON_PASSWORD']
                },
                database : {
                    $aliases: ['POSTGRESQL_ADDON_DB']
                },
            },
            charset  : 'utf8',
            pool: {
                min: {
                    $aliases: ['POSTGRESQL_ADDON_MIN_CONNECTIONS'],
                    $default: 1
                },
                max: {
                    $aliases: ['POSTGRESQL_ADDON_MAX_CONNECTIONS'],
                    $default: 3
                }
            }
        },
        fileStorage: false,
        storage: {
            active: 'cellar',
            cellar: {
                accessKeyId: {
                    $aliases: ['CELLAR_ADDON_KEY_ID']
                },
                secretAccessKey: {
                    $aliases: ['CELLAR_ADDON_KEY_SECRET']
                },
                bucket: {
                    $aliases: ['CELLAR_BUCKET']
                },
                host: {
                    $aliases: ['CELLAR_ADDON_HOST']
                }
            }
        },
        paths: {
            contentPath: path.join(__dirname, 'content'),
        },
        server: {
            host: '0.0.0.0',
            port: {
                $default: 8080,
                $aliases: ['PORT']
            }
        },
        logging: false
    }

});

module.exports = config;
<commit_msg>Remove the fileStorage disabling config<commit_after>// # Ghost Configuration

var path = require('path');
var env = require('common-env')();

var config = env.getOrElseAll({
    production: {
        url: {
         $aliases: ['BLOG_URL']
        },
        mail: {
            transport: 'SMTP',
            options: {
                service: 'Mailgun',
                auth: {
                    user: {
                        $aliases: ['MAILGUN_SMTP_LOGIN']
                    },
                    pass: {
                        $aliases: ['MAILGUN_SMTP_PASSWORD']
                    }
                }
            }
        },
        database: {
            client: 'pg',
            connection: {
                host     : {
                    $aliases: ['POSTGRESQL_ADDON_HOST']
                },
                user     : {
                    $aliases: ['POSTGRESQL_ADDON_USER']
                },
                password : {
                    $aliases: ['POSTGRESQL_ADDON_PASSWORD']
                },
                database : {
                    $aliases: ['POSTGRESQL_ADDON_DB']
                },
            },
            charset  : 'utf8',
            pool: {
                min: {
                    $aliases: ['POSTGRESQL_ADDON_MIN_CONNECTIONS'],
                    $default: 1
                },
                max: {
                    $aliases: ['POSTGRESQL_ADDON_MAX_CONNECTIONS'],
                    $default: 3
                }
            }
        },
        storage: {
            active: 'cellar',
            cellar: {
                accessKeyId: {
                    $aliases: ['CELLAR_ADDON_KEY_ID']
                },
                secretAccessKey: {
                    $aliases: ['CELLAR_ADDON_KEY_SECRET']
                },
                bucket: {
                    $aliases: ['CELLAR_BUCKET']
                },
                host: {
                    $aliases: ['CELLAR_ADDON_HOST']
                }
            }
        },
        paths: {
            contentPath: path.join(__dirname, 'content'),
        },
        server: {
            host: '0.0.0.0',
            port: {
                $default: 8080,
                $aliases: ['PORT']
            }
        },
        logging: false
    }

});

module.exports = config;
<|endoftext|>


<commit_before>var tape = require('tape'),
    venc = require('vega-encode'), // eslint-disable-line no-unused-vars
    vega = require('vega-dataflow'),
    runtime = require('../');

tape('Parser parses dataflow specs', function(test) {
  var values = [
    {"x": 1,  "y": 28},
    {"x": 2,  "y": 43},
    {"x": 3,  "y": 81},
    {"x": 4,  "y": 19}
  ];
  var spec = {operators: [
    {id:0, type:'Operator', value:500},
    {id:1, type:'Operator', value:300},
    {id:2, type:'Collect',  value:{$ingest: values}},
    {id:3, type:'Aggregate', params:{groupby:{$field:'x'}, pulse:{$ref:2}}},
    {id:4, type:'Values', params:{field:{$field:'x'}, pulse:{$ref:3}}},
    {id:5, type:'Scale', params:{type:'band', range:[0,{$ref:0}], domain:{$ref:4}}},
    {id:6, type:'Extent', params:{field:{$field:'y'}, pulse:{$ref:2}}},
    {id:7, type:'Scale', params:{type:'linear', range:[{$ref:1},0], domain:{$ref:6}}}
  ]};

  var df  = new vega.Dataflow(),
      ctx = runtime.parse(spec, runtime.context(df, vega.transforms)),
      ops = ctx.nodes;

  test.equal(Object.keys(ctx.fn).length, 2);
  test.equal(Object.keys(ops).length, spec.operators.length);
  test.equal(df.run(), spec.operators.length);

  test.equal(ops[0].value, 500);

  test.equal(ops[1].value, 300);

  test.equal(ops[2].value.length, values.length);

  test.equal(Object.keys(ops[3].value).length, values.length);

  test.deepEqual(ops[4].value, [1, 2, 3, 4]);

  var sx = ops[5].value;
  test.deepEqual(sx.domain(), [1, 2, 3, 4]);
  test.deepEqual(sx.range(), [0, 500]);

  test.deepEqual(ops[6].value, [19, 81]);

  var sy = ops[7].value;
  test.deepEqual(sy.domain(), [19, 81]);
  test.deepEqual(sy.range(), [300, 0]);

  test.end();
});
<commit_msg>Update tests to track dataflow revisions.<commit_after>var tape = require('tape'),
    venc = require('vega-encode'), // eslint-disable-line no-unused-vars
    vega = require('vega-dataflow'),
    runtime = require('../');

tape('Parser parses dataflow specs', function(test) {
  var values = [
    {"x": 1,  "y": 28},
    {"x": 2,  "y": 43},
    {"x": 3,  "y": 81},
    {"x": 4,  "y": 19},
    {"x": 4,  "y": 20}
  ];
  var spec = {operators: [
    {id:0, type:'Operator', value:500},
    {id:1, type:'Operator', value:300},
    {id:2, type:'Collect',  value:{$ingest: values}},
    {id:3, type:'Aggregate', params:{groupby:{$field:'x'}, pulse:{$ref:2}}},
    {id:4, type:'Collect',  params:{pulse:{$ref:3}}},
    {id:5, type:'Values', params:{field:{$field:'x'}, pulse:{$ref:4}}},
    {id:6, type:'Scale', params:{type:'band', range:[0,{$ref:0}], domain:{$ref:5}}},
    {id:7, type:'Extent', params:{field:{$field:'y'}, pulse:{$ref:2}}},
    {id:8, type:'Scale', params:{type:'linear', range:[{$ref:1},0], domain:{$ref:7}}}
  ]};

  var df  = new vega.Dataflow(),
      ctx = runtime.parse(spec, runtime.context(df, vega.transforms)),
      ops = ctx.nodes;

  test.equal(Object.keys(ctx.fn).length, 2);
  test.equal(Object.keys(ops).length, spec.operators.length);
  test.equal(df.run(), spec.operators.length);

  test.equal(ops[0].value, 500);

  test.equal(ops[1].value, 300);

  test.equal(ops[2].value.length, values.length);

  test.equal(Object.keys(ops[3].value).length, 4);

  test.deepEqual(ops[4].value.length, 4);

  test.deepEqual(ops[5].value, [1, 2, 3, 4]);

  var sx = ops[6].value;
  test.deepEqual(sx.domain(), [1, 2, 3, 4]);
  test.deepEqual(sx.range(), [0, 500]);

  test.deepEqual(ops[7].value, [19, 81]);

  var sy = ops[8].value;
  test.deepEqual(sy.domain(), [19, 81]);
  test.deepEqual(sy.range(), [300, 0]);

  test.end();
});
<|endoftext|>


<commit_before>tinyMCEPopup.requireLangPack();

var AddvideoDialog = {
	init : function() {
		var f = document.forms[0];

		// Get the selected contents as text and place it in the input
		f.videourl.value = tinyMCEPopup.editor.selection.getContent({format : 'text'});
		f.videtitle.value = tinyMCEPopup.editor.selection.getContent({format : 'text'});
	},

  insert : function() {
    // Insert the contents from the input into the document

    // VIDEO URL
    var url = document.forms[0].videourl.value;

    // VIDEO Title
    var title = document.forms[0].videotitle.value;

    // REGEXP
    var re=new RegExp(/[\\?\\&]v=([^\\?\\&]+)/);

    // VIDEO ID
    var videoid = re.exec(url);

    // Add Link and img to the body

    tinyMCEPopup.editor.execCommand('mceInsertContent', false, "");
    tinyMCEPopup.close();
  }
};

AddvideoDialog.init();
tinyMCEPopup.onInit.add(AddvideoDialog.init, AddvideoDialog);<commit_msg>updated addvideo plugin<commit_after>tinyMCEPopup.requireLangPack();

var AddvideoDialog = {
	init : function() {
		var f = document.forms[0];

		// Get the selected contents as text and place it in the input
		f.videourl.value = tinyMCEPopup.editor.selection.getContent({format : 'text'});
		f.videtitle.value = tinyMCEPopup.editor.selection.getContent({format : 'text'});
	},

  insert : function() {
    // Insert the contents from the input into the document

    // VIDEO URL
    var url = document.forms[0].videourl.value;

    // VIDEO Title
    var title = document.forms[0].videotitle.value;

    // REGEXP
    var re=new RegExp(/[\\?\\&]v=([^\\?\\&]+)/);

    // VIDEO ID
    var videoid = re.exec(url);

    // Add Link and img to the body

    tinyMCEPopup.editor.execCommand('mceInsertContent', false, "");
    tinyMCEPopup.close();
  }
};

AddvideoDialog.init();
tinyMCEPopup.onInit.add(AddvideoDialog.init, AddvideoDialog);<|endoftext|>