<commit_before>let testElem = document.createElement('div')
let prefix = null
let eventPrefix = null

export function noop(){}

export function getCoords(el){
    if(el === undefined) el = this
    if(!isDOM(el)) return

    let box = el.getBoundingClientRect(),
    self= window,
    doc = el.ownerDocument,
    body = doc.body,
    html = doc.documentElement,
    clientTop = html.clientTop || body.clientTop || 0,
    clientLeft = html.clientLeft || body.clientLeft || 0

    return {
        top: (box.top + (self.pageYOffset || html.scrollTop || body.scrollTop ) - clientTop),
        left: (box.left + (self.pageXOffset || html.scrollLeft || body.scrollLeft) - clientLeft)
    }
}

export function getStyle(el, name, removeUnit = ""){
    if(typeof el === "string") [el, name, removeUnit] = [this, el, name === undefined ? "" : name]
    if(!isDOM(el)) return

    var style = window.getComputedStyle ? window.getComputedStyle(el, null)[name] : el.currentStyle[name]

    if((name === 'width' || name === 'height') && style === 'auto'){
        if(name == 'width') style = el.offsetWidth
        else if(name == 'height') style = el.offsetHeight
    }

    if(removeUnit !== "" && getType(style) === 'String') {
        style = ~~style.replace(new RegExp(removeUnit),"")
    }

    return style
}

export function escapeHTML(str){
    return str.replace(/&/g,"&")
              .replace(/</g,"<")
              .replace(/>/g,">")
              .replace(/"/g,""")
              .replace(/'/g,"'")
}

export function getDOMState(el, key){
    if(typeof el === 'string') [el, key] = [this, el]

    let attr = null
    if(el instanceof angular.element) {
        attr = ::el.attr
    } else if(isDOM(el)) {
        attr = ::el.getAttribute
    } else {
        throw new Error("Element was not specified.")
    }

    let ret = attr(key)

    if(ret == undefined){
        return false
    } else if(ret === ""){
        return true
    } else if(/true|false/i.test(ret)){
        return !!ret
    } else if(/^\d{1,}$/.test(ret)){
        return ~~ret
    }

    return ret
}

export function addClass(el, cls){
    if(typeof el === 'string') [el, cls] = [this, el]
    if(!isDOM(el)) return

    let clsList = cls.split(' ')

    while(cls = clsList.pop()){
        if (el.classList) {
            el.classList.add(cls)
        } else {
            let cur = ' ' + (el.getAttribute('class') || '') + ' '
            if (cur.indexOf(' ' + cls + ' ') < 0) {
                el.setAttribute('class', (cur + cls).trim())
            }
        }
    }
    return el
}

export function removeClass(el, cls){
    if(typeof el === 'string') [el, cls] = [this, el]
    if(!isDOM(el)) return

    let clsList = cls.split(' ')
    while(cls = clsList.pop()){
        if (el.classList) {
            el.classList.remove(cls)
        } else {
            let cur = ' ' + (el.getAttribute('class') || '') + ' '
            let tar = ' ' + cls + ' '
            while (cur.indexOf(tar) >= 0) {
                cur = cur.replace(tar, ' ')
            }

            el.setAttribute('class', cur.trim())
        }

        if (!el.className) {
            el.removeAttribute('class')
        }
    }
    return el
}

export function replaceClass(el, orig, mdi){
    if(typeof el === 'string') [el, orig, mdi] = [this, el, orig]
    if(!isDOM(el)) return
    el::removeClass(orig)
    el::addClass(mdi)
    return el
}

export function on (el, event, cb) {
    if(typeof el === 'string') [el, event, cb] = [this, el, event]
    if(!isDOM(el)) return
    let evts = event.split(' ')
    while (evts.length){
        el.addEventListener(evts.pop(), cb)
    }
    return el
}

export function off(el, event, cb){
    if(typeof el === 'string') [el, event, cb] = [this, el, event]
    if(!isDOM(el)) return
    let evts = event.split(' ')
    while (evts.length){
        el.removeEventListener(evts.pop(), cb)
    }
    return el
}

export function before(el, target) {
    if(arguments.length === 1) [el, target] = [this, el]
    el = toDOM(el)
    target.parentNode.insertBefore(el, target)
    return el
}

export function after(el, target) {
    if(arguments.length === 1) [el, target] = [this, el]
    el = toDOM(el)
    return el.nextSibling ? before(target,el.nextSibling) : el.parentNode.appendChild(target), target
}

export function prepend(target, el){
    if(arguments.length === 1) [target, el] = [this, target]
    el = toDOM(el)
    return target.firstChild ? el::before(target.firstChild) : target.appendChild(el), el
}

export function last(target, el){
    if(arguments.length === 1) [target, el] = [this, target]
    el = toDOM(el)
    return target.length > 0 ? el::after(target.lastChild) : target.appendChild(el), el
}

export function remove(el){
    if(arguments.length === 0) [el] = [this]
    el.parentNode.removeChild(el)
}

export function replace(target, el){
    if(arguments.length === 1) [target, el] = [this, target]
    el = toDOM(el)

    let parent = target.parentNode
    if(parent){
        parent.replaceChild(el, target)
    }
    return el
}

export function isDOM(el){
    if (el.nodeType && el.nodeName) return true
    return false
}

export function toDOM(el){ //remark 支持多个元素 类似123
321
  用fragment?
    if(arguments.length === 0) el = this
    if(typeof el === 'string'){
        let dom = createElem('div')
        dom.innerHTML = el
        el = dom.firstChild
    }

    return el
}

/*
function fragmentFromString(strHTML) {
    var temp = document.createElement('template');
    temp.innerHTML = strHTML;
    return temp.content;
}
*/

export function detechPrefix(){
    if(prefix !== null && eventPrefix !== null) return { prefix, eventPrefix }

    let vendor = { Webkit: 'webkit', Moz: '', O: 'o' }

    for(var i in vendor){
        if (testElem.style[i + 'TransitionProperty'] !== undefined) {
            prefix = '-' + i.toLowerCase() + '-'
            eventPrefix = vendor[i]
            return { prefix, eventPrefix }
        }
    }

    prefix = eventPrefix = ""
    return { prefix, eventPrefix }
}

export function onMotionEnd(el, cb){
    if(typeof el === 'function') [el, cb] = [this, el]
    if(!isDOM(el) && !(el instanceof angular.element)) return
    if(el instanceof angular.element) el = el[0]

    let {prefix, eventPrefix} = detechPrefix()

    let handler = e => { //remark
        if(e && e.target === el){
            el::off(eventPrefix + 'TransitionEnd', handler)
            el::off('animationend webkitAnimationEnd MSAnimationEnd oAnimationEnd', handler)
            cb()
        }
    }
    el::on(eventPrefix + 'TransitionEnd', handler)
    el::on('animationend webkitAnimationEnd MSAnimationEnd oAnimationEnd', handler)
    return el
}

export function debounce(func, wait){
    let timeout, args, context, timestamp, result
    let later = () => {
        let last = Date.now() - timestamp
        if (last < wait && last >= 0) {
            timeout = setTimeout(later, wait - last)
        } else {
            timeout = null
            result = func.apply(context, args)
            if (!timeout) context = args = null
        }
    }

    return function() {
        context = this
        args = arguments
        timestamp = Date.now()
        if (!timeout)  timeout = setTimeout(later, wait)
        return result
    }
}

export function query(el){
    let base = this
        ? this.__esModule ? document : this
        : document
    if (typeof el === 'string') {
        let selector = el
        el = base.querySelector(selector)
    }
    return el
}

export function queryAll(el){
    let base = this
        ? this.__esModule ? document : this
        : document
    if (typeof el === 'string') {
        let selector = el
        el = base.querySelectorAll(selector)
    }
    return el
}

export function createElem(tag){
    return document.createElement(tag)
}

export function getType(obj){
    if(arguments.length === 0) obj = this
    return Object.prototype.toString.call(obj).replace(/^\[object (\w+)\]$/,'$1')
}

export function is(v1, v2){
    if(this !== undefined){
        [v1, v2] = [this, v1]
    }

    if(!Object.is){
        if (v1 === 0 && v2 === 0) {
            return 1 / v1 === 1 / v2
        }

        if (v1 !== v1) {
            return v2 !== v2
        }

        return v1 === v2
    } else {
        return Object.is(v1, v2)
    }
}

let _FMId = 1
export function generateFermiId(){
    let id = _FMId.toString().split('')
    let len = id.length
    for(let i = 0; i < (5 - len); i++){
        id.unshift("0")
    }
    _FMId++
    return id.join('.')
}

export function nextId(){
    return _FMId++
}

export function clamp(val, min, max){
    return val < min ? min : (val > max ? max : val)
}

export function def(obj, key, option){
    Object.defineProperty(obj, key, option)
}

export function setStyle(el, obj){
    if(arguments.length === 1) [el, obj] = [this, el]
    for(let i in obj){
        if(obj.hasOwnProperty(i)){
            el.style[i] = obj[i]
        }
    }
}

export function inDoc(el) {
    if(arguments.length === 0) el = this
    let doc = document.documentElement
    let parent = el && el.parentNode
    return doc === el || doc === parent || !!(parent && parent.nodeType === 1 && (doc.contains(parent)))
}

export function range(size, start = 0){
    let arr = []
    for(let i = start; i <= size; i++) arr.push(i)
    return arr
}

export function generateUID(){
   return '_F' + ("0000" + (Math.random() * Math.pow(36,6) << 0).toString(36)).slice(-6) + nextId()
}

export function queue(isAsync = false, interval = 0){
    let waiting = []

    let next = () => {
        let fn = waiting.shift()
        if(fn){
            isAsync
            ? setTimeout(() => fn(next), interval)
            : fn(next)
        }
    }

    let entry = fn => {
        waiting.push(fn)
        if (waiting.length === 1) next()
    }

    entry.count = () => waiting.length
    return entry
}

export function isHidden(el) {
  return !(el.offsetWidth || el.offsetHeight || el.getClientRects().length)
}

/*export function extend(target){
    if(!this.$new) throw new Error("caller was not a angular scope variable.")
    let dest = this
    let ignore = []
    if(target.constructor){
        let re = /(?:this\.)(\w+)/gm
        let source = target.constructor.toString()
        source.match(re).forEach(e => ignore.push(e.substr(5)))
    }

    for (let key in target) {
        if (!dest[key] && ignore.indexOf(key) ===-1 && target.hasOwnProperty(key)) {
            dest[key] = target[key]
        }
    }

    export function toggleClass(el, namespace, state, suffix){
        if(arguments.length === 3) [el, namespace, state, suffix] = [this, el, namespace, state]

        return function(){

            state
            ? el::replaceClass('hide', namespace + '-' + suffix['true'])
            : el::replaceClass(namespace + '-' + suffix['true'], namespace + '-' + suffix['false'])::onMotionEnd(() => {
                //debugger
                el::replaceClass(namespace + '-' + suffix['false'], 'hide')
            })

            state = !state
        }
    }
}*/
<commit_msg>update<commit_after>let testElem = document.createElement('div')
let prefix = null
let eventPrefix = null
let reUnit = /width|height|top|left|right|bottom|margin|padding/i
let reBool = /true|false/i

export function noop(){}

export function getCoords(el){
    if(el === undefined) el = this
    if(!isDOM(el)) return

    let box = el.getBoundingClientRect(),
    self= window,
    doc = el.ownerDocument,
    body = doc.body,
    html = doc.documentElement,
    clientTop = html.clientTop || body.clientTop || 0,
    clientLeft = html.clientLeft || body.clientLeft || 0

    return {
        top: (box.top + (self.pageYOffset || html.scrollTop || body.scrollTop ) - clientTop),
        left: (box.left + (self.pageXOffset || html.scrollLeft || body.scrollLeft) - clientLeft)
    }
}

export function getStyle(el, name, removeUnit = ""){
    if(typeof el === "string") [el, name, removeUnit] = [this, el, name === undefined ? "" : name]
    if(!isDOM(el)) return

    var style = window.getComputedStyle ? window.getComputedStyle(el, null)[name] : el.currentStyle[name]

    if((name === 'width' || name === 'height') && style === 'auto'){
        if(name == 'width') style = el.offsetWidth
        else if(name == 'height') style = el.offsetHeight
    }

    if(removeUnit !== "" && getType(style) === 'String') {
        style = ~~style.replace(new RegExp(removeUnit), "")
    }

    return style
}

export function escapeHTML(str){
    return str.replace(/&/g,"&")
              .replace(/</g,"<")
              .replace(/>/g,">")
              .replace(/"/g,""")
              .replace(/'/g,"'")
}

export function getDOMState(el, key){
    if(typeof el === 'string') [el, key] = [this, el]

    let attr = null
    if(el instanceof angular.element) {
        attr = ::el.attr
    } else if(isDOM(el)) {
        attr = ::el.getAttribute
    } else {
        throw new Error("Element was not specified.")
    }

    let ret = attr(key)

    if(ret == undefined){
        return false
    } else if(ret === ""){
        return true
    } else if(reBool.test(ret)){
        return !!ret
    } else if(/^\d{1,}$/.test(ret)){
        return ~~ret
    }

    return ret
}

export function addClass(el, cls){
    if(typeof el === 'string') [el, cls] = [this, el]
    if(!isDOM(el)) return

    let clsList = cls.split(' ')

    while(cls = clsList.pop()){
        if (el.classList) {
            el.classList.add(cls)
        } else {
            let cur = ' ' + (el.getAttribute('class') || '') + ' '
            if (cur.indexOf(' ' + cls + ' ') < 0) {
                el.setAttribute('class', (cur + cls).trim())
            }
        }
    }
    return el
}

export function removeClass(el, cls){
    if(typeof el === 'string') [el, cls] = [this, el]
    if(!isDOM(el)) return

    let clsList = cls.split(' ')
    while(cls = clsList.pop()){
        if (el.classList) {
            el.classList.remove(cls)
        } else {
            let cur = ' ' + (el.getAttribute('class') || '') + ' '
            let tar = ' ' + cls + ' '
            while (cur.indexOf(tar) >= 0) {
                cur = cur.replace(tar, ' ')
            }

            el.setAttribute('class', cur.trim())
        }

        if (!el.className) {
            el.removeAttribute('class')
        }
    }
    return el
}

export function replaceClass(el, orig, mdi){
    if(typeof el === 'string') [el, orig, mdi] = [this, el, orig]
    if(!isDOM(el)) return
    el::removeClass(orig)
    el::addClass(mdi)
    return el
}

export function on (el, event, cb) {
    if(typeof el === 'string') [el, event, cb] = [this, el, event]
    if(!isDOM(el)) return
    let evts = event.split(' ')
    while (evts.length){
        el.addEventListener(evts.pop(), cb)
    }
    return el
}

export function off(el, event, cb){
    if(typeof el === 'string') [el, event, cb] = [this, el, event]
    if(!isDOM(el)) return
    let evts = event.split(' ')
    while (evts.length){
        el.removeEventListener(evts.pop(), cb)
    }
    return el
}

export function before(el, target) {
    if(arguments.length === 1) [el, target] = [this, el]
    el = toDOM(el)
    target.parentNode.insertBefore(el, target)
    return el
}

export function after(el, target) {
    if(arguments.length === 1) [el, target] = [this, el]
    el = toDOM(el)
    return el.nextSibling ? before(target,el.nextSibling) : el.parentNode.appendChild(target), target
}

export function prepend(target, el){
    if(arguments.length === 1) [target, el] = [this, target]
    el = toDOM(el)
    return target.firstChild ? el::before(target.firstChild) : target.appendChild(el), el
}

export function last(target, el){
    if(arguments.length === 1) [target, el] = [this, target]
    el = toDOM(el)
    return target.length > 0 ? el::after(target.lastChild) : target.appendChild(el), el
}

export function remove(el){
    if(arguments.length === 0) [el] = [this]
    el.parentNode.removeChild(el)
}

export function replace(target, el){
    if(arguments.length === 1) [target, el] = [this, target]
    el = toDOM(el)

    let parent = target.parentNode
    if(parent){
        parent.replaceChild(el, target)
    }
    return el
}

export function isDOM(el){
    if (el.nodeType && el.nodeName) return true
    return false
}

export function toDOM(el){ //remark 支持多个元素 类似123
321
  用fragment?
    if(arguments.length === 0) el = this
    if(typeof el === 'string'){
        let dom = createElem('div')
        dom.innerHTML = el
        el = dom.firstChild
    }

    return el
}

/*
function fragmentFromString(strHTML) {
    var temp = document.createElement('template');
    temp.innerHTML = strHTML;
    return temp.content;
}
*/

export function detechPrefix(){
    if(prefix !== null && eventPrefix !== null) return { prefix, eventPrefix }

    let vendor = { Webkit: 'webkit', Moz: '', O: 'o' }

    for(var i in vendor){
        if (testElem.style[i + 'TransitionProperty'] !== undefined) {
            prefix = '-' + i.toLowerCase() + '-'
            eventPrefix = vendor[i]
            return { prefix, eventPrefix }
        }
    }

    prefix = eventPrefix = ""
    return { prefix, eventPrefix }
}

export function onMotionEnd(el, cb){
    if(typeof el === 'function') [el, cb] = [this, el]
    if(!isDOM(el) && !(el instanceof angular.element)) return
    if(el instanceof angular.element) el = el[0]

    let {prefix, eventPrefix} = detechPrefix()

    let handler = e => { //remark
        if(e && e.target === el){
            el::off(eventPrefix + 'TransitionEnd', handler)
            el::off('animationend webkitAnimationEnd MSAnimationEnd oAnimationEnd', handler)
            cb()
        }
    }
    el::on(eventPrefix + 'TransitionEnd', handler)
    el::on('animationend webkitAnimationEnd MSAnimationEnd oAnimationEnd', handler)
    return el
}

export function debounce(func, wait){
    let timeout, args, context, timestamp, result
    let later = () => {
        let last = Date.now() - timestamp
        if (last < wait && last >= 0) {
            timeout = setTimeout(later, wait - last)
        } else {
            timeout = null
            result = func.apply(context, args)
            if (!timeout) context = args = null
        }
    }

    return function() {
        context = this
        args = arguments
        timestamp = Date.now()
        if (!timeout)  timeout = setTimeout(later, wait)
        return result
    }
}

export function query(el){
    let base = this
        ? this.__esModule ? document : this
        : document
    if (typeof el === 'string') {
        let selector = el
        el = base.querySelector(selector)
    }
    return el
}

export function queryAll(el){
    let base = this
        ? this.__esModule ? document : this
        : document
    if (typeof el === 'string') {
        let selector = el
        el = base.querySelectorAll(selector)
    }
    return el
}

export function createElem(tag){
    return document.createElement(tag)
}

export function getType(obj){
    if(arguments.length === 0) obj = this
    return Object.prototype.toString.call(obj).replace(/^\[object (\w+)\]$/,'$1')
}

export function is(v1, v2){
    if(this !== undefined){
        [v1, v2] = [this, v1]
    }

    if(!Object.is){
        if (v1 === 0 && v2 === 0) {
            return 1 / v1 === 1 / v2
        }

        if (v1 !== v1) {
            return v2 !== v2
        }

        return v1 === v2
    } else {
        return Object.is(v1, v2)
    }
}

let _FMId = 1
export function generateFermiId(){
    let id = _FMId.toString().split('')
    let len = id.length
    for(let i = 0; i < (5 - len); i++){
        id.unshift("0")
    }
    _FMId++
    return id.join('.')
}

export function nextId(){
    return _FMId++
}

export function clamp(val, min, max){
    return val < min ? min : (val > max ? max : val)
}

export function def(obj, key, option){
    Object.defineProperty(obj, key, option)
}

export function setStyle(el, obj){
    if(arguments.length === 1) [el, obj] = [this, el]
    for(let i in obj){
        if(obj.hasOwnProperty(i)){
            el.style[i] = obj[i]
        }
    }
}

export function inDoc(el) {
    if(arguments.length === 0) el = this
    let doc = document.documentElement
    let parent = el && el.parentNode
    return doc === el || doc === parent || !!(parent && parent.nodeType === 1 && (doc.contains(parent)))
}

export function range(size, start = 0){
    let arr = []
    for(let i = start; i <= size; i++) arr.push(i)
    return arr
}

export function generateUID(){
   return '_F' + ("0000" + (Math.random() * Math.pow(36,6) << 0).toString(36)).slice(-6) + nextId()
}

export function queue(isAsync = false, interval = 0){
    let waiting = []

    let next = () => {
        let fn = waiting.shift()
        if(fn){
            isAsync
            ? setTimeout(() => fn(next), interval)
            : fn(next)
        }
    }

    let entry = fn => {
        waiting.push(fn)
        if (waiting.length === 1) next()
    }

    entry.count = () => waiting.length
    return entry
}

export function isHidden(el){
  return !(el.offsetWidth || el.offsetHeight || el.getClientRects().length)
}

export function forceReflow(el) {
    el.offsetHeight
}

export function setStyles(el, styles){
    if(arguments.length === 1) [el, obj] = [this, el]
    let hasCSSText = (typeof el.style.cssText) !== 'undefined'
    let oldStyleText
    let oldStyle = {}
    oldStyleText = hasCSSText ? el.style.cssText : el.getAttribute('style')
    oldStyleText.split(';').forEach(css => {
        if(css.indexOf(':') !== -1){
            let [key, value] = css.split(':')
            originStyle[key.trim()] = value.trim()
        }
    })

    let newStyle = {}
    Object.keys(styles).forEach(key => {
        let value = styles[key]
        if(reUnit.test(styles[key])){
            value += 'px'
        }
        newStyle[key] = value
    })

    let mergedStyle = Object.assign({}, oldStyle, newStyle)
    let styleText = Object.keys(mergedStyle).map(key => key + ': ' + mergedStyle[key] + ';').join(' ')
    if(hasCSSText){
        el.style.cssText = styleText
    } else {
        el.setAttribute('style', styleText)
    }
}

/*export function extend(target){
    if(!this.$new) throw new Error("caller was not a angular scope variable.")
    let dest = this
    let ignore = []
    if(target.constructor){
        let re = /(?:this\.)(\w+)/gm
        let source = target.constructor.toString()
        source.match(re).forEach(e => ignore.push(e.substr(5)))
    }

    for (let key in target) {
        if (!dest[key] && ignore.indexOf(key) ===-1 && target.hasOwnProperty(key)) {
            dest[key] = target[key]
        }
    }

    export function toggleClass(el, namespace, state, suffix){
        if(arguments.length === 3) [el, namespace, state, suffix] = [this, el, namespace, state]

        return function(){

            state
            ? el::replaceClass('hide', namespace + '-' + suffix['true'])
            : el::replaceClass(namespace + '-' + suffix['true'], namespace + '-' + suffix['false'])::onMotionEnd(() => {
                //debugger
                el::replaceClass(namespace + '-' + suffix['false'], 'hide')
            })

            state = !state
        }
    }
}*/
<|endoftext|>


<commit_before>// @flow
const { getOriginalLocation } = require("devtools-source-map");

import type { Pause, Frame } from "../types";

function updateFrameLocations(frames: Frame[]): Promise<Frame[]> {
  if (!frames || frames.length == 0) {
    return Promise.resolve(frames);
  }

  return Promise.all(
    frames.map(frame => {
      return getOriginalLocation(frame.location).then(loc => {
        return Object.assign(frame, {
          location: loc,
        });
      });
    })
  );
}

// Map protocol pause "why" reason to a valid L10N key
// These are the known unhandled reasons:
// "breakpointConditionThrown", "clientEvaluated"
// "interrupted", "attached"
const reasons = {
  debuggerStatement: "whyPaused.debuggerStatement",
  breakpoint: "whyPaused.breakpoint",
  exception: "whyPaused.exception",
  resumeLimit: "whyPaused.resumeLimit",
  pauseOnDOMEvents: "whyPaused.pauseOnDOMEvents",
  breakpointConditionThrown: "whyPaused.breakpointConditionThrown",

  // V8
  DOM: "whyPaused.breakpoint",
  EventListener: "whyPaused.pauseOnDOMEvents",
  XHR: "whyPaused.xhr",
  promiseRejection: "whyPaused.promiseRejection",
  assert: "whyPaused.assert",
  debugCommand: "whyPaused.debugCommand",
  other: "whyPaused.other",
};

function getPauseReason(pauseInfo: Pause): string | null {
  if (!pauseInfo) {
    return null;
  }

  let reasonType = pauseInfo.getIn(["why"]).get("type");
  if (!reasons[reasonType]) {
    console.log("Please file an issue: reasonType=", reasonType);
  }
  return reasons[reasonType];
}

module.exports = {
  updateFrameLocations,
  getPauseReason,
};
<commit_msg>updated file to es module (#2472)<commit_after>// @flow
import { getOriginalLocation } from "devtools-source-map";

import type { Pause, Frame } from "../types";

export function updateFrameLocations(frames: Frame[]): Promise<Frame[]> {
  if (!frames || frames.length == 0) {
    return Promise.resolve(frames);
  }

  return Promise.all(
    frames.map(frame => {
      return getOriginalLocation(frame.location).then(loc => {
        return Object.assign(frame, {
          location: loc,
        });
      });
    })
  );
}

// Map protocol pause "why" reason to a valid L10N key
// These are the known unhandled reasons:
// "breakpointConditionThrown", "clientEvaluated"
// "interrupted", "attached"
const reasons = {
  debuggerStatement: "whyPaused.debuggerStatement",
  breakpoint: "whyPaused.breakpoint",
  exception: "whyPaused.exception",
  resumeLimit: "whyPaused.resumeLimit",
  pauseOnDOMEvents: "whyPaused.pauseOnDOMEvents",
  breakpointConditionThrown: "whyPaused.breakpointConditionThrown",

  // V8
  DOM: "whyPaused.breakpoint",
  EventListener: "whyPaused.pauseOnDOMEvents",
  XHR: "whyPaused.xhr",
  promiseRejection: "whyPaused.promiseRejection",
  assert: "whyPaused.assert",
  debugCommand: "whyPaused.debugCommand",
  other: "whyPaused.other",
};

export function getPauseReason(pauseInfo: Pause): string | null {
  if (!pauseInfo) {
    return null;
  }

  let reasonType = pauseInfo.getIn(["why"]).get("type");
  if (!reasons[reasonType]) {
    console.log("Please file an issue: reasonType=", reasonType);
  }
  return reasons[reasonType];
}
<|endoftext|>


<commit_before>
function initTab(id) {
    $('id').click(function (e) {
        e.preventDefault();
        $('id').tab('show');
    });
}

angular.module('BaselineModule',
    [])

    .controller('BaselineController',
        [   '$rootScope','$http',
            'LocationHierarchyService',
            'FieldWorkerService',
            'LocationService',
            BaselineController]);

function BaselineController($rootScope,
                     $http,
                     LocationHierarchyService,
                     FieldWorkerService,
                     LocationService
            )
            {
                var vm = this;
                var headers = { authorization: "Basic " + $rootScope.credentials };
                vm.selectedHierarchy = [];

                vm.selectedSocialGroups = [];

                vm.displayCollection = [].concat(vm.allSocialGroups);

                //remove to the real data holder
                vm.removeSelectedSocialGroup = function removeItem(row) {
                    var index = vm.selectedSocialGroups.indexOf(row);
                    if (index !== -1) {
                        vm.selectedSocialGroups.splice(index, 1);
                    }
                }

                vm.addToSocialGroups = function(sg){
                    vm.selectedSocialGroups = vm.selectedSocialGroups.concat(sg);
                }

                vm.saveFieldWorker = function() {
                    var result = vm.allFieldWorkers.filter(
                        function(fw) {
                            return fw.uuid === vm.currentFieldWorkerUuid;
                        });
                    vm.currentFieldWorker = result[0];
                };

                vm.saveLocationHierarchy = function() {
                    var parentIndex = vm.selectedHierarchy.length - 2;
                    var lastIndex = vm.selectedHierarchy.length - 1;

                    var parent = vm.selectedHierarchy[parentIndex];
                    var last = vm.selectedHierarchy[lastIndex];
                    var children = vm.locationHierarchies[parent];
                    vm.currentHierarchy = children.find(function(child) {
                        return child.uuid === last;
                    });
                };

                vm.availableHierarchies = function() {
                    var result = [];

                    vm.selectedHierarchy.forEach(function(h) {
                        result.push(vm.locationHierarchies[h]);
                    });
                    return result;
                };

                vm.init = function() {
                    var tabIds = ['#baselineTab', '#locationTab',
                        '#groupTab', '#individualsTab',
                        '#relationshipsTab'];

                    tabIds.map(initTab);

                    var fieldworkersUrl = $rootScope.restApiUrl + "/fieldWorkers/bulk.json";
                    var socialGroupUrl = $rootScope.restApiUrl + "/socialGroups/bulk.json";

                    var codesUrl = $rootScope.restApiUrl + "/projectCodes/bulk.json";

                    $http.get(codesUrl, {headers: headers})
                        .then(function(response) {
                            vm.codes = response.data;
                        });

                    FieldWorkerService.getAllFieldWorkers(function(fieldworkers) {
                        vm.allFieldWorkers = fieldworkers;
                    });

                    LocationHierarchyService.locationHierarchies(function(hierarchyTree) {
                        vm.locationHierarchies = hierarchyTree;
                    });
                    LocationHierarchyService.getLevels().then(function(response) {
                        vm.allHierarchyLevels = response.data;
                    });

                    // Placeholder; TODO: develop socialgroup/service.js
                    $http.get(socialGroupUrl, {headers: headers})
                        .then(function(response) {
                            vm.allSocialGroups = response.data.map(function(sg) {
                                return {
                                    uuid: sg.uuid,
                                    extId: sg.extId,
                                    groupName: sg.groupName,
                                    groupType: sg.groupType};
                            });
                        });

                };

                function individualsSuccess(result) {
                    var membershipsUrl = $rootScope.restApiUrl + "/memberships",
                        residenciesUrl = $rootScope.restApiUrl + "/residencies",
                        relationshipsUrl = $rootScope.restApiUrl + "/relationships";
                }

                function groupSuccess(result) {
                    var individualsUrl = $rootScope.restApiUrl + "/individuals";

                }

                function locationSuccess(result) {
                    var socialGroupsUrl = $rootScope.restApiUrl + "/socialGroups";
                }

                vm.submitVisit = function() {
                    LocationService.submit(vm, locationSuccess);
                };

                return vm;
            };
<commit_msg>Update baseline.js<commit_after>
function initTab(id) {
    $('id').click(function (e) {
        e.preventDefault();
        $('id').tab('show');
    });
}

angular.module('BaselineModule',
    [])

    .controller('BaselineController',
        [   '$rootScope','$http',
            'LocationHierarchyService',
            'FieldWorkerService',
            'LocationService',
            BaselineController]);

function BaselineController($rootScope,
                     $http,
                     LocationHierarchyService,
                     FieldWorkerService,
                     LocationService
            )
            {
                var vm = this;
                var headers = { authorization: "Basic " + $rootScope.credentials };
                vm.selectedHierarchy = [];

                vm.selectedSocialGroups = [];

                vm.displayCollection = [].concat(vm.allSocialGroups);

                //remove to the real data holder
                vm.removeSelectedSocialGroup = function removeItem(row) {
                    var index = vm.selectedSocialGroups.indexOf(row);
                    if (index !== -1) {
                        vm.selectedSocialGroups.splice(index, 1);
                    }
                }

                vm.saveFieldWorker = function() {
                    var result = vm.allFieldWorkers.filter(
                        function(fw) {
                            return fw.uuid === vm.currentFieldWorkerUuid;
                        });
                    vm.currentFieldWorker = result[0];
                };

                vm.saveLocationHierarchy = function() {
                    var parentIndex = vm.selectedHierarchy.length - 2;
                    var lastIndex = vm.selectedHierarchy.length - 1;

                    var parent = vm.selectedHierarchy[parentIndex];
                    var last = vm.selectedHierarchy[lastIndex];
                    var children = vm.locationHierarchies[parent];
                    vm.currentHierarchy = children.find(function(child) {
                        return child.uuid === last;
                    });
                };

                vm.availableHierarchies = function() {
                    var result = [];

                    vm.selectedHierarchy.forEach(function(h) {
                        result.push(vm.locationHierarchies[h]);
                    });
                    return result;
                };

                vm.init = function() {
                    var tabIds = ['#baselineTab', '#locationTab',
                        '#groupTab', '#individualsTab',
                        '#relationshipsTab'];

                    tabIds.map(initTab);

                    var fieldworkersUrl = $rootScope.restApiUrl + "/fieldWorkers/bulk.json";
                    var socialGroupUrl = $rootScope.restApiUrl + "/socialGroups/bulk.json";

                    var codesUrl = $rootScope.restApiUrl + "/projectCodes/bulk.json";

                    $http.get(codesUrl, {headers: headers})
                        .then(function(response) {
                            vm.codes = response.data;
                        });

                    FieldWorkerService.getAllFieldWorkers(function(fieldworkers) {
                        vm.allFieldWorkers = fieldworkers;
                    });

                    LocationHierarchyService.locationHierarchies(function(hierarchyTree) {
                        vm.locationHierarchies = hierarchyTree;
                    });
                    LocationHierarchyService.getLevels().then(function(response) {
                        vm.allHierarchyLevels = response.data;
                    });

                    // Placeholder; TODO: develop socialgroup/service.js
                    $http.get(socialGroupUrl, {headers: headers})
                        .then(function(response) {
                            vm.allSocialGroups = response.data.map(function(sg) {
                                return {
                                    uuid: sg.uuid,
                                    extId: sg.extId,
                                    groupName: sg.groupName,
                                    groupType: sg.groupType};
                            });
                        });

                };

                function individualsSuccess(result) {
                    var membershipsUrl = $rootScope.restApiUrl + "/memberships",
                        residenciesUrl = $rootScope.restApiUrl + "/residencies",
                        relationshipsUrl = $rootScope.restApiUrl + "/relationships";
                }

                function groupSuccess(result) {
                    var individualsUrl = $rootScope.restApiUrl + "/individuals";

                }

                function locationSuccess(result) {
                    var socialGroupsUrl = $rootScope.restApiUrl + "/socialGroups";
                }

                vm.submitVisit = function() {
                    LocationService.submit(vm, locationSuccess);
                };

                return vm;
            };
<|endoftext|>


<commit_before>angular.module('travel.services', [])

////////////////// AuthMe //////////////////////

.factory("AuthMe", function ($http){

  var createUser = function(user){
    return $http({
      method: 'POST',
      url: '/signup',
      data: JSON.stringify(user)
    })
    .then(function (resp){
      return resp.data;
    });
  };

  var googleLogin = function(){
    return $http({
      method: 'GET',
      url: '/auth/google'
    }).then(function (resp){
      return resp.data;
    });
  };

  var facebookLogin = function(){
    return $http({
      method: 'GET',
      url: '/auth/facebook'
    }).then(function (resp){
      return resp.data;
    });
  };

  var loginUser = function(user){
    return $http({
      method: 'POST',
      url: '/login',
      data: JSON.stringify(user)
    })
    .then(function (resp){
      return resp.data;
    });
  };

  var isLoggedIn = function(){
    return $http({
      method: 'GET',
      url: '/api/check'
    })
    .then(function (resp){
      return resp.data;
    });
  };

  var logout = function(){
    return $http({
      method: 'GET',
      url: '/logout'
    });
  };

  return {
    logout: logout,
    facebookLogin: facebookLogin,
    googleLogin: googleLogin,
    createUser: createUser,
    loginUser: loginUser,
    isLoggedIn: isLoggedIn
  };

})

////////////////// Groups //////////////////////

.factory('Groups', function ($http, $rootScope) {
  // HTTP REQ FUNCTIONS

  /*
    @data {object} has:
      @prop {str} username. (email)
      @prop {int} groupId.
  */
  var addParticipant = function(data) {
    return $http({
      method: 'POST',
      url: '/api/group/add',
      data: data
    });
  };
  /*
    @data {object} has:
      @prop {str} groupName.  Group title.
      @prop {int} destinationId.
      @prop {int} userId.
  */
  var createGroup = function(data){
    return $http({
      method: 'POST',
      url: '/api/group',
      data: data
    })
    .then(function (resp) {
      return resp.data;
    });
  };
  var getUserGroups = function(userId){
    return $http({
      method: 'GET',
      url: '/api/group',
      params: { userId: userId }
    })
    .then(function(resp){
      return resp.data;
    });
  };

  // NOT HTTP REQ FUNCTIONS
  var selectGroup = function (next) {
    return function (groupInfo) {
      $rootScope.currentGroup = groupInfo;
      $rootScope.destination  = groupInfo.destination;
      next();
    };
  };

  return {
    // HTTP REQ FUNCTIONS
    getUserGroups: getUserGroups,
    createGroup: createGroup,
    addParticipant: addParticipant,

    // NOT HTTP REQ FUNCTIONS
    selectGroup: selectGroup,
  };
})

////////////////// UTIL //////////////////////

.factory('Util', function () {
  var transToPermalink = function (string) {
    // Leave commented-out to let the server throw errors for now
    // if (!string) return;

    return string.trim().replace(/\s+/g, '-').toLowerCase();
  };

  return {
    transToPermalink: transToPermalink
  };
})

////////////////// VENUES //////////////////////

.factory('Venues', function ($http) {

  ////////////////// PLACES TO EXPLORE //////////////////////

  var getAllDestinations = function () {
    return $http({
      method: 'GET',
      url: '/api/dest/',
      params: { limit: 375 }
    }).then(function(res) {
      console.log(res.data.response.destinations);
      return res.data.response.destinations;
    });
  };

  /*
    @params {object} query has:
      @prop {int} destinationId
  */
  var getVenues = function(query){
    return $http({
      method: 'GET',
      url: '/api/dest/venues',
      params: query
    })
    .then(function successCb (resp){
      return resp.data;
    }, function errCb (resp) {
      console.error(resp);
      return resp;
    });
  };

  /*
    @params {object} query has:
      @prop {str} venueId
  */
  var getDetailedVenueInfo = function(query){
    return $http({
      method: 'GET',
      url: '/api/dest/venues/info',
      params: query
    })
    .then(function successCb (resp){
      return resp.data;
    }, function errCb (resp) {
      console.error(resp);
      return resp;
    });
  };

  ////////////////// RATINGS //////////////////////

  /*
    @params {object} query has:
      @prop {str} groupId
      @prop {str} userId
  */
  var getRatings = function(query){
    return $http({
      method: 'GET',
      url: '/api/rating',
      params: query
    })
    .then(function(resp){
      return resp.data;
    });
  };

  /*
    @data {object} data has:
      @prop {str} groupId
      @prop {str} userId
      @prop {number} rating
      @prop {object} venue
  */
  var addRating = function(data) {
    return $http({
      method: 'POST',
      url: '/api/rating',
      data: data
    });
  };

  ////////////////// GROUP FAVORITES - ADMIN ONLY //////////////////////

  /*
    @data {object} data has:
      @prop {str} groupId
      @prop {str} userId
      @prop {object} venue
      @prop {str} fromDate
      @prop {str} toDate
  */
  var addtoItinerary = function(data) {
    return $http({
      method: 'POST',
      url: '/api/itin',
      data: data
    });
  };

  ////////////////// ITINERARY //////////////////////

  /*
    @params {object} query has:
      @prop {str} groupId
      @prop {str} userId
  */
  var getItinerary = function(query){
    return $http({
      method: 'GET',
      url: '/api/itin',
      params: query
    })
    .then(function(resp){
      return resp.data;
    });
  };

  ////////////////// ADD TO USER FAVORITES - NON FUNCTIONAL - SAVE FOR LATER //////////////////////

  var getUserFavorites = function (userId) {
    return $http({
      method: 'GET',
      url: '/api/fav/user',
      params: {userId: userId}
    })
    .then(function(resp) {
      console.log(resp.data);
      return resp.data;
    });
  };

  /*
    @param {object} query has:
      @prop {str} userId
      @prop {object} venue
  */
  var addToUserFavorites = function (query) {
    return $http({
      method: 'POST',
      url: '/api/fav',
      data: query
    });
  };

  ////////////////// EXPORTING ALL THE FUNCTIONS //////////////////////

  return {
    getAllDestinations: getAllDestinations,
    getVenues: getVenues,
    getUserFavorites: getUserFavorites,
    addToUserFavorites: addToUserFavorites,
    addRating: addRating,
    getRatings: getRatings,
    getItinerary: getItinerary,
    addtoItinerary: addtoItinerary,
    getDetailedVenueInfo: getDetailedVenueInfo
  };

})

////////////////// TRANSFACTORY STORAGE //////////////////////

.factory('CurrentInfo', function ($http) {
  var destination = {
    name: null,
    basicInfo: null,
    venues: null
  };
  return {
    destination: destination
  };
});

// ////////////////// SESSION STORAGE //////////////////////

// .factory('SessionStorage', function ($http, $location, $window) {
//   var sessionExists = function () {
//     return !!$window.sessionStorage.getItem('knowhere');
//   };

//   return {
//     sessionExists: sessionExists
//   };
// });
<commit_msg>(fix) Fix service Venues.getAllDestinations() bug<commit_after>angular.module('travel.services', [])

////////////////// AuthMe //////////////////////

.factory("AuthMe", function ($http){

  var createUser = function(user){
    return $http({
      method: 'POST',
      url: '/signup',
      data: JSON.stringify(user)
    })
    .then(function (resp){
      return resp.data;
    });
  };

  var googleLogin = function(){
    return $http({
      method: 'GET',
      url: '/auth/google'
    }).then(function (resp){
      return resp.data;
    });
  };

  var facebookLogin = function(){
    return $http({
      method: 'GET',
      url: '/auth/facebook'
    }).then(function (resp){
      return resp.data;
    });
  };

  var loginUser = function(user){
    return $http({
      method: 'POST',
      url: '/login',
      data: JSON.stringify(user)
    })
    .then(function (resp){
      return resp.data;
    });
  };

  var isLoggedIn = function(){
    return $http({
      method: 'GET',
      url: '/api/check'
    })
    .then(function (resp){
      return resp.data;
    });
  };

  var logout = function(){
    return $http({
      method: 'GET',
      url: '/logout'
    });
  };

  return {
    logout: logout,
    facebookLogin: facebookLogin,
    googleLogin: googleLogin,
    createUser: createUser,
    loginUser: loginUser,
    isLoggedIn: isLoggedIn
  };

})

////////////////// Groups //////////////////////

.factory('Groups', function ($http, $rootScope) {
  // HTTP REQ FUNCTIONS

  /*
    @data {object} has:
      @prop {str} username. (email)
      @prop {int} groupId.
  */
  var addParticipant = function(data) {
    return $http({
      method: 'POST',
      url: '/api/group/add',
      data: data
    });
  };
  /*
    @data {object} has:
      @prop {str} groupName.  Group title.
      @prop {int} destinationId.
      @prop {int} userId.
  */
  var createGroup = function(data){
    return $http({
      method: 'POST',
      url: '/api/group',
      data: data
    })
    .then(function (resp) {
      return resp.data;
    });
  };
  var getUserGroups = function(userId){
    return $http({
      method: 'GET',
      url: '/api/group',
      params: { userId: userId }
    })
    .then(function(resp){
      return resp.data;
    });
  };

  // NOT HTTP REQ FUNCTIONS
  var selectGroup = function (next) {
    return function (groupInfo) {
      $rootScope.currentGroup = groupInfo;
      $rootScope.destination  = groupInfo.destination;
      next();
    };
  };

  return {
    // HTTP REQ FUNCTIONS
    getUserGroups: getUserGroups,
    createGroup: createGroup,
    addParticipant: addParticipant,

    // NOT HTTP REQ FUNCTIONS
    selectGroup: selectGroup,
  };
})

////////////////// UTIL //////////////////////

.factory('Util', function () {
  var transToPermalink = function (string) {
    // Leave commented-out to let the server throw errors for now
    // if (!string) return;

    return string.trim().replace(/\s+/g, '-').toLowerCase();
  };

  return {
    transToPermalink: transToPermalink
  };
})

////////////////// VENUES //////////////////////

.factory('Venues', function ($http) {

  ////////////////// PLACES TO EXPLORE //////////////////////

  var getAllDestinations = function () {
    return $http({
      method: 'GET',
      url: '/api/dest/',
      params: { limit: 375 }
    }).then(function(res) {
      console.log(res.data);
      return res.data.destinations;
    });
  };

  /*
    @params {object} query has:
      @prop {int} destinationId
  */
  var getVenues = function(query){
    return $http({
      method: 'GET',
      url: '/api/dest/venues',
      params: query
    })
    .then(function successCb (resp){
      return resp.data;
    }, function errCb (resp) {
      console.error(resp);
      return resp;
    });
  };

  /*
    @params {object} query has:
      @prop {str} venueId
  */
  var getDetailedVenueInfo = function(query){
    return $http({
      method: 'GET',
      url: '/api/dest/venues/info',
      params: query
    })
    .then(function successCb (resp){
      return resp.data;
    }, function errCb (resp) {
      console.error(resp);
      return resp;
    });
  };

  ////////////////// RATINGS //////////////////////

  /*
    @params {object} query has:
      @prop {str} groupId
      @prop {str} userId
  */
  var getRatings = function(query){
    return $http({
      method: 'GET',
      url: '/api/rating',
      params: query
    })
    .then(function(resp){
      return resp.data;
    });
  };

  /*
    @data {object} data has:
      @prop {str} groupId
      @prop {str} userId
      @prop {number} rating
      @prop {object} venue
  */
  var addRating = function(data) {
    return $http({
      method: 'POST',
      url: '/api/rating',
      data: data
    });
  };

  ////////////////// GROUP FAVORITES - ADMIN ONLY //////////////////////

  /*
    @data {object} data has:
      @prop {str} groupId
      @prop {str} userId
      @prop {object} venue
      @prop {str} fromDate
      @prop {str} toDate
  */
  var addtoItinerary = function(data) {
    return $http({
      method: 'POST',
      url: '/api/itin',
      data: data
    });
  };

  ////////////////// ITINERARY //////////////////////

  /*
    @params {object} query has:
      @prop {str} groupId
      @prop {str} userId
  */
  var getItinerary = function(query){
    return $http({
      method: 'GET',
      url: '/api/itin',
      params: query
    })
    .then(function(resp){
      return resp.data;
    });
  };

  ////////////////// ADD TO USER FAVORITES - NON FUNCTIONAL - SAVE FOR LATER //////////////////////

  var getUserFavorites = function (userId) {
    return $http({
      method: 'GET',
      url: '/api/fav/user',
      params: {userId: userId}
    })
    .then(function(resp) {
      console.log(resp.data);
      return resp.data;
    });
  };

  /*
    @param {object} query has:
      @prop {str} userId
      @prop {object} venue
  */
  var addToUserFavorites = function (query) {
    return $http({
      method: 'POST',
      url: '/api/fav',
      data: query
    });
  };

  ////////////////// EXPORTING ALL THE FUNCTIONS //////////////////////

  return {
    getAllDestinations: getAllDestinations,
    getVenues: getVenues,
    getUserFavorites: getUserFavorites,
    addToUserFavorites: addToUserFavorites,
    addRating: addRating,
    getRatings: getRatings,
    getItinerary: getItinerary,
    addtoItinerary: addtoItinerary,
    getDetailedVenueInfo: getDetailedVenueInfo
  };

})

////////////////// TRANSFACTORY STORAGE //////////////////////

.factory('CurrentInfo', function ($http) {
  var destination = {
    name: null,
    basicInfo: null,
    venues: null
  };
  return {
    destination: destination
  };
});

// ////////////////// SESSION STORAGE //////////////////////

// .factory('SessionStorage', function ($http, $location, $window) {
//   var sessionExists = function () {
//     return !!$window.sessionStorage.getItem('knowhere');
//   };

//   return {
//     sessionExists: sessionExists
//   };
// });
<|endoftext|>


<commit_before>var React = require('react');
var ReactDOM = require('react-dom');

// var StoryContainer = require('./StoryContainer');
var StoryTitle = require('./StoryTitle');
var StoryContainer = require('./StoryContainer.js');
var Fwib = require('./Fwib.js');
var UsersInRoom = require('./UsersInRoom.js');
var GoButton = require('./GoButton.js');
var LeaveGameButton = require('./LeaveGameButton.js');

var io = require('socket.io-client');
var socket = io.connect();

module.exports = React.createClass({

  contextTypes: {
    router: React.PropTypes.object.isRequired
  },
  getInitialState: function() {

    return {users: [], fwibs:[], text: '', turn: 0, myTurn: false, gameState: 'open', active: false, title: ''};

  },
  componentWillMount: function(){
  },
  componentDidMount: function() {
   socket.emit('title', {gamehash: this.props.params.game_hash});
   socket.on('title:update', this._setTitle)
   socket.on('init', this._initialize);
   socket.on('send:fwib', this._fwibReceive);
   socket.on('user:join', this._userJoined);
   socket.on('user:left', this._userLeft);
   socket.on('update:turn', this._setTurn);
   socket.on('update:users', this._updateUsers);
   socket.on('update:active_game', this.props.setActiveGame);
   socket.on('game:start', this.startUp);
   socket.on('game:end', this.gameEnd);
   socket.emit('subscribe', this.props.params.game_hash);
    if(!this.props.active_game){
      console.log('this.params.game_hash', this.props.params.game_hash);
      console.log(this.props.joinGame)
      this.props.joinGame({user: this.props.user, game_hash: this.props.params.game_hash});
    }
    if(this.state.user === undefined){ // change to find user in users array - Maybe not?
    // Fetch all info for this gameroom this.params.url
      var {user} = this.props;
      var {users} = this.state;
      socket.emit('fetch:users', {user: user, users: users, game_hash: this.props.params.game_hash});
    }
  },

  _initialize: function(data) {
    var {users, user} = data;
    users = users.map((u) => u.username)
    this.setState({users, user});
  },

  _fwibReceive: function(fwib) {
    console.log('fwib', fwib)
    var {fwibs} = this.state;
    fwibs.push(fwib);
    this.setState({fwibs});
  },

  _userJoined: function(data) {
    // Should just need to grab all data for this user - only broadcast
    var {user, users, fwibs, turn} = this.state;
    var {name} = data;
    this.setState({users, fwibs});

    // TODO: put this logic in GO button function instead!
    var {myTurn} = this.state;
    if (user===users[0]) { myTurn = true };
    this.setState({myTurn});
  },
  leaveGame: function() {
    // on clicking leave room button,
    // change game state from active to ?????
    socket.emit('leave:game', {username: this.props.user, game_hash: this.props.active_game});
    socket.emit('unsubscribe', this.props.params.game_hash);
    this.context.router.replace(`/lobby`);
  },
  _userLeft: function(data) { // TODO: need Leave Room button
    var {users, fwibs} = this.state;
    var {name} = data;
    var index = users.indexOf(name);
    users.splice(index, 1);

    this.setState({users, fwibs});
  },

  _setTurn: function(data){
    var {turn, user, users, myTurn} = this.state;
    turn = data.turn;
    if (user === users[turn]) {
      myTurn = true;
    }
    this.setState({turn, myTurn});
  },

  _setTitle: function(data) {
    this.setState({title: data.title});
  },

  _changeTurn: function(){
    var {turn, users} = this.state;
    turn++;
    if(turn >= users.length){
      turn = 0;
    }
    return turn;
  },
  _updateUsers: function(data){
    console.log('update users:', data)
    var {users} = data
    users = users.map((u)=>u.username);
    this.setState({users: users});
  },
  handleFwibSubmit: function(fwib) {
    var {fwibs, turn, users, user, myTurn} = this.state;
    if(user === users[turn]){ // This logic isn't necessary anymore
      fwibs.push(fwib);
      turn = this._changeTurn();
      myTurn = false;
      fwib.game_hash = this.props.params.game_hash;
      this.setState({fwibs, turn, myTurn});
      socket.emit('change:turn', {turn: turn, game_hash: this.props.params.game_hash});
      socket.emit('send:fwib', fwib);
    }
    else {
      console.log('It\'s ' + users[turn] + '\'s turn!');
    }
  },

  onGo: function() {
    this.setState({ gameState: 'in progress'});
    this._setTurn({turn: this.state.turn});
    socket.emit('update:game:inprogress', {game_hash: this.props.params.game_hash}) // send only to users listening to this channel (game_hash)
  },
  startUp: function() {
    this.setState({ gameState: 'in progress' });
  },
  gameEnd: function() {
    this.setState({ gameState: 'completed' });
  },
  render: function() {
    // Add user to this game if they are not already
    // if(!this.props.active_game){
    //   console.log('this.params.game_hash', this.props.params.game_hash)
    //   this.props.joinGame({user: this.props.user, game_hash: this.props.params.game_hash});
    // }
    // if(this.state.user === undefined){ // change to find user in users array - Maybe not?
    // // Fetch all info for this gameroom this.params.url
    //   var {user} = this.props;
    //   var {users} = this.state;
    //   socket.emit('fetch:users', {user: user, users: users, game_hash: this.props.params.game_hash});
    // }
    console.log('gameState', this.state.gameState)
    var display = this.state.gameState !== 'open' ? (<StoryContainer fwibs={this.state.fwibs} onFwibSubmit={this.handleFwibSubmit} user={this.state.user} active_game={this.props.params.game_hash} myTurn={this.state.myTurn} gameState={this.state.gameState} />)
                                                  : (<GoButton goButtonPush={this.onGo} gameStart={this.startUp}/>);
    var leave = this.state.gameState === 'open' || this.state.gameState === 'completed' ? (<LeaveGameButton leaveGame={this.leaveGame} />) : null;
    console.log('after', this.state.gameState)

    return (

              <StoryTitle title={this.state.title} />
              {display}
              {leave}

              <UsersInRoom user={this.state.user} users={this.state.users} turn={this.state.turn} />

    );
  }
});
<commit_msg>Commented out gameview compDidMount<commit_after>var React = require('react');
var ReactDOM = require('react-dom');

// var StoryContainer = require('./StoryContainer');
var StoryTitle = require('./StoryTitle');
var StoryContainer = require('./StoryContainer.js');
var Fwib = require('./Fwib.js');
var UsersInRoom = require('./UsersInRoom.js');
var GoButton = require('./GoButton.js');
var LeaveGameButton = require('./LeaveGameButton.js');

var io = require('socket.io-client');
var socket = io.connect();

module.exports = React.createClass({

  contextTypes: {
    router: React.PropTypes.object.isRequired
  },
  getInitialState: function() {

    return {users: [], fwibs:[], text: '', turn: 0, myTurn: false, gameState: 'open', active: false, title: ''};

  },
  componentWillMount: function(){
  },
  componentDidMount: function() {
   socket.emit('title', {gamehash: this.props.params.game_hash});
   socket.on('title:update', this._setTitle)
   socket.on('init', this._initialize);
   socket.on('send:fwib', this._fwibReceive);
   socket.on('user:join', this._userJoined);
   socket.on('user:left', this._userLeft);
   socket.on('update:turn', this._setTurn);
   socket.on('update:users', this._updateUsers);
   socket.on('update:active_game', this.props.setActiveGame);
   socket.on('game:start', this.startUp);
   socket.on('game:end', this.gameEnd);
   socket.emit('subscribe', this.props.params.game_hash);
    // if(!this.props.active_game){
      console.log('this.params.game_hash', this.props.params.game_hash);
      console.log(this.props.joinGame)
      this.props.joinGame({user: this.props.user, game_hash: this.props.params.game_hash});
    // }
    if(this.state.user === undefined){ // change to find user in users array - Maybe not?
    // Fetch all info for this gameroom this.params.url
      var {user} = this.props;
      var {users} = this.state;
      socket.emit('fetch:users', {user: user, users: users, game_hash: this.props.params.game_hash});
    }
  },

  _initialize: function(data) {
    var {users, user} = data;
    users = users.map((u) => u.username)
    this.setState({users, user});
  },

  _fwibReceive: function(fwib) {
    console.log('fwib', fwib)
    var {fwibs} = this.state;
    fwibs.push(fwib);
    this.setState({fwibs});
  },

  _userJoined: function(data) {
    // Should just need to grab all data for this user - only broadcast
    var {user, users, fwibs, turn} = this.state;
    var {name} = data;
    this.setState({users, fwibs});

    // TODO: put this logic in GO button function instead!
    var {myTurn} = this.state;
    if (user===users[0]) { myTurn = true };
    this.setState({myTurn});
  },
  leaveGame: function() {
    // on clicking leave room button,
    // change game state from active to ?????
    socket.emit('leave:game', {username: this.props.user, game_hash: this.props.active_game});
    socket.emit('unsubscribe', this.props.params.game_hash);
    this.context.router.replace(`/lobby`);
  },
  _userLeft: function(data) { // TODO: need Leave Room button
    var {users, fwibs} = this.state;
    var {name} = data;
    var index = users.indexOf(name);
    users.splice(index, 1);

    this.setState({users, fwibs});
  },

  _setTurn: function(data){
    var {turn, user, users, myTurn} = this.state;
    turn = data.turn;
    if (user === users[turn]) {
      myTurn = true;
    }
    this.setState({turn, myTurn});
  },

  _setTitle: function(data) {
    this.setState({title: data.title});
  },

  _changeTurn: function(){
    var {turn, users} = this.state;
    turn++;
    if(turn >= users.length){
      turn = 0;
    }
    return turn;
  },
  _updateUsers: function(data){
    console.log('update users:', data)
    var {users} = data
    users = users.map((u)=>u.username);
    this.setState({users: users});
  },
  handleFwibSubmit: function(fwib) {
    var {fwibs, turn, users, user, myTurn} = this.state;
    if(user === users[turn]){ // This logic isn't necessary anymore
      fwibs.push(fwib);
      turn = this._changeTurn();
      myTurn = false;
      fwib.game_hash = this.props.params.game_hash;
      this.setState({fwibs, turn, myTurn});
      socket.emit('change:turn', {turn: turn, game_hash: this.props.params.game_hash});
      socket.emit('send:fwib', fwib);
    }
    else {
      console.log('It\'s ' + users[turn] + '\'s turn!');
    }
  },

  onGo: function() {
    this.setState({ gameState: 'in progress'});
    this._setTurn({turn: this.state.turn});
    socket.emit('update:game:inprogress', {game_hash: this.props.params.game_hash}) // send only to users listening to this channel (game_hash)
  },
  startUp: function() {
    this.setState({ gameState: 'in progress' });
  },
  gameEnd: function() {
    this.setState({ gameState: 'completed' });
  },
  render: function() {
    // Add user to this game if they are not already
    // if(!this.props.active_game){
    //   console.log('this.params.game_hash', this.props.params.game_hash)
    //   this.props.joinGame({user: this.props.user, game_hash: this.props.params.game_hash});
    // }
    // if(this.state.user === undefined){ // change to find user in users array - Maybe not?
    // // Fetch all info for this gameroom this.params.url
    //   var {user} = this.props;
    //   var {users} = this.state;
    //   socket.emit('fetch:users', {user: user, users: users, game_hash: this.props.params.game_hash});
    // }
    console.log('gameState', this.state.gameState)
    var display = this.state.gameState !== 'open' ? (<StoryContainer fwibs={this.state.fwibs} onFwibSubmit={this.handleFwibSubmit} user={this.state.user} active_game={this.props.params.game_hash} myTurn={this.state.myTurn} gameState={this.state.gameState} />)
                                                  : (<GoButton goButtonPush={this.onGo} gameStart={this.startUp}/>);
    var leave = this.state.gameState === 'open' || this.state.gameState === 'completed' ? (<LeaveGameButton leaveGame={this.leaveGame} />) : null;
    console.log('after', this.state.gameState)

    return (

              <StoryTitle title={this.state.title} />
              {display}
              {leave}

              <UsersInRoom user={this.state.user} users={this.state.users} turn={this.state.turn} />

    );
  }
});
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';

import FormInputLabel from './FormInputLabel';
import FormInputHelp from './FormInputHelp';
import FormInputErrors from './FormInputErrors';

class FormSelect extends React.Component {
  static propTypes = {
    options: PropTypes.arrayOf(
      PropTypes.shape({
        label: PropTypes.string.isRequired,
        value: PropTypes.string.isRequired
      })
    ).isRequired,
    value: PropTypes.string,
    label: PropTypes.string,
    name: PropTypes.string,
    help: PropTypes.node,
    className: PropTypes.string,
    onChange: PropTypes.func,
    errors: PropTypes.array,
    required: PropTypes.bool,
    disabled: PropTypes.bool
  };

  render() {
    return (

        <FormInputLabel
          label={this.props.label}
          errors={this._hasErrors()}
          required={this.props.required}
        >
          {this._renderSelect()}
        </FormInputLabel>
        <FormInputErrors errors={this.props.errors} />
        <FormInputHelp>{this.props.help}</FormInputHelp>

    );
  }

  focus() {
    this.input.focus();
  }

  _hasErrors() {
    return this.props.errors && this.props.errors.length > 0;
  }

  _renderSelect() {
    return (
      <select name={this.props.name} className="select" defaultValue={this.props.value} onChange={this.props.onChange} disabled={this.props.disabled}>
        <option />
        {this.props.options.map((option, idx) => {
          return (
            <option key={idx} value={option.value}>{option.label}</option>
          );
        })}
      </select>
    );
  }
}

export default FormSelect;
<commit_msg>Only bother rendering the blank option if not required<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';

import FormInputLabel from './FormInputLabel';
import FormInputHelp from './FormInputHelp';
import FormInputErrors from './FormInputErrors';

class FormSelect extends React.Component {
  static propTypes = {
    options: PropTypes.arrayOf(
      PropTypes.shape({
        label: PropTypes.string.isRequired,
        value: PropTypes.string.isRequired
      })
    ).isRequired,
    value: PropTypes.string,
    label: PropTypes.string,
    name: PropTypes.string,
    help: PropTypes.node,
    className: PropTypes.string,
    onChange: PropTypes.func,
    errors: PropTypes.array,
    required: PropTypes.bool,
    disabled: PropTypes.bool
  };

  render() {
    return (

        <FormInputLabel
          label={this.props.label}
          errors={this._hasErrors()}
          required={this.props.required}
        >
          {this._renderSelect()}
        </FormInputLabel>
        <FormInputErrors errors={this.props.errors} />
        <FormInputHelp>{this.props.help}</FormInputHelp>

    );
  }

  focus() {
    this.input.focus();
  }

  _hasErrors() {
    return this.props.errors && this.props.errors.length > 0;
  }

  _renderSelect() {
    return (
      <select name={this.props.name} className="select" defaultValue={this.props.value} onChange={this.props.onChange} disabled={this.props.disabled}>
        {!this.props.required && <option />}
        {this.props.options.map((option, idx) => {
          return (
            <option key={idx} value={option.value}>{option.label}</option>
          );
        })}
      </select>
    );
  }
}

export default FormSelect;
<|endoftext|>


<commit_before>import Ember from 'ember';
import Analytics from '../mixins/analytics';

export default Ember.Component.extend(Analytics, {
    // jscs:disable disallowQuotedKeysInObjects
    subjectTooltips: {
        'Physical Sciences': 'Astronomical Sciences, Chemistry, Materials Science, Mathematics, Physics',
        'Engineering and Technology': 'Civil Engineering, Digital Imaging, Fluidics, Nanotechnology, Synthetic Biology',
        'Biology and Life Sciences': 'Ecology, Genetics, Neuroscience, Toxicology, Zoology',
        'Research and Analysis Methods': 'Computational Techniques, Decision Analysis, Imaging Techniques, Research Assessment, Simulation and Modeling',
        'Medicine and Health Sciences': 'Anatomy, Epidemiology, Medical Ethics, Oncology, Sports and Exercise Medicine',
        'Social and Behavioral Sciences': 'Anthropology, Economics, Philosophy, Political Science, Psychology',
        'Science Policy': 'Bioethics, Open Science, Research Integrity, Science Education, Technology Regulations',
        'People and Places': 'Demography, Geographical Locations, Population Groups',
        'Computer and Information Sciences': 'Artificial Intelligence, Cryptography, Data Visualization, Library Science, Software Engineering',
        'Earth Sciences': 'Atmospheric Science, Geology, Hydrology, Marine and Aquatic Sciences, Mineralogy',
        'Ecology and Environmental Sciences': 'Biogeochemistry, Environmental Geology, Natural Resources, Soil Science, Sustainability Science',
        'Business': 'Accounting, Finance and Financial Management, Human Resource Management, Marketing, Taxation',
        'Law': 'Civil Law, Criminal Law, Legislation, State and Local Government Law, Supreme Court of the United States',
        'Education': 'Curriculum Instruction, Educational Administration and Supervision, Educational Leadership, Higher Education, Liberal Studies',
        'Arts and Humanities': 'Fine Arts, History, Music, Philosophy, Religion',
        'Architecture': 'Architectural Engineering, Construction Engineering, Environmental Design, Interior Architecture, Landscape Architecture'
    },
    // jscs:enable
    sortedList: Ember.computed('list', 'list.content', function() {
        if (!this.get('list')) {
            return;
        }
        const sortedList = this.get('list').sortBy('text');
        const pairedList = [];
        for (let i = 0; i < sortedList.get('length'); i += 2) {
            let pair = [];
            pair.pushObject(sortedList.objectAt(i));
            if (sortedList.objectAt(i + 1)) {
                pair.pushObject(sortedList.objectAt(i + 1));
            }
            pairedList.pushObject(pair);
        }
        return pairedList;
    })
});
<commit_msg>Undo tooltip top level subject capitalization<commit_after>import Ember from 'ember';
import Analytics from '../mixins/analytics';

export default Ember.Component.extend(Analytics, {
    // jscs:disable disallowQuotedKeysInObjects
    subjectTooltips: {
        'Physical sciences': 'Astronomical Sciences, Chemistry, Materials Science, Mathematics, Physics',
        'Engineering and technology': 'Civil Engineering, Digital Imaging, Fluidics, Nanotechnology, Synthetic Biology',
        'Biology and life sciences': 'Ecology, Genetics, Neuroscience, Toxicology, Zoology',
        'Research and analysis methods': 'Computational Techniques, Decision Analysis, Imaging Techniques, Research Assessment, Simulation and Modeling',
        'Medicine and health sciences': 'Anatomy, Epidemiology, Medical Ethics, Oncology, Sports and Exercise Medicine',
        'Social and behavioral sciences': 'Anthropology, Economics, Philosophy, Political Science, Psychology',
        'Science policy': 'Bioethics, Open Science, Research Integrity, Science Education, Technology Regulations',
        'People and places': 'Demography, Geographical Locations, Population Groups',
        'Computer and information sciences': 'Artificial Intelligence, Cryptography, Data Visualization, Library Science, Software Engineering',
        'Earth sciences': 'Atmospheric Science, Geology, Hydrology, Marine and Aquatic Sciences, Mineralogy',
        'Ecology and environmental sciences': 'Biogeochemistry, Environmental Geology, Natural Resources, Soil Science, Sustainability Science',
        'Business': 'Accounting, Finance and Financial Management, Human Resource Management, Marketing, Taxation',
        'Law': 'Civil Law, Criminal Law, Legislation, State and Local Government Law, Supreme Court of the United States',
        'Education': 'Curriculum Instruction, Educational Administration and Supervision, Educational Leadership, Higher Education, Liberal Studies',
        'Arts and humanities': 'Fine Arts, History, Music, Philosophy, Religion',
        'Architecture': 'Architectural Engineering, Construction Engineering, Environmental Design, Interior Architecture, Landscape Architecture'
    },
    // jscs:enable
    sortedList: Ember.computed('list', 'list.content', function() {
        if (!this.get('list')) {
            return;
        }
        const sortedList = this.get('list').sortBy('text');
        const pairedList = [];
        for (let i = 0; i < sortedList.get('length'); i += 2) {
            let pair = [];
            pair.pushObject(sortedList.objectAt(i));
            if (sortedList.objectAt(i + 1)) {
                pair.pushObject(sortedList.objectAt(i + 1));
            }
            pairedList.pushObject(pair);
        }
        return pairedList;
    })
});
<|endoftext|>


<commit_before>const FormManager = require('../../common/form_manager');
const localize    = require('../../../_common/localize').localize;

const LostPassword = (() => {
    const form_id = '#frm_lost_password';

    const responseHandler = (response) => {
        if (response.verify_email) {
            $('#password_reset_description').setVisibility(0);
            $('#check_spam').setVisibility(1);
            $(form_id).html($('<div/>', { class: 'notice-msg', text: localize('Please check your email for the password reset link.') }));
        } else if (response.error) {
            const $form_error = $('#form_error');
            $form_error.setVisibility(1).text(localize(response.error.message));
            $('#email').one('input', () => $form_error.setVisibility(0)); // remove error message on input
        }
    };

    const onLoad = () => {
        FormManager.init(form_id, [
            { selector: '#email', validations: ['req', 'email'], request_field: 'verify_email' },
            { request_field: 'type', value: 'reset_password' },
        ]);
        FormManager.handleSubmit({
            form_selector       : form_id,
            fnc_response_handler: responseHandler,
        });
    };

    return {
        onLoad,
    };
})();

module.exports = LostPassword;
<commit_msg>set text before visibility<commit_after>const FormManager = require('../../common/form_manager');
const localize    = require('../../../_common/localize').localize;

const LostPassword = (() => {
    const form_id = '#frm_lost_password';

    const responseHandler = (response) => {
        if (response.verify_email) {
            $('#password_reset_description').setVisibility(0);
            $('#check_spam').setVisibility(1);
            $(form_id).html($('<div/>', { class: 'notice-msg', text: localize('Please check your email for the password reset link.') }));
        } else if (response.error) {
            const $form_error = $('#form_error');
            $form_error.text(localize(response.error.message)).setVisibility(1);
            $('#email').one('input', () => $form_error.setVisibility(0)); // remove error message on input
        }
    };

    const onLoad = () => {
        FormManager.init(form_id, [
            { selector: '#email', validations: ['req', 'email'], request_field: 'verify_email' },
            { request_field: 'type', value: 'reset_password' },
        ]);
        FormManager.handleSubmit({
            form_selector       : form_id,
            fnc_response_handler: responseHandler,
        });
    };

    return {
        onLoad,
    };
})();

module.exports = LostPassword;
<|endoftext|>


<commit_before>/*
 * Offerings object parses the offerings json that we get from socket.send({offerings: {hierachy :1 ...}}
 * and outputs in usable form, like it gives markets, submarkets, underlyings, contractForms
 *
 *
 * Usage:
 *
 * use `Offerings.details` to populate this object first
 *
 * then use
 *
 * `Offerings.markets` to get markets like Forex, Random etc
 * `Offerings.contractForms` like risefall, higherlower
 *
 */
var Offerings = (function () {
    'use strict';

    var tradeMarkets, tradeSubmarkets, tradeUnderlyings, tradeContractForms, responseData, form, barrier;

    var details = function (data, market, formName, barrierCategory, submarket, underlying) {
        responseData = data;
        tradeMarkets = [];
        var offerings = data.offerings.offerings;

        var submarketElements = {}, underlyingElements = {}, contractCategories = {};

        submarketElements['all'] = 'All';

        var formBarrier = getFormNameBarrierCategory(formName);
        form = formName = formBarrier['formName'];
        barrier = barrierCategory = formBarrier['barrierCategory'];

        market_label:
        for (var i = 0, offlen = offerings.length; i < offlen; i++) {
            market = market || 'Forex';
            var mkt = offerings[i].market;
            tradeMarkets.push(mkt);
            if (mkt.toLowerCase() === market.toLowerCase()) {
                submarket_label:
                for(var j = 0, sbmktlen = offerings[i].available.length; j < sbmktlen; j++) {
                    var loop_submarket = offerings[i].available[j].submarket;
                    if (submarket && submarket !== loop_submarket) {
                        continue submarket_label;
                    }
                    underlying_label:
                    for (var k = 0, undrlylen = offerings[i].available[j].available.length; k < undrlylen; k++) {
                        var loop_underlying = offerings[i].available[j].available[k];
                        if(underlying && underlying !== loop_underlying.symbol) {
                            continue underlying_label;
                        }
                        for (var l = 0, ctcategorylen = offerings[i].available[j].available[k].available.length; l < ctcategorylen; l++) {
                            var contractCategory = offerings[i].available[j].available[k].available[l].contract_category, isBarrierUndefinedRequired = false;

                            for (var m = 0, ctcategoryavalen = offerings[i].available[j].available[k].available[l].available.length; m < ctcategoryavalen; m++) {

                                for (var property in  offerings[i].available[j].available[k].available[l].available[m]) {
                                    if (offerings[i].available[j].available[k].available[l].available[m].hasOwnProperty(property)) {
                                        var prop_value = offerings[i].available[j].available[k].available[l].available[m][property];
                                        if (property === 'barrier_category') {
                                            if (!barrierCategory) {
                                                barrierCategory = prop_value;
                                                isBarrierUndefinedRequired = true;
                                            }
                                            if (contractCategory && !contractCategories.hasOwnProperty(contractCategory)) {
                                                if (contractCategory === 'callput') {
                                                    if( prop_value === 'euro_atm') {
                                                        contractCategories['risefall'] = 'risefall';
                                                    } else {
                                                        contractCategories['higherlower'] = 'higherlower';
                                                    }
                                                } else {
                                                    contractCategories[contractCategory] = contractCategory;
                                                }

                                            }
                                            if(formName === contractCategory && barrierCategory === prop_value) {
                                                var submarketId = loop_submarket.toLowerCase().replace(/ /g, '_');
                                                submarketElements[submarketId] = loop_submarket;
                                                underlyingElements[loop_underlying.symbol] = {
                                                    display: loop_underlying.symbol_display,
                                                    classname: submarketId
                                                };
                                            }
                                            if (isBarrierUndefinedRequired) {
                                                barrierCategory = undefined;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        if(underlying && underlying === loop_underlying.symbol) {
                            break underlying_label;
                        }
                    }
                    if (submarket && submarket === loop_submarket) {
                        break submarket_label;
                    }
                }
            } else {
                continue;
            }
        }
        tradeContractForms = contractCategories;
        tradeSubmarkets = submarketElements;
        tradeUnderlyings = underlyingElements;
    };

    return {
        details: details,
        offerings: function () { return responseData; },
        markets: function () { return tradeMarkets; },
        submarkets: function () { return tradeSubmarkets; },
        underlyings: function () { return tradeUnderlyings; },
        contractForms: function () { return tradeContractForms; },
        form: function (name) {
            if (name) {
                form = getFormNameBarrierCategory(name);
                barrier(form['barrier']);
                form = form['formName'];
            }
            return form;
        },
        barrier: function (name) {
            if (name) {
                barrier = name;
            }
            return barrier;
        }
    };

})();
<commit_msg>update offerings to take into consideration contract display<commit_after>/*
 * Offerings object parses the offerings json that we get from socket.send({offerings: {hierachy :1 ...}}
 * and outputs in usable form, like it gives markets, submarkets, underlyings, contractForms
 *
 *
 * Usage:
 *
 * use `Offerings.details` to populate this object first
 *
 * then use
 *
 * `Offerings.markets` to get markets like Forex, Random etc
 * `Offerings.contractForms` like risefall, higherlower
 *
 */
var Offerings = (function () {
    'use strict';

    var tradeMarkets, tradeSubmarkets, tradeUnderlyings, tradeContractForms, responseData, form, barrier;

    var details = function (data, market, formName, barrierCategory, submarket, underlying) {
        responseData = data;
        tradeMarkets = [];
        var offerings = data.offerings.offerings;

        var submarketElements = {}, underlyingElements = {}, contractCategories = {};

        submarketElements['all'] = 'All';

        var formBarrier = getFormNameBarrierCategory(formName);
        form = formName = formBarrier['formName'];
        barrier = barrierCategory = formBarrier['barrierCategory'];

        market_label:
        for (var i = 0, offlen = offerings.length; i < offlen; i++) {
            market = market || 'Forex';
            var mkt = offerings[i].market;
            tradeMarkets.push(mkt);
            if (mkt.toLowerCase() === market.toLowerCase()) {
                submarket_label:
                for(var j = 0, sbmktlen = offerings[i].available.length; j < sbmktlen; j++) {
                    var loop_submarket = offerings[i].available[j].submarket;
                    if (submarket && submarket !== loop_submarket) {
                        continue submarket_label;
                    }
                    underlying_label:
                    for (var k = 0, undrlylen = offerings[i].available[j].available.length; k < undrlylen; k++) {
                        var loop_underlying = offerings[i].available[j].available[k];
                        if(underlying && underlying !== loop_underlying.symbol) {
                            continue underlying_label;
                        }
                        for (var l = 0, ctcategorylen = offerings[i].available[j].available[k].available.length; l < ctcategorylen; l++) {
                            var currentContract = offerings[i].available[j].available[k].available[l],
                                contractCategory = currentContract['contract_category'],
                                isBarrierUndefinedRequired = false;

                            for (var m = 0, ctcategoryavalen = currentContract.available.length; m < ctcategoryavalen; m++) {

                                for (var property in  currentContract.available[m]) {
                                    if (currentContract.available[m].hasOwnProperty(property)) {
                                        var prop_value = currentContract.available[m][property];
                                        if (property === 'barrier_category') {
                                            if (!barrierCategory) {
                                                barrierCategory = prop_value;
                                                isBarrierUndefinedRequired = true;
                                            }
                                            if (contractCategory && !contractCategories.hasOwnProperty(contractCategory)) {
                                                if (contractCategory === 'callput') {
                                                    if( prop_value === 'euro_atm') {
                                                        contractCategories['risefall'] = Content.localize().textFormRiseFall;
                                                    } else {
                                                        contractCategories['higherlower'] = Content.localize().textFormHigherLower;
                                                    }
                                                } else {
                                                    contractCategories[contractCategory] = currentContract['contract_category_display'];
                                                }

                                            }
                                            if(formName === contractCategory && barrierCategory === prop_value) {
                                                var submarketId = loop_submarket.toLowerCase().replace(/ /g, '_');
                                                submarketElements[submarketId] = loop_submarket;
                                                underlyingElements[loop_underlying.symbol] = {
                                                    display: loop_underlying.symbol_display,
                                                    classname: submarketId
                                                };
                                            }
                                            if (isBarrierUndefinedRequired) {
                                                barrierCategory = undefined;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        if(underlying && underlying === loop_underlying.symbol) {
                            break underlying_label;
                        }
                    }
                    if (submarket && submarket === loop_submarket) {
                        break submarket_label;
                    }
                }
            } else {
                continue;
            }
        }
        tradeContractForms = contractCategories;
        tradeSubmarkets = submarketElements;
        tradeUnderlyings = underlyingElements;
    };

    return {
        details: details,
        offerings: function () { return responseData; },
        markets: function () { return tradeMarkets; },
        submarkets: function () { return tradeSubmarkets; },
        underlyings: function () { return tradeUnderlyings; },
        contractForms: function () { return tradeContractForms; },
        form: function (name) {
            if (name) {
                form = getFormNameBarrierCategory(name);
                barrier(form['barrier']);
                form = form['formName'];
            }
            return form;
        },
        barrier: function (name) {
            if (name) {
                barrier = name;
            }
            return barrier;
        }
    };

})();
<|endoftext|>