<commit_before>
    /**
     Make the DOM object look like a button
     */
    XF.ui.button = {

        // Selectors will be used to detect button's elements on the page
        selector : 'A[data-role=button], BUTTON, INPUT[type=submit], INPUT[type=reset], INPUT[type=button], [data-appearance=backbtn]',

        render : function (button, options) {
            var jQButton = $(button),
                enhancedButton,
                innerStuff;

            if (!button || !(jQButton instanceof $) || jQButton.attr('data-skip-enhance') == 'true') {
                return;
            }

            if (button.nodeName == 'A' || button.nodeName == 'BUTTON') {
                enhancedButton = jQButton.attr({'data-skip-enhance':true});
                innerStuff = jQButton.html();
                jQButton.html('');

                // If it's INPUT - it's wrapped in a DIV and the necessary classes are added to the DIV.
            } else if (button.nodeName == 'INPUT') {
                // The input is assigned a class xf-input-hidden
                enhancedButton = $('

').append(jQButton.clone().addClass('xf-input-hidden').attr({'data-skip-enhance':true}));

                if (jQButton.hasOwnProperty('outerHtml')) {
                    jQButton.outerHtml(enhancedButton);
                }
                innerStuff = jQButton.attr('value');
            } else {
                // how did U get there? o_O
                return;
            }

            var isSmall = (options.small && options.small === true ? true : options.appearance == 'backbtn' ? true : false),
                position = options.position || '',
                id = jQButton.attr('id') || XF.utils.uniqueID();

            if (position !== '') {
                enhancedButton.addClass('xf-button-float-' + position);
            }

            if (jQButton.parents(XF.ui.header.selector).length > 0) {
                var hposition = position || 'right';
                enhancedButton.addClass('xf-button-header-' + hposition);
                enhancedButton.addClass('xf-button-float-' + hposition);
            }

            // The class xf-button is added to the button.
            // If it has data-small="true" attribute, the class should be xf-button-small.
            enhancedButton.addClass(isSmall ? 'xf-button-small' : 'xf-button');

            // If data-appearance="backbtn" attribute is present, xf-button-back class is also added.
            if (options.appearance === 'backbtn') {
                enhancedButton.addClass('xf-button-back');
            }

            var iconName = options.icon;

            if (options.appearance === 'backbtn' /*&& !jQButton.attr('data-icon')*/) {
                iconName = 'left';
            }

            if (iconName) {

                // If data-icon attribute is present, a SPAN.xf-icon is added inside the button.
                var iconSpan = $('');

                // The value of data-icon attribute is used to generate icon class: e.g. xf-icon-dots.
                iconSpan.addClass('xf-icon-' + iconName);

                // If the button had data-small=true or data-appearance="backbtn" attributes,
                // xf-icon-small class is also added to SPAN.xf-icon
                if (isSmall) {
                    iconSpan.addClass('xf-icon-small');
                } else {
                    iconSpan.addClass('xf-icon-big');
                }

                // A class denoting icon position is also added to the button. Default: xf-iconpos-left.
                // The value is taken from data-iconpos attr.
                // Possible values: left, right, top, bottom.
                var iconPos = options.iconpos || 'left';

                if (iconPos != 'left' && iconPos != 'right' && iconPos != 'top' && iconPos != 'bottom') {
                    iconPos = 'left';
                }
                enhancedButton.addClass('xf-iconpos-' + iconPos);
                enhancedButton.append(iconSpan);

            }

            if (innerStuff) {
                var textSpan = $('').append(innerStuff);

                // The text of buttons is placed inside span.xf-button-small-text for small buttons
                if (isSmall || options.appearance == 'backbtn') {
                    textSpan.addClass('xf-button-small-text');
                    // and span.xf-button-text for big ones.
                } else {
                    textSpan.addClass('xf-button-text');
                }
                enhancedButton.append(textSpan);
            } else {

                if (isSmall) {
                    enhancedButton.addClass('xf-button-small-icon-only');
                }
            }

            // If data-special="true" attribute is present add xf-button-special class.
            if (options.special == true) {
                enhancedButton.addClass('xf-button-special');
            }

            // If data-alert="true" attribute is present add xf-button-alert class.
            if (options.alert == true) {
                enhancedButton.addClass('xf-button-alert');
            }

            enhancedButton.attr('id', id);
        }
    };
<commit_msg>UI options.small fixed<commit_after>
    /**
     Make the DOM object look like a button
     */
    XF.ui.button = {

        // Selectors will be used to detect button's elements on the page
        selector : 'A[data-role=button], BUTTON, INPUT[type=submit], INPUT[type=reset], INPUT[type=button], [data-appearance=backbtn]',

        render : function (button, options) {
            var jQButton = $(button),
                enhancedButton,
                innerStuff;

            if (!button || !(jQButton instanceof $) || jQButton.attr('data-skip-enhance') == 'true') {
                return;
            }

            if (button.nodeName == 'A' || button.nodeName == 'BUTTON') {
                enhancedButton = jQButton.attr({'data-skip-enhance':true});
                innerStuff = jQButton.html();
                jQButton.html('');

                // If it's INPUT - it's wrapped in a DIV and the necessary classes are added to the DIV.
            } else if (button.nodeName == 'INPUT') {
                // The input is assigned a class xf-input-hidden
                enhancedButton = $('

').append(jQButton.clone().addClass('xf-input-hidden').attr({'data-skip-enhance':true}));

                if (jQButton.hasOwnProperty('outerHtml')) {
                    jQButton.outerHtml(enhancedButton);
                }
                innerStuff = jQButton.attr('value');
            } else {
                // how did U get there? o_O
                return;
            }

            var isSmall = ((options && options.small === true) ? true : (options && options.appearance == 'backbtn') ? true : false),
                position = options.position || '',
                id = jQButton.attr('id') || XF.utils.uniqueID();

            if (position !== '') {
                enhancedButton.addClass('xf-button-float-' + position);
            }

            if (jQButton.parents(XF.ui.header.selector).length > 0) {
                var hposition = position || 'right';
                enhancedButton.addClass('xf-button-header-' + hposition);
                enhancedButton.addClass('xf-button-float-' + hposition);
            }

            // The class xf-button is added to the button.
            // If it has data-small="true" attribute, the class should be xf-button-small.
            enhancedButton.addClass(isSmall ? 'xf-button-small' : 'xf-button');

            // If data-appearance="backbtn" attribute is present, xf-button-back class is also added.
            if (options.appearance === 'backbtn') {
                enhancedButton.addClass('xf-button-back');
            }

            var iconName = options.icon;

            if (options.appearance === 'backbtn' /*&& !jQButton.attr('data-icon')*/) {
                iconName = 'left';
            }

            if (iconName) {

                // If data-icon attribute is present, a SPAN.xf-icon is added inside the button.
                var iconSpan = $('');

                // The value of data-icon attribute is used to generate icon class: e.g. xf-icon-dots.
                iconSpan.addClass('xf-icon-' + iconName);

                // If the button had data-small=true or data-appearance="backbtn" attributes,
                // xf-icon-small class is also added to SPAN.xf-icon
                if (isSmall) {
                    iconSpan.addClass('xf-icon-small');
                } else {
                    iconSpan.addClass('xf-icon-big');
                }

                // A class denoting icon position is also added to the button. Default: xf-iconpos-left.
                // The value is taken from data-iconpos attr.
                // Possible values: left, right, top, bottom.
                var iconPos = options.iconpos || 'left';

                if (iconPos != 'left' && iconPos != 'right' && iconPos != 'top' && iconPos != 'bottom') {
                    iconPos = 'left';
                }
                enhancedButton.addClass('xf-iconpos-' + iconPos);
                enhancedButton.append(iconSpan);

            }

            if (innerStuff) {
                var textSpan = $('').append(innerStuff);

                // The text of buttons is placed inside span.xf-button-small-text for small buttons
                if (isSmall || options.appearance == 'backbtn') {
                    textSpan.addClass('xf-button-small-text');
                    // and span.xf-button-text for big ones.
                } else {
                    textSpan.addClass('xf-button-text');
                }
                enhancedButton.append(textSpan);
            } else {

                if (isSmall) {
                    enhancedButton.addClass('xf-button-small-icon-only');
                }
            }

            // If data-special="true" attribute is present add xf-button-special class.
            if (options.special == true) {
                enhancedButton.addClass('xf-button-special');
            }

            // If data-alert="true" attribute is present add xf-button-alert class.
            if (options.alert == true) {
                enhancedButton.addClass('xf-button-alert');
            }

            enhancedButton.attr('id', id);
        }
    };
<|endoftext|>


<commit_before>(function(){

  var markletFrame;
  var markletDiv;
  var markletStyle;

  if (!document.getElementById("arena")) {
    initialize()
  }

  function initialize(){
    createFrame();
    createTarget();
    createStyle();

    document.addEventListener('dragstart', startDrag, true);
    document.addEventListener('dragend', stopDrag, true);
    document.addEventListener('mousedown', sendClick, true);

    markletDiv.addEventListener("dragover", dragOver, true);
    markletDiv.addEventListener("dragenter", dragEnter, false);
    markletDiv.addEventListener("dragleave", dragLeave, false);
    markletDiv.addEventListener("drop", drop, false);
  }

  function getURL(msg){
    baseUrl = "https://www.are.na/save/";

    url = baseUrl + encodeURIComponent(msg.url);
    url += "?original_source_url=" + encodeURIComponent(msg.url);
    url += "&original_source_title=" + encodeURIComponent(msg.title);

    return url;
  };

  function createFrame(){
    markletFrame = document.createElement("iframe");
    markletFrame.name = markletFrame.id = "arena_frame";
    markletFrame.src = getURL({
      url: window.location.href,
      title: window.document.title
    });
    document.body.appendChild(markletFrame)
  }

  function createTarget(){
    markletDiv = document.createElement("div");
    markletDiv.id = "arena_div";
    document.body.appendChild(markletDiv);
  }

  function createStyle(){
    markletStyle = document.createElement("style");
    markletStyle.type = "text/css";
    markletCSS = "#arena_frame,#arena_div{overflow:hidden;width:300px;height:420px;position:fixed;top:20px;right:20px;border:none}#arena_frame.is-expanded{height:670px}#arena_frame{z-index:9999999998;background:rgba(255,255,255,0.75);box-shadow: 3px 4px 10px rgba(0, 0, 0, .4);}#arena_frame:hover{background:rgba(255,255,255,0.9); box-shadow: 3px 4px 10px rgba(0, 0, 0, .5);}#arena_div{z-index:9999999999;display:none;opacity:0}";

    if (markletStyle.styleSheet) {
      markletStyle.styleSheet.cssText = markletCSS;
    } else {
      markletStyle.appendChild(document.createTextNode(markletCSS));
    }
    document.body.appendChild(markletStyle);
  }

  document.onkeyup = function(e){
    if (e || window.event) {
      e = window.event;
      if (e.keyCode == 27) closeBookmarklet();
    }
  }

  window.addEventListener("message", function(e){
    switch (e.data.action) {
      case "close":
        closeBookmarklet();
        break;
      case "expand":
        el = document.getElementById('arena_frame');
        addClass(el, 'is-expanded');
        break;
      case "contract":
        el = document.getElementById('arena_frame');
        removeClass(el, 'is-expanded');
        break;
    }
  });

  function closeBookmarklet() {
    if (markletFrame) document.body.removeChild(markletFrame)
    if (markletDiv) document.body.removeNode(markletDiv)
    if (markletStyle) document.body.removeNode(markletStyle)
  }

  function startDrag(e) {
    var targetParent;

    sendMessage({
      action: "drag"
    });

    if (typeof e.dataTransfer.getData("text/html") == "undefined"
      || e.target.tagName == "IMG") {

      targetParent = closest(e.target, "A") || document.createElement('A')

      parentHTML = targetParent.cloneNode(false);
      parentHTML.href = parentHTML.href;

      targetImage = e.target.cloneNode(false);
      targetImage.src = targetImage.src;
      parentHTML.appendChild(targetImage);
      e.dataTransfer.setData("text/html", parentHTML.outerHTML);
    }

    markletDiv.style.display = "block";
  };

  function stopDrag(e) {
    markletDiv.style.display = "none";
  };

  function dragOver(e) {
    e.stopPropagation();
    e.preventDefault();
    return false;
  }

  function dragEnter(e) {
    sendMessage({
      action: "dragenter"
    })
    return false
  }

  function dragLeave(e) {
    sendMessage({
      action: "dragleave"
    })
    return false
  }

  function sendClick() {
    sendMessage({
      action: "click"
    })
  }

  function drop(e) {
    var data = {
      source: location.href,
      title: document.title
    }

    for (var i in e.dataTransfer.types) {
      data[e.dataTransfer.types[i]] = e.dataTransfer.getData(e.dataTransfer.types[i]);
    }

    sendMessage({
      action: "drop",
      value: data
    });

    e.stopPropagation();
    e.preventDefault();
    return false;
  }

  function closest(that, tagname) {
    while (that.parentNode) {
      that = that.parentNode;
      if (that.tagName == tagname) return that
    }
    return false;
  }

  function sendMessage(data) {
    markletFrame.contentWindow.postMessage(data, "*")
  }

  function hasClass(el, className) {
    if (el.classList)
      return el.classList.contains(className)
    else
      return !!el.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)'))
  }

  function addClass(el, className) {
    if (el.classList)
      el.classList.add(className)
    else if (!hasClass(el, className)) el.className += " " + className
  }

  function removeClass(el, className) {
    if (el.classList)
      el.classList.remove(className)
    else if (hasClass(el, className)) {
      var reg = new RegExp('(\\s|^)' + className + '(\\s|$)')
      el.className=el.className.replace(reg, ' ')
    }
  }

})();
<commit_msg>update loaded route<commit_after>(function(){

  var markletFrame;
  var markletDiv;
  var markletStyle;

  if (!document.getElementById("arena")) {
    initialize()
  }

  function initialize(){
    createFrame();
    createTarget();
    createStyle();

    document.addEventListener('dragstart', startDrag, true);
    document.addEventListener('dragend', stopDrag, true);
    document.addEventListener('mousedown', sendClick, true);

    markletDiv.addEventListener("dragover", dragOver, true);
    markletDiv.addEventListener("dragenter", dragEnter, false);
    markletDiv.addEventListener("dragleave", dragLeave, false);
    markletDiv.addEventListener("drop", drop, false);
  }

  function getURL(msg){
    baseUrl = "https://ervell-staging.are.na/save/";

    url = baseUrl + encodeURIComponent(msg.url);
    url += "?original_source_url=" + encodeURIComponent(msg.url);
    url += "&original_source_title=" + encodeURIComponent(msg.title);

    return url;
  };

  function createFrame(){
    markletFrame = document.createElement("iframe");
    markletFrame.name = markletFrame.id = "arena_frame";
    markletFrame.src = getURL({
      url: window.location.href,
      title: window.document.title
    });
    document.body.appendChild(markletFrame)
  }

  function createTarget(){
    markletDiv = document.createElement("div");
    markletDiv.id = "arena_div";
    document.body.appendChild(markletDiv);
  }

  function createStyle(){
    markletStyle = document.createElement("style");
    markletStyle.type = "text/css";
    markletCSS = "#arena_frame,#arena_div{overflow:hidden;width:300px;height:420px;position:fixed;top:20px;right:20px;border:none}#arena_frame.is-expanded{height:670px}#arena_frame{z-index:9999999998;background:rgba(255,255,255,0.75);box-shadow: 3px 4px 10px rgba(0, 0, 0, .4);}#arena_frame:hover{background:rgba(255,255,255,0.9); box-shadow: 3px 4px 10px rgba(0, 0, 0, .5);}#arena_div{z-index:9999999999;display:none;opacity:0}";

    if (markletStyle.styleSheet) {
      markletStyle.styleSheet.cssText = markletCSS;
    } else {
      markletStyle.appendChild(document.createTextNode(markletCSS));
    }
    document.body.appendChild(markletStyle);
  }

  document.onkeyup = function(e){
    if (e || window.event) {
      e = window.event;
      if (e.keyCode == 27) closeBookmarklet();
    }
  }

  window.addEventListener("message", function(e){
    switch (e.data.action) {
      case "close":
        closeBookmarklet();
        break;
      case "expand":
        el = document.getElementById('arena_frame');
        addClass(el, 'is-expanded');
        break;
      case "contract":
        el = document.getElementById('arena_frame');
        removeClass(el, 'is-expanded');
        break;
    }
  });

  function closeBookmarklet() {
    if (markletFrame) document.body.removeChild(markletFrame)
    if (markletDiv) document.body.removeNode(markletDiv)
    if (markletStyle) document.body.removeNode(markletStyle)
  }

  function startDrag(e) {
    var targetParent;

    sendMessage({
      action: "drag"
    });

    if (typeof e.dataTransfer.getData("text/html") == "undefined"
      || e.target.tagName == "IMG") {

      targetParent = closest(e.target, "A") || document.createElement('A')

      parentHTML = targetParent.cloneNode(false);
      parentHTML.href = parentHTML.href;

      targetImage = e.target.cloneNode(false);
      targetImage.src = targetImage.src;
      parentHTML.appendChild(targetImage);
      e.dataTransfer.setData("text/html", parentHTML.outerHTML);
    }

    markletDiv.style.display = "block";
  };

  function stopDrag(e) {
    markletDiv.style.display = "none";
  };

  function dragOver(e) {
    e.stopPropagation();
    e.preventDefault();
    return false;
  }

  function dragEnter(e) {
    sendMessage({
      action: "dragenter"
    })
    return false
  }

  function dragLeave(e) {
    sendMessage({
      action: "dragleave"
    })
    return false
  }

  function sendClick() {
    sendMessage({
      action: "click"
    })
  }

  function drop(e) {
    var data = {
      source: location.href,
      title: document.title
    }

    for (var i in e.dataTransfer.types) {
      data[e.dataTransfer.types[i]] = e.dataTransfer.getData(e.dataTransfer.types[i]);
    }

    sendMessage({
      action: "drop",
      value: data
    });

    e.stopPropagation();
    e.preventDefault();
    return false;
  }

  function closest(that, tagname) {
    while (that.parentNode) {
      that = that.parentNode;
      if (that.tagName == tagname) return that
    }
    return false;
  }

  function sendMessage(data) {
    markletFrame.contentWindow.postMessage(data, "*")
  }

  function hasClass(el, className) {
    if (el.classList)
      return el.classList.contains(className)
    else
      return !!el.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)'))
  }

  function addClass(el, className) {
    if (el.classList)
      el.classList.add(className)
    else if (!hasClass(el, className)) el.className += " " + className
  }

  function removeClass(el, className) {
    if (el.classList)
      el.classList.remove(className)
    else if (hasClass(el, className)) {
      var reg = new RegExp('(\\s|^)' + className + '(\\s|$)')
      el.className=el.className.replace(reg, ' ')
    }
  }

})();
<|endoftext|>


<commit_before>// ==========================================================================
// Project:   MySystem.Link
// Copyright: ©2010 My Company, Inc.
// ==========================================================================
/*globals MySystem LinkIt SC*/

/** @class

  @extends SC.Record
  @version 0.1
*/
MySystem.Link = SC.Record.extend(LinkIt.Link,
/** @scope MySystem.Link.prototype */ {
  color: SC.Record.attr(String),
  text: SC.Record.attr(String),

  startNode: SC.Record.toOne('MySystem.Node', {
    inverse: 'outLinks'
  }),

  endNode:  SC.Record.toOne('MySystem.Node', {
    inverse: 'inLinks'
  }),

  label: {
    text: "label",
    fontSize: 12,
    fontFamily: 'sans-serif',
    fontStyle: 'normal',
    backgroundColor: "#FF0000"
  },

  startTerminal: SC.Record.attr(String),
  endTerminal: SC.Record.attr(String),

  init: function () {
    sc_super();
    // setup the links property initially
    //this.invokeLater(this._calculateLinks);
  },

  _textChanged: function() {
    console.log('_textChanged!');
    this.invokeOnce(this._setLabel);
  }.observes('.text'),

  _setLabel: function() {
    var newLabel = {
      text: this.get('text'),
      fontSize: 12,
      fontFamily: 'sans-serif',
      fontStyle: 'normal',
      backgroundColor: "#FF0000"
    };
    this.set("label", newLabel);
  }

}) ;
<commit_msg>trivial update to comment.<commit_after>// ==========================================================================
// Project:   MySystem.Link
// Copyright: ©2010 My Concord Consrtium, Inc.
// ==========================================================================
/*globals MySystem LinkIt SC*/

/** @class

  @extends SC.Record
  @version 0.1
*/
MySystem.Link = SC.Record.extend(LinkIt.Link,
/** @scope MySystem.Link.prototype */ {
  color: SC.Record.attr(String),
  text: SC.Record.attr(String),

  startNode: SC.Record.toOne('MySystem.Node', {
    inverse: 'outLinks'
  }),

  endNode:  SC.Record.toOne('MySystem.Node', {
    inverse: 'inLinks'
  }),

  label: {
    text: "label",
    fontSize: 12,
    fontFamily: 'sans-serif',
    fontStyle: 'normal',
    backgroundColor: "#FF0000"
  },

  startTerminal: SC.Record.attr(String),
  endTerminal: SC.Record.attr(String),

  init: function () {
    sc_super();
    // setup the links property initially
    //this.invokeLater(this._calculateLinks);
  },

  _textChanged: function() {
    console.log('_textChanged!');
    this.invokeOnce(this._setLabel);
  }.observes('.text'),

  _setLabel: function() {
    var newLabel = {
      text: this.get('text'),
      fontSize: 12,
      fontFamily: 'sans-serif',
      fontStyle: 'normal',
      backgroundColor: "#FF0000"
    };
    this.set("label", newLabel);
  }

}) ;
<|endoftext|>


<commit_before><commit_msg>adjust patching code to new versions of p5.js and p5play.js<commit_after><|endoftext|>


<commit_before>import 'babel-polyfill'
import 'isomorphic-fetch'
import path from 'path'
import fs from 'fs'
import { renderToString } from 'react-dom/server'
import React from 'react'
import Helmet from 'react-helmet'
import Honeybadger from 'honeybadger'
import { createMemoryHistory, match, RouterContext } from 'react-router'
import { Provider } from 'react-redux'
import { createElloStore } from './src/store'
import createRoutes from './src/routes'
import { syncHistoryWithStore } from 'react-router-redux'
import { serverRoot } from './src/sagas'
import { updateStrings as updateTimeAgoStrings } from './src/vendor/time_ago_in_words'

const indexStr = fs.readFileSync(path.join(__dirname, './public/index.html'), 'utf-8')

// Return promises for initial loads
function preRender(renderProps, store, sagaTask) {
  const promises = renderProps.components.map(component => ((component && component.preRender) ? component.preRender(store, renderProps) : null)).filter(component => !!component)
  return Promise.all(promises).then(() => {
    store.close()
    return sagaTask.done
  })
}

function handlePrerender(context) {
  const { access_token, originalUrl, url } = context

  console.log(`Spun up child process ${process.pid} to render ${url} isomorphically`)

  const memoryHistory = createMemoryHistory(originalUrl)
  const store = createElloStore(memoryHistory, {
    authentication: {
      accessToken: access_token,
      isLoggedIn: false,
    },
  })
  const isServer = true
  const routes = createRoutes(store, isServer)
  const history = syncHistoryWithStore(memoryHistory, store)
  const sagaTask = store.runSaga(serverRoot)

  match({ history, routes, location: url }, (error, redirectLocation, renderProps) => {
    // populate the router store object for initial render
    if (error) {
      console.log('ELLO MATCH ERROR', error)
    } else if (redirectLocation) {
      console.log('ELLO HANDLE REDIRECT', redirectLocation)
      process.send({ type: 'redirect', location: redirectLocation.pathname }, null, {}, () => {
        process.exit(0)
      })
    } else if (!renderProps) {
      console.log('NO RENDER PROPS')
      process.exit(1)
      return
    }

    const InitialComponent = (
      <Provider store={store}>
        <RouterContext {...renderProps} />
      </Provider>
    )

    preRender(renderProps, store, sagaTask).then(() => {
      const componentHTML = renderToString(InitialComponent)
      const head = Helmet.rewind()
      const state = store.getState()
      const initialStateTag = `<script id="initial-state">window.__INITIAL_STATE__ = ${JSON.stringify(state)}</script>`
      // Add helmet's stuff after the last statically rendered meta tag
      const html = indexStr.replace(
        'content="ie=edge">',
        `content="ie=edge">${head.title.toString()} ${head.meta.toString()} ${head.link.toString()}`
      ).replace('

', `<div id="root">${componentHTML}</div>${initialStateTag}`)
      process.send({ type: 'render', body: html }, null, {}, () => {
        process.exit(0)
      })
    }).catch((err) => {
      // this will give you a js error like:
      // `window is not defined`
      console.log('ELLO CATCH ERROR', err)
      Honeybadger.notify(err);
      process.send({ type: 'error' }, null, {}, () => {
        process.exit(1)
      })
    })
    renderToString(InitialComponent)
  })
}

process.on('message', handlePrerender)

export default handlePrerender
<commit_msg>Update where the meta tags get cutoff<commit_after>import 'babel-polyfill'
import 'isomorphic-fetch'
import path from 'path'
import fs from 'fs'
import { renderToString } from 'react-dom/server'
import React from 'react'
import Helmet from 'react-helmet'
import Honeybadger from 'honeybadger'
import { createMemoryHistory, match, RouterContext } from 'react-router'
import { Provider } from 'react-redux'
import { createElloStore } from './src/store'
import createRoutes from './src/routes'
import { syncHistoryWithStore } from 'react-router-redux'
import { serverRoot } from './src/sagas'
import { updateStrings as updateTimeAgoStrings } from './src/vendor/time_ago_in_words'

const indexStr = fs.readFileSync(path.join(__dirname, './public/index.html'), 'utf-8')

// Return promises for initial loads
function preRender(renderProps, store, sagaTask) {
  const promises = renderProps.components.map(component => ((component && component.preRender) ? component.preRender(store, renderProps) : null)).filter(component => !!component)
  return Promise.all(promises).then(() => {
    store.close()
    return sagaTask.done
  })
}

function handlePrerender(context) {
  const { access_token, originalUrl, url } = context

  console.log(`Spun up child process ${process.pid} to render ${url} isomorphically`)

  const memoryHistory = createMemoryHistory(originalUrl)
  const store = createElloStore(memoryHistory, {
    authentication: {
      accessToken: access_token,
      isLoggedIn: false,
    },
  })
  const isServer = true
  const routes = createRoutes(store, isServer)
  const history = syncHistoryWithStore(memoryHistory, store)
  const sagaTask = store.runSaga(serverRoot)

  match({ history, routes, location: url }, (error, redirectLocation, renderProps) => {
    // populate the router store object for initial render
    if (error) {
      console.log('ELLO MATCH ERROR', error)
    } else if (redirectLocation) {
      console.log('ELLO HANDLE REDIRECT', redirectLocation)
      process.send({ type: 'redirect', location: redirectLocation.pathname }, null, {}, () => {
        process.exit(0)
      })
    } else if (!renderProps) {
      console.log('NO RENDER PROPS')
      process.exit(1)
      return
    }

    const InitialComponent = (
      <Provider store={store}>
        <RouterContext {...renderProps} />
      </Provider>
    )

    preRender(renderProps, store, sagaTask).then(() => {
      const componentHTML = renderToString(InitialComponent)
      const head = Helmet.rewind()
      const state = store.getState()
      const initialStateTag = `<script id="initial-state">window.__INITIAL_STATE__ = ${JSON.stringify(state)}</script>`
      // Add helmet's stuff after the last statically rendered meta tag
      const html = indexStr.replace(
        'rel="copyright">',
        `rel="copyright">${head.title.toString()} ${head.meta.toString()} ${head.link.toString()}`
      ).replace('

', `<div id="root">${componentHTML}</div>${initialStateTag}`)
      process.send({ type: 'render', body: html }, null, {}, () => {
        process.exit(0)
      })
    }).catch((err) => {
      // this will give you a js error like:
      // `window is not defined`
      console.log('ELLO CATCH ERROR', err)
      Honeybadger.notify(err);
      process.send({ type: 'error' }, null, {}, () => {
        process.exit(1)
      })
    })
    renderToString(InitialComponent)
  })
}

process.on('message', handlePrerender)

export default handlePrerender
<|endoftext|>


<commit_before>import mongoose from 'mongoose';
import register from './register';
import { authorizedForDomain } from './auth';
import { unsetDomainIfNeeded } from './domains';

mongoose.Promise = global.Promise;

// /api/form-templates

const unsetReferences = (data) => {
  data = unsetDomainIfNeeded(data);
  if (!data.linkedFormTemplateId) {
    delete data.linkedFormTemplateId;
    if (!data.$unset) {
      data.$unset = {};
    }
    data.$unset.linkedFormTemplateId = '';
  }
  return data;
};

const fieldValue = (field, templateFieldMap, optionMap) => {
  const templateField = templateFieldMap[field.templateFieldId];
  let value;
  if (templateField.type === 'count' || templateField.type === 'number') {
    value = templateField.value * field.value;
  } else if (templateField.type === 'choice' && field.optionId) {
    const option = optionMap[field.optionId];
    value = option.value;
  } else if (templateField.type === 'choices' && field.optionIds.length > 0) {
    value = field.optionIds.map((optionId) => {
      const option = optionMap[optionId];
      return option.value;
    });
    value = value.reduce((t, v) => (t + parseFloat(v, 10)), 0);
  } else {
    value = field.value;
  }
  return value;
};

const calculateTotals = (data) => {
  const Form = mongoose.model('Form');
  return Form.find({ formTemplateId: data._id }).exec()
  .then((forms) => {
    const formTemplate = data.toObject();
    const templateFieldMap = {};
    const optionMap = {};
    const totals = {};
    const remains = {};
    formTemplate.sections.forEach((section) => {
      section.fields.forEach((field) => {
        templateFieldMap[field._id] = field;
        field.options.forEach((option) => { optionMap[option._id] = option; });
        if (field.type === 'count' || field.type === 'number'
          || field.monetary) {
          totals[field._id] = 0;
        }
        if (field.limit) {
          remains[field._id] = parseFloat(field.limit, 10);
        } else {
          field.options.forEach((option) => {
            if (option.limit !== undefined) {
              if (!remains[field._id]) {
                remains[field._id] = {};
              }
              remains[field._id][option._id] = parseFloat(option.limit, 10);
            }
          });
        }
      });
    });

    forms.forEach((form) => {
      form.fields.forEach((field) => {
        const total = totals[field.templateFieldId];
        if (total >= 0) {
          const value = parseFloat(
            fieldValue(field, templateFieldMap, optionMap), 10);
          if (value) {
            totals[field.templateFieldId] += value;
          }
        }

        const remaining = remains[field.templateFieldId];
        if (remaining !== undefined) {
          if (typeof remaining === 'object') {
            // options
            (field.optionIds || []).forEach((optionId) => {
              if (remaining[optionId] >= 0) {
                remaining[optionId] -= 1;
              }
            });
          } else {
            const templateField = templateFieldMap[field.templateFieldId];
            if (templateField.type === 'number' || templateField.type === 'count') {
              remains[field.templateFieldId] -= parseFloat(field.value, 10);
            } else {
              remains[field.templateFieldId] -= 1;
            }
          }
        }
      });
    });
    formTemplate.totals = totals;
    formTemplate.remains = remains;
    return formTemplate;
  });
};

export default function (router) {
  register(router, {
    category: 'form-templates',
    modelName: 'FormTemplate',
    index: {
      authorize: authorizedForDomain,
      populate: [
        { path: 'linkedFormTemplateId', select: 'name' },
      ],
    },
    get: {
      populate: [
        { path: 'linkedFormTemplateId', select: 'name' },
      ],
      transformOut: (formTemplate, req) => {
        if (formTemplate && req.query.totals) {
          return calculateTotals(formTemplate);
        }
        return formTemplate;
      },
    },
    put: {
      transformIn: unsetReferences,
      transformOut: (formTemplate) => {
        // update all Forms for this formTemplate to have the same domain
        const Form = mongoose.model('Form');
        return Form.update({ formTemplateId: formTemplate._id },
          { $set: { domainId: formTemplate.domainId } }, { multi: true }).exec()
          .then(() => formTemplate);
      },
    },
  });
}
<commit_msg>Fixed an issue with null as a limit value.<commit_after>import mongoose from 'mongoose';
import register from './register';
import { authorizedForDomain } from './auth';
import { unsetDomainIfNeeded } from './domains';

mongoose.Promise = global.Promise;

// /api/form-templates

const unsetReferences = (data) => {
  data = unsetDomainIfNeeded(data);
  if (!data.linkedFormTemplateId) {
    delete data.linkedFormTemplateId;
    if (!data.$unset) {
      data.$unset = {};
    }
    data.$unset.linkedFormTemplateId = '';
  }
  return data;
};

const fieldValue = (field, templateFieldMap, optionMap) => {
  const templateField = templateFieldMap[field.templateFieldId];
  let value;
  if (templateField.type === 'count' || templateField.type === 'number') {
    value = templateField.value * field.value;
  } else if (templateField.type === 'choice' && field.optionId) {
    const option = optionMap[field.optionId];
    value = option.value;
  } else if (templateField.type === 'choices' && field.optionIds.length > 0) {
    value = field.optionIds.map((optionId) => {
      const option = optionMap[optionId];
      return option.value;
    });
    value = value.reduce((t, v) => (t + parseFloat(v, 10)), 0);
  } else {
    value = field.value;
  }
  return value;
};

const calculateTotals = (data) => {
  const Form = mongoose.model('Form');
  return Form.find({ formTemplateId: data._id }).exec()
  .then((forms) => {
    const formTemplate = data.toObject();
    const templateFieldMap = {};
    const optionMap = {};
    const totals = {};
    const remains = {};
    formTemplate.sections.forEach((section) => {
      section.fields.forEach((field) => {
        templateFieldMap[field._id] = field;
        field.options.forEach((option) => { optionMap[option._id] = option; });
        if (field.type === 'count' || field.type === 'number'
          || field.monetary) {
          totals[field._id] = 0;
        }
        if (field.limit) {
          remains[field._id] = parseFloat(field.limit, 10);
        } else {
          field.options.forEach((option) => {
            if (option.limit !== undefined && option.limit !== null) {
              if (!remains[field._id]) {
                remains[field._id] = {};
              }
              remains[field._id][option._id] = parseFloat(option.limit, 10);
            }
          });
        }
      });
    });

    forms.forEach((form) => {
      form.fields.forEach((field) => {
        const total = totals[field.templateFieldId];
        if (total >= 0) {
          const value = parseFloat(
            fieldValue(field, templateFieldMap, optionMap), 10);
          if (value) {
            totals[field.templateFieldId] += value;
          }
        }

        const remaining = remains[field.templateFieldId];
        if (remaining !== undefined) {
          if (typeof remaining === 'object') {
            // options
            (field.optionIds || []).forEach((optionId) => {
              if (remaining[optionId] >= 0) {
                remaining[optionId] -= 1;
              }
            });
          } else {
            const templateField = templateFieldMap[field.templateFieldId];
            if (templateField.type === 'number' || templateField.type === 'count') {
              remains[field.templateFieldId] -= parseFloat(field.value, 10);
            } else {
              remains[field.templateFieldId] -= 1;
            }
          }
        }
      });
    });
    formTemplate.totals = totals;
    formTemplate.remains = remains;
    return formTemplate;
  });
};

export default function (router) {
  register(router, {
    category: 'form-templates',
    modelName: 'FormTemplate',
    index: {
      authorize: authorizedForDomain,
      populate: [
        { path: 'linkedFormTemplateId', select: 'name' },
      ],
    },
    get: {
      populate: [
        { path: 'linkedFormTemplateId', select: 'name' },
      ],
      transformOut: (formTemplate, req) => {
        if (formTemplate && req.query.totals) {
          return calculateTotals(formTemplate);
        }
        return formTemplate;
      },
    },
    put: {
      transformIn: unsetReferences,
      transformOut: (formTemplate) => {
        // update all Forms for this formTemplate to have the same domain
        const Form = mongoose.model('Form');
        return Form.update({ formTemplateId: formTemplate._id },
          { $set: { domainId: formTemplate.domainId } }, { multi: true }).exec()
          .then(() => formTemplate);
      },
    },
  });
}
<|endoftext|>


<commit_before>
function addHandlerOnEvent (handler, miid, eventName) {

    var self = this;

    // if the handler is a module function name as string
    if (typeof handler === "string" && typeof self[handler] === "function") {
        self.on(eventName, miid, function() {
            self[handler].apply(self, arguments);
        });
        return;
    }

    // else it must be an array of objects
    if (handler.length) {
        self.on(eventName, miid, function() {
            for (var i in handler) {
                var step = handler[i];

                // this step is a handler function
                if (step.handler) {
                    var name = null;
                    var args = [];

                    switch (typeof step.handler) {
                        case "object":
                            name = step.handler.name;
                            args = step.handler.args || [];
                            break;
                        case "string":
                            name = step.handler;
                            break;
                    }
                    if (typeof self[name] === "function") {
                        var allArgs = [];
                        // first we push the fixed (mono.json arguments)
                        for (var i in args) {
                            allArgs.push(args[i]);
                        }
                        // then come the dynamic ones from the emit arguments (data context, callback, etc.)
                        for (var i = 0, l = arguments.length; i < l; ++i) {
                            allArgs.push(arguments[i]);
                        }

                        self[name].apply(self, allArgs);
                    }
                    continue;
                }

                // this step is an event emit
                if (step.emit) {
                    self.emit(step.emit, data);
                    continue;
                }
            }
        });

        return;
    }
}

module.exports = function(config) {

    var self = this;

    // process only the listen property in the configurations
    for (var miid in config.listen) {

        var miidEvents = config.listen[miid];

        for (var eventName in miidEvents) {
            addHandlerOnEvent.call(self, miidEvents[eventName], miid, eventName);
        }
    }
}

<commit_msg>Added global functions as handlers support.<commit_after>function addHandlerOnEvent (handler, miid, eventName) {

    var self = this;

    // if the handler is a module function name as string
    if (typeof handler === "string" && typeof self[handler] === "function") {
        self.on(eventName, miid, function() {
            self[handler].apply(self, arguments);
        });
        return;
    }

    // else it must be an array of objects
    if (handler.length) {
        self.on(eventName, miid, function() {
            for (var i in handler) {
                var step = handler[i];

                // this step is a handler function
                if (step.handler) {
                    var name = null;
                    var args = [];

                    switch (typeof step.handler) {
                        case "object":
                            name = step.handler.name;
                            args = step.handler.args || [];
                            break;
                        case "string":
                            name = step.handler;
                            break;
                    }

                    // module functions
                    if (typeof self[name] === "function") {
                        var allArgs = [];
                        // first we push the fixed (application.json arguments)
                        for (var i in args) {
                            allArgs.push(args[i]);
                        }
                        // then come the dynamic ones from the emit arguments (data context, callback, etc.)
                        for (var i = 0, l = arguments.length; i < l; ++i) {
                            allArgs.push(arguments[i]);
                        }

                        self[name].apply(self, allArgs);
                    }

                    // global functions
                    if (typeof window[name] === "function") {

                        var allArgs = [];

                        // first we push the fixed (application.json arguments)
                        for (var i in args) {
                            allArgs.push(args[i]);
                        }

                        // then come the dynamic ones from the emit arguments (data context, callback, etc.)
                        for (var i = 0, l = arguments.length; i < l; ++i) {
                            allArgs.push(arguments[i]);
                        }

                        window[name].apply(self, allArgs);
                    }

                    continue;
                }

                // this step is an event emit
                if (step.emit) {
                    self.emit(step.emit, data);
                    continue;
                }
            }
        });

        return;
    }
}

module.exports = function(config) {

    var self = this;

    // process only the listen property in the configurations
    for (var miid in config.listen) {

        var miidEvents = config.listen[miid];

        for (var eventName in miidEvents) {
            addHandlerOnEvent.call(self, miidEvents[eventName], miid, eventName);
        }
    }
}
<|endoftext|>


<commit_before>/**
 * EVENTS HANDLING
 *
 * Smart events managing by altering the properties of a HTML element
 **
 * usage:

new UIElement({
        name:               NAME OF YOUR EVENT,
        eventHtmlElement:   PASS HTML ELEMENT,
        handler:            ANONYMOS FUNCTION OR FUNCTION PASSED BY REF,
        eventType:          EVENT TYPE
        useCapture:         DEFAULT IS FALSE, you can pass TRUE
    });
 **
 * example:

new UIElement({
        name:               'My event',
        eventHtmlElement:   document.getElementById('myElement');
        handler:            function(){alert('it works')},
        eventType:          'click'
    });

document.getElementById('myElement').hasEvent(EVENT NAME);  -> true or false
document.getElementById('myElement').detach(EVENT NAME);    -> detaches the requested event
document.getElementById('myElement').detach();              -> detaches all events
document.getElementById('myElement').events                 -> returns array of all attached events if any

//inside the events handler
this.detach()                                               -> detaches self
this.detach('name')                                         -> detaches other event

 * Inside the event handler 'this' refers to the event attached
 * and stores its configuration and a reference to the HTML element.
 **
 * You can detach these events from within the handler like this:
 this.eventHtmlElement.detach(this.eventConfig.name)

 *
 * If you need to control it from somewhere else you can store the event
 * into a variable and access it from there like this:
 var myEventVariable = new UIElement({...});

 * console.log(myEventVariable) will output the same as console.log(this)
 * from withing the event handler
 *
 * Proper FOR/WHILE loop attach of events - the class is handling the check for that.
 * You can't attach events with the same name.
 */

var UIElement = (function()
{
    'use strict';

    // Empty function
    function noop() {}

    if (typeof Object.prototype.detach === 'undefined')
    {
        // This prevents showing an error if you try to evoke the detach method of
        // non EventObject.
        // NOTE: Element.prototype.foo works in iOS 8.1+
        Object.prototype.detach = noop;
    }

    function UIElement(config)
    {
        if (!config)
        {
            return false;
        }

        // Self-Invoking Constructor
        // Make sure that a constructor function always behaves like one even
        // if called without `new`.
        if (!(this instanceof UIElement))
        {
            return new UIElement(config);
        }

        // Apply configuration
        this.eventHtmlElement = config.eventHtmlElement;

        this.eventConfig = {
            name: config.name,
            eventType: config.eventType,
            handler: config.handler === undefined ? false : config.handler,
            useCapture: config.useCapture === undefined ? false : config.useCapture
        };

        this.init();
    }

    //main function
    UIElement.prototype.init = function ()
    {
        //if HTML element is not UI element
        if (!this.eventHtmlElement.eventsList)
        {
            //add array to store events
            this.eventHtmlElement.eventsList = [];

            //extend model for this element with 'events'
            Object.defineProperty(this.eventHtmlElement, 'events',
            {
                //if no value passed return all values stored
                get: function ()
                {
                    return this.eventsList;
                },

                //if value is passed, push into the array
                set: function (e)
                {
                    this.eventsList.push(e);
                }
            });

            // nables us to check if a specific event is attached by name
            this.eventHtmlElement.hasEvent = function (name)
            {
                for (var i = 0; i < this.eventsList.length; i += 1)
                {
                    if (this.eventsList[i].name == name)
                    {
                        return true;
                    }
                }

                return false;
            };

            //enables us to detach specific or all events
            this.eventHtmlElement.detach = function (name)
            {
                var i, ev, eventType, handler, useCapture;
                //detach all events if no event specified
                if (name === undefined || name === '')
                {
                    for (i = 0; i < this.eventsList.length; i += 1)
                    {
                        ev = this.eventsList[i];
                        eventType = ev.eventType;
                        handler = ev.handler;
                        useCapture = ev.useCapture;
                        this.removeEventListener(eventType, handler, useCapture);
                    }
                    this.eventsList = [];

                    //check for and detach if event is attached
                }
                else if (this.hasEvent(name))
                {
                    for (i = 0; i < this.eventsList.length; i += 1)
                    {
                        if (this.eventsList[i].name == name)
                        {
                            ev = this.eventsList.splice(i, 1)[0];
                            useCapture = ev.useCapture;
                            eventType = ev.eventType;
                            handler = ev.handler;
                        }
                    }
                    this.removeEventListener(eventType, handler, useCapture);
                }
                //if proper condition is not met
                return false;
            };
        }
        //if this event exist ... do nothing
        else if (this.eventHtmlElement.hasEvent(this.eventConfig.name))
        {
            return false;
        }

        //pass scope, apply event, save configuration for future uses
        this.eventConfig.handler = this.eventConfig.handler.bind(this);
        this.eventHtmlElement.addEventListener(this.eventConfig.eventType, this.eventConfig.handler, this.eventConfig.useCapture);
        this.eventHtmlElement.events = this.eventConfig;
    };

    //detach event method called from the event object stored in a variable
    //you can also detach one event from within a handler of another event
    UIElement.prototype.detach = function (name)
    {
        var eventName = name === undefined ? this.eventConfig.name : name;

        //we need this to be able to find where in the array is our event
        //so we could remove it from it
        for (var i = 0; i < this.eventHtmlElement.eventsList.length; i += 1)
        {
            //do we want to detach event different from the one which invokes this method?
            if (name !== undefined && this.eventHtmlElement.eventsList[i].name == eventName)
            {
                var eventData = this.eventHtmlElement.eventsList.splice(i, 1);
                this.eventConfig.eventType = eventData[0].eventType;
                this.eventConfig.handler = eventData[0].handler;

            }
            //if not remove myself from the array of events
            else if (this.eventHtmlElement.eventsList[i].name == eventName)
            {
                this.eventHtmlElement.eventsList.splice(i, 1);
            }
        }

        //detach the event
        this.eventHtmlElement.removeEventListener(this.eventConfig.eventType, this.eventConfig.handler, this.eventConfig.useCapture);
    };

    return UIElement;
}());
<commit_msg>Optimized the detach logic<commit_after>/**
 * EVENTS HANDLING
 *
 * Smart events managing by altering the properties of a HTML element
 **
 * usage:

new UIElement({
        name:               NAME OF YOUR EVENT,
        eventHtmlElement:   PASS HTML ELEMENT,
        handler:            ANONYMOS FUNCTION OR FUNCTION PASSED BY REF,
        eventType:          EVENT TYPE
        useCapture:         DEFAULT IS FALSE, you can pass TRUE
    });
 **
 * example:

new UIElement({
        name:               'My event',
        eventHtmlElement:   document.getElementById('myElement');
        handler:            function(){alert('it works')},
        eventType:          'click'
    });

document.getElementById('myElement').hasEvent(EVENT NAME);  -> true or false
document.getElementById('myElement').detach(EVENT NAME);    -> detaches the requested event
document.getElementById('myElement').detach();              -> detaches all events
document.getElementById('myElement').events                 -> returns array of all attached events if any

//inside the events handler
this.detach()                                               -> detaches self
this.detach('name')                                         -> detaches other event

 * Inside the event handler 'this' refers to the event attached
 * and stores its configuration and a reference to the HTML element.
 **
 * You can detach these events from within the handler like this:
 this.eventHtmlElement.detach(this.eventConfig.name)

 *
 * If you need to control it from somewhere else you can store the event
 * into a variable and access it from there like this:
 var myEventVariable = new UIElement({...});

 * console.log(myEventVariable) will output the same as console.log(this)
 * from withing the event handler
 *
 * Proper FOR/WHILE loop attach of events - the class is handling the check for that.
 * You can't attach events with the same name.
 */

var UIElement = (function()
{
    'use strict';

    // Empty function
    function noop() {}

    if (typeof Object.prototype.detach === 'undefined')
    {
        // This prevents showing an error if you try to evoke the detach method of
        // non EventObject.
        // NOTE: Element.prototype.foo works in iOS 8.1+
        Object.prototype.detach = noop;
    }

    if (typeof Object.prototype.hasEvent === 'undefined')
    {
        // This prevents showing an error if you try to evoke the detach method of
        // non EventObject.
        Object.prototype.hasEvent = noop;
    }

    function UIElement(config)
    {
        if (!config)
        {
            return false;
        }

        // Self-Invoking Constructor
        // Make sure that a constructor function always behaves like one even
        // if called without `new`.
        if (!(this instanceof UIElement))
        {
            return new UIElement(config);
        }

        // Apply configuration
        this.eventHtmlElement = config.eventHtmlElement;

        this.eventConfig = {
            name: config.name,
            eventType: config.eventType,
            handler: config.handler === undefined ? false : config.handler,
            useCapture: config.useCapture === undefined ? false : config.useCapture
        };

        this.init();
    }

    //main function
    UIElement.prototype.init = function ()
    {
        //if HTML element is not UI element
        if (!this.eventHtmlElement.eventsList)
        {
            //add array to store events
            this.eventHtmlElement.eventsList = [];

            //extend model for this element with 'events'
            Object.defineProperty(this.eventHtmlElement, 'events',
            {
                //if no value passed return all values stored
                get: function ()
                {
                    return this.eventsList;
                },

                //if value is passed, push into the array
                set: function (e)
                {
                    this.eventsList.push(e);
                }
            });

            // nables us to check if a specific event is attached by name
            this.eventHtmlElement.hasEvent = function (name)
            {
                for (var i = 0; i < this.eventsList.length; i += 1)
                {
                    if (this.eventsList[i].name == name)
                    {
                        return true;
                    }
                }

                return false;
            };

            //enables us to detach specific or all events
            this.eventHtmlElement.detach = function (name)
            {
                var i, ev, eventType, handler, useCapture;
                //detach all events if no event specified
                if (name === undefined || name === '')
                {
                    for (i = 0; i < this.eventsList.length; i += 1)
                    {
                        ev = this.eventsList[i];
                        eventType = ev.eventType;
                        handler = ev.handler;
                        useCapture = ev.useCapture;
                        this.removeEventListener(eventType, handler, useCapture);
                    }
                    this.eventsList = [];

                    //check for and detach if event is attached
                }
                else if (this.hasEvent(name))
                {
                    for (i = 0; i < this.eventsList.length; i += 1)
                    {
                        if (this.eventsList[i].name == name)
                        {
                            ev = this.eventsList.splice(i, 1)[0];
                            useCapture = ev.useCapture;
                            eventType = ev.eventType;
                            handler = ev.handler;
                        }
                    }
                    this.removeEventListener(eventType, handler, useCapture);
                }
                //if proper condition is not met
                return false;
            };
        }
        //if this event exist ... do nothing
        else if (this.eventHtmlElement.hasEvent(this.eventConfig.name))
        {
            return false;
        }

        //pass scope, apply event, save configuration for future uses
        this.eventConfig.handler = this.eventConfig.handler.bind(this);
        this.eventHtmlElement.addEventListener(this.eventConfig.eventType, this.eventConfig.handler, this.eventConfig.useCapture);
        this.eventHtmlElement.events = this.eventConfig;
    };

    //detach event method called from the event object stored in a variable
    //you can also detach one event from within a handler of another event
    UIElement.prototype.detach = function (name)
    {
        var eventName = name === undefined ? this.eventConfig.name : name,
            eventData;

        //we need this to be able to find where in the array is our event
        //so we could remove it from it
        for (var i = 0; i < this.eventHtmlElement.eventsList.length; i += 1)
        {
            if (this.eventHtmlElement.eventsList[i].name === eventName)
            {
                //remove myself from the array of events
                eventData = this.eventHtmlElement.eventsList.splice(i, 1);

                //do we want to detach event different from the one which invokes this method?
                if (name !== undefined)
                {
                    this.eventConfig.eventType = eventData[0].eventType;
                    this.eventConfig.handler = eventData[0].handler;
                }
            }
        }

        //detach the event
        this.eventHtmlElement.removeEventListener(this.eventConfig.eventType, this.eventConfig.handler, this.eventConfig.useCapture);
    };

    return UIElement;
}());
<|endoftext|>


<commit_before>
eventParsers = {
	InitGameParser: function(rawdata) {
		var data = {};
		var parts = rawdata.split("\\");
		parts.splice(0, 1); // The data section of an InitGame line starts with a \
		for (var i = 0; i < parts.length / 2; i += 2) {
			data[parts[i]] = parts[i + 1];
		}
		return data;
	},
	InitAuthParser: function(rawdata) {
		var data = {};
		var parts = rawdata.split("\\");
		parts.splice(0, 1); // Same reason as above
		for (var i = 0; i < parts.length / 2; i += 2) {
			data[parts[i]] = parts[i + 1];
		}
		return data;
	},
	ShutdownGameParser: function(rawdata) {
		return null;
	},
	ClientConnectParser: function(rawdata) {
		var data = {};
		return rawdata;
	},
	ClientDisconnectParser: function(rawdata) {
		var data = {};
		return rawdata;
	},
	ClientUserinfoParser: function(rawdata) {
		var data = {};
		return rawdata;
	},
	ClientUserinfoChangedParser: function(rawdata) {
		var data = {};
		return rawdata;
	},
	ClientSpawnParser: function(rawdata) {
		var data = {};
		return rawdata;
	},
	ClientBeginParser: function(rawdata) {
		var data = {};
		return rawdata;
	},
	sayparser: function(rawdata) {
		var data = {};
		return rawdata;
	},
	sayteamParser: function(rawdata) {
		var data = {};
		return rawdata;
	},
	KillParser: function(rawdata) {
		var data = {};
		return rawdata;
	},
	SurvivorWinnerParser: function(rawdata) {
		var data = {};
		return rawdata;
	}
}
<commit_msg>Parse ClientConnect, ClientDisconnect, ClientSpawn, ClientBegin<commit_after>
eventParsers = {
	InitGameParser: function(rawdata) {
		var data = {};
		var parts = rawdata.split("\\");
		parts.splice(0, 1); // The data section of an InitGame line starts with a \
		for (var i = 0; i < parts.length / 2; i += 2) {
			data[parts[i]] = parts[i + 1];
		}
		return data;
	},
	InitAuthParser: function(rawdata) {
		var data = {};
		var parts = rawdata.split("\\");
		parts.splice(0, 1); // Same reason as above
		for (var i = 0; i < parts.length / 2; i += 2) {
			data[parts[i]] = parts[i + 1];
		}
		return data;
	},
	ShutdownGameParser: function(rawdata) {
		return null;
	},
	ClientConnectParser: function(rawdata) {
		return parseInt(rawdata);
	},
	ClientDisconnectParser: function(rawdata) {
		return parseInt(rawdata);
	},
	ClientUserinfoParser: function(rawdata) {
		var data = {};
		return rawdata;
	},
	ClientUserinfoChangedParser: function(rawdata) {
		var data = {};
		return rawdata;
	},
	ClientSpawnParser: function(rawdata) {
		return parseInt(rawdata);
	},
	ClientBeginParser: function(rawdata) {
		return parseInt(rawdata);
	},
	sayparser: function(rawdata) {
		var data = {};
		return rawdata;
	},
	sayteamParser: function(rawdata) {
		var data = {};
		return rawdata;
	},
	KillParser: function(rawdata) {
		var data = {};
		return rawdata;
	},
	SurvivorWinnerParser: function(rawdata) {
		var data = {};
		return rawdata;
	}
}
<|endoftext|>


<commit_before>/* ex: set tabstop=2 softtabstop=2 shiftwidth=2 : */

/*jshint unused:false, boss:true */
/*global setProperty:true, elementFitsDescription:true */

(function (root, name) {
  "use strict";
  // in case we decide to change those names later on
  var delegateSelector = "selector",
      delegateFunction = "handler";

  // shorthand or toggle individual state of delegateFunction
  function changeState(delegateArray, item, state) {
    var i, delegateItem;
    for (i = 0; delegateItem = delegateArray[i]; i++) {
      if (delegateItem[delegateSelector] === item) {
        delegateItem.disabled = Boolean(state);
        break;
      }
    }
  }

  function getEventTarget(e) {
    e = e || window.event;
    return e.target || e.srcElement;
  }

  function execute(func, scope) {
    if (func) {
      func.call(scope);
    }
  }

  function setEnv(scope) {
    var _previousInstance = scope.constructor.__registered__[scope.getRootElementSelector()];
    var _self = (_previousInstance.scope)[_previousInstance.variable] || scope;
    _previousInstance = null;
    return _self;
  }

  function pushIntoDelegates(toArr, fromArr, startPos) {
    startPos = startPos || 0;
    if (fromArr.length === startPos + 1 && typeof fromArr[startPos] === "array") {
      [].push.apply(toArr, fromArr[startPos]);
    }
    else {
      for (var i = startPos, item; item = fromArr[i]; i++) {
        if (item.selector) {
          toArr.push(item);
        }
      }
    }
    return toArr;
  }

  function addEventListenerHelper(element, _event, _obj) {
    if (element.addEventListener) {
      element.addEventListener(_event, _obj, false);
    }
    else if (element.attachEvent) {
      element.attachEvent("on" + _event, _obj);
    }
  }

  function removeEventListenerHelper(element, _event, _obj) {
    if (element.removeEventListener) {
      element.removeEventListener(_event, _obj);
    }
    else if (element.detachEvent) {
      element.detachEvent("on" + _event, _obj);
    }
  }

  /**
   * @name DelegateList
   * @function
   *
   * @description
   * constructor for delegates method object/array
   * create a object simular to array
   * better not subclassing JavaScript Array
   * https://perfectionkills.com/how-ecmascript-5-still-does-not-allow-to-subclass-an-array
   *
   * @param arr ARRAY
   */
  function DelegateList(arr) {
    /*jshint validthis:true */
    this.disabled = false;
    this.delegates = arr || [];

    // allow overwrite
    setProperty(this, "__unlistened__", false, true);
  }

  /*
   * we do not use this.disable to modify the master disable switch
   * because user might accidentally calls this method without giving an argument
   * for that circumstance, we should do nothing
   * instead, we use disableAll to modify the master disable switch
   */
  DelegateList.prototype.disable = function (item) {
    if (item) {
      changeState(this.delegates, item, true);
    }
    return this;
  };

  DelegateList.prototype.enable = function (item) {
    if (item) {
      changeState(this.delegates, item, false);
    }
    return this;
  };

  DelegateList.prototype.disableAll = function () {
    this.disabled = true;
    return this;
  };

  DelegateList.prototype.enableAll = function () {
    this.disabled = false;
    return this;
  };

  /**
   * @name handleEvent
   * @function
   *
   * @description
   * actual function to attach events
   * we all know that we could bind object in addEventListener
   * http://w3.org/TR/DOM-Level-2-Events/events.html
   * provided there is a `handleEvent' property in the object
   * here is the trick, we COULD use a function to generate an object with
   * `handleEvent' nicely hidden inside its `prototype'
   *
   * @param evt
   */
  DelegateList.prototype.handleEvent = function (evt) {
    // master switch
    if (this.disabled || this.delegates.length === 0) {
      return;
    }

    var i, item, targetElement = getEventTarget(evt);

    for (i = 0; item = this.delegates[i]; i++) {
      if (item.disabled) {
        continue;
      }
      // FIXME: add documentation explaining why we use this instead of querySelector match
      if (elementFitsDescription(targetElement, item[delegateSelector])) {
        execute(item[delegateFunction], targetElement);
      }
    } // end of for loop
  };

  /**
   * @name listen
   * @function
   *
   * @description
   *
   * @param arr
   */
  DelegateList.prototype.listen = function () {
    this.delegates = this.delegates || [];
    // better than [].concat because concat will create a new array
    this.delegates = pushIntoDelegates(this.delegates, arguments);

    if (this.__unlistened__ === true) {
      addEventListenerHelper(this.getRootElement(), this.__event__, this);
      this.__unlistened__ = false;
    }
  };

  DelegateList.prototype.unlisten = function () {
    removeEventListenerHelper(this.getRootElement(), this.__event__, this);
    this.__unlistened__ = true;
  };
  DelegateList.prototype.isUnlistened = function () {
    return this.__unlistened__ || false;
  };

  // constructor for event delegate Center
  function EventList(element, registeredVariable, scope) {
    var selectorString = null;
    if (!element || element === document) {
      element = document;
      selectorString = "document";
    }
    else {
      /* this is only mute jshint warning */
      /*global jQuery:true*/
      // if `element' is a jQuery object
      if ("jQuery" in window && element instanceof jQuery) {
        selectorString = element.selector;
        element = element[0];
        // jQuery.selector return "" for $(document), $(document.body)
        // so we have to do some extra check
        if (jQuery(document)[0] === element) {
          selectorString = "document";
        }
        else if (jQuery("body")[0] === element) {
          selectorString = "body";
        }
      }

      // if `element' is a string
      // we do not have to use getTypeOf
      // typeof seems to be enough
      else if (typeof element === "string") {
        if ("querySelector" in document) {
          selectorString = element;
          if (!(element = document.querySelector(selectorString))) {
            throw new TypeError("Unable to parse element: unexpected response from querySelector.");
          }
        }
      }
    }

    if (!element.addEventListener && !element.attachEvent) {
      throw new Error("Unable to find addEventListener and attachEvent on element.");
    }

    // record every instance's variable name (if possible)
    // By the hidden info, we could make each new EventList a singleton
    // if we re-instantiated EventList, it will return proper object
    this.constructor.__registered__ = this.constructor.__registered__ || {};

    var _previousInstance = this.constructor.__registered__[selectorString];
    // FIXME compare __root__ for better matching
    if (_previousInstance) {
      if ((_previousInstance.scope)[_previousInstance.variable]) {
        return (_previousInstance.scope)[_previousInstance.variable];
      }
      _previousInstance = null;
    }
    else if (registeredVariable) {
      // Object key must be string
      // or must have identical value when toString is called
      // http://www.hacksparrow.com/object-as-javascript-objects-key.html
      this.constructor.__registered__[selectorString] =
                                          { "variable"  : registeredVariable,
                                            "scope"     : scope || root
                                          };
    }

    setProperty(this, "__root__", element);

    if (selectorString) {
      setProperty(this, "__rootSelector__", selectorString);
    }
  }

  // focus and blur does NOT bubble up
  EventList.prototype.listen = function () {
    var _self = setEnv(this);

    if (!arguments.length) {
      return _self;
    }
    var _event = arguments[0];

    if (!Object.prototype.hasOwnProperty.call(document.body, "on" + _event)) {
      throw new TypeError(_event + " unavailable.");
    }

    var delegateArray = [];
    // skipping the first argument
    delegateArray = pushIntoDelegates([], arguments, 1);

    // singleton for every event
    if (!_self.hasOwnProperty(_event)) {
      _self[_event] = new DelegateList(delegateArray);
      // until we have a better solution, we'll have to contaminate all object
      // created by DelegateList
      setProperty(_self[_event], "__root__", _self.getRootElement());
      setProperty(_self[_event], "__event__", _event);

      addEventListenerHelper(_self.getRootElement(), _event, _self[_event]);
    }
    else {
      _self[_event].listen(delegateArray);

      if (_self[_event].isUnlistened) {
        //_self.getRootElement().addEventListener(_event, _self[_event]);
        addEventListenerHelper(_self.getRootElement(), _event, _self[_event]);
        _self.__unlistened__ = false;
      }
    }
    delegateArray = null;

    return _self;
  };

  // only add a flag not to listen and removeEventListener
  // does NOT remove the EventList item
  EventList.prototype.unlisten = function (_event) {
    var _self = setEnv(this);

    removeEventListenerHelper(_self.getRootElement(), _event, _self[_event]);
    _self[_event].__unlistened__ = true;

    return _self;
  };

  // only safe way to remove EventList item
  EventList.prototype.remove = function (_event) {
    var _self = setEnv(this);

    _self.unlisten(_event);
    delete _self[_event];

    return _self;
  };

  EventList.prototype.disable = function (_event) {
    var _self = setEnv(this);

    if (this[_event]) {
      this[_event].disabled = true;
    }
    return _self;
  };

  // for lesser browser
  // always check for `__' prefix in for-in loop
  // TODO: do we need this iterator?
  EventList.prototype.loop = function (_callback) {
    var _self = setEnv(this);

    _callback = _callback || function (key) { console.log(key); };

    // for browser that support `propertyIsEnumberable'
    // we check if prototype
    var key, value;
    if ("propertyIsEnumerable" in _self) {
      for (key in _self) {
        if (_self.hasOwnProperty(key) && _self[key].constructor.name === "DelegateList") {
          _callback.call(_self, key, value);
        }
      }
    }
    else {
      for (key in _self) {
        if (key !== "prototype" && ~key.indexOf("__")) {
          _callback.call(_self, key, value);
        }
      }
    }
  };

  EventList.prototype.getRootElement = function () {
    // we do not use _self for safety reasons
    if (this.__root__) {
      return this.__root__;
    }
    else {
      throw new Error("Root element not found.");
    }
  };

  EventList.prototype.getRootElementSelector = function () {
    // we do not use _self for safety reasons
    if (this.__rootSelector__) {
      return this.__rootSelector__;
    }
    else {
      // cannot throw error
      return null;
    }
  };

  EventList.prototype.isUnlistened = function () {
    var _self = setEnv(this);

    return _self.__unlistened__ || false;
  };

  // Events.* has no way of knowing the `__root__'
  // we have to delay this prototype function declaration
  // to dismiss `EventList' not found error
  DelegateList.prototype.getRootElement = EventList.prototype.getRootElement;

  // in case we need multiple instances
  root[name] = EventList;
}(this, "EventList"));
// test
//var a = new EventList("body","a"); a.x=1; var b = new EventList("body");
<commit_msg>fixed various bug that I found using unit test<commit_after>/* ex: set tabstop=2 softtabstop=2 shiftwidth=2 : */

/*jshint unused:false, boss:true */
/*global setProperty:true, elementFitsDescription:true */

(function (root, name) {
  "use strict";
  // in case we decide to change those names later on
  var delegateSelector = "selector",
      delegateFunction = "handler";

  // shorthand or toggle individual state of delegateFunction
  function changeState(delegateArray, item, state) {
    var i, delegateItem;
    for (i = 0; delegateItem = delegateArray[i]; i++) {
      if (delegateItem[delegateSelector] === item) {
        delegateItem.disabled = Boolean(state);
        break;
      }
    }
  }

  function getEventTarget(e) {
    e = e || window.event;
    return e.target || e.srcElement;
  }

  function execute(func, scope) {
    if (func) {
      func.call(scope);
    }
  }

  function setEnv(scope) {
    var _self, _previousInstance = scope.constructor.__registered__[scope.getRootElementSelector()];
    if (_previousInstance) {
      _self = (_previousInstance.scope)[_previousInstance.variable] || scope;
    }
    else {
      _self = scope;
    }
    _previousInstance = null;
    return _self;
  }

  function addEventListenerHelper(element, _event, _obj) {
    if (element.addEventListener) {
      element.addEventListener(_event, _obj, false);
    }
    else if (element.attachEvent) {
      element.attachEvent("on" + _event, _obj);
    }
  }

  function removeEventListenerHelper(element, _event, _obj) {
    if (element.removeEventListener) {
      element.removeEventListener(_event, _obj);
    }
    else if (element.detachEvent) {
      element.detachEvent("on" + _event, _obj);
    }
  }

  /**
   * @name DelegateList
   * @function
   *
   * @description
   * constructor for delegates method object/array
   * create a object simular to array
   * better not subclassing JavaScript Array
   * https://perfectionkills.com/how-ecmascript-5-still-does-not-allow-to-subclass-an-array
   *
   * @param arr ARRAY
   */
  function DelegateList(arr) {
    /*jshint validthis:true */
    this.disabled = false;
    if (arr) {
      arr = arr.filter(function(i) {
        if (i.hasOwnProperty(delegateSelector)) {
          return true;
        }
      });
    }
    this.delegates = arr || [];

    // allow overwrite
    setProperty(this, "__unlistened__", false, true);
  }

  /*
   * we do not use this.disable to modify the master disable switch
   * because user might accidentally calls this method without giving an argument
   * for that circumstance, we should do nothing
   * instead, we use disableAll to modify the master disable switch
   */
  DelegateList.prototype.disable = function (item) {

    if (item) {
      changeState(this.delegates, item, true);
    }
    return this;
  };

  DelegateList.prototype.enable = function (item) {
    if (item) {
      changeState(this.delegates, item, false);
    }
    return this;
  };

  DelegateList.prototype.disableAll = function () {
    this.disabled = true;
    return this;
  };

  DelegateList.prototype.enableAll = function () {
    this.disabled = false;
    return this;
  };

  /**
   * @name handleEvent
   * @function
   *
   * @description
   * actual function to attach events
   * we all know that we could bind object in addEventListener
   * http://w3.org/TR/DOM-Level-2-Events/events.html
   * provided there is a `handleEvent' property in the object
   * here is the trick, we COULD use a function to generate an object with
   * `handleEvent' nicely hidden inside its `prototype'
   *
   * @param evt
   */
  DelegateList.prototype.handleEvent = function (evt) {
    // master switch
    if (this.disabled || this.delegates.length === 0) {
      return;
    }

    var i, item, targetElement = getEventTarget(evt);

    for (i = 0; item = this.delegates[i]; i++) {
      if (item.disabled) {
        continue;
      }
      // FIXME: add documentation explaining why we use this instead of querySelector match
      if (elementFitsDescription(targetElement, item[delegateSelector])) {
        execute(item[delegateFunction], targetElement);
      }
    } // end of for loop
  };

  /**
   * @name listen
   * @function
   *
   * @description
   *
   * @param arr
   */
  DelegateList.prototype.listen = function () {
    // make arguments an array
    var arr, i, item;
    switch (arguments.length) {
    case 0:
      arr = [];
      break;
    case 1:
      arr = arguments[0];
      arr = (arr instanceof Array) ? arr : [arr];
      break;
    default:
      arr = [].slice.call(arguments);
    }

    this.delegates = this.delegates || [];
    for (i = 0; item = arr[i]; i++) {
      if (item.hasOwnProperty(delegateSelector)) {
        this.delegates.push(item);
      }
    }

    if (this.__unlistened__ === true) {
      addEventListenerHelper(this.getRootElement(), this.__event__, this);
      this.__unlistened__ = false;
    }
  };

  DelegateList.prototype.unlisten = function () {
    removeEventListenerHelper(this.getRootElement(), this.__event__, this);
    this.__unlistened__ = true;
  };
  DelegateList.prototype.isUnlistened = function () {
    return this.__unlistened__ || false;
  };

  // constructor for event delegate Center
  function EventList(element, registeredVariable, variableScope) {
    var selectorString = null;
    if (!element || element === document || element === "document") {
      element = document;
      selectorString = "document";
    }
    else {
      /* this is only mute jshint warning */
      /*global jQuery:true*/
      // if `element' is a jQuery object
      if ("jQuery" in window && element instanceof jQuery) {
        selectorString = element.selector;
        element = element[0];
        // jQuery.selector return "" for $(document), $(document.body)
        // so we have to do some extra check
        if (element === document) {
          selectorString = "document";
        }
        else if (element === document.body) {
          selectorString = "body";
        }
      }

      // if `element' is a string
      // we do not have to use getTypeOf
      // typeof seems to be enough
      else if (typeof element === "string") {
        if ("querySelector" in document) {
          selectorString = element;
          if (!(element = document.querySelector(selectorString))) {
            throw new TypeError("Unable to parse element: unexpected response from querySelector.");
          }
        }
      }
      else if (element.length) {
        element = element[0];
      }
    }

    if (!element.addEventListener && !element.attachEvent) {
      throw new Error("Unable to find addEventListener and attachEvent on element.");
    }

    // record every instance's variable name (if possible)
    // By the hidden info, we could make each new EventList a singleton
    // if we re-instantiated EventList, it will return proper object
    this.constructor.__registered__ = this.constructor.__registered__ || {};

    var _previousInstance = this.constructor.__registered__[selectorString];
    // FIXME compare __root__ for better matching
    if (_previousInstance) {
      if ((_previousInstance.scope)[_previousInstance.variable]) {
        return (_previousInstance.scope)[_previousInstance.variable];
      }
      _previousInstance = null;
    }
    else if (registeredVariable) {
      variableScope = variableScope || root;
      variableScope[registeredVariable] = this;
      // Object key must be string
      // or must have identical value when toString is called
      // http://www.hacksparrow.com/object-as-javascript-objects-key.html
      this.constructor.__registered__[selectorString] =
                                          { "variable"  : registeredVariable,
                                            "scope"     : variableScope
                                          };

    }

    setProperty(this, "__root__", element);

    if (selectorString) {
      setProperty(this, "__rootSelector__", selectorString);
    }
  }

  // focus and blur does NOT bubble up
  EventList.prototype.listen = function () {
    var _self = setEnv(this);

    if (!arguments.length) {
      return _self;
    }
    var _event = arguments[0];

    if (!(("on" + _event) in document.body)) {
      throw new TypeError(_event + " unavailable.");
    }

    var arr = [].slice.call(arguments, 1);

    if (arr.length === 1) {
      if (!arr[0]) {
        arr = [];
      }
      else {
        arr = (arr[0] instanceof Array) ? arr[0] : arr;
      }
    }
    // singleton for every event
    if (!_self.hasOwnProperty(_event)) {
      _self[_event] = new DelegateList(arr);
      // until we have a better solution, we'll have to contaminate all object
      // created by DelegateList
      setProperty(_self[_event], "__root__", _self.getRootElement());
      setProperty(_self[_event], "__event__", _event);

      addEventListenerHelper(_self.getRootElement(), _event, _self[_event]);
    }
    else {
      _self[_event].listen(arr);

      if (_self[_event].isUnlistened) {
        //_self.getRootElement().addEventListener(_event, _self[_event]);
        addEventListenerHelper(_self.getRootElement(), _event, _self[_event]);
        _self.__unlistened__ = false;
      }
    }
    arr = null;

    return _self;
  };

  // only add a flag not to listen and removeEventListener
  // does NOT remove the EventList item
  EventList.prototype.unlisten = function (_event) {
    var _self = setEnv(this);

    removeEventListenerHelper(_self.getRootElement(), _event, _self[_event]);
    _self[_event].__unlistened__ = true;

    return _self;
  };

  // only safe way to remove EventList item
  EventList.prototype.remove = function (_event) {
    var _self = setEnv(this);

    _self.unlisten(_event);
    delete _self[_event];

    return _self;
  };

  EventList.prototype.disable = function (_event) {
    var _self = setEnv(this);

    if (this[_event]) {
      this[_event].disabled = true;
    }
    return _self;
  };

  EventList.prototype.enable = function (_event) {
    var _self = setEnv(this);

    if (this[_event]) {
      if (this[_event].disabled) {
        this[_event].disabled = false;
      }
    }
    return _self;
  };

  // for lesser browser
  // always check for `__' prefix in for-in loop
  // TODO: do we need this iterator?
  EventList.prototype.loop = function (_callback) {
    var _self = setEnv(this);

    _callback = _callback || function (key) { console.log(key); };

    // for browser that support `propertyIsEnumberable'
    // we check if prototype
    var key, value;
    if ("propertyIsEnumerable" in _self) {
      for (key in _self) {
        if (_self.hasOwnProperty(key) && _self[key].constructor.name === "DelegateList") {
          _callback.call(_self, key, value);
        }
      }
    }
    else {
      for (key in _self) {
        if (key !== "prototype" && ~key.indexOf("__")) {
          _callback.call(_self, key, value);
        }
      }
    }
  };

  EventList.prototype.getRootElement = function () {
    // we do not use _self for safety reasons
    if (this.__root__) {
      return this.__root__;
    }
    else {
      throw new Error("Root element not found.");
    }
  };

  EventList.prototype.getRootElementSelector = function () {
    // we do not use _self for safety reasons
    if (this.__rootSelector__) {
      return this.__rootSelector__;
    }
    else {
      // cannot throw error
      return null;
    }
  };

  EventList.prototype.isUnlistened = function () {
    var _self = setEnv(this);

    return _self.__unlistened__ || false;
  };

  // Events.* has no way of knowing the `__root__'
  // we have to delay this prototype function declaration
  // to dismiss `EventList' not found error
  DelegateList.prototype.getRootElement = EventList.prototype.getRootElement;

  // in case we need multiple instances
  root[name] = EventList;
}(this, "EventList"));
<|endoftext|>


<commit_before>import passport from 'passport';
import { Strategy } from 'passport-helsinki';

import serverConfig from './config';

function configurePassport() {
  let helsinkiStrategy;
  helsinkiStrategy = new Strategy(
    {
      clientID: process.env.CLIENT_ID,
      clientSecret: process.env.CLIENT_SECRET,
      callbackURL: `http://localhost:${serverConfig.port}/login/helsinki/return`,
    },
    (accessToken, refreshToken, profile, cb) => {
      helsinkiStrategy.getAPIToken(accessToken, process.env.TARGET_APP, (token) => {
        profile.token = token;
        return cb(null, profile);
      });
    });

  passport.use(helsinkiStrategy);

  passport.serializeUser((user, cb) => {
    cb(null, user);
  });

  passport.deserializeUser((obj, cb) => {
    cb(null, obj);
  });

  return passport;
}

export default configurePassport;
<commit_msg>Fix login callbackUrl on production<commit_after>import passport from 'passport';
import { Strategy } from 'passport-helsinki';

import serverConfig from './config';

function configurePassport() {
  let helsinkiStrategy;
  const callbackURL = (
    serverConfig.isProduction ?
    'http://respa.hel.ninja/login/helsinki/return' :
    `http://localhost:${serverConfig.port}/login/helsinki/return`
  );
  helsinkiStrategy = new Strategy(
    {
      clientID: process.env.CLIENT_ID,
      clientSecret: process.env.CLIENT_SECRET,
      callbackURL,
    },
    (accessToken, refreshToken, profile, cb) => {
      helsinkiStrategy.getAPIToken(accessToken, process.env.TARGET_APP, (token) => {
        profile.token = token;
        return cb(null, profile);
      });
    });

  passport.use(helsinkiStrategy);

  passport.serializeUser((user, cb) => {
    cb(null, user);
  });

  passport.deserializeUser((obj, cb) => {
    cb(null, obj);
  });

  return passport;
}

export default configurePassport;
<|endoftext|>


<commit_before>const roles = require('../models').Role;

module.exports = {
  create(req, res) {
    return roles
      .create({
        name: req.body.name,
      })
      .then(role => res.status(201).send(role))
      .catch(error => res.status(400).send(error));
  },
};
<commit_msg>[feature #141877939] Add additional endpoints for the routes<commit_after>const roles = require('../models').Role;

class Roles {
  create(req, res) {
    return roles
    .create(req.body)
    .then((role) => {
      res.status(201).send({
        message: 'Role created succesfully',
        role,
      });
    })
    .catch(error => res.status(400).send(error.errors));
  }
  update(req, res) {
    return roles
    .findById(req.params.id)
    .then((role) => {
      if (!role) {
        return res.status(404).send({
          message: 'Role Not Found',
        });
      }
      return role
        .update(req.body)
        .then(() => res.status(200).send(role))
        .catch(error => res.status(400).send(error));
    })
    .catch(error => res.status(400).send(error));
  }
  findOne(req, res) {
    return roles
    .findById(req.params.id)
    .then((role) => {
      if (!role) {
        return res.status(404).send({
          message: 'Role Not Found',
        });
      }
      return res.status(200).send(role);
    })
    .catch(error => res.status(400).send(error));
  }
  listAll(req, res) {
    return roles
    .findAll()
    .then(role => res.status(200).send({ message: 'Listing all available roles', role }))
    .catch(error => res.status(400).send(error));
  }
  delete(req, res) {
    return roles
    .find({
      where: {
        id: req.params.id,
      },
    })
    .then((role) => {
      if (!role) {
        return res.status(404).send({
          message: 'Role not found',
        });
      }
      return role
        .destroy()
        .then(() => {
          res.status(200).send({
            message: 'Role deleted successfully',
          });
        })
        .catch(error => res.status(400).send(error));
    })
    .catch(error => res.status(400).send(error));
  }
}

exports.Roles = Roles;
<|endoftext|>


<commit_before>/*
  Expand - Short Page Fix
  Version: 1.2
  Developer: Jonathan Chute
  Year: 2016
*/

(function( $ ) {
    $.fn.expand = function(options) {

        var settings = $.extend( {
            'end':   ''
        }, options);

        var mainObj = $(this);
            if(mainObj[0] === undefined)
                return;
        var wrapper = mainObj.parent();

        setHeight();

        $(window).on("load resize", function(){
            setHeight();
        });

        function setHeight() {
            var height = $(window).height();

            height -= subtract('html', true);
            height -= subtract('body', true);
            height -= (!compare($('body'), wrapper)) ? subtract(wrapper, true) : 0;
            height -= subtract(mainObj, false);

            $(wrapper).children().not(mainObj).each(function(){
                var position = $(this).css('position');
                if(position == 'absolute' || position == 'fixed') return true;
                height -= $(this).outerHeight(true);
                if(settings.end != '') if($(this).is(settings.end)) return false;
            });

            $(mainObj).css('min-height', height);
        }

        function subtract(object, padding) {
            var total = 0;

            total += parseInt($(object).css('marginTop'));
            total += parseInt($(object).css('marginBottom'));
            total += parseInt($(object).css('borderTopWidth'));
            total += parseInt($(object).css('borderBottomWidth'));

            if(padding) {
                total += parseInt($(object).css('paddingTop'));
                total += parseInt($(object).css('paddingBottom'));
            }

            return total;
        }

        function compare(object1, object2) {
            if(object1.length !== object2.length) return false;
            for(var i = 0; i < object1.length; i++ ) {
                if(object1[i] !== object2[i]) return false;
            }
            return true;
        }

    };
})( jQuery );
<commit_msg>Update expand.js<commit_after>/*
  Expand - Short Page Fix
  Version: 1.3
  Developer: Jonathan Chute
  Year: 2017
*/
(function( $ ) {
    $.fn.expand = function(options) {

        var settings = $.extend( {
            'end':   '',
            'after': false,
        }, options);

        var mainObj = $(this);
            if(mainObj[0] === undefined)
                return;
        var wrapper = mainObj.parent();

        setHeight();

        $(window).on("load resize", function(){
            setHeight();
            settings.after();
        });

        function setHeight() {
            var height = $(window).height();

            height -= subtract('html', true);
            height -= subtract('body', true);
            height -= (!compare($('body'), wrapper)) ? subtract(wrapper, true) : 0;
            height -= subtract(mainObj, false);

            $(wrapper).children().not(mainObj).each(function(){
                var position = $(this).css('position');
                if(position == 'absolute' || position == 'fixed') return true;
                height -= $(this).outerHeight(true);
                if(settings.end != '') if($(this).is(settings.end)) return false;
            });

            $(mainObj).css('min-height', height);
        }

        function subtract(object, padding) {
            var total = 0;

            total += parseInt($(object).css('marginTop'));
            total += parseInt($(object).css('marginBottom'));
            total += parseInt($(object).css('borderTopWidth'));
            total += parseInt($(object).css('borderBottomWidth'));

            if(padding) {
                total += parseInt($(object).css('paddingTop'));
                total += parseInt($(object).css('paddingBottom'));
            }

            return total;
        }

        function compare(object1, object2) {
            if(object1.length !== object2.length) return false;
            for(var i = 0; i < object1.length; i++ ) {
                if(object1[i] !== object2[i]) return false;
            }
            return true;
        }

    };
})( jQuery );
<|endoftext|>