<commit_before>import idMixin from '../../mixins/id'

export default {
  mixins: [idMixin],
  render (h) {
    let content = h(false)
    if (this.localActive || !this.computedLazy) {
      content = h(
        this.tag,
        {
          ref: 'panel',
          class: this.tabClasses,
          directives: [{ name: 'show', value: this.localActive }],
          attrs: {
            role: 'tabpanel',
            id: this.safeId(),
            'aria-hidden': this.localActive ? 'false' : 'true',
            'aria-expanded': this.localActive ? 'true' : 'false',
            'aria-lablelledby': this.controlledBy || null
          }
        },
        [this.$slots.default]
      )
    }
    return h(
      'transition',
      {
        props: { mode: 'out-in' },
        on: {
          beforeEnter: this.beforeEnter,
          afterEnter: this.afterEnter,
          afterLeave: this.afterLeave
        }
      },
      [content]
    )
  },
  methods: {
    beforeEnter () {
      this.show = false
    },
    afterEnter () {
      this.show = true
    },
    afterLeave () {
      this.show = false
    }
  },
  data () {
    return {
      localActive: this.active && !this.disabled,
      show: false
    }
  },
  mounted () {
    this.show = this.localActive
  },
  computed: {
    tabClasses () {
      return [
        'tab-pane',
        this.$parent && this.$parent.card && !this.noBody ? 'card-body' : '',
        this.show ? 'show' : '',
        this.computedFade ? 'fade' : '',
        this.disabled ? 'disabled' : '',
        this.localActive ? 'active' : ''
      ]
    },
    controlledBy () {
      return this.buttonId || this.safeId('__BV_tab_button__')
    },
    computedFade () {
      return this.$parent.fade
    },
    computedLazy () {
      return this.$parent.lazy
    },
    _isTab () {
      // For parent sniffing of child
      return true
    }
  },
  props: {
    active: {
      type: Boolean,
      default: false
    },
    tag: {
      type: String,
      default: 'div'
    },
    buttonId: {
      type: String,
      default: ''
    },
    title: {
      type: String,
      default: ''
    },
    titleItemClass: {
      // Sniffed by tabs.vue and added to nav 'li.nav-item'
      type: [String, Array, Object],
      default: null
    },
    titleLinkClass: {
      // Sniffed by tabs.vue and added to nav 'a.nav-link'
      type: [String, Array, Object],
      default: null
    },
    headHtml: {
      // Is this actually ever used?
      type: String,
      default: null
    },
    disabled: {
      type: Boolean,
      default: false
    },
    noBody: {
      type: Boolean,
      default: false
    },
    href: {
      type: String,
      default: '#'
    }
  }
}
<commit_msg>fix(tab): fix the delay in tab transition (#1812) (#1806)<commit_after>import idMixin from '../../mixins/id'

export default {
  mixins: [idMixin],
  render (h) {
    let content = h(false)
    if (this.localActive || !this.computedLazy) {
      content = h(
        this.tag,
        {
          ref: 'panel',
          class: this.tabClasses,
          directives: [{ name: 'show', value: this.localActive }],
          attrs: {
            role: 'tabpanel',
            id: this.safeId(),
            'aria-hidden': this.localActive ? 'false' : 'true',
            'aria-expanded': this.localActive ? 'true' : 'false',
            'aria-lablelledby': this.controlledBy || null
          }
        },
        [this.$slots.default]
      )
    }
    return h(
      'transition',
      {
        props: { mode: 'out-in' },
        on: {
          beforeEnter: this.beforeEnter,
          beforeLeave: this.beforeLeave
        }
      },
      [content]
    )
  },
  methods: {
    beforeEnter () {
      // change opacity 1 frame after display
      // otherwise css transition won't happen
      window.requestAnimationFrame(() => { this.show = true })
    },
    beforeLeave () {
      this.show = false
    }
  },
  data () {
    return {
      localActive: this.active && !this.disabled,
      show: false
    }
  },
  mounted () {
    this.show = this.localActive
  },
  computed: {
    tabClasses () {
      return [
        'tab-pane',
        this.$parent && this.$parent.card && !this.noBody ? 'card-body' : '',
        this.show ? 'show' : '',
        this.computedFade ? 'fade' : '',
        this.disabled ? 'disabled' : '',
        this.localActive ? 'active' : ''
      ]
    },
    controlledBy () {
      return this.buttonId || this.safeId('__BV_tab_button__')
    },
    computedFade () {
      return this.$parent.fade
    },
    computedLazy () {
      return this.$parent.lazy
    },
    _isTab () {
      // For parent sniffing of child
      return true
    }
  },
  props: {
    active: {
      type: Boolean,
      default: false
    },
    tag: {
      type: String,
      default: 'div'
    },
    buttonId: {
      type: String,
      default: ''
    },
    title: {
      type: String,
      default: ''
    },
    titleItemClass: {
      // Sniffed by tabs.vue and added to nav 'li.nav-item'
      type: [String, Array, Object],
      default: null
    },
    titleLinkClass: {
      // Sniffed by tabs.vue and added to nav 'a.nav-link'
      type: [String, Array, Object],
      default: null
    },
    headHtml: {
      // Is this actually ever used?
      type: String,
      default: null
    },
    disabled: {
      type: Boolean,
      default: false
    },
    noBody: {
      type: Boolean,
      default: false
    },
    href: {
      type: String,
      default: '#'
    }
  }
}
<|endoftext|>


<commit_before>/**
 * Created by ryan on 16/05/16.
 */
<commit_msg>Moved ID Generator code from model into helper class<commit_after>/**
 * Created by ryan on 16/05/16.
 */
var IdGenerator = {
    nextID : (function () {
        var nextID = 1;

        return function () {

            if (typeof window !== 'undefined') {
                throw new Error("Client Model must not create its own IDs!");
            }

            return nextID++;
        };
    }())
};

module.exports = IdGenerator;
<|endoftext|>


<commit_before>'use strict';
module.exports = {
  "QUESTIONS_EN_US": [
    {
      "What breed of dog was Marley in the film Marley & Me?": [
        "Labrador Retriever",
        "Golden Retriever",
        "Dalmatian",
        "Shiba Inu"
      ]
    },
    {
      "Which movie released in 2016 features Superman and Batman fighting?": [
        "Batman v Superman: Dawn of Justice",
        "Batman v Superman: Superapocalypse",
        "Batman v Superman: Black of Knight",
        "Batman v Superman: Knightfall"
      ]
    },
    {
      "Who starred as Bruce Wayne and Batman in Tim Burtons 1989 movie Batman?": [
        "Michael Keaton",
        "George Clooney",
        "Val Kilmer",
        "Adam West"
      ]
    },
    {
      "What name did Tom Hanks give to his volleyball companion in the film `Cast Away`?": [
        "Wilson",
        "Friday",
        "Jones",
        "Billy"
      ]
    },
    {
      "Who directed E.T. the Extra-Terrestrial (1982)?": [
        "Steven Spielberg",
        "Stanley Kubrick",
        "James Cameron",
        "Tim Burton"
      ]
    },
    {
      "What is the highest grossing film of all time (without adjusting for inflation)?": [
        "Avatar",
        "Jurassic World",
        "Star Wars: The Force Awakens",
        "Titanic"
      ]
    },
    {
      "Which animated movie was first to feature a celebrity as a voice actor?": [
        "Aladdin",
        "Toy Story",
        "James and the Giant Peach",
        "The Hunchback of Notre Dame"
      ]
    },
    {
      "When was the movie Con Air released?": [
        "1997",
        "1985",
        "1999",
        "1990"
      ]
    },
    {
      "Who wrote and directed the 1986 film Platoon?": [
        "Oliver Stone",
        "Francis Ford Coppola",
        "Stanley Kubrick",
        "Michael Cimino"
      ]
    },
    {
      "Who played the female lead in the 1933 film King Kong?": [
        "Fay Wray",
        "Jean Harlow",
        "Vivien Leigh",
        "Mae West"
      ]
    },
    {
      "Which actress danced the twist with John Travolta in Pulp Fiction?": [
        "Uma Thurman",
        "Kathy Griffin",
        "Pam Grier",
        "Bridget Fonda"
      ]
    },
    {
      "Who starred in the film 1973 movie Enter The Dragon?": [
        "Bruce Lee",
        "Jackie Chan",
        "Jet Li",
        " Yun-Fat Chow"
      ]
    },
    {
      "Which movie contains the quote, Say hello to my little friend!?": [
        "Scarface",
        "Reservoir Dogs",
        "Heat",
        "Goodfellas"
      ]
    },
    {
      "Who directed the movies Pulp Fiction, Reservoir Dogs and Django Unchained?": [
        "Quentin Tarantino",
        "Martin Scorcese",
        "Steven Spielberg",
        "James Cameron"
      ]
    },
    {
      "The Queen song `A Kind Of Magic` is featured in which 1986 film?": [
        "Highlander",
        "Flash Gordon",
        "Labyrinth",
        "Howard the Duck"
      ]
    },
    {
      "This movie contains the quote, Nobody puts Baby in a corner,": [
        "Dirty Dancing",
        "Three Men and a Baby",
        "Ferris Bueller's Day Off",
        "Pretty in Pink"
      ]
    },
    {
      "What was the first James Bond film?": [
        "Dr. No",
        "Goldfinger",
        "From Russia With Love",
        "Thunderball"
      ]
    },
    {
      "Which of these actors/actresses is NOT a part of the cast for the 2016 movie Suicide Squad?": [
        "Scarlett Johansson",
        "Jared Leto",
        "Will Smith",
        "Margot Robbie"
      ]
    },
    {
      "Which movie includes a giant bunny-like spirit who has magic powers including growing trees?": [
        "My Neighbor Totoro",
        "Hop",
        "Rise of the Guardians",
        "Alice in Wonderland"
      ]
    },
    {
      "Who in Pulp Fiction says No, they got the metric system there, they wouldnt know what the fuck a Quarter Pounder is,": [
        "Vincent Vega",
        "Jules Winnfield",
        "Jimmie Dimmick",
        "Butch Coolidge"
      ]
    },
    {
      "In the movie Spaceballs, what are the Spaceballs attempting to steal from Planet Druidia?": [
        "Air",
        "The Schwartz",
        "Princess Lonestar",
        "Meatballs"
      ]
    },
    {
      "What was the first monster to appear alongside Godzilla?": [
        "Anguirus",
        "King Kong",
        "Mothra",
        "King Ghidora"
      ]
    },
    {
      "In the movie Gremlins, after what time of day should you not feed Mogwai?": [
        "Midnight",
        "Evening",
        "Morning",
        "Afternoon"
      ]
    },
    {
      "When does Rogue One, A Star Wars Story take place chronologically in the series?": [
        "Between Episode 3 and 4",
        "After Episode 6",
        "Before Episode 1",
        "Between Episode 4 and 5"
      ]
    },
    {
      "The first rule is, you dont talk about it is a reference to which movie?": [
        "Fight Club",
        "The Island",
        "Unthinkable",
        "American Pie"
      ]
    },
    {
      "In the 2012 film, The Lorax, who is the antagonist?": [
        "Aloysius O'Hare",
        "Ted Wiggins",
        "The Once-Ler",
        "Grammy Norma"
      ]
    },
    {
      "In the 1992 film Army of Darkness, what name does Ash give to his double-barreled shotgun?": [
        "Boomstick",
        "Bloomstick",
        "Blastbranch",
        "2-Pump Chump"
      ]
    },
    {
      "In the 1995 film Balto, who are Steeles accomplices?": [
        "Kaltag, Nikki, and Star",
        "Dusty, Kirby, and Ralph",
        "Nuk, Yak, and Sumac",
        "Jenna, Sylvie, and Dixie"
      ]
    },
    {
      "What is the name of the island that Jurassic Park is built on?": [
        "Isla Nublar",
        "Isla Sorna",
        "Isla Muerta",
        "Isla Pena"
      ]
    }
  ]
}
<commit_msg>clean up ET question<commit_after>{
  "QUESTIONS_EN_US": [
    {
      "What breed of dog was Marley in the film Marley & Me?": [
        "Labrador Retriever",
        "Golden Retriever",
        "Dalmatian",
        "Shiba Inu"
      ]
    },
    {
      "Which movie released in 2016 features Superman and Batman fighting?": [
        "Batman v Superman: Dawn of Justice",
        "Batman v Superman: Superapocalypse",
        "Batman v Superman: Black of Knight",
        "Batman v Superman: Knightfall"
      ]
    },
    {
      "Who starred as Bruce Wayne and Batman in Tim Burtons 1989 movie Batman?": [
        "Michael Keaton",
        "George Clooney",
        "Val Kilmer",
        "Adam West"
      ]
    },
    {
      "What name did Tom Hanks give to his volleyball companion in the film `Cast Away`?": [
        "Wilson",
        "Friday",
        "Jones",
        "Billy"
      ]
    },
    {
      "Who directed ET, the Extra-Terrestrial (1982)?": [
        "Steven Spielberg",
        "Stanley Kubrick",
        "James Cameron",
        "Tim Burton"
      ]
    },
    {
      "What is the highest grossing film of all time (without adjusting for inflation)?": [
        "Avatar",
        "Jurassic World",
        "Star Wars: The Force Awakens",
        "Titanic"
      ]
    },
    {
      "Which animated movie was first to feature a celebrity as a voice actor?": [
        "Aladdin",
        "Toy Story",
        "James and the Giant Peach",
        "The Hunchback of Notre Dame"
      ]
    },
    {
      "When was the movie Con Air released?": [
        "1997",
        "1985",
        "1999",
        "1990"
      ]
    },
    {
      "Who wrote and directed the 1986 film Platoon?": [
        "Oliver Stone",
        "Francis Ford Coppola",
        "Stanley Kubrick",
        "Michael Cimino"
      ]
    },
    {
      "Who played the female lead in the 1933 film King Kong?": [
        "Fay Wray",
        "Jean Harlow",
        "Vivien Leigh",
        "Mae West"
      ]
    },
    {
      "Which actress danced the twist with John Travolta in Pulp Fiction?": [
        "Uma Thurman",
        "Kathy Griffin",
        "Pam Grier",
        "Bridget Fonda"
      ]
    },
    {
      "Who starred in the film 1973 movie Enter The Dragon?": [
        "Bruce Lee",
        "Jackie Chan",
        "Jet Li",
        " Yun-Fat Chow"
      ]
    },
    {
      "Which movie contains the quote, Say hello to my little friend!?": [
        "Scarface",
        "Reservoir Dogs",
        "Heat",
        "Goodfellas"
      ]
    },
    {
      "Who directed the movies Pulp Fiction, Reservoir Dogs and Django Unchained?": [
        "Quentin Tarantino",
        "Martin Scorcese",
        "Steven Spielberg",
        "James Cameron"
      ]
    },
    {
      "The Queen song `A Kind Of Magic` is featured in which 1986 film?": [
        "Highlander",
        "Flash Gordon",
        "Labyrinth",
        "Howard the Duck"
      ]
    },
    {
      "This movie contains the quote, Nobody puts Baby in a corner,": [
        "Dirty Dancing",
        "Three Men and a Baby",
        "Ferris Bueller's Day Off",
        "Pretty in Pink"
      ]
    },
    {
      "What was the first James Bond film?": [
        "Dr. No",
        "Goldfinger",
        "From Russia With Love",
        "Thunderball"
      ]
    },
    {
      "Which of these actors/actresses is NOT a part of the cast for the 2016 movie Suicide Squad?": [
        "Scarlett Johansson",
        "Jared Leto",
        "Will Smith",
        "Margot Robbie"
      ]
    },
    {
      "Which movie includes a giant bunny-like spirit who has magic powers including growing trees?": [
        "My Neighbor Totoro",
        "Hop",
        "Rise of the Guardians",
        "Alice in Wonderland"
      ]
    },
    {
      "Who in Pulp Fiction says No, they got the metric system there, they wouldnt know what the fuck a Quarter Pounder is,": [
        "Vincent Vega",
        "Jules Winnfield",
        "Jimmie Dimmick",
        "Butch Coolidge"
      ]
    },
    {
      "In the movie Spaceballs, what are the Spaceballs attempting to steal from Planet Druidia?": [
        "Air",
        "The Schwartz",
        "Princess Lonestar",
        "Meatballs"
      ]
    },
    {
      "What was the first monster to appear alongside Godzilla?": [
        "Anguirus",
        "King Kong",
        "Mothra",
        "King Ghidora"
      ]
    },
    {
      "In the movie Gremlins, after what time of day should you not feed Mogwai?": [
        "Midnight",
        "Evening",
        "Morning",
        "Afternoon"
      ]
    },
    {
      "When does Rogue One, A Star Wars Story take place chronologically in the series?": [
        "Between Episode 3 and 4",
        "After Episode 6",
        "Before Episode 1",
        "Between Episode 4 and 5"
      ]
    },
    {
      "The first rule is, you dont talk about it is a reference to which movie?": [
        "Fight Club",
        "The Island",
        "Unthinkable",
        "American Pie"
      ]
    },
    {
      "In the 2012 film, The Lorax, who is the antagonist?": [
        "Aloysius O'Hare",
        "Ted Wiggins",
        "The Once-Ler",
        "Grammy Norma"
      ]
    },
    {
      "In the 1992 film Army of Darkness, what name does Ash give to his double-barreled shotgun?": [
        "Boomstick",
        "Bloomstick",
        "Blastbranch",
        "2-Pump Chump"
      ]
    },
    {
      "In the 1995 film Balto, who are Steeles accomplices?": [
        "Kaltag, Nikki, and Star",
        "Dusty, Kirby, and Ralph",
        "Nuk, Yak, and Sumac",
        "Jenna, Sylvie, and Dixie"
      ]
    },
    {
      "What is the name of the island that Jurassic Park is built on?": [
        "Isla Nublar",
        "Isla Sorna",
        "Isla Muerta",
        "Isla Pena"
      ]
    }
  ]
}<|endoftext|>


<commit_before>/* @flow */

import { isDef, isUndef } from 'shared/util'
import { updateListeners } from 'core/vdom/helpers/index'
import { isIE, isChrome, supportsPassive } from 'core/util/index'
import { RANGE_TOKEN, CHECKBOX_RADIO_TOKEN } from 'web/compiler/directives/model'

// normalize v-model event tokens that can only be determined at runtime.
// it's important to place the event as the first in the array because
// the whole point is ensuring the v-model callback gets called before
// user-attached handlers.
function normalizeEvents (on) {
  /* istanbul ignore if */
  if (isDef(on[RANGE_TOKEN])) {
    // IE input[type=range] only supports `change` event
    const event = isIE ? 'change' : 'input'
    on[event] = [].concat(on[RANGE_TOKEN], on[event] || [])
    delete on[RANGE_TOKEN]
  }
  // This was originally intended to fix #4521 but no longer necessary
  // after 2.5. Keeping it for backwards compat with generated code from < 2.4
  /* istanbul ignore if */
  if (isDef(on[CHECKBOX_RADIO_TOKEN])) {
    on.change = [].concat(on[CHECKBOX_RADIO_TOKEN], on.change || [])
    delete on[CHECKBOX_RADIO_TOKEN]
  }
}

let target: any

function createOnceHandler (event, handler, capture) {
  const _target = target // save current target element in closure
  return function onceHandler () {
    const res = handler.apply(null, arguments)
    if (res !== null) {
      remove(event, onceHandler, capture, _target)
    }
  }
}

function add (
  name: string,
  handler: Function,
  capture: boolean,
  passive: boolean
) {
  if (isChrome) {
    // async edge case #6566: inner click event triggers patch, event handler
    // attached to outer element during patch, and triggered again. This only
    // happens in Chrome as it fires microtask ticks between event propagation.
    // the solution is simple: we save the timestamp when a handler is attached,
    // and the handler would only fire if the event passed to it was fired
    // AFTER it was attached.
    const now = performance.now()
    const original = handler
    handler = original._wrapper = function (e) {
      if (e.timeStamp > now) {
        return original.apply(this, arguments)
      }
    }
  }
  target.addEventListener(
    name,
    handler,
    supportsPassive
      ? { capture, passive }
      : capture
  )
}

function remove (
  name: string,
  handler: Function,
  capture: boolean,
  _target?: HTMLElement
) {
  (_target || target).removeEventListener(
    name,
    handler._wrapper || handler,
    capture
  )
}

function updateDOMListeners (oldVnode: VNodeWithData, vnode: VNodeWithData) {
  if (isUndef(oldVnode.data.on) && isUndef(vnode.data.on)) {
    return
  }
  const on = vnode.data.on || {}
  const oldOn = oldVnode.data.on || {}
  target = vnode.elm
  normalizeEvents(on)
  updateListeners(on, oldOn, add, remove, createOnceHandler, vnode.context)
  target = undefined
}

export default {
  create: updateDOMListeners,
  update: updateDOMListeners
}
<commit_msg>refactor: should also fire handler if timestamp was same<commit_after>/* @flow */

import { isDef, isUndef } from 'shared/util'
import { updateListeners } from 'core/vdom/helpers/index'
import { isIE, isChrome, supportsPassive } from 'core/util/index'
import { RANGE_TOKEN, CHECKBOX_RADIO_TOKEN } from 'web/compiler/directives/model'

// normalize v-model event tokens that can only be determined at runtime.
// it's important to place the event as the first in the array because
// the whole point is ensuring the v-model callback gets called before
// user-attached handlers.
function normalizeEvents (on) {
  /* istanbul ignore if */
  if (isDef(on[RANGE_TOKEN])) {
    // IE input[type=range] only supports `change` event
    const event = isIE ? 'change' : 'input'
    on[event] = [].concat(on[RANGE_TOKEN], on[event] || [])
    delete on[RANGE_TOKEN]
  }
  // This was originally intended to fix #4521 but no longer necessary
  // after 2.5. Keeping it for backwards compat with generated code from < 2.4
  /* istanbul ignore if */
  if (isDef(on[CHECKBOX_RADIO_TOKEN])) {
    on.change = [].concat(on[CHECKBOX_RADIO_TOKEN], on.change || [])
    delete on[CHECKBOX_RADIO_TOKEN]
  }
}

let target: any

function createOnceHandler (event, handler, capture) {
  const _target = target // save current target element in closure
  return function onceHandler () {
    const res = handler.apply(null, arguments)
    if (res !== null) {
      remove(event, onceHandler, capture, _target)
    }
  }
}

function add (
  name: string,
  handler: Function,
  capture: boolean,
  passive: boolean
) {
  if (isChrome) {
    // async edge case #6566: inner click event triggers patch, event handler
    // attached to outer element during patch, and triggered again. This only
    // happens in Chrome as it fires microtask ticks between event propagation.
    // the solution is simple: we save the timestamp when a handler is attached,
    // and the handler would only fire if the event passed to it was fired
    // AFTER it was attached.
    const now = performance.now()
    const original = handler
    handler = original._wrapper = function (e) {
      if (e.timeStamp >= now) {
        return original.apply(this, arguments)
      }
    }
  }
  target.addEventListener(
    name,
    handler,
    supportsPassive
      ? { capture, passive }
      : capture
  )
}

function remove (
  name: string,
  handler: Function,
  capture: boolean,
  _target?: HTMLElement
) {
  (_target || target).removeEventListener(
    name,
    handler._wrapper || handler,
    capture
  )
}

function updateDOMListeners (oldVnode: VNodeWithData, vnode: VNodeWithData) {
  if (isUndef(oldVnode.data.on) && isUndef(vnode.data.on)) {
    return
  }
  const on = vnode.data.on || {}
  const oldOn = oldVnode.data.on || {}
  target = vnode.elm
  normalizeEvents(on)
  updateListeners(on, oldOn, add, remove, createOnceHandler, vnode.context)
  target = undefined
}

export default {
  create: updateDOMListeners,
  update: updateDOMListeners
}
<|endoftext|>


<commit_before>angular.module('ntt.TreeDnD')
    .factory(
    '$TreeDnDControl', function () {
        var _target, _parent,
            i, len;

        function fnSetCollapse(node) {
            node.__expanded__ = false;
        }

        function fnSetExpand(node) {
            node.__expanded__ = true;
        }

        function _$init(scope) {
            var n, tree = {
                selected_node:       null,
                for_all_descendants: scope.for_all_descendants,
                select_node:         function (node) {
                    if (!node) {
                        if (tree.selected_node) {
                            delete tree.selected_node.__selected__;
                        }
                        tree.selected_node = null;
                        return null;
                    }

                    if (node !== tree.selected_node) {
                        if (tree.selected_node) {
                            delete tree.selected_node.__selected__;
                        }
                        node.__selected__  = true;
                        tree.selected_node = node;
                        tree.expand_all_parents(node);
                        if (angular.isFunction(tree.on_select)) {
                            tree.on_select(node);
                        }
                    }
                    return node;
                },
                deselect_node:       function () {
                    _target = null;
                    if (tree.selected_node) {
                        delete tree.selected_node.__selected__;
                        _target            = tree.selected_node;
                        tree.selected_node = null;
                    }
                    return _target;
                },
                get_parent:          function (node) {
                    if (node && node.__parent_real__ !== null) {
                        return scope.tree_nodes[node.__parent_real__];
                    }
                    return null;
                },
                for_all_ancestors:   function (child, fn) {
                    _parent = tree.get_parent(child);
                    if (_parent) {
                        if (fn(_parent)) {
                            return false;
                        }

                        return tree.for_all_ancestors(_parent, fn);
                    }
                    return true;
                },
                expand_all_parents:  function (child) {
                    child = child || tree.selected_node;
                    if (typeof child === 'object') {
                        tree.for_all_ancestors(
                            child, fnSetExpand
                        )
                    }
                },
                collapse_all_parents:               function (child) {
                    child = child || tree.selected_node;
                    if (typeof child === 'object') {
                        tree.for_all_ancestors(
                            child, fnSetCollapse
                        )
                    }
                },

                reload_data:                       function () {
                    return scope.reload_data();
                },
                add_node:                          function (parent, new_node, index) {
                    if (typeof index !== 'number') {
                        if (parent) {
                            parent.__children__.push(new_node);
                            parent.__expanded__ = true;
                        } else {
                            scope.treeData.push(new_node);
                        }
                    } else {
                        if (parent) {
                            parent.__children__.splice(index, 0, new_node);
                            parent.__expanded__ = true;
                        } else {
                            scope.treeData.splice(index, 0, new_node);
                        }
                    }
                    return new_node;
                },
                add_node_root:                     function (new_node) {
                    tree.add_node(null, new_node);
                    return new_node;
                },
                expand_all:                        function () {
                    len = scope.treeData.length;
                    for (i = 0; i < len; i++) {
                        tree.for_all_descendants(
                            scope.treeData[i], fnSetExpand
                        );
                    }
                },
                collapse_all:                      function () {
                    len = scope.treeData.length;
                    for (i = 0; i < len; i++) {
                        tree.for_all_descendants(
                            scope.treeData[i], fnSetCollapse
                        );
                    }
                },
                remove_node:                       function (node) {
                    node = node || tree.selected_node;
                    if (typeof node === 'object') {
                        if (node.__parent_real__ !== null) {
                            _parent = tree.get_parent(node).__children__;
                        } else {
                            _parent = scope.treeData;
                        }

                        _parent.splice(node.__index__, 1);

                        tree.reload_data();

                        if (tree.selected_node === node) {
                            tree.selected_node = null;
                        }
                    }
                },
                expand_node:                       function (node) {
                    node = node || tree.selected_node;
                    if (typeof node === 'object' && node.__expanded__) {
                        node.__expanded__ = true;
                        return node;
                    }
                },
                collapse_node:                     function (node) {
                    node = node || tree.selected_node;
                    if (typeof node === 'object') {
                        node.__expanded__ = false;
                        return node;
                    }
                },
                get_selected_node:                 function () {
                    return tree.selected_node;
                },
                get_first_node:                    function () {
                    len = scope.treeData.length;
                    if (len > 0) {
                        return scope.treeData[0];
                    }
                    return null;
                },
                get_children:                      function (node) {
                    return node.__children__;
                },
                get_siblings:                      function (node) {
                    node = node || tree.selected_node;
                    if (typeof node === 'object') {
                        _parent = tree.get_parent(node);
                        if (_parent) {
                            _target = _parent.__children__;
                        } else {
                            _target = scope.treeData;
                        }
                        return _target;
                    }
                },
                get_next_sibling:                  function (node) {
                    node = node || tree.selected_node;
                    if (typeof node === 'object') {
                        _target = tree.get_siblings(node);
                        n       = _target.length;
                        if (node.__index__ < n) {
                            return _target[node.__index__ + 1];
                        }
                    }
                },
                get_prev_sibling:                  function (node) {
                    node    = node || tree.selected_node;
                    _target = tree.get_siblings(node);
                    if (node.__index__ > 0) {
                        return _target[node.__index__ - 1];
                    }
                },
                get_first_child:                   function (node) {
                    node = node || tree.selected_node;
                    if (typeof node === 'object') {
                        _target = node.__children__;
                        if (_target && _target.length > 0) {
                            return node.__children__[0];
                        }
                    }
                    return null;
                },
                get_closest_ancestor_next_sibling: function (node) {
                    node    = node || tree.selected_node;
                    _target = tree.get_next_sibling(node);
                    if (_target) {
                        return _target;
                    }

                    _parent = tree.get_parent(node);
                    if(_parent)
                    	return tree.get_closest_ancestor_next_sibling(_parent);

                    return null;
                },
                get_next_node:                     function (node) {
                    node = node || tree.selected_node;

                    if (typeof node === 'object') {
                        _target = tree.get_first_child(node);
                        if (_target) {
                            return _target;
                        } else {
                            return tree.get_closest_ancestor_next_sibling(node);
                        }
                    }
                },
                get_prev_node:                     function (node) {
                    node = node || tree.selected_node;

                    if (typeof node === 'object') {
                        _target = tree.get_prev_sibling(node);
                        if (_target) {
                            return tree.get_last_descendant(_target);
                        }

                        _parent = tree.get_parent(node);
                        return _parent;
                    }
                },
                get_last_descendant:               scope.getLastDescendant,
                select_parent_node:                function (node) {
                    node = node || tree.selected_node;

                    if (typeof node === 'object') {
                        _parent = tree.get_parent(node);
                        if (_parent) {
                            return tree.select_node(_parent);
                        }
                    }
                },
                select_first_node:                 function () {
                    var firstNode = tree.get_first_node();
                    return tree.select_node(firstNode);
                },
                select_next_sibling:               function (node) {
                    node = node || tree.selected_node;

                    if (typeof node === 'object') {
                        _target = tree.get_next_sibling(node);
                        if (_target) {
                            return tree.select_node(_target);
                        }
                    }
                },
                select_prev_sibling:               function (node) {
                    node = node || tree.selected_node;

                    if (typeof node === 'object') {
                        _target = tree.get_prev_sibling(node);
                        if (_target) {
                            return tree.select_node(_target);
                        }
                    }
                },
                select_next_node:                  function (node) {
                    node = node || tree.selected_node;

                    if (typeof node === 'object') {
                        _target = tree.get_next_node(node);
                        if (_target) {
                            return tree.select_node(_target);
                        }
                    }
                },
                select_prev_node:                  function (node) {
                    node = node || tree.selected_node;

                    if (typeof node === 'object') {
                        _target = tree.get_prev_node(node);
                        if (_target) {
                            return tree.select_node(_target);
                        }
                    }
                }
            };
            angular.extend(scope.tree, tree);
            return scope.tree;
        }

        return _$init;
    }
);<commit_msg>Added missing curly braces<commit_after>angular.module('ntt.TreeDnD')
    .factory(
    '$TreeDnDControl', function () {
        var _target, _parent,
            i, len;

        function fnSetCollapse(node) {
            node.__expanded__ = false;
        }

        function fnSetExpand(node) {
            node.__expanded__ = true;
        }

        function _$init(scope) {
            var n, tree = {
                selected_node:       null,
                for_all_descendants: scope.for_all_descendants,
                select_node:         function (node) {
                    if (!node) {
                        if (tree.selected_node) {
                            delete tree.selected_node.__selected__;
                        }
                        tree.selected_node = null;
                        return null;
                    }

                    if (node !== tree.selected_node) {
                        if (tree.selected_node) {
                            delete tree.selected_node.__selected__;
                        }
                        node.__selected__  = true;
                        tree.selected_node = node;
                        tree.expand_all_parents(node);
                        if (angular.isFunction(tree.on_select)) {
                            tree.on_select(node);
                        }
                    }
                    return node;
                },
                deselect_node:       function () {
                    _target = null;
                    if (tree.selected_node) {
                        delete tree.selected_node.__selected__;
                        _target            = tree.selected_node;
                        tree.selected_node = null;
                    }
                    return _target;
                },
                get_parent:          function (node) {
                    if (node && node.__parent_real__ !== null) {
                        return scope.tree_nodes[node.__parent_real__];
                    }
                    return null;
                },
                for_all_ancestors:   function (child, fn) {
                    _parent = tree.get_parent(child);
                    if (_parent) {
                        if (fn(_parent)) {
                            return false;
                        }

                        return tree.for_all_ancestors(_parent, fn);
                    }
                    return true;
                },
                expand_all_parents:  function (child) {
                    child = child || tree.selected_node;
                    if (typeof child === 'object') {
                        tree.for_all_ancestors(
                            child, fnSetExpand
                        )
                    }
                },
                collapse_all_parents:               function (child) {
                    child = child || tree.selected_node;
                    if (typeof child === 'object') {
                        tree.for_all_ancestors(
                            child, fnSetCollapse
                        )
                    }
                },

                reload_data:                       function () {
                    return scope.reload_data();
                },
                add_node:                          function (parent, new_node, index) {
                    if (typeof index !== 'number') {
                        if (parent) {
                            parent.__children__.push(new_node);
                            parent.__expanded__ = true;
                        } else {
                            scope.treeData.push(new_node);
                        }
                    } else {
                        if (parent) {
                            parent.__children__.splice(index, 0, new_node);
                            parent.__expanded__ = true;
                        } else {
                            scope.treeData.splice(index, 0, new_node);
                        }
                    }
                    return new_node;
                },
                add_node_root:                     function (new_node) {
                    tree.add_node(null, new_node);
                    return new_node;
                },
                expand_all:                        function () {
                    len = scope.treeData.length;
                    for (i = 0; i < len; i++) {
                        tree.for_all_descendants(
                            scope.treeData[i], fnSetExpand
                        );
                    }
                },
                collapse_all:                      function () {
                    len = scope.treeData.length;
                    for (i = 0; i < len; i++) {
                        tree.for_all_descendants(
                            scope.treeData[i], fnSetCollapse
                        );
                    }
                },
                remove_node:                       function (node) {
                    node = node || tree.selected_node;
                    if (typeof node === 'object') {
                        if (node.__parent_real__ !== null) {
                            _parent = tree.get_parent(node).__children__;
                        } else {
                            _parent = scope.treeData;
                        }

                        _parent.splice(node.__index__, 1);

                        tree.reload_data();

                        if (tree.selected_node === node) {
                            tree.selected_node = null;
                        }
                    }
                },
                expand_node:                       function (node) {
                    node = node || tree.selected_node;
                    if (typeof node === 'object' && node.__expanded__) {
                        node.__expanded__ = true;
                        return node;
                    }
                },
                collapse_node:                     function (node) {
                    node = node || tree.selected_node;
                    if (typeof node === 'object') {
                        node.__expanded__ = false;
                        return node;
                    }
                },
                get_selected_node:                 function () {
                    return tree.selected_node;
                },
                get_first_node:                    function () {
                    len = scope.treeData.length;
                    if (len > 0) {
                        return scope.treeData[0];
                    }
                    return null;
                },
                get_children:                      function (node) {
                    return node.__children__;
                },
                get_siblings:                      function (node) {
                    node = node || tree.selected_node;
                    if (typeof node === 'object') {
                        _parent = tree.get_parent(node);
                        if (_parent) {
                            _target = _parent.__children__;
                        } else {
                            _target = scope.treeData;
                        }
                        return _target;
                    }
                },
                get_next_sibling:                  function (node) {
                    node = node || tree.selected_node;
                    if (typeof node === 'object') {
                        _target = tree.get_siblings(node);
                        n       = _target.length;
                        if (node.__index__ < n) {
                            return _target[node.__index__ + 1];
                        }
                    }
                },
                get_prev_sibling:                  function (node) {
                    node    = node || tree.selected_node;
                    _target = tree.get_siblings(node);
                    if (node.__index__ > 0) {
                        return _target[node.__index__ - 1];
                    }
                },
                get_first_child:                   function (node) {
                    node = node || tree.selected_node;
                    if (typeof node === 'object') {
                        _target = node.__children__;
                        if (_target && _target.length > 0) {
                            return node.__children__[0];
                        }
                    }
                    return null;
                },
                get_closest_ancestor_next_sibling: function (node) {
                    node    = node || tree.selected_node;
                    _target = tree.get_next_sibling(node);
                    if (_target) {
                        return _target;
                    }

                    _parent = tree.get_parent(node);
                    if(_parent)
                    {
                    	return tree.get_closest_ancestor_next_sibling(_parent);
                    }

                    return null;
                },
                get_next_node:                     function (node) {
                    node = node || tree.selected_node;

                    if (typeof node === 'object') {
                        _target = tree.get_first_child(node);
                        if (_target) {
                            return _target;
                        } else {
                            return tree.get_closest_ancestor_next_sibling(node);
                        }
                    }
                },
                get_prev_node:                     function (node) {
                    node = node || tree.selected_node;

                    if (typeof node === 'object') {
                        _target = tree.get_prev_sibling(node);
                        if (_target) {
                            return tree.get_last_descendant(_target);
                        }

                        _parent = tree.get_parent(node);
                        return _parent;
                    }
                },
                get_last_descendant:               scope.getLastDescendant,
                select_parent_node:                function (node) {
                    node = node || tree.selected_node;

                    if (typeof node === 'object') {
                        _parent = tree.get_parent(node);
                        if (_parent) {
                            return tree.select_node(_parent);
                        }
                    }
                },
                select_first_node:                 function () {
                    var firstNode = tree.get_first_node();
                    return tree.select_node(firstNode);
                },
                select_next_sibling:               function (node) {
                    node = node || tree.selected_node;

                    if (typeof node === 'object') {
                        _target = tree.get_next_sibling(node);
                        if (_target) {
                            return tree.select_node(_target);
                        }
                    }
                },
                select_prev_sibling:               function (node) {
                    node = node || tree.selected_node;

                    if (typeof node === 'object') {
                        _target = tree.get_prev_sibling(node);
                        if (_target) {
                            return tree.select_node(_target);
                        }
                    }
                },
                select_next_node:                  function (node) {
                    node = node || tree.selected_node;

                    if (typeof node === 'object') {
                        _target = tree.get_next_node(node);
                        if (_target) {
                            return tree.select_node(_target);
                        }
                    }
                },
                select_prev_node:                  function (node) {
                    node = node || tree.selected_node;

                    if (typeof node === 'object') {
                        _target = tree.get_prev_node(node);
                        if (_target) {
                            return tree.select_node(_target);
                        }
                    }
                }
            };
            angular.extend(scope.tree, tree);
            return scope.tree;
        }

        return _$init;
    }
);<|endoftext|>


<commit_before>// Copyright (c) 2015 Uber Technologies, Inc.

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var TypedError = require('error/typed');
var read = require('../lib/read');
var write = require('../lib/write');
var Frame = require('./frame');

module.exports = ErrorResponse;

var emptyBuffer = new Buffer(0);

// TODO: enforce message ID of this frame is Frame.NullId when
// errorBody.code.ProtocolError = ErrorResponse.Codes.ProtocolError

// code:1 id:4 message~2
function ErrorResponse(code, id, message) {
    if (!(this instanceof ErrorResponse)) {
        return new ErrorResponse(code, id, message);
    }
    var self = this;
    self.code = code;
    if (id === null || id === undefined) {
        self.id = Frame.NullId;
    } else {
        self.id = id;
    }
    self.message = message ? write.bufferOrString(message) : emptyBuffer;
}

ErrorResponse.TypeCode = 0xff;

var Codes = {
    // 0x00 not a valid value for "code", do not use.
    Timeout: 0x01,
    Cancelled: 0x02,
    Busy: 0x03,
    Declined: 0x04,
    UnexpectedError: 0x05,
    BadRequest: 0x06,
    ProtocolError: 0xff
};

var CodeNames = {};
CodeNames[Codes.Timeout] = 'timeout';
CodeNames[Codes.Cancelled] = 'canceled';
CodeNames[Codes.Busy] = 'busy';
CodeNames[Codes.Declined] = 'declined';
CodeNames[Codes.UnexpectedError] = 'unexpected error';
CodeNames[Codes.BadRequest] = 'bad request';
CodeNames[Codes.ProtocolError] = 'protocol error';

var CodeErrors = {};
CodeErrors[Codes.Timeout] = TypedError({
    type: 'tchannel.timeout',
    isErrorFrame: true,
    errorCode: Codes.Timeout,
    originalId: null
});
CodeErrors[Codes.Cancelled] = TypedError({
    type: 'tchannel.canceled',
    isErrorFrame: true,
    errorCode: Codes.Cancelled,
    originalId: null
});
CodeErrors[Codes.Busy] = TypedError({
    type: 'tchannel.busy',
    isErrorFrame: true,
    errorCode: Codes.Busy,
    originalId: null
});
CodeErrors[Codes.Declined] = TypedError({
    type: 'tchannel.declined',
    isErrorFrame: true,
    errorCode: Codes.Declined,
    originalId: null
});
CodeErrors[Codes.UnexpectedError] = TypedError({
    type: 'tchannel.unexpected',
    isErrorFrame: true,
    errorCode: Codes.UnexpectedError,
    originalId: null
});
CodeErrors[Codes.BadRequest] = TypedError({
    type: 'tchannel.bad-request',
    isErrorFrame: true,
    errorCode: Codes.BadRequest,
    originalId: null
});
CodeErrors[Codes.ProtocolError] = TypedError({
    type: 'tchannel.protocol',
    isErrorFrame: true,
    errorCode: Codes.ProtocolError,
    originalId: null
});

ErrorResponse.Codes = Codes;
ErrorResponse.CodeNames = CodeNames;
ErrorResponse.CodeErrors = CodeErrors;

ErrorResponse.read = read.chained(read.series([
    read.UInt8,    // code:1
    read.UInt32BE, // id:4
    read.buf2      // message~2
]), function buildErrorRes(results, buffer, offset) {
    var code = results[0];
    var id = results[1];
    var message = results[2];
    var res = new ErrorResponse(code, id, message);
    return [null, offset, res];
});

ErrorResponse.prototype.write = function writeErrorRes() {
    var self = this;
    return write.series([
        write.UInt8(self.code, 'ErrorResponse code'),  // code:1
        write.UInt32BE(self.id, 'ErrorResponse id'),   // id:4
        write.buf2(self.message, 'ErrorResponse arg1') // message~2
    ]);
};
<commit_msg>Use null-prototyped objects for error code lookup<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var TypedError = require('error/typed');
var read = require('../lib/read');
var write = require('../lib/write');
var Frame = require('./frame');

module.exports = ErrorResponse;

var emptyBuffer = new Buffer(0);

// TODO: enforce message ID of this frame is Frame.NullId when
// errorBody.code.ProtocolError = ErrorResponse.Codes.ProtocolError

// code:1 id:4 message~2
function ErrorResponse(code, id, message) {
    if (!(this instanceof ErrorResponse)) {
        return new ErrorResponse(code, id, message);
    }
    var self = this;
    self.code = code;
    if (id === null || id === undefined) {
        self.id = Frame.NullId;
    } else {
        self.id = id;
    }
    self.message = message ? write.bufferOrString(message) : emptyBuffer;
}

ErrorResponse.TypeCode = 0xff;

var Codes = Object.create(null);
// 0x00 not a valid value for "code", do not use.
Codes.Timeout = 0x01;
Codes.Cancelled = 0x02;
Codes.Busy = 0x03;
Codes.Declined = 0x04;
Codes.UnexpectedError = 0x05;
Codes.BadRequest = 0x06;
Codes.ProtocolError = 0xf;

var CodeNames = Object.create(null);
CodeNames[Codes.Timeout] = 'timeout';
CodeNames[Codes.Cancelled] = 'canceled';
CodeNames[Codes.Busy] = 'busy';
CodeNames[Codes.Declined] = 'declined';
CodeNames[Codes.UnexpectedError] = 'unexpected error';
CodeNames[Codes.BadRequest] = 'bad request';
CodeNames[Codes.ProtocolError] = 'protocol error';

var CodeErrors = Object.create(null);
CodeErrors[Codes.Timeout] = TypedError({
    type: 'tchannel.timeout',
    isErrorFrame: true,
    errorCode: Codes.Timeout,
    originalId: null
});
CodeErrors[Codes.Cancelled] = TypedError({
    type: 'tchannel.canceled',
    isErrorFrame: true,
    errorCode: Codes.Cancelled,
    originalId: null
});
CodeErrors[Codes.Busy] = TypedError({
    type: 'tchannel.busy',
    isErrorFrame: true,
    errorCode: Codes.Busy,
    originalId: null
});
CodeErrors[Codes.Declined] = TypedError({
    type: 'tchannel.declined',
    isErrorFrame: true,
    errorCode: Codes.Declined,
    originalId: null
});
CodeErrors[Codes.UnexpectedError] = TypedError({
    type: 'tchannel.unexpected',
    isErrorFrame: true,
    errorCode: Codes.UnexpectedError,
    originalId: null
});
CodeErrors[Codes.BadRequest] = TypedError({
    type: 'tchannel.bad-request',
    isErrorFrame: true,
    errorCode: Codes.BadRequest,
    originalId: null
});
CodeErrors[Codes.ProtocolError] = TypedError({
    type: 'tchannel.protocol',
    isErrorFrame: true,
    errorCode: Codes.ProtocolError,
    originalId: null
});

ErrorResponse.Codes = Codes;
ErrorResponse.CodeNames = CodeNames;
ErrorResponse.CodeErrors = CodeErrors;

ErrorResponse.read = read.chained(read.series([
    read.UInt8,    // code:1
    read.UInt32BE, // id:4
    read.buf2      // message~2
]), function buildErrorRes(results, buffer, offset) {
    var code = results[0];
    var id = results[1];
    var message = results[2];
    var res = new ErrorResponse(code, id, message);
    return [null, offset, res];
});

ErrorResponse.prototype.write = function writeErrorRes() {
    var self = this;
    return write.series([
        write.UInt8(self.code, 'ErrorResponse code'),  // code:1
        write.UInt32BE(self.id, 'ErrorResponse id'),   // id:4
        write.buf2(self.message, 'ErrorResponse arg1') // message~2
    ]);
};
<|endoftext|>


<commit_before>jest.autoMockOff();

const thePlugin = require('../../../utils/test-transform')(require('../scalar-replacement'));
const theUnsafePlugin = require('../../../utils/test-transform')([[require('../scalar-replacement'), { unsafe: true }]]);
const thePluginVerifies = require('../../../utils/test-transform').withVerifier(require('../scalar-replacement'));
const dumpScope = require('../../../utils/dump-scope');

describe('scalar-replacement', () => {
	describe('succeeds on', () => {
		thePlugin('basic', `
			var x = {
				a: 1,
			};
		`, `
			var _x$a = 1;
		`);
		thePlugin('nested', `
			var x = {
				a: 1,
				b: { c: 2 }
			};
		`, `
			var _x$a = 1,
			    _x$b$c = 2;
		`);
		thePlugin('replacing references', `
			var x = {
				a: 1
			};
			x.a;
		`, `
			var _x$a = 1;
			_x$a;
		`);
		thePlugin('replacing nested references', `
			var x = {
				a: 1,
				b: { c: 5 }
			};
			x.a;
			x.b.c;
		`, `
			var _x$a = 1,
			    _x$b$c = 5;
			_x$a;
			_x$b$c;
		`);
		thePlugin('preserves const and let', `
			const x = {
				a: 1,
			};
			let y = {
				b: 2,
			};
		`, `
			const _x$a = 1;
			let _y$b = 2;
		`);
		thePlugin('quoted props', `
			var x = {
				'a': 1,
				['b']: 2
			};
		`, `
			var _x$a = 1,
			    _x$b = 2;
		`);
		thePlugin('quoted member access', `
			var x = {
				a: 1,
			};
			x['a'];
		`, `
			var _x$a = 1;
			_x$a;
		`);
		thePlugin('non-identifier props', `
			var x = {
				'-': 1,
			};
			x['-'];
		`, `
			var _x$_ = 1;
			_x$_;
		`);
		thePlugin('semi-identifier props with numbers', `
			var x = {
				'9n': 1
			};
			x['9n'];
		`, `
			var _x$9n = 1;
			_x$9n;
		`);
		thePlugin('non-identifier props name collisions', `
			var x = {
				'-': 1,
				_: 2,
				'/': 3
			};
			x['-'];
			x._;
			x['/'];
		`, `
			var _x$_ = 1,
			    _x$_2 = 2,
			    _x$_3 = 3;
			_x$_;
			_x$_2;
			_x$_3;
		`);
		thePlugin('shadowed references', `
			var x = {
				a: 1
			};
			function foo() {
				var _x$a;
				x.a;
			}
		`, `
			var _x$a2 = 1;
			function foo() {
				var _x$a;
				_x$a2;
			}
		`);
		thePlugin('externally-shadowed references', `
			var x = {
				a: 1
			};
			var _x$a;
			function foo() {
				x.a;
			}
		`, `
			var _x$a2 = 1;
			var _x$a;
			function foo() {
				_x$a2;
			}
		`);
		thePlugin('double-shadowed references', `
			var x = {
				a: 1
			};
			function foo() {
				var _x$a;
				var _x$a2;
				x.a;
			}
		`, `
			var _x$a3 = 1;
			function foo() {
				var _x$a;
				var _x$a2;
				_x$a3;
			}
		`);
		thePlugin('double-externally-shadowed references', `
			var x = {
				a: 1
			};
			var _x$a;
			var _x$a2;
			function foo() {
				x.a;
			}
		`, `
			var _x$a3 = 1;
			var _x$a;
			var _x$a2;
			function foo() {
				_x$a3;
			}
		`);
		thePlugin('combination-shadowed references', `
			var x = {
				a: 1
			};
			var _x$a;
			function foo() {
				var _x$a2;
				x.a;
			}
		`, `
			var _x$a3 = 1;
			var _x$a;
			function foo() {
				var _x$a2;
				_x$a3;
			}
		`);
		thePlugin('duplicate keys', `
			var x = {
				a: 1,
				a: 2,
				['a']: 3,
			};
		`, `
			var _x$a = 3;
		`);
		thePlugin('arrow functions', `
			var x = {
				a: () => 1
			};
		`, `
			var _x$a = () => 1;
		`);
		thePlugin('methods', `
			var x = {
				a(y) {
					y;
				},
				async b(z) {
					z;
				},
				*c(w) {
					w;
				}
			};
		`, `
			var _x$a = function a(y) {
				y;
			},
			    _x$b = async function b(z) {
				z;
			},
			    _x$c = function* c(w) {
				w;
			};
		`);
		thePlugin('methods with string names', `
			var x = {
				'a'(y) {
					y;
				},
				async 'b'(z) {
					z;
				},
				*'c'(w) {
					w;
				}
			};
		`, `
			var _x$a = function a(y) {
				y;
			},
			    _x$b = async function b(z) {
				z;
			},
			    _x$c = function* c(w) {
				w;
			};
		`);
		thePlugin('methods with computed names', `
			var x = {
				['-a'](y) {
					y;
				},
				async ['9b'](z) {
					z;
				},
				*['-c'](w) {
					w;
				}
			};
		`, `
			var _x$_a = function _a(y) {
				y;
			},
			    _x$9b = async function _b(z) {
				z;
			},
			    _x$_c = function* _c(w) {
				w;
			};
		`);
		thePlugin('preserves ordering of nearby vars', `
			var x = 1,
				y = {
					a: 2,
					b: 3,
				},
				z = 4;
		`, `
			var x = 1,
			    _y$a = 2,
			    _y$b = 3,
			    z = 4;
		`);
		thePlugin('preserves ordering when nested', `
			var x = {
				a: 1,
				b: {
					c: 3,
					d: 4,
				},
				e: 5,
			};
		`, `
			var _x$a = 1,
			    _x$b$c = 3,
			    _x$b$d = 4,
			    _x$e = 5;
		`);
		thePlugin('nearby `this`', `
			var x = this,
				y = {
					a: 5
				},
				z = this;
			this;
		`, `
			var x = this,
			    _y$a = 5,
			    z = this;
			this;
		`);

		thePluginVerifies('correctly fixes bindings', path => {
			const fooScope = path.get('body.1').scope;
			expect(dumpScope(fooScope)).toBe([
				'FunctionDeclaration',
				'Program',
				`- _x$a ${JSON.stringify({ constant: true, references: 1, violations: 0, kind: 'var' })}`,
				`- _x$b$c ${JSON.stringify({ constant: true, references: 1, violations: 0, kind: 'var' })}`,
				`- foo ${JSON.stringify({ constant: true, references: 0, violations: 0, kind: 'hoisted' })}`,
			].join('\n'));
		}, `
			var x = {
				a: 1,
				b: { c: 5 }
			};
			function foo() {
				x.a;
				x.b.c;
			}
		`, `
			var _x$a = 1,
			    _x$b$c = 5;
			function foo() {
				_x$a;
				_x$b$c;
			}
		`);
		thePluginVerifies('doesn\'t break bindings when inserting into var sequence', path => {
			const fooScope = path.get('body.1').scope;
			expect(dumpScope(fooScope)).toBe([
				'FunctionDeclaration',
				'Program',
				`- y ${JSON.stringify({ constant: false, references: 0, violations: 1, kind: 'var' })}`,
				`- _x$a ${JSON.stringify({ constant: true, references: 1, violations: 0, kind: 'var' })}`,
				`- _x$b$c ${JSON.stringify({ constant: true, references: 1, violations: 0, kind: 'var' })}`,
				`- z ${JSON.stringify({ constant: true, references: 1, violations: 0, kind: 'var' })}`,
				`- foo ${JSON.stringify({ constant: true, references: 0, violations: 0, kind: 'hoisted' })}`,
			].join('\n'));
		}, `
			var y = 1,
				x = {
					a: 1,
					b: { c: 5 }
				},
				z = 2;
			function foo() {
				y = 2;
				x.a;
				x.b.c;
				z;
			}
		`, `
			var y = 1,
			    _x$a = 1,
			    _x$b$c = 5,
			    z = 2;
			function foo() {
				y = 2;
				_x$a;
				_x$b$c;
				z;
			}
		`);
		thePlugin('mutation only of inner object', `
			var x = {
				a: { b: 5 }
			};
			x.a.b = 5;
		`, `
			var _x$a = { b: 5 };
			_x$a.b = 5;
		`);

		describe('with unsafe', () => {
			theUnsafePlugin('mutation, assignment', `
				var x = {
					a: 1
				};
				x.a = 2;
			`, `
				var _x$a = 1;
				_x$a = 2;
			`);
			theUnsafePlugin('mutation, exotic assignment', `
				var x = {
					a: 1
				};
				x.a += 1;
				var y = {
					a: 1
				};
				y.a |= 2;
			`, `
				var _x$a = 1;
				_x$a += 1;
				var _y$a = 1;
				_y$a |= 2;
			`);
			theUnsafePlugin('mutation, array destructuring', `
				var x = {
					a: 1
				};
				[x.a] = foo;
			`, `
				var _x$a = 1;
				[_x$a] = foo;
			`);
			theUnsafePlugin('mutation, object destructuring', `
				var x = {
					a: 1
				};
				({ y: x.a } = foo);
			`, `
				var _x$a = 1;
				({ y: _x$a } = foo);
			`);
		});
	});

	describe('bails out on', () => {
		thePlugin('mutated variable', `
			var x = {
				a: 5,
				get y() {}
			};
			x = {};
		`);
		thePlugin('getters', `
			var x = {
				a: 5,
				get y() {}
			};
		`);
		thePlugin('setters', `
			var x = {
				a: 5,
				set y(v) {}
			};
		`);
		thePlugin('__proto__', `
			var x = {
				a: 5,
				__proto__: 6
			};
			var y = {
				a: 5,
				'__proto__': 6
			};
		`);
		thePlugin('unknown props', `
			var x = {
				a: 5
			};
			x.hasOwnProperty;
		`);
		thePlugin('computed props', `
			var x = {
				['x' + 'y']: 5
			};
		`);
		thePlugin('computed props through variable', `
			var x = {
				[y]: 5
			};
		`);
		thePlugin('computed member access', `
			var x = {
				ab: 5
			};
			x['a' + 'b'];
		`);
		thePlugin('object spread', `
			var x = {
				ab: 5,
				...foo
			};
		`);
		thePlugin('computed member access through variable', `
			var x = {
				ab: 5
			};
			x[ab];
		`);
		thePlugin('referencing this, simple cases', `
			var x = {
				a: function () {
					this;
				}
			};
			var y = {
				a() {
					this;
				}
			};
			var z = {
				async a() {
					this;
				}
			};
			var w = {
				*a() {
					this;
				}
			};
		`);
		thePlugin('referencing this, in IIFE initializer', `
			var x = {
				x: (() => {
					return function () {
						this;
					};
				})()
			};
		`);
		thePlugin('referencing this, deep in IIFE initializer', `
			var x = {
				x: (() => {
					return function () {
						() => this;
					};
				})()
			};
		`);
		thePlugin('mutation, assignment', `
			var x = {
				a: 1
			};
			x.a = 2;
		`);
		thePlugin('mutation, exotic assignment', `
			var x = {
				a: 1
			};
			x.a += 1;
			var y = {
				a: 1
			};
			y.a |= 2;
		`);
		thePlugin('mutation, array destructuring', `
			var x = {
				a: 1
			};
			[x.a] = foo;
		`);
		thePlugin('mutation, object destructuring', `
			var x = {
				a: 1
			};
			({ y: x.a } = foo);
		`);
		thePlugin('mutation, complex destructuring', `
			var x = {
				a: 1
			};
			[{ foo: [{ y: x.a }] }] = foo;
		`);
	});
});
<commit_msg>scalar-replacement: add test for destructuring<commit_after>jest.autoMockOff();

const thePlugin = require('../../../utils/test-transform')(require('../scalar-replacement'));
const theUnsafePlugin = require('../../../utils/test-transform')([[require('../scalar-replacement'), { unsafe: true }]]);
const thePluginVerifies = require('../../../utils/test-transform').withVerifier(require('../scalar-replacement'));
const dumpScope = require('../../../utils/dump-scope');

describe('scalar-replacement', () => {
	describe('succeeds on', () => {
		thePlugin('basic', `
			var x = {
				a: 1,
			};
		`, `
			var _x$a = 1;
		`);
		thePlugin('nested', `
			var x = {
				a: 1,
				b: { c: 2 }
			};
		`, `
			var _x$a = 1,
			    _x$b$c = 2;
		`);
		thePlugin('replacing references', `
			var x = {
				a: 1
			};
			x.a;
		`, `
			var _x$a = 1;
			_x$a;
		`);
		thePlugin('replacing nested references', `
			var x = {
				a: 1,
				b: { c: 5 }
			};
			x.a;
			x.b.c;
		`, `
			var _x$a = 1,
			    _x$b$c = 5;
			_x$a;
			_x$b$c;
		`);
		thePlugin('preserves const and let', `
			const x = {
				a: 1,
			};
			let y = {
				b: 2,
			};
		`, `
			const _x$a = 1;
			let _y$b = 2;
		`);
		thePlugin('quoted props', `
			var x = {
				'a': 1,
				['b']: 2
			};
		`, `
			var _x$a = 1,
			    _x$b = 2;
		`);
		thePlugin('quoted member access', `
			var x = {
				a: 1,
			};
			x['a'];
		`, `
			var _x$a = 1;
			_x$a;
		`);
		thePlugin('non-identifier props', `
			var x = {
				'-': 1,
			};
			x['-'];
		`, `
			var _x$_ = 1;
			_x$_;
		`);
		thePlugin('semi-identifier props with numbers', `
			var x = {
				'9n': 1
			};
			x['9n'];
		`, `
			var _x$9n = 1;
			_x$9n;
		`);
		thePlugin('non-identifier props name collisions', `
			var x = {
				'-': 1,
				_: 2,
				'/': 3
			};
			x['-'];
			x._;
			x['/'];
		`, `
			var _x$_ = 1,
			    _x$_2 = 2,
			    _x$_3 = 3;
			_x$_;
			_x$_2;
			_x$_3;
		`);
		thePlugin('shadowed references', `
			var x = {
				a: 1
			};
			function foo() {
				var _x$a;
				x.a;
			}
		`, `
			var _x$a2 = 1;
			function foo() {
				var _x$a;
				_x$a2;
			}
		`);
		thePlugin('externally-shadowed references', `
			var x = {
				a: 1
			};
			var _x$a;
			function foo() {
				x.a;
			}
		`, `
			var _x$a2 = 1;
			var _x$a;
			function foo() {
				_x$a2;
			}
		`);
		thePlugin('double-shadowed references', `
			var x = {
				a: 1
			};
			function foo() {
				var _x$a;
				var _x$a2;
				x.a;
			}
		`, `
			var _x$a3 = 1;
			function foo() {
				var _x$a;
				var _x$a2;
				_x$a3;
			}
		`);
		thePlugin('double-externally-shadowed references', `
			var x = {
				a: 1
			};
			var _x$a;
			var _x$a2;
			function foo() {
				x.a;
			}
		`, `
			var _x$a3 = 1;
			var _x$a;
			var _x$a2;
			function foo() {
				_x$a3;
			}
		`);
		thePlugin('combination-shadowed references', `
			var x = {
				a: 1
			};
			var _x$a;
			function foo() {
				var _x$a2;
				x.a;
			}
		`, `
			var _x$a3 = 1;
			var _x$a;
			function foo() {
				var _x$a2;
				_x$a3;
			}
		`);
		thePlugin('duplicate keys', `
			var x = {
				a: 1,
				a: 2,
				['a']: 3,
			};
		`, `
			var _x$a = 3;
		`);
		thePlugin('arrow functions', `
			var x = {
				a: () => 1
			};
		`, `
			var _x$a = () => 1;
		`);
		thePlugin('methods', `
			var x = {
				a(y) {
					y;
				},
				async b(z) {
					z;
				},
				*c(w) {
					w;
				}
			};
		`, `
			var _x$a = function a(y) {
				y;
			},
			    _x$b = async function b(z) {
				z;
			},
			    _x$c = function* c(w) {
				w;
			};
		`);
		thePlugin('methods with string names', `
			var x = {
				'a'(y) {
					y;
				},
				async 'b'(z) {
					z;
				},
				*'c'(w) {
					w;
				}
			};
		`, `
			var _x$a = function a(y) {
				y;
			},
			    _x$b = async function b(z) {
				z;
			},
			    _x$c = function* c(w) {
				w;
			};
		`);
		thePlugin('methods with computed names', `
			var x = {
				['-a'](y) {
					y;
				},
				async ['9b'](z) {
					z;
				},
				*['-c'](w) {
					w;
				}
			};
		`, `
			var _x$_a = function _a(y) {
				y;
			},
			    _x$9b = async function _b(z) {
				z;
			},
			    _x$_c = function* _c(w) {
				w;
			};
		`);
		thePlugin('preserves ordering of nearby vars', `
			var x = 1,
				y = {
					a: 2,
					b: 3,
				},
				z = 4;
		`, `
			var x = 1,
			    _y$a = 2,
			    _y$b = 3,
			    z = 4;
		`);
		thePlugin('preserves ordering when nested', `
			var x = {
				a: 1,
				b: {
					c: 3,
					d: 4,
				},
				e: 5,
			};
		`, `
			var _x$a = 1,
			    _x$b$c = 3,
			    _x$b$d = 4,
			    _x$e = 5;
		`);
		thePlugin('nearby `this`', `
			var x = this,
				y = {
					a: 5
				},
				z = this;
			this;
		`, `
			var x = this,
			    _y$a = 5,
			    z = this;
			this;
		`);

		thePluginVerifies('correctly fixes bindings', path => {
			const fooScope = path.get('body.1').scope;
			expect(dumpScope(fooScope)).toBe([
				'FunctionDeclaration',
				'Program',
				`- _x$a ${JSON.stringify({ constant: true, references: 1, violations: 0, kind: 'var' })}`,
				`- _x$b$c ${JSON.stringify({ constant: true, references: 1, violations: 0, kind: 'var' })}`,
				`- foo ${JSON.stringify({ constant: true, references: 0, violations: 0, kind: 'hoisted' })}`,
			].join('\n'));
		}, `
			var x = {
				a: 1,
				b: { c: 5 }
			};
			function foo() {
				x.a;
				x.b.c;
			}
		`, `
			var _x$a = 1,
			    _x$b$c = 5;
			function foo() {
				_x$a;
				_x$b$c;
			}
		`);
		thePluginVerifies('doesn\'t break bindings when inserting into var sequence', path => {
			const fooScope = path.get('body.1').scope;
			expect(dumpScope(fooScope)).toBe([
				'FunctionDeclaration',
				'Program',
				`- y ${JSON.stringify({ constant: false, references: 0, violations: 1, kind: 'var' })}`,
				`- _x$a ${JSON.stringify({ constant: true, references: 1, violations: 0, kind: 'var' })}`,
				`- _x$b$c ${JSON.stringify({ constant: true, references: 1, violations: 0, kind: 'var' })}`,
				`- z ${JSON.stringify({ constant: true, references: 1, violations: 0, kind: 'var' })}`,
				`- foo ${JSON.stringify({ constant: true, references: 0, violations: 0, kind: 'hoisted' })}`,
			].join('\n'));
		}, `
			var y = 1,
				x = {
					a: 1,
					b: { c: 5 }
				},
				z = 2;
			function foo() {
				y = 2;
				x.a;
				x.b.c;
				z;
			}
		`, `
			var y = 1,
			    _x$a = 1,
			    _x$b$c = 5,
			    z = 2;
			function foo() {
				y = 2;
				_x$a;
				_x$b$c;
				z;
			}
		`);
		thePlugin('mutation only of inner object', `
			var x = {
				a: { b: 5 }
			};
			x.a.b = 5;
		`, `
			var _x$a = { b: 5 };
			_x$a.b = 5;
		`);

		describe('with unsafe', () => {
			theUnsafePlugin('mutation, assignment', `
				var x = {
					a: 1
				};
				x.a = 2;
			`, `
				var _x$a = 1;
				_x$a = 2;
			`);
			theUnsafePlugin('mutation, exotic assignment', `
				var x = {
					a: 1
				};
				x.a += 1;
				var y = {
					a: 1
				};
				y.a |= 2;
			`, `
				var _x$a = 1;
				_x$a += 1;
				var _y$a = 1;
				_y$a |= 2;
			`);
			theUnsafePlugin('mutation, array destructuring', `
				var x = {
					a: 1
				};
				[x.a] = foo;
			`, `
				var _x$a = 1;
				[_x$a] = foo;
			`);
			theUnsafePlugin('mutation, object destructuring', `
				var x = {
					a: 1
				};
				({ y: x.a } = foo);
			`, `
				var _x$a = 1;
				({ y: _x$a } = foo);
			`);
		});
	});

	describe('bails out on', () => {
		thePlugin('mutated variable', `
			var x = {
				a: 5,
				get y() {}
			};
			x = {};
		`);
		thePlugin('getters', `
			var x = {
				a: 5,
				get y() {}
			};
		`);
		thePlugin('setters', `
			var x = {
				a: 5,
				set y(v) {}
			};
		`);
		thePlugin('__proto__', `
			var x = {
				a: 5,
				__proto__: 6
			};
			var y = {
				a: 5,
				'__proto__': 6
			};
		`);
		thePlugin('unknown props', `
			var x = {
				a: 5
			};
			x.hasOwnProperty;
		`);
		thePlugin('computed props', `
			var x = {
				['x' + 'y']: 5
			};
		`);
		thePlugin('computed props through variable', `
			var x = {
				[y]: 5
			};
		`);
		thePlugin('computed member access', `
			var x = {
				ab: 5
			};
			x['a' + 'b'];
		`);
		thePlugin('object spread', `
			var x = {
				ab: 5,
				...foo
			};
		`);
		thePlugin('destructuring', `
			var { a } = {
				a: 5
			};
		`);
		thePlugin('computed member access through variable', `
			var x = {
				ab: 5
			};
			x[ab];
		`);
		thePlugin('referencing this, simple cases', `
			var x = {
				a: function () {
					this;
				}
			};
			var y = {
				a() {
					this;
				}
			};
			var z = {
				async a() {
					this;
				}
			};
			var w = {
				*a() {
					this;
				}
			};
		`);
		thePlugin('referencing this, in IIFE initializer', `
			var x = {
				x: (() => {
					return function () {
						this;
					};
				})()
			};
		`);
		thePlugin('referencing this, deep in IIFE initializer', `
			var x = {
				x: (() => {
					return function () {
						() => this;
					};
				})()
			};
		`);
		thePlugin('mutation, assignment', `
			var x = {
				a: 1
			};
			x.a = 2;
		`);
		thePlugin('mutation, exotic assignment', `
			var x = {
				a: 1
			};
			x.a += 1;
			var y = {
				a: 1
			};
			y.a |= 2;
		`);
		thePlugin('mutation, array destructuring', `
			var x = {
				a: 1
			};
			[x.a] = foo;
		`);
		thePlugin('mutation, object destructuring', `
			var x = {
				a: 1
			};
			({ y: x.a } = foo);
		`);
		thePlugin('mutation, complex destructuring', `
			var x = {
				a: 1
			};
			[{ foo: [{ y: x.a }] }] = foo;
		`);
	});
});
<|endoftext|>


<commit_before>var View = require('../../core/view');
var LOGO_URL = 'https://cartodb.s3.amazonaws.com/static/new_logo.png';
var URL = 'http://cartodb.com';

module.exports = View.extend({
  className: 'CDB-Logo',
  tagName: 'a',

  render: function () {
    var img = document.createElement('img');
    img.setAttribute('src', LOGO_URL);
    img.setAttribute('alt', URL);
    img.setAttribute('title', URL);
    this.$el.html(img);
    this.$el.attr('href', URL);
    return this;
  }
});
<commit_msg>Adding target blanck to logo link<commit_after>var View = require('../../core/view');
var LOGO_URL = 'https://cartodb.s3.amazonaws.com/static/new_logo.png';
var URL = 'http://cartodb.com';

module.exports = View.extend({
  className: 'CDB-Logo',
  tagName: 'a',

  render: function () {
    var img = document.createElement('img');
    img.setAttribute('src', LOGO_URL);
    img.setAttribute('alt', URL);
    img.setAttribute('title', URL);
    img.setAttribute('target', '_blank');
    this.$el.html(img);
    this.$el.attr('href', URL);
    return this;
  }
});
<|endoftext|>


<commit_before>angular.module('rapid-build').controller('formValidationController', ['$scope', '$element', 'rbEventService',
	($scope, $element, rbEvents) => {
		// Builder
		// =======
		$scope.markup = `
<form action>
	<rb-input
		name="name"
		label="Name"
		validation='["required"]'>
	</rb-input>
	<rb-radios
		toggle
		name="heroes"
		label-key="name"
		label="Superheroes"
		validation='["required"]'
		data='[
			{ "id": 1, "name": "batman" },
			{ "id": 2, "name": "superman" },
			{ "id": 3, "name": "wolverine" }
		]'>
	</rb-radios>
	<rb-button type="submit">
		Submit
	</rb-button>
</form>
		`.trim();
}]);<commit_msg>chore(docs): add checkbox to form validation example<commit_after>angular.module('rapid-build').controller('formValidationController', ['$scope', '$element', 'rbEventService',
	($scope, $element, rbEvents) => {
		// Builder
		// =======
		$scope.markup = `
<form action>
	<rb-input
		name="name"
		label="Name"
		validation='["required"]'>
	</rb-input>
	<rb-radios
		toggle
		name="heroes"
		label-key="name"
		label="Superheroes"
		validation='["required"]'
		data='[
			{ "id": 1, "name": "batman" },
			{ "id": 2, "name": "superman" },
			{ "id": 3, "name": "wolverine" }
		]'>
	</rb-radios>
	<rb-checkbox
		label="Superman"
		validation='["required"]'
		sublabel="Is Awesome?">
	</rb-checkbox>
	<rb-button type="submit">
		Submit
	</rb-button>
</form>
		`.trim();
}]);<|endoftext|>


<commit_before>/**
 * The Relais card communication protocol implementation.
 * Taken from my old "Relais.cs".
 * @module io/relais
 * @author Sören Gade
 *
 * @requires serialport
 * */

/**
 * A callback that simly indicated whether a certain task was successful.
 * @callback SuccessCallback
 * @param {bool} success
 * */

var util = require('util');
var async = require('async');
var Serial = require('./serial').Serial;

/**
 * Options for the serial port.
 * @constant
 * @type {Object}
 * @default
 * */
var SERIAL_OPTIONS = {
  baudrate: 19200,
  databits: 8,
  stopbits: 1,
  parity: 'none'
};
/**
 * Commands the Relais card understands.
 * @constant
 * @type {Object}
 * @default
 * */
var Commands = {
  NoOperation: 0,
  Setup: 1,
  GetPort: 2,
  SetPort: 3,
  Getption: 4,
  SetOption: 5,
  SetSingle: 6,
  DelSingle: 7,
  Toggle: 8
};
/**
 * Relais can be identified via a certain byte. These are there values.
 * @constant
 * @type {Object}
 * @default
 * */
var RelaisByteCount = {
  One: 1,
  Two: 2,
  Three: 4,
  Four: 8,
  Five: 16,
  Six: 32,
  Seven: 64,
  Eight: 128
};
/**
 * Name for the part of the messages send between us and the relais card.
 * @constant
 * @type {Object}
 * @default
 * */
var RelaisByteNames = {
  Command: 0,
  Address: 1,
  DataByte: 2,
  CheckSum: 3
};

/**
 * @constructor
 * @extends events.EventEmitter
 * */
function Relais(port) {
  /**
   * The id our card has.
   * @instance
   * */
  this.relaisID = 0;

  // our custom parser
  // emit after 4 bytes each
  SERIAL_OPTIONS.parser = (function() {
    var blockSize = 4;
    var data = new Buffer(0);

    return function(emitter, buffer) {
      data = new Buffer( data + buffer );

      var numParts = data.length / blockSize;
      var numRest = data.length % blockSize;

      var parts = [];
      for ( var i = 0; i < numParts; i++ ) {
        var buf = new Buffer(blockSize);
        data.copy(buf, 0, i * blockSize, i * blockSize + blockSize);

        parts.push(buf);
      }
      if ( numRest <= 0 ) {
        data = new Buffer(0);
      } else {
        var tmp = new Buffer(numRest);
        data.copy(tmp, 0, data.length - 1 - numRest, data.length - 1 - numRest + blockSize);
        data = tmp;
      }

      parts.forEach(function(bufferPart) {
        emitter.emit('data', bufferPart);
      });
    };

  }());
  Serial.call(this, port, SERIAL_OPTIONS);

  /* ==========
   * PRIVATE
   * ==========
   * */
  /**
   * @param {uint} delay
   * @param {Function} relaisOperation - An operation that is passed a relais number that it should work on.
   * @param {Callback} callback
   * */
  var _iterateAllRelais = function(delay, relaisOperation, callback) {
    var self = this;
    delay = ( delay > 0 ) ? delay : 0;
    callback = callback || function() {};

    if ( delay === 0 ) {
      relaisOperation.call(self, self.getAllRelais());
    } else {
      var relaisNums = [ 1, 2, 4, 8, 16, 32, 64, 128 ];

      async.eachSeries(relaisNums, function(item, cb) {

        // item == relaisnum
        relaisOperation.call(self, item);

        setTimeout(function() {
          cb();
        }, delay);

      }, function(err) {
        if ( err ) {
          callback(err);
          throw err;
        }
        // done
        callback(null);
      });

    }
  };

  /* ==========
   * PUBLIC
   * ==========
   * */
  /*
   * Disclaimer:
   * Ported directly from old .cs source file:
   * | | | | | | | | | | | | | | | | | | | | |
   * | | | | | | | | | | | | | | | | | | | | |
   * v v v v v v v v v v v v v v v v v v v v v
   * */
  /**
   * @param {byte} command
   * @param {byte} [data]
   * @param {Callback} callback - Callback for Relais#write (Error) and Relais#read (Result).
   * */
  this.send = function(command, data, callback) {
    var self = this;
    if ( !callback ) {
      if ( typeof data === "function" ) {
        callback = data;
        data = 0;
      } else {
        callback = function() {};
      }
    }

    if ( !self.isOpen ) {
      return callback(new Error('Relais port is closed.'));
    }

    var buffer = new Buffer(4);
    buffer[RelaisByteNames.Command] = command;
    buffer[RelaisByteNames.Address] = self.relaisID;
    buffer[RelaisByteNames.DataByte] = data;
    buffer[RelaisByteNames.CheckSum] = ( command ^ self.relaisID ^ data );

    // call callback after write
    self.serialPort.once('data', function(data) {

      console.log("Response from relais card:", data);
      if ( typeof data !== "object" ) { // should be "Buffer"
        throw new Error("Invalid response data from relais card:", data);
      }

      var responseCommand = data[RelaisByteNames.Command];
      var responseAddress = data[RelaisByteNames.Address];
      if ( responseCommand === 255 ) { // error
        var err1 = new Error("Error from Relais card " + responseAddress + ".");
        return callback(err);
      }

      if ( responseCommand !== ( 255 - command ) ) {
        var err2 = new Error("Invalid response command. Expected " + ( 255 - command ) + " got " + responseCommand);
        return callback(err);
      }

      callback(null, data);

    });

    return self.write(buffer, function(err) {
      if ( err ) {
        callback(err);
      }
    });
  };

  this.getMoreRelais = function(relais1, relais2, relais3, relais4, relais5, relais6, relais7, relais8) {
    var retVal = ( RelaisByteCount.One * relais1 );
    retVal += ( RelaisByteCount.Two * relais2 );
    retVal += ( RelaisByteCount.Three * relais3 );
    retVal += ( RelaisByteCount.Four * relais4 );
    retVal += ( RelaisByteCount.Five * relais5 );
    retVal += ( RelaisByteCount.Six * relais6 );
    retVal += ( RelaisByteCount.Seven * relais7 );
    retVal += ( RelaisByteCount.Eight * relais8 );

    return retVal;
  };
  this.getAllRelais = function() {
    return this.getMoreRelais(1, 1, 1, 1, 1, 1, 1, 1);
  };

  /**
   * @param {Callback} [callback]
   * */
  this.noOperation = function(callback) {
    var self = this;
    callback = callback || function() {};

    return self.send(Commands.NoOperation, function(err, data) {
      if ( !!err ) {
        callback(err);
      }

      var ok = ( data[RelaisByteNames.Command] === 255 );
      callback(err, ok);

    });
  };
  /**
   * @param {Callback} [callback]
   * */
  this.NOP = function(callback) {
    return this.noOperation(callback);
  };

  /**
   * @param {Callback} [callback]
   * */
  this.setup = function(callback) {
    var self = this;
    callback = callback || function() {};

    if ( self.relaisID !== 0 ) {
      return callback(new Error("Relais ID is already set to", self.relaisID));
    }

    return self.send(Commands.Setup, function(err, data) {
      if ( !!err ) {
        return callback(err);
      }

      // set relais id according to response from relais card
      self.relaisID = data[RelaisByteNames.Address];

      callback(err, true);

    });
  };

  /**
   * @param {Callback} [callback]
   * */
  this.getPort = function(callback) {
    var self = this;
    callback = callback || function() {};

    self.send(Commands.GetPort, 0, function(err, data) {
      if ( err ) {
        callback(err);
      } else {

        if ( data[RelaisByteNames.Command] === ( 255 - Commands.GetPort ) ) {
          var port = data[RelaisByteNames.DataByte];
          callback(err, port);
        } else {
          callback(err, 0);
        }

      }
    });
  };

  /**
   * @param {byte} relais
   * */
  this.setPort = function(relais) {
    this.send(Commands.SetPort, relais);
  };

  /**
   * @param {Callback} [callback]
   * */
  this.getOption = function(callback) {
    var self = this;
    callback = callback || function() {};

    self.send(Commands.GetOption, 0, function(err, data) {
      if ( err ) {
        callback(err);
      } else {

        if ( data[RelaisByteNames.Command] === ( 255 - Commands.GetOption) ) {
          var dataByte = data[RelaisByteNames.DataByte];
          callback(err, dataByte);
        } else {
          callback(err, 0);
        }

      }
    });
  };

  /**
   * @param {byte} option
   * */
  this.setOption = function(option) {
    this.send(Commands.SetOption, option);
  };

  /**
   * @param {byte} relais
   * @param {Callback} [callback]
   * */
  this.setSingle = function(relais, callback) {
    var self = this;
    callback = callback || function() {};

    self.send(Commands.SetSingle, relais, function(err, data) {
      if ( err ) {
        callback(err);
      } else {

        if ( data[RelaisByteNames.Command] === ( 255 - Commands.SetSingle ) ) {
          var single = data[RelaisByteNames.DataByte];
          callback(err, single);
        } else {
          callback(err, 0);
        }

      }
    });
  };

  /**
   * @param {byte} relais
   * @param {Callback} [callback]
   * */
  this.delSingle = function(relais, callback) {
    var self = this;
    callback = callback || function() {};

    self.send(Commands.DelSingle, relais, function(err, data) {
      if ( err ) {
        callback(err);
      } else {

        if ( data[RelaisByteNames.Command] === ( 255 - Commands.DelSingle ) ) {
          var single = data[RelaisByteNames.DataByte];
          callback(err, single);
        } else {
          callback(err, 0);
        }

      }
    });
  };

  /**
   * @param {byte} relais
   * @param {Callback} [callback]
   * */
  this.toggle = function(relais, callback) {
    var self = this;
    callback = callback || function() {};

    self.send(Commands.Toggle, relais, function(err, data) {
      if ( err ) {
        callback(err);
      } else {

        if ( data[RelaisByteNames.Command] === ( 255 - Commands.Toggle ) ) {
          var resp = data[RelaisByteNames.DataByte];
          callback(err, resp);
        } else {
          callback(err, 0);
        }

      }
    });
  };

  /**
   * @param {int} delay
   * @param {Callback} [callback]
   * */
  this.activateAll = function(delay, callback) {
    _iterateAllRelais.call(this, delay, this.setSingle, callback);
  };

  /**
   * @param {int} delay
   * @param {Callback} [callback]
   * */
  this.deactivateAll = function(delay, callback) {
    _iterateAllRelais.call(this, delay, this.delSingle, callback);
  };
}
util.inherits(Relais, Serial);

module.exports = Relais;
<commit_msg>Fixed variable usage.<commit_after>/**
 * The Relais card communication protocol implementation.
 * Taken from my old "Relais.cs".
 * @module io/relais
 * @author Sören Gade
 *
 * @requires serialport
 * */

/**
 * A callback that simly indicated whether a certain task was successful.
 * @callback SuccessCallback
 * @param {bool} success
 * */

var util = require('util');
var async = require('async');
var Serial = require('./serial').Serial;

/**
 * Options for the serial port.
 * @constant
 * @type {Object}
 * @default
 * */
var SERIAL_OPTIONS = {
  baudrate: 19200,
  databits: 8,
  stopbits: 1,
  parity: 'none'
};
/**
 * Commands the Relais card understands.
 * @constant
 * @type {Object}
 * @default
 * */
var Commands = {
  NoOperation: 0,
  Setup: 1,
  GetPort: 2,
  SetPort: 3,
  Getption: 4,
  SetOption: 5,
  SetSingle: 6,
  DelSingle: 7,
  Toggle: 8
};
/**
 * Relais can be identified via a certain byte. These are there values.
 * @constant
 * @type {Object}
 * @default
 * */
var RelaisByteCount = {
  One: 1,
  Two: 2,
  Three: 4,
  Four: 8,
  Five: 16,
  Six: 32,
  Seven: 64,
  Eight: 128
};
/**
 * Name for the part of the messages send between us and the relais card.
 * @constant
 * @type {Object}
 * @default
 * */
var RelaisByteNames = {
  Command: 0,
  Address: 1,
  DataByte: 2,
  CheckSum: 3
};

/**
 * @constructor
 * @extends events.EventEmitter
 * */
function Relais(port) {
  /**
   * The id our card has.
   * @instance
   * */
  this.relaisID = 0;

  // our custom parser
  // emit after 4 bytes each
  SERIAL_OPTIONS.parser = (function() {
    var blockSize = 4;
    var data = new Buffer(0);

    return function(emitter, buffer) {
      data = new Buffer( data + buffer );

      var numParts = data.length / blockSize;
      var numRest = data.length % blockSize;

      var parts = [];
      for ( var i = 0; i < numParts; i++ ) {
        var buf = new Buffer(blockSize);
        data.copy(buf, 0, i * blockSize, i * blockSize + blockSize);

        parts.push(buf);
      }
      if ( numRest <= 0 ) {
        data = new Buffer(0);
      } else {
        var tmp = new Buffer(numRest);
        data.copy(tmp, 0, data.length - 1 - numRest, data.length - 1 - numRest + blockSize);
        data = tmp;
      }

      parts.forEach(function(bufferPart) {
        emitter.emit('data', bufferPart);
      });
    };

  }());
  Serial.call(this, port, SERIAL_OPTIONS);

  /* ==========
   * PRIVATE
   * ==========
   * */
  /**
   * @param {uint} delay
   * @param {Function} relaisOperation - An operation that is passed a relais number that it should work on.
   * @param {Callback} callback
   * */
  var _iterateAllRelais = function(delay, relaisOperation, callback) {
    var self = this;
    delay = ( delay > 0 ) ? delay : 0;
    callback = callback || function() {};

    if ( delay === 0 ) {
      relaisOperation.call(self, self.getAllRelais());
    } else {
      var relaisNums = [ 1, 2, 4, 8, 16, 32, 64, 128 ];

      async.eachSeries(relaisNums, function(item, cb) {

        // item == relaisnum
        relaisOperation.call(self, item);

        setTimeout(function() {
          cb();
        }, delay);

      }, function(err) {
        if ( err ) {
          callback(err);
          throw err;
        }
        // done
        callback(null);
      });

    }
  };

  /* ==========
   * PUBLIC
   * ==========
   * */
  /*
   * Disclaimer:
   * Ported directly from old .cs source file:
   * | | | | | | | | | | | | | | | | | | | | |
   * | | | | | | | | | | | | | | | | | | | | |
   * v v v v v v v v v v v v v v v v v v v v v
   * */
  /**
   * @param {byte} command
   * @param {byte} [data]
   * @param {Callback} callback - Callback for Relais#write (Error) and Relais#read (Result).
   * */
  this.send = function(command, data, callback) {
    var self = this;
    if ( !callback ) {
      if ( typeof data === "function" ) {
        callback = data;
        data = 0;
      } else {
        callback = function() {};
      }
    }

    if ( !self.isOpen ) {
      return callback(new Error('Relais port is closed.'));
    }

    var buffer = new Buffer(4);
    buffer[RelaisByteNames.Command] = command;
    buffer[RelaisByteNames.Address] = self.relaisID;
    buffer[RelaisByteNames.DataByte] = data;
    buffer[RelaisByteNames.CheckSum] = ( command ^ self.relaisID ^ data );

    // call callback after write
    self.serialPort.once('data', function(data) {

      console.log("Response from relais card:", data);
      if ( typeof data !== "object" ) { // should be "Buffer"
        throw new Error("Invalid response data from relais card:", data);
      }

      var responseCommand = data[RelaisByteNames.Command];
      var responseAddress = data[RelaisByteNames.Address];
      if ( responseCommand === 255 ) { // error
        var err1 = new Error("Error from Relais card " + responseAddress + ".");
        return callback(err1);
      }

      if ( responseCommand !== ( 255 - command ) ) {
        var err2 = new Error("Invalid response command. Expected " + ( 255 - command ) + " got " + responseCommand);
        return callback(err2);
      }

      callback(null, data);

    });

    return self.write(buffer, function(err) {
      if ( err ) {
        callback(err);
      }
    });
  };

  this.getMoreRelais = function(relais1, relais2, relais3, relais4, relais5, relais6, relais7, relais8) {
    var retVal = ( RelaisByteCount.One * relais1 );
    retVal += ( RelaisByteCount.Two * relais2 );
    retVal += ( RelaisByteCount.Three * relais3 );
    retVal += ( RelaisByteCount.Four * relais4 );
    retVal += ( RelaisByteCount.Five * relais5 );
    retVal += ( RelaisByteCount.Six * relais6 );
    retVal += ( RelaisByteCount.Seven * relais7 );
    retVal += ( RelaisByteCount.Eight * relais8 );

    return retVal;
  };
  this.getAllRelais = function() {
    return this.getMoreRelais(1, 1, 1, 1, 1, 1, 1, 1);
  };

  /**
   * @param {Callback} [callback]
   * */
  this.noOperation = function(callback) {
    var self = this;
    callback = callback || function() {};

    return self.send(Commands.NoOperation, function(err, data) {
      if ( !!err ) {
        callback(err);
      }

      var ok = ( data[RelaisByteNames.Command] === 255 );
      callback(err, ok);

    });
  };
  /**
   * @param {Callback} [callback]
   * */
  this.NOP = function(callback) {
    return this.noOperation(callback);
  };

  /**
   * @param {Callback} [callback]
   * */
  this.setup = function(callback) {
    var self = this;
    callback = callback || function() {};

    if ( self.relaisID !== 0 ) {
      return callback(new Error("Relais ID is already set to", self.relaisID));
    }

    return self.send(Commands.Setup, function(err, data) {
      if ( !!err ) {
        return callback(err);
      }

      // set relais id according to response from relais card
      self.relaisID = data[RelaisByteNames.Address];

      callback(err, true);

    });
  };

  /**
   * @param {Callback} [callback]
   * */
  this.getPort = function(callback) {
    var self = this;
    callback = callback || function() {};

    self.send(Commands.GetPort, 0, function(err, data) {
      if ( err ) {
        callback(err);
      } else {

        if ( data[RelaisByteNames.Command] === ( 255 - Commands.GetPort ) ) {
          var port = data[RelaisByteNames.DataByte];
          callback(err, port);
        } else {
          callback(err, 0);
        }

      }
    });
  };

  /**
   * @param {byte} relais
   * */
  this.setPort = function(relais) {
    this.send(Commands.SetPort, relais);
  };

  /**
   * @param {Callback} [callback]
   * */
  this.getOption = function(callback) {
    var self = this;
    callback = callback || function() {};

    self.send(Commands.GetOption, 0, function(err, data) {
      if ( err ) {
        callback(err);
      } else {

        if ( data[RelaisByteNames.Command] === ( 255 - Commands.GetOption) ) {
          var dataByte = data[RelaisByteNames.DataByte];
          callback(err, dataByte);
        } else {
          callback(err, 0);
        }

      }
    });
  };

  /**
   * @param {byte} option
   * */
  this.setOption = function(option) {
    this.send(Commands.SetOption, option);
  };

  /**
   * @param {byte} relais
   * @param {Callback} [callback]
   * */
  this.setSingle = function(relais, callback) {
    var self = this;
    callback = callback || function() {};

    self.send(Commands.SetSingle, relais, function(err, data) {
      if ( err ) {
        callback(err);
      } else {

        if ( data[RelaisByteNames.Command] === ( 255 - Commands.SetSingle ) ) {
          var single = data[RelaisByteNames.DataByte];
          callback(err, single);
        } else {
          callback(err, 0);
        }

      }
    });
  };

  /**
   * @param {byte} relais
   * @param {Callback} [callback]
   * */
  this.delSingle = function(relais, callback) {
    var self = this;
    callback = callback || function() {};

    self.send(Commands.DelSingle, relais, function(err, data) {
      if ( err ) {
        callback(err);
      } else {

        if ( data[RelaisByteNames.Command] === ( 255 - Commands.DelSingle ) ) {
          var single = data[RelaisByteNames.DataByte];
          callback(err, single);
        } else {
          callback(err, 0);
        }

      }
    });
  };

  /**
   * @param {byte} relais
   * @param {Callback} [callback]
   * */
  this.toggle = function(relais, callback) {
    var self = this;
    callback = callback || function() {};

    self.send(Commands.Toggle, relais, function(err, data) {
      if ( err ) {
        callback(err);
      } else {

        if ( data[RelaisByteNames.Command] === ( 255 - Commands.Toggle ) ) {
          var resp = data[RelaisByteNames.DataByte];
          callback(err, resp);
        } else {
          callback(err, 0);
        }

      }
    });
  };

  /**
   * @param {int} delay
   * @param {Callback} [callback]
   * */
  this.activateAll = function(delay, callback) {
    _iterateAllRelais.call(this, delay, this.setSingle, callback);
  };

  /**
   * @param {int} delay
   * @param {Callback} [callback]
   * */
  this.deactivateAll = function(delay, callback) {
    _iterateAllRelais.call(this, delay, this.delSingle, callback);
  };
}
util.inherits(Relais, Serial);

module.exports = Relais;
<|endoftext|>