<commit_before>/* global GOVUK */

(function () {
  'use strict'

  var root = this
  var $ = root.jQuery

  if (typeof root.GOVUK === 'undefined') { root.GOVUK = {} }

  $.expr[':'].contains = function (obj, index, meta) {
    return (obj.textContent || obj.innerText || '').toUpperCase().indexOf(meta[3].toUpperCase()) >= 0
  }

  var CountryFilter = function (input) {
    var enterKeyCode = 13
    var filterInst = this

    this.container = input.closest('.js-travel-container')
    input.keyup(function () {
      var filter = $(this).val()

      filterInst.filterListItems(filter)
      filterInst.track(filter)
    }).keypress(function (event) {
      // eslint-disable-next-line eqeqeq
      if (event.which == enterKeyCode) {
        event.preventDefault()
      }
    })

    $('.js-country-count', this.container).attr('aria-live', 'polite')

    $(document).bind('countrieslist', this.updateCounter)
  }

  CountryFilter.prototype.filterHeadings = function (countryHeadings) {
    var filterInst = this

    var headingHasVisibleCountries = function (headingFirstLetter) {
      var countries = filterInst.container.querySelector('#' + headingFirstLetter.toUpperCase()).querySelectorAll('li')
      var countryList = []

      for (var i = 0; i < countries.length; i++) {
        var innerVar = countries[i].style.display === 'none' ? countries[i] : undefined
        if (innerVar) { countryList.push(innerVar) }
      }

      return countryList.length < countries.length
    }

    for (var i = 0; i < countryHeadings.length; i++) {
      var header = countryHeadings[i].textContent.match(/[A-Z]{1}$/)[0]

      if (headingHasVisibleCountries(header)) {
        countryHeadings[i].parentNode.style.display = ''
      } else {
        countryHeadings[i].parentNode.style.display = 'none'
      }
    }
  }

  CountryFilter.prototype.doesSynonymMatch = function (elem, synonym) {
    var synonyms = elem.getAttribute('data-synonyms').split('|')
    var results = []

    for (var i = 0; i < synonyms.length; i++) {
      if (synonyms[i].toLowerCase().indexOf(synonym.toLowerCase()) > -1) {
        results.push(synonyms[i])
      }
    }

    return results
  }

  CountryFilter.prototype.filterListItems = function (filter) {
    var countryHeadings = this.container.querySelectorAll('h3.countries-initial-letter')
    var listItems = this.container.querySelectorAll('ul.js-countries-list li')

    var itemsShowing = 0
    var synonymMatch = false
    var filterInst = this
    var i = 0
    var listItem = null

    for (i = 0; i < listItems.length; i++) {
      listItem = listItems[i]
      var link = listItem.getElementsByTagName('a')[0]
      listItem.textContent = ''
      listItem.appendChild(link)
      listItem.style.display = ''
    }

    filter = filter.replace(/^\s+|\s+$/g, '')
    if (filter && filter.length > 0) {
      var hideCount = 0
      for (i = 0; i < listItems.length; i++) {
        listItem = listItems[i]
        if (listItem.children[0].firstChild.textContent.toLowerCase().includes(filter.toLowerCase())) {
          listItem.style.display = ''
        } else {
          listItem.style.display = 'none'
          hideCount += 1
        }
      }
      itemsShowing = listItems.length - hideCount

      for (i = 0; i < listItems.length; i++) {
        listItem = listItems[i]
        var synonyms = filterInst.doesSynonymMatch(listItem, filter)
        if (synonyms.length > 0) {
          synonymMatch = true
          listItem.style.display = ''
          for (var j = 0; j < synonyms.length; j++) {
            listItem.appendChild(document.createTextNode('(' + synonyms[j] + ') '))
          }
        }
      }

      if (synonymMatch) {
        itemsShowing = 0
        for (i = 0; i < listItems.length; i++) {
          if (listItems[i].style.display !== 'none') {
            itemsShowing += 1
          }
        }
      }
    } else {
      for (i = 0; i < countryHeadings.length; i++) {
        countryHeadings[i].style.display = ''
      }

      itemsShowing = listItems.length
    }

    this.filterHeadings(countryHeadings)
    this.updateCounter(itemsShowing)
  }

  CountryFilter.prototype.updateCounter = function (showingCount) {
    var counter = this.container.getElementsByClassName('js-country-count')[0]
    var filter = this.container.getElementsByClassName('js-filter-count')[0]

    filter.innerText = showingCount
    counter.innerHTML = counter.innerHTML.replace(/\s*results$/, '')
    // eslint-disable-next-line eqeqeq
    if (showingCount == 0) { // this is intentional type-conversion
      counter.appendChild(document.createTextNode(' results'))
    }
  }

  CountryFilter.prototype._trackTimeout = false

  CountryFilter.prototype.track = function (search) {
    clearTimeout(this._trackTimeout)
    var pagePath = this.pagePath()
    this._trackTimeout = root.setTimeout(function () {
      if (pagePath) {
        GOVUK.analytics.trackEvent('searchBoxFilter', search, { label: pagePath, nonInteraction: true })
      }
    }, 1000)
  }

  CountryFilter.prototype.pagePath = function () {
    window.location.pathname.split('/').pop()
  }

  GOVUK.countryFilter = CountryFilter

  $('#country-filter input#country').each(function (idx, input) {
    new GOVUK.countryFilter($(input)) // eslint-disable-line new-cap, no-new
  })
}).call(this)
<commit_msg>Remove jQ from pagePath<commit_after>/* global GOVUK */

(function () {
  'use strict'

  var root = this
  var $ = root.jQuery

  if (typeof root.GOVUK === 'undefined') { root.GOVUK = {} }

  $.expr[':'].contains = function (obj, index, meta) {
    return (obj.textContent || obj.innerText || '').toUpperCase().indexOf(meta[3].toUpperCase()) >= 0
  }

  var CountryFilter = function (input) {
    var enterKeyCode = 13
    var filterInst = this

    this.container = input.closest('.js-travel-container')
    input.keyup(function () {
      var filter = $(this).val()

      filterInst.filterListItems(filter)
      filterInst.track(filter)
    }).keypress(function (event) {
      // eslint-disable-next-line eqeqeq
      if (event.which == enterKeyCode) {
        event.preventDefault()
      }
    })

    $('.js-country-count', this.container).attr('aria-live', 'polite')

    $(document).bind('countrieslist', this.updateCounter)
  }

  CountryFilter.prototype.filterHeadings = function (countryHeadings) {
    var filterInst = this

    var headingHasVisibleCountries = function (headingFirstLetter) {
      var countries = filterInst.container.querySelector('#' + headingFirstLetter.toUpperCase()).querySelectorAll('li')
      var countryList = []

      for (var i = 0; i < countries.length; i++) {
        var innerVar = countries[i].style.display === 'none' ? countries[i] : undefined
        if (innerVar) { countryList.push(innerVar) }
      }

      return countryList.length < countries.length
    }

    for (var i = 0; i < countryHeadings.length; i++) {
      var header = countryHeadings[i].textContent.match(/[A-Z]{1}$/)[0]

      if (headingHasVisibleCountries(header)) {
        countryHeadings[i].parentNode.style.display = ''
      } else {
        countryHeadings[i].parentNode.style.display = 'none'
      }
    }
  }

  CountryFilter.prototype.doesSynonymMatch = function (elem, synonym) {
    var synonyms = elem.getAttribute('data-synonyms').split('|')
    var results = []

    for (var i = 0; i < synonyms.length; i++) {
      if (synonyms[i].toLowerCase().indexOf(synonym.toLowerCase()) > -1) {
        results.push(synonyms[i])
      }
    }

    return results
  }

  CountryFilter.prototype.filterListItems = function (filter) {
    var countryHeadings = this.container.querySelectorAll('h3.countries-initial-letter')
    var listItems = this.container.querySelectorAll('ul.js-countries-list li')

    var itemsShowing = 0
    var synonymMatch = false
    var filterInst = this
    var i = 0
    var listItem = null

    for (i = 0; i < listItems.length; i++) {
      listItem = listItems[i]
      var link = listItem.getElementsByTagName('a')[0]
      listItem.textContent = ''
      listItem.appendChild(link)
      listItem.style.display = ''
    }

    filter = filter.replace(/^\s+|\s+$/g, '')
    if (filter && filter.length > 0) {
      var hideCount = 0
      for (i = 0; i < listItems.length; i++) {
        listItem = listItems[i]
        if (listItem.children[0].firstChild.textContent.toLowerCase().includes(filter.toLowerCase())) {
          listItem.style.display = ''
        } else {
          listItem.style.display = 'none'
          hideCount += 1
        }
      }
      itemsShowing = listItems.length - hideCount

      for (i = 0; i < listItems.length; i++) {
        listItem = listItems[i]
        var synonyms = filterInst.doesSynonymMatch(listItem, filter)
        if (synonyms.length > 0) {
          synonymMatch = true
          listItem.style.display = ''
          for (var j = 0; j < synonyms.length; j++) {
            listItem.appendChild(document.createTextNode('(' + synonyms[j] + ') '))
          }
        }
      }

      if (synonymMatch) {
        itemsShowing = 0
        for (i = 0; i < listItems.length; i++) {
          if (listItems[i].style.display !== 'none') {
            itemsShowing += 1
          }
        }
      }
    } else {
      for (i = 0; i < countryHeadings.length; i++) {
        countryHeadings[i].style.display = ''
      }

      itemsShowing = listItems.length
    }

    this.filterHeadings(countryHeadings)
    this.updateCounter(itemsShowing)
  }

  CountryFilter.prototype.updateCounter = function (showingCount) {
    var counter = this.container.getElementsByClassName('js-country-count')[0]
    var filter = this.container.getElementsByClassName('js-filter-count')[0]

    filter.innerText = showingCount
    counter.innerHTML = counter.innerHTML.replace(/\s*results$/, '')
    // eslint-disable-next-line eqeqeq
    if (showingCount == 0) { // this is intentional type-conversion
      counter.appendChild(document.createTextNode(' results'))
    }
  }

  CountryFilter.prototype._trackTimeout = false

  CountryFilter.prototype.track = function (search) {
    clearTimeout(this._trackTimeout)
    var pagePath = this.pagePath()
    this._trackTimeout = root.setTimeout(function () {
      if (pagePath) {
        GOVUK.analytics.trackEvent('searchBoxFilter', search, { label: pagePath, nonInteraction: true })
      }
    }, 1000)
  }

  CountryFilter.prototype.pagePath = function () {
    window.location.pathname.split('/').pop()
  }

  GOVUK.countryFilter = CountryFilter

  var inputs = root.document.querySelectorAll('input#country')
  for (var i = 0; i < inputs.length; i++) {
    new GOVUK.countryFilter(inputs[i]) // eslint-disable-line new-cap, no-new
  }
}).call(this)
<|endoftext|>


<commit_before>/* ============================================================================

 >4SESz.,     _,     ,gSEE2zx.,_        .azx                    ,w.
@Sh. "QEE3.  JEE3.  &ss  `*4EEEEE2x.,_  "EEV  ,aS5^;dEEEE2x.,   VEEF  _
\E2`_,gF4EEEx.?jF   EE5L       `*4EEEEE2zpn..ZEEF ;sz.  `*EEESzw.w* '|EE.
  ,dEEF   `"?j]  _,_   ,_  _,     _,.     L.EEEF  !EEF  _,,  `"``    EE7   ,,_
 :EEE7 ,ws,`|EEL`JEEL`JEE)`JEEL zE5` E3. / [EE3  ,w.  zE2` Ek .zE5^JZE3.,6EF [3
 {EEE. VEE7.EE2  AE3. EEV  ZEEL{EEL ws. ;  [EE1  EEEt{E3. JEELEE3. JE5LJEEF ,w,
  \EEk,,>^ JEEL,@EEF ZE5L,ZE5^ "Q3. V2`.    \EEk,,J' "Q[ yE2^ VE[_zEE[,"QEL V5F
          ,ss  :EE7 ;EEF               L,szzw..            ,.,            ``
          \E5.,E5F  EE1.              /; ``*4EEEZhw._      EEEL
            ````     ``              JEEE.     `"45EEEhw.,,,]

From 2010 till ∞
typecode-js v 0.1
*/

define(['jquery', 'NIseed'], function($) {

    var window = this,
    NI = window.NI;

    NI.co.Merlin = {
        PREVIOUS_STEP: 'prev',
        NEXT_STEP: 'next',
        CURRENT_STEP: 'current',

        DISABLED_CLASS: 'state-disabled'
    };

    var Merlin = function(options) {

        var self = this, o, internal, fn, handlers;

        o = $.extend({
            name: null,
            $e: null,
            selector: '',
            steps: {},
            data: {},
            controls: {
                prev: null,
                next: null
            },
            transition: null, // function(last_step, current_step) {...}
            first_step: null
        }, options);

        internal = {
            name: 'mod.Merlin' + (o.name ? ' ' + o.name : ''),
            $e: (o.$e ? o.$e : $(o.selector)),
            steps: o.steps,
            data: o.data,
            controls: o.controls,
            last_step: null,
            current_step: null,
            n_step_renders: 0
        };

        fn = {
            init: function() {
                fn.init_controls();
                fn.init_steps();
                fn.show_first_step();
            },
            init_controls: function() {
                $.each(internal.controls, function(k, control) {
                    if (!control) {
                        return true;
                    }
                    if (handlers[k]) {
                        if (typeof control === 'string') {
                            control = $(control, internal.$e);
                            internal.controls[k] = control;
                        }
                        control.on('click.Merlin', handlers[k]);
                    }
                });
            },
            init_steps: function() {
                $.each(internal.steps, function(k, step) {
                    step.name = k;
                    step.n_times_shown = 0;
                    step.merlin = self;
                    if (!step.extensions){
                        step.extensions = [];
                    }
                    if (!step.$e) {
                        if (step.selector) {
                            step.$e = internal.$e.find(step.selector);
                        } else {
                            return;
                        }
                    }
                    step.$e.hide();
                });
            },
            show_first_step: function() {
                if (o.first_step) {
                    this.show_step(o.first_step);
                }
            },
            show_step: function(name, data) {

                // Sanity

                if (typeof name !== 'string' && !$.isFunction(name)) {
                    return false;
                }

                // Validation

                if (internal.current_step && internal.current_step.valid === false) {
                    return false;
                }

                // Special names

                if ($.isFunction(name)) {
                    name = name(self);
                }

                if (name === NI.co.Merlin.PREVIOUS_STEP) {
                    if (internal.current_step && internal.current_step.prev) {
                        fn.show_step(internal.current_step.prev);
                    }
                    return;
                } else if (name === NI.co.Merlin.NEXT_STEP) {
                    if (internal.current_step && internal.current_step.next) {
                        fn.show_step(internal.current_step.next);
                    }
                    return;
                } else if (name === NI.co.Merlin.CURRENT_STEP) {
                    if (internal.current_step) {
                        fn.show_step(internal.current_step.name);
                    }
                    return;
                }

                if (!internal.steps[name]) {
                    return false;
                }

                if (internal.current_step) {
                    if (name === internal.current_step.name) {
                        if ($.isFunction(internal.current_step.visible)) {
                            internal.current_step.visible.apply(internal.current_step, [self, data]);
                        }
                        for(i = 0; i < internal.current_step.extensions.length; i++){
                            if($.isFunction(internal.current_step.extensions[i].visible)){
                                internal.current_step.extensions[i].visible.apply(internal.current_step, [self, data]);
                            }
                        }
                        return true;
                    }
                    for(i = 0; i < internal.current_step.extensions.length; i++){
                        if($.isFunction(internal.current_step.extensions[i].finish)){
                            if(internal.current_step.extensions[i].finish.apply(internal.current_step, [self, data]) === false){
                                return false;
                            }
                        }
                    }
                    if ($.isFunction(internal.current_step.finish)) {
                        if (internal.current_step.finish.apply(internal.current_step, [self]) === false) {
                            return false;
                        }
                    }
                    internal.last_step = internal.current_step;
                } else {
                    internal.last_step = null;
                }

                internal.current_step = internal.steps[name];

                fn.transition_steps();

                if (internal.current_step.n_times_shown === 0) {
                    if ($.isFunction(internal.current_step.init)) {
                        internal.current_step.init.apply(internal.current_step, [self, data]);
                    }
                    console.log(internal.current_step);
                    for(i = 0; i < internal.current_step.extensions.length; i++){
                        if($.isFunction(internal.current_step.extensions[i].init)){
                            internal.current_step.extensions[i].init.apply(internal.current_step, [self, data]);
                        }
                    }
                }

                fn.update_controls();

                internal.n_step_renders += 1;
                if ($.isFunction(internal.current_step.visible)) {
                    internal.current_step.visible.apply(internal.current_step, [self, data]);
                }
                for(i = 0; i < internal.current_step.extensions.length; i++){
                    if($.isFunction(internal.current_step.extensions[i].visible)){
                        internal.current_step.extensions[i].visible.apply(internal.current_step, [self, data]);
                    }
                }

                internal.current_step.n_times_shown += 1;
            },
            prev: function() {
                this.show_step(NI.co.Merlin.PREVIOUS_STEP);
            },
            next: function() {
                this.show_step(NI.co.Merlin.NEXT_STEP);
            },
            transition_steps: function() {
                var last_step = internal.last_step,
                current_step = internal.current_step;

                if ($.isFunction(o.transition)) {
                    o.transition.apply(self, [last_step, current_step]);
                } else {
                    Merlin.default_step_transition(last_step, current_step);
                }
            },
            get_current_step: function() {
                return internal.current_step ? internal.current_step : false;
            },
            update_controls: function() {
                var current_step = internal.current_step;
                if (internal.controls.prev) {
                    if (current_step.prev) {
                        internal.controls.prev.removeClass(NI.co.Merlin.DISABLED_CLASS);
                    } else {
                        internal.controls.prev.addClass(NI.co.Merlin.DISABLED_CLASS);
                    }
                }
                if (internal.controls.next) {
                    if (current_step.next) {
                        internal.controls.next.removeClass(NI.co.Merlin.DISABLED_CLASS);
                    } else {
                        internal.controls.next.addClass(NI.co.Merlin.DISABLED_CLASS);
                    }
                }
            },
            set_data: function(d) {
                var data;

                if (!d || typeof d !== 'object') {
                    return;
                }

                data = internal.data;

                $.each(d, function(k, v) {
                    data[k] = v;
                });
            },
            get_data: function() {
                var d = {};
                $.each(internal.data, function(k, v) {
                    d[k] = v;
                });
                return d;
            },
            set_val: function(k, v) {
                internal.data[k] = v;
            },
            get_val: function(k) {
                return internal.data[k];
            },
            get_dom: function() {
                return internal.$e;
            },
            get_name: function() {
                return o.name;
            },
            destroy: function() {
                $.each(internal.controls, function(k, control) {
                    if (handlers[k]) {
                        if (typeof control === 'string') {
                            control = $(control);
                        }
                        control.off('click.Merlin', handlers[k]);
                    }
                });
                $.each(internal.steps, function() {
                    if ($.isFunction(this.destroy)) {
                        this.destroy.apply(this, [self]);
                    }
                });
            }
        };

        handlers = {
            prev: function(e) {
                e.preventDefault();
                if ($(this).hasClass(NI.co.Merlin.DISABLED_CLASS)) {
                    return;
                }
                fn.show_step(NI.co.Merlin.PREVIOUS_STEP);
            },
            next: function(e) {
                e.preventDefault();
                if ($(this).hasClass(NI.co.Merlin.DISABLED_CLASS)) {
                    return;
                }
                fn.show_step(NI.co.Merlin.NEXT_STEP);
            },
            refresh: function(e) {
                e.preventDefault();
                fn.show_step(NI.co.Merlin.CURRENT_STEP);
            }
        };

        this.show_first_step = fn.show_first_step;
        this.show_step = fn.show_step;
        this.prev = fn.prev;
        this.next = fn.next;
        this.get_current_step = fn.get_current_step;
        this.set_data = fn.set_data;
        this.get_data = fn.get_data;
        this.set_val = fn.set_val;
        this.get_val = fn.get_val;
        this.get_dom = fn.get_dom;
        this.get_name = fn.get_name;
        this.destroy = fn.destroy;

        fn.init();
        console.log(internal);
    };

    Merlin.default_step_transition = function(last_step, current_step) {
        if (last_step && last_step.$e) {
            last_step.$e.hide();
        }
        if(current_step.$e){
            current_step.$e.show();
        }

    };

    NI.Merlin = Merlin;

    return Merlin;
});<commit_msg>some work on things for architizer<commit_after>/* ============================================================================

 >4SESz.,     _,     ,gSEE2zx.,_        .azx                    ,w.
@Sh. "QEE3.  JEE3.  &ss  `*4EEEEE2x.,_  "EEV  ,aS5^;dEEEE2x.,   VEEF  _
\E2`_,gF4EEEx.?jF   EE5L       `*4EEEEE2zpn..ZEEF ;sz.  `*EEESzw.w* '|EE.
  ,dEEF   `"?j]  _,_   ,_  _,     _,.     L.EEEF  !EEF  _,,  `"``    EE7   ,,_
 :EEE7 ,ws,`|EEL`JEEL`JEE)`JEEL zE5` E3. / [EE3  ,w.  zE2` Ek .zE5^JZE3.,6EF [3
 {EEE. VEE7.EE2  AE3. EEV  ZEEL{EEL ws. ;  [EE1  EEEt{E3. JEELEE3. JE5LJEEF ,w,
  \EEk,,>^ JEEL,@EEF ZE5L,ZE5^ "Q3. V2`.    \EEk,,J' "Q[ yE2^ VE[_zEE[,"QEL V5F
          ,ss  :EE7 ;EEF               L,szzw..            ,.,            ``
          \E5.,E5F  EE1.              /; ``*4EEEZhw._      EEEL
            ````     ``              JEEE.     `"45EEEhw.,,,]

From 2010 till ∞
typecode-js v 0.1
*/

define(['jquery', 'NIseed'], function($) {

    var window = this,
    NI = window.NI;

    NI.co.Merlin = {
        PREVIOUS_STEP: 'prev',
        NEXT_STEP: 'next',
        CURRENT_STEP: 'current',

        DISABLED_CLASS: 'state-disabled'
    };

    var Merlin = function(options) {

        var self = this, o, internal, fn, handlers;

        o = $.extend({
            name: null,
            $e: null,
            selector: '',
            steps: {},
            data: {},
            controls: {
                prev: null,
                next: null
            },
            transition: null, // function(last_step, current_step) {...}
            first_step: null
        }, options);

        internal = {
            name: 'mod.Merlin' + (o.name ? ' ' + o.name : ''),
            $e: (o.$e ? o.$e : $(o.selector)),
            steps: o.steps,
            data: o.data,
            controls: o.controls,
            last_step: null,
            current_step: null,
            n_step_renders: 0
        };

        fn = {
            init: function() {
                fn.init_controls();
                fn.init_steps();
                fn.show_first_step();
                internal.$e.addClass('merlin-init');
            },
            init_controls: function() {
                $.each(internal.controls, function(k, control) {
                    if (!control) {
                        return true;
                    }
                    if (handlers[k]) {
                        if (typeof control === 'string') {
                            control = $(control, internal.$e);
                            internal.controls[k] = control;
                        }
                        control.on('click.Merlin', handlers[k]);
                    }
                });
            },
            init_steps: function() {
                $.each(internal.steps, function(k, step) {
                    step.name = k;
                    step.n_times_shown = 0;
                    step.merlin = self;
                    if (!step.extensions){
                        step.extensions = [];
                    }
                    if (!step.$e) {
                        if (step.selector) {
                            step.$e = internal.$e.find(step.selector);
                        } else {
                            return;
                        }
                    }
                    step.$e.hide();
                });
            },
            show_first_step: function() {
                if (o.first_step) {
                    this.show_step(o.first_step);
                }
            },
            show_step: function(name, data) {

                // Sanity

                if (typeof name !== 'string' && !$.isFunction(name)) {
                    return false;
                }

                // Validation

                if (internal.current_step && internal.current_step.valid === false) {
                    return false;
                }

                // Special names

                if ($.isFunction(name)) {
                    name = name(self);
                }

                if (name === NI.co.Merlin.PREVIOUS_STEP) {
                    if (internal.current_step && internal.current_step.prev) {
                        fn.show_step(internal.current_step.prev);
                    }
                    return;
                } else if (name === NI.co.Merlin.NEXT_STEP) {
                    if (internal.current_step && internal.current_step.next) {
                        fn.show_step(internal.current_step.next);
                    }
                    return;
                } else if (name === NI.co.Merlin.CURRENT_STEP) {
                    if (internal.current_step) {
                        fn.show_step(internal.current_step.name);
                    }
                    return;
                }

                if (!internal.steps[name]) {
                    return false;
                }

                if (internal.current_step) {
                    if (name === internal.current_step.name) {
                        if ($.isFunction(internal.current_step.visible)) {
                            internal.current_step.visible.apply(internal.current_step, [self, data]);
                        }
                        for(i = 0; i < internal.current_step.extensions.length; i++){
                            if($.isFunction(internal.current_step.extensions[i].visible)){
                                internal.current_step.extensions[i].visible.apply(internal.current_step, [self, data]);
                            }
                        }
                        return true;
                    }
                    for(i = 0; i < internal.current_step.extensions.length; i++){
                        if($.isFunction(internal.current_step.extensions[i].finish)){
                            if(internal.current_step.extensions[i].finish.apply(internal.current_step, [self, data]) === false){
                                return false;
                            }
                        }
                    }
                    if ($.isFunction(internal.current_step.finish)) {
                        if (internal.current_step.finish.apply(internal.current_step, [self]) === false) {
                            return false;
                        }
                    }
                    internal.last_step = internal.current_step;
                } else {
                    internal.last_step = null;
                }

                internal.current_step = internal.steps[name];

                fn.transition_steps();

                if (internal.current_step.n_times_shown === 0) {
                    if ($.isFunction(internal.current_step.init)) {
                        internal.current_step.init.apply(internal.current_step, [self, data]);
                    }
                    console.log(internal.current_step);
                    for(i = 0; i < internal.current_step.extensions.length; i++){
                        if($.isFunction(internal.current_step.extensions[i].init)){
                            internal.current_step.extensions[i].init.apply(internal.current_step, [self, data]);
                        }
                    }
                }

                fn.update_controls();

                internal.n_step_renders += 1;
                if ($.isFunction(internal.current_step.visible)) {
                    internal.current_step.visible.apply(internal.current_step, [self, data]);
                }
                for(i = 0; i < internal.current_step.extensions.length; i++){
                    if($.isFunction(internal.current_step.extensions[i].visible)){
                        internal.current_step.extensions[i].visible.apply(internal.current_step, [self, data]);
                    }
                }

                internal.current_step.n_times_shown += 1;
            },
            prev: function() {
                this.show_step(NI.co.Merlin.PREVIOUS_STEP);
            },
            next: function() {
                this.show_step(NI.co.Merlin.NEXT_STEP);
            },
            transition_steps: function() {
                var last_step = internal.last_step,
                current_step = internal.current_step;

                if ($.isFunction(o.transition)) {
                    o.transition.apply(self, [last_step, current_step]);
                } else {
                    Merlin.default_step_transition(last_step, current_step);
                }
            },
            get_current_step: function() {
                return internal.current_step ? internal.current_step : false;
            },
            update_controls: function() {
                var current_step = internal.current_step;
                if (internal.controls.prev) {
                    if (current_step.prev) {
                        internal.controls.prev.removeClass(NI.co.Merlin.DISABLED_CLASS);
                    } else {
                        internal.controls.prev.addClass(NI.co.Merlin.DISABLED_CLASS);
                    }
                }
                if (internal.controls.next) {
                    if (current_step.next) {
                        internal.controls.next.removeClass(NI.co.Merlin.DISABLED_CLASS);
                    } else {
                        internal.controls.next.addClass(NI.co.Merlin.DISABLED_CLASS);
                    }
                }
            },
            set_data: function(d) {
                var data;

                if (!d || typeof d !== 'object') {
                    return;
                }

                data = internal.data;

                $.each(d, function(k, v) {
                    data[k] = v;
                });
            },
            get_data: function() {
                var d = {};
                $.each(internal.data, function(k, v) {
                    d[k] = v;
                });
                return d;
            },
            set_val: function(k, v) {
                internal.data[k] = v;
            },
            get_val: function(k) {
                return internal.data[k];
            },
            get_dom: function() {
                return internal.$e;
            },
            get_name: function() {
                return o.name;
            },
            destroy: function() {
                $.each(internal.controls, function(k, control) {
                    if (handlers[k]) {
                        if (typeof control === 'string') {
                            control = $(control);
                        }
                        control.off('click.Merlin', handlers[k]);
                    }
                });
                $.each(internal.steps, function() {
                    if ($.isFunction(this.destroy)) {
                        this.destroy.apply(this, [self]);
                    }
                });
            }
        };

        handlers = {
            prev: function(e) {
                e.preventDefault();
                if ($(this).hasClass(NI.co.Merlin.DISABLED_CLASS)) {
                    return;
                }
                fn.show_step(NI.co.Merlin.PREVIOUS_STEP);
            },
            next: function(e) {
                e.preventDefault();
                if ($(this).hasClass(NI.co.Merlin.DISABLED_CLASS)) {
                    return;
                }
                fn.show_step(NI.co.Merlin.NEXT_STEP);
            },
            refresh: function(e) {
                e.preventDefault();
                fn.show_step(NI.co.Merlin.CURRENT_STEP);
            }
        };

        this.show_first_step = fn.show_first_step;
        this.show_step = fn.show_step;
        this.prev = fn.prev;
        this.next = fn.next;
        this.get_current_step = fn.get_current_step;
        this.set_data = fn.set_data;
        this.get_data = fn.get_data;
        this.set_val = fn.set_val;
        this.get_val = fn.get_val;
        this.get_dom = fn.get_dom;
        this.get_name = fn.get_name;
        this.destroy = fn.destroy;

        fn.init();
        console.log(internal);
    };

    Merlin.default_step_transition = function(last_step, current_step) {
        if (last_step && last_step.$e) {
            last_step.$e.hide();
        }
        if(current_step.$e){
            current_step.$e.show();
        }

    };

    NI.Merlin = Merlin;

    return Merlin;
});<|endoftext|>


<commit_before>//------------------------------------------------------------------------
// scan the current location to detect parameters
function scanUrl()	{
    let result = new Array();
    let arg = window.location.search.substring(1);
    let n = arg.indexOf("=");
    while (n > 0) {
        let option  = arg.substr(0,n);
        let remain = arg.substr(n+1);
        let next = remain.indexOf("?");
        if (next > 0) {
            let value = remain.substr(0,next);
            result.push ( {option: option, value: value} );
            arg = remain.substr(next + 1);
            n = arg.indexOf("=");
        }
        else {
            result.push ( {option: option, value: remain} );
            break;
        }
    }
    return result;
	}

//------------------------------------------------------------------------
// scan the current location to detect parameters
function scanOptions()	{
console.log ("lxml code scan options: " + window.location);
    let options = this.scanUrl();
    for (let i=0; i<options.length; i++) {
        let option = options[i].option;
        let value = options[i].value;
        switch (option) {
            case "s":
console.log ("lxml code receive s request id: " + value);
            let gmn = localStorage.getItem(value);
            if (gmn) {
console.log ("lxml code put id: " + value);
                var div = document.getElementById("code");
                div.innerHTML =  gmn;
				window.postMessage(gmn, "https://guidoeditor.grame.fr");
                // document.body.innerText = gmn;
            }
            break;
        }
    }
}

scanOptions();<commit_msg>set target to *<commit_after>//------------------------------------------------------------------------
// scan the current location to detect parameters
function scanUrl()	{
    let result = new Array();
    let arg = window.location.search.substring(1);
    let n = arg.indexOf("=");
    while (n > 0) {
        let option  = arg.substr(0,n);
        let remain = arg.substr(n+1);
        let next = remain.indexOf("?");
        if (next > 0) {
            let value = remain.substr(0,next);
            result.push ( {option: option, value: value} );
            arg = remain.substr(next + 1);
            n = arg.indexOf("=");
        }
        else {
            result.push ( {option: option, value: remain} );
            break;
        }
    }
    return result;
	}

//------------------------------------------------------------------------
// scan the current location to detect parameters
function scanOptions()	{
console.log ("lxml code scan options: " + window.location);
    let options = this.scanUrl();
    for (let i=0; i<options.length; i++) {
        let option = options[i].option;
        let value = options[i].value;
        switch (option) {
            case "s":
console.log ("lxml code receive s request id: " + value);
            let gmn = localStorage.getItem(value);
            if (gmn) {
console.log ("lxml code put id: " + value);
                var div = document.getElementById("code");
                div.innerHTML =  gmn;
				// window.postMessage(gmn, "https://guidoeditor.grame.fr");
				window.postMessage(gmn, "*");
                // document.body.innerText = gmn;
            }
            break;
        }
    }
}

scanOptions();<|endoftext|>


<commit_before>// LICENSE : MIT
"use strict";
export function filter(commits, done) {
    var results = [];
    var promises = commits.map(function (commit) {
        return commit.getDiff().then(function (diffList) {
            diffList.forEach(function (diff) {
                diff.patches().forEach(function (patch) {
                    patch.hunks().forEach(function (hunk) {
                        hunk.lines().forEach(function (line) {
                            var sign = String.fromCharCode(line.origin());
                            if (sign === "+") {

                            } else {
                                if (/forget/.test(line.content())) {
                                    results.push(commit);
                                    console.log(commit)
                                }
                            }
                        });
                    });
                });
            });
        })
    });
    Promise.all(promises).then(function () {
        done(results);
    });
}<commit_msg>chore: add comment to example filter script<commit_after>// LICENSE : MIT
"use strict";
export default function filter(commits, done) {
    var results = [];
    var promises = commits.map(function (commit) {
        return commit.getDiff().then(function (diffList) {
            diffList.forEach(function (diff) {
                diff.patches().forEach(function (patch) {
                    patch.hunks().forEach(function (hunk) {
                        hunk.lines().forEach(function (line) {
                            // + or -
                            var sign = String.fromCharCode(line.origin());
                            if (sign === "+") {

                            } else if (sign === "-") {
                                if (/forget/.test(line.content())) {
                                    results.push(commit);
                                    console.log(commit)
                                }
                            }
                        });
                    });
                });
            });
        })
    });
    Promise.all(promises).then(function () {
        done(results);
    });
}<|endoftext|>


<commit_before>/**
 * @module
 * @prototype {Function} __touchHandler
 */

import { SmoothScrollbar } from '../smooth-scrollbar';
import { GLOBAL_ENV } from '../shared/';

const MIN_VELOCITY = 100;

let activeScrollbar = null;

/**
 * @method
 * @internal
 * Touch event handlers builder
 */
function __touchHandler() {
    const {
        targets,
        movementLocked,
        __touchRecord,
    } = this;

    const {
        container,
    } = targets;

    this.__addEvent(container, 'touchstart', (evt) => {
        if (this.__isDrag) return;

        const { __timerID, movement } = this;

        // stop scrolling but keep movement for overscrolling
        cancelAnimationFrame(__timerID.scrollTo);
        if (!this.__willOverscroll('x')) movement.x = 0;
        if (!this.__willOverscroll('y')) movement.y = 0;

        // start records
        __touchRecord.track(evt);
        this.__autoLockMovement();
    });

    this.__addEvent(container, 'touchmove', (evt) => {
        if (this.__isDrag) return;
        if (activeScrollbar && activeScrollbar !== this) return;

        __touchRecord.update(evt);

        let { x, y } = __touchRecord.getDelta();

        if (this.__shouldPropagateMovement(x, y)) {
            return this.__updateThrottle();
        }

        const { movement, MAX_OVERSCROLL, options } = this;

        if (movement.x && this.__willOverscroll('x', x)) {
            let factor = 2;

            if (options.overscrollEffect === 'bounce') {
                factor += Math.abs(10 * movement.x / MAX_OVERSCROLL);
            }

            if (Math.abs(movement.x) >= MAX_OVERSCROLL) {
                x = 0;
            } else {
                x /= factor;
            }
        }
        if (movement.y && this.__willOverscroll('y', y)) {
            let factor = 2;

            if (options.overscrollEffect === 'bounce') {
                factor += Math.abs(10 * movement.y / MAX_OVERSCROLL);
            }

            if (Math.abs(movement.y) >= MAX_OVERSCROLL) {
                y = 0;
            } else {
                y /= factor;
            }
        }

        this.__autoLockMovement();

        evt.preventDefault();

        this.__addMovement(x, y, true);
        activeScrollbar = this;
    });

    this.__addEvent(container, 'touchcancel touchend', (evt) => {
        if (this.__isDrag) return;

        const { speed } = this.options;

        let { x, y } = __touchRecord.getVelocity();

        x = movementLocked.x ? 0 : Math.min(x * GLOBAL_ENV.EASING_MULTIPLIER, 1000);
        y = movementLocked.y ? 0 : Math.min(y * GLOBAL_ENV.EASING_MULTIPLIER, 1000);

        this.__addMovement(
            Math.abs(x) > MIN_VELOCITY ? (x * speed) : 0,
            Math.abs(y) > MIN_VELOCITY ? (y * speed) : 0,
            true
        );

        this.__unlockMovement();
        __touchRecord.release(evt);
        activeScrollbar = null;
    });
};

Object.defineProperty(SmoothScrollbar.prototype, '__touchHandler', {
    value: __touchHandler,
    writable: true,
    configurable: true,
});
<commit_msg>fix(touch): fix touch velocity resizer<commit_after>/**
 * @module
 * @prototype {Function} __touchHandler
 */

import { SmoothScrollbar } from '../smooth-scrollbar';
import { GLOBAL_ENV } from '../shared/';
import { pickInRange } from '../utils/';

const MIN_VELOCITY = 100;

let activeScrollbar = null;

/**
 * @method
 * @internal
 * Touch event handlers builder
 */
function __touchHandler() {
    const {
        targets,
        __touchRecord,
    } = this;

    const {
        container,
    } = targets;

    this.__addEvent(container, 'touchstart', (evt) => {
        if (this.__isDrag) return;

        const { __timerID, movement } = this;

        // stop scrolling but keep movement for overscrolling
        cancelAnimationFrame(__timerID.scrollTo);
        if (!this.__willOverscroll('x')) movement.x = 0;
        if (!this.__willOverscroll('y')) movement.y = 0;

        // start records
        __touchRecord.track(evt);
        this.__autoLockMovement();
    });

    this.__addEvent(container, 'touchmove', (evt) => {
        if (this.__isDrag) return;
        if (activeScrollbar && activeScrollbar !== this) return;

        __touchRecord.update(evt);

        let { x, y } = __touchRecord.getDelta();

        if (this.__shouldPropagateMovement(x, y)) {
            return this.__updateThrottle();
        }

        const { movement, MAX_OVERSCROLL, options } = this;

        if (movement.x && this.__willOverscroll('x', x)) {
            let factor = 2;

            if (options.overscrollEffect === 'bounce') {
                factor += Math.abs(10 * movement.x / MAX_OVERSCROLL);
            }

            if (Math.abs(movement.x) >= MAX_OVERSCROLL) {
                x = 0;
            } else {
                x /= factor;
            }
        }
        if (movement.y && this.__willOverscroll('y', y)) {
            let factor = 2;

            if (options.overscrollEffect === 'bounce') {
                factor += Math.abs(10 * movement.y / MAX_OVERSCROLL);
            }

            if (Math.abs(movement.y) >= MAX_OVERSCROLL) {
                y = 0;
            } else {
                y /= factor;
            }
        }

        this.__autoLockMovement();

        evt.preventDefault();

        this.__addMovement(x, y, true);
        activeScrollbar = this;
    });

    this.__addEvent(container, 'touchcancel touchend', (evt) => {
        if (this.__isDrag) return;

        const { speed } = this.options;

        const velocity = __touchRecord.getVelocity();
        const movement = {};

        Object.keys(velocity).forEach(dir => {
            const value = pickInRange(velocity[dir] * GLOBAL_ENV.EASING_MULTIPLIER, -1e3, 1e3);

            // throw small values
            movement[dir] = Math.abs(value) > MIN_VELOCITY ? (value * speed) : 0;
        });

        this.__addMovement(
            movement.x,
            movement.y,
            true
        );

        this.__unlockMovement();
        __touchRecord.release(evt);
        activeScrollbar = null;
    });
};

Object.defineProperty(SmoothScrollbar.prototype, '__touchHandler', {
    value: __touchHandler,
    writable: true,
    configurable: true,
});
<|endoftext|>


<commit_before>'use strict';

describe('Controller: MainCtrl', function () {

  // load the controller's module
  // beforeEach(module('gruntAnguarlApp'));
  //
  // var MainCtrl,
  //   scope;
  //
  // // Initialize the controller and a mock scope
  // beforeEach(inject(function ($controller, $rootScope) {
  //   scope = $rootScope.$new();
  //   MainCtrl = $controller('MainCtrl', {
  //     $scope: scope
  //   });
  // }));

  it('should be true', function () {
    expect(3).toBe(3);
  });
});
<commit_msg>testing travis<commit_after>'use strict';

describe('Controller: MainCtrl', function () {

  // load the controller's module
  // beforeEach(module('gruntAnguarlApp'));
  //
  // var MainCtrl,
  //   scope;
  //
  // // Initialize the controller and a mock scope
  // beforeEach(inject(function ($controller, $rootScope) {
  //   scope = $rootScope.$new();
  //   MainCtrl = $controller('MainCtrl', {
  //     $scope: scope
  //   });
  // }));

  it('should be true', function () {
    expect(3).toBe(4);
  });
});
<|endoftext|>


<commit_before>F("tbody", F.Components.table_part.extend({
  init: function(name, $container) {
    var self = this;
    self._super(name, $container);
    self.fieldByName = {};
    self.current = 0;
    self.options = {limit: 10};
    self.subscribe(F.TOPIC.DATA_TABLE.RELOAD, function(topic, data){
      self.load({reset: true});
    });
    self.subscribe(F.TOPIC.DATA_TABLE.LOAD_MORE, function(topic, data){
      self.load();
    });
    self.subscribe(F.TOPIC.DATA_TABLE.SHOW_COLUMN, function(topic, data){
      self.showColumn(data);
    });
    self.subscribe(F.TOPIC.DATA_TABLE.HIDE_COLUMN, function(topic, data){
      self.hideColumn(data);
    });
  },
  afterRender: function(cb){
    var self = this;
    self.$('.cbx-doc').click(function(ev){
      var checkedDocs = [];
      self.$('.cbx-doc').each(function(){
        if (this.checked) {
          checkedDocs.push($(this).closest(".doc").data("id"));
        }
      });
      self.publish("doc.checked", checkedDocs);
    });
    self.$('.doc-value').click(function(){
      var docId = $(this).closest(".doc").data("id");
      var params = {
        conn: F.env.conn,
        db: F.env.db,
        col: F.env.col,
        doc: docId
      };
      F.navigate("document", params);
    });
    cb();
  },
  render: function(cb, param) {
    if (param && param.reset) {
      this._super(cb);
    } else {
      var contents = F.Render(this.template, this.data);
      this.$container.append(contents);
      cb();
    }
  },
  getData: function(cb, param) {
    var self = this;
    if (!F.env.db || !F.env.col) {
      self.data = {};
      return cb();
    }
    if (param && param.reset) self.current = 0;
    self.options.skip = self.current;
    var countQuery = "conn/" + F.env.conn + "/db/" + F.env.db + "/col/" + F.env.col;
    var dataQuery = countQuery + "/doc?options=" + encodeURIComponent(JSON.stringify(self.options));
    F.require([countQuery, dataQuery], function(data){
      var total = data[countQuery].count;

      var flattenData = [];
      var fieldAdded = {};
      data[dataQuery].forEach(function(v){
        var f = MONGRES.flatten(v);
        for (var i in f) {
          if (!(i in self.fieldByName)) {
            fieldAdded[i] = true;
            self.fieldByName[i] = true;
          }
        }
        flattenData.push(f);
      });

      var fields = [];
      for (var i in self.fieldByName) fields.push(i);
      fields.sort();

      self.publish(F.TOPIC.DATA_TABLE.HEAD_UPDATED, fields);

      var config = MONGRES.getColumnConfig().getAll();
      var hide = config ? function(v){
        return (v in config && !config[v]);
      } : function(){ return false; };
      records = [];
      flattenData.forEach(function(d){
        r = {_id: d._id, values: []};
        fields.forEach(function(f){
          r.values.push({
            classValue: MONGRES.col2Class(f),
            value: d[f],
            hide: hide(f),
          });
        });
        records.push(r);
      });
      self.data = {
        records: records,
        idString: function(){
          if (this._id.indexOf("ObjectID('") === 0) {
            return this._id.substr(10, 24);
          } else {
            return this._id;
          }
        }
      };

      // if (fields.changed) update existing table
      if (self.current > 0) {
        var insertCols = [];
        var lastV = null;
        fields.forEach(function(v){
          if (v in fieldAdded && lastV) { insertCols.push({me: v, after: lastV}); }
          lastV = v;
        });
        insertCols.forEach(function(v){
          var $after = self.$("." + MONGRES.col2Class(v.after));
          var classes = MONGRES.col2Class(v.me) + (hide(v) ? " hide" : "");
          var $me = $('	');
          $after.after($me);
        });
      }
      self.current += records.length;
      self.publish(
        F.TOPIC.DATA_TABLE.BODY_UPDATED,
        {all_loaded: (self.current >= total)}
      );

      cb();
    });
  },
}));

<commit_msg>fix errors for integer _id<commit_after>F("tbody", F.Components.table_part.extend({
  init: function(name, $container) {
    var self = this;
    self._super(name, $container);
    self.fieldByName = {};
    self.current = 0;
    self.options = {limit: 10};
    self.subscribe(F.TOPIC.DATA_TABLE.RELOAD, function(topic, data){
      self.load({reset: true});
    });
    self.subscribe(F.TOPIC.DATA_TABLE.LOAD_MORE, function(topic, data){
      self.load();
    });
    self.subscribe(F.TOPIC.DATA_TABLE.SHOW_COLUMN, function(topic, data){
      self.showColumn(data);
    });
    self.subscribe(F.TOPIC.DATA_TABLE.HIDE_COLUMN, function(topic, data){
      self.hideColumn(data);
    });
  },
  afterRender: function(cb){
    var self = this;
    self.$('.cbx-doc').click(function(ev){
      var checkedDocs = [];
      self.$('.cbx-doc').each(function(){
        if (this.checked) {
          checkedDocs.push($(this).closest(".doc").data("id"));
        }
      });
      self.publish("doc.checked", checkedDocs);
    });
    self.$('.doc-value').click(function(){
      var docId = $(this).closest(".doc").data("id");
      var params = {
        conn: F.env.conn,
        db: F.env.db,
        col: F.env.col,
        doc: docId
      };
      F.navigate("document", params);
    });
    cb();
  },
  render: function(cb, param) {
    if (param && param.reset) {
      this._super(cb);
    } else {
      var contents = F.Render(this.template, this.data);
      this.$container.append(contents);
      cb();
    }
  },
  getData: function(cb, param) {
    var self = this;
    if (!F.env.db || !F.env.col) {
      self.data = {};
      return cb();
    }
    if (param && param.reset) self.current = 0;
    self.options.skip = self.current;
    var countQuery = "conn/" + F.env.conn + "/db/" + F.env.db + "/col/" + F.env.col;
    var dataQuery = countQuery + "/doc?options=" + encodeURIComponent(JSON.stringify(self.options));
    F.require([countQuery, dataQuery], function(data){
      var total = data[countQuery].count;

      var flattenData = [];
      var fieldAdded = {};
      data[dataQuery].forEach(function(v){
        var f = MONGRES.flatten(v);
        for (var i in f) {
          if (!(i in self.fieldByName)) {
            fieldAdded[i] = true;
            self.fieldByName[i] = true;
          }
        }
        flattenData.push(f);
      });

      var fields = [];
      for (var i in self.fieldByName) fields.push(i);
      fields.sort();

      self.publish(F.TOPIC.DATA_TABLE.HEAD_UPDATED, fields);

      var config = MONGRES.getColumnConfig().getAll();
      var hide = config ? function(v){
        return (v in config && !config[v]);
      } : function(){ return false; };
      records = [];
      flattenData.forEach(function(d){
        r = {_id: d._id, values: []};
        fields.forEach(function(f){
          r.values.push({
            classValue: MONGRES.col2Class(f),
            value: d[f],
            hide: hide(f),
          });
        });
        records.push(r);
      });
      self.data = {
        records: records,
        idString: function(){
          if (typeof(this._id) === 'string' && this._id.indexOf("ObjectID('") === 0) {
            return this._id.substr(10, 24);
          } else {
            return this._id;
          }
        }
      };

      // if (fields.changed) update existing table
      if (self.current > 0) {
        var insertCols = [];
        var lastV = null;
        fields.forEach(function(v){
          if (v in fieldAdded && lastV) { insertCols.push({me: v, after: lastV}); }
          lastV = v;
        });
        insertCols.forEach(function(v){
          var $after = self.$("." + MONGRES.col2Class(v.after));
          var classes = MONGRES.col2Class(v.me) + (hide(v) ? " hide" : "");
          var $me = $('	');
          $after.after($me);
        });
      }
      self.current += records.length;
      self.publish(
        F.TOPIC.DATA_TABLE.BODY_UPDATED,
        {all_loaded: (self.current >= total)}
      );

      cb();
    });
  },
}));

<|endoftext|>


<commit_before>//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Draws "labels" using svg:text and d3plus.utils.wordwrap
//------------------------------------------------------------------------------
d3plus.shape.labels = function(vars,selection) {

  var scale = vars.zoom_behavior.scaleExtent()[1]

  //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  // Label Exiting
  //----------------------------------------------------------------------------
  remove = function(text) {

    if (vars.timing) {
      text
        .transition().duration(vars.timing)
        .attr("opacity",0)
        .remove()
    }
    else {
      text.remove()
    }

  }

  //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  // Label Styling
  //----------------------------------------------------------------------------
  style = function(text,wrap) {

    function x_pos(t) {

      var align = t.anchor || vars.style.labels.align,
          tspan = this.tagName == "tspan",
          share = tspan ? this.parentNode.className.baseVal == "d3plus_share" : this.className.baseVal == "d3plus_share",
          width = d3.select(this).node().getComputedTextLength()/scale

      if (align == "middle" || share) {
        var pos = t.x-width/2
      }
      else if ((align == "end" && !d3plus.rtl) || (align == "start" && d3plus.rtl)) {
        var pos = t.x+t.w/2-width
      }
      else {
        var pos = t.x-t.w/2
      }

      if (tspan) {
        var t_width = this.getComputedTextLength()/scale
        if (align == "middle") {
          if (d3plus.rtl) {
            pos -= (width-t_width)/2
          }
          else {
            pos += (width-t_width)/2
          }
        }
        else if (align == "end") {
          if (d3plus.rtl) {
            pos -= (width-t_width)
          }
          else {
            pos += (width-t_width)
          }
        }
      }

      if (d3plus.rtl) {
        pos += width
      }

      return pos*scale

    }

    function y_pos(t) {

      if (d3.select(this).select("tspan").empty()) {
        return 0
      }
      else {

        var align = vars.style.labels.align,
            height = d3.select(this).node().getBBox().height/scale,
            diff = (parseFloat(d3.select(this).style("font-size"),10)/5)/scale

        if (this.className.baseVal == "d3plus_share") {
          var data = d3.select(this.parentNode).datum()
          var pheight = data.d3plus.r ? data.d3plus.r*2 : data.d3plus.height
          pheight = pheight/scale
          if (align == "end") {
            var y = t.y-pheight/2+diff/2
          }
          else {
            var y = t.y+pheight/2-height-diff/2
          }
        }
        else {

          if (align == "middle" || t.valign == "center") {
            var y = t.y-height/2-diff/2
          }
          else if (align == "end") {
            var y = t.y+t.h/2-height+diff/2
          }
          else {
            var y = t.y-t.h/2-diff
          }

        }

        return y*scale

      }
    }

    text
      .style("font-weight",vars.style.font.weight)
      .attr("font-family",vars.style.font.family)
      .attr("text-anchor","start")
      .attr("fill", function(t){
        if (t.color) {
          return t.color
        }
        else {
          var d = d3.select(this.parentNode).datum()
          return d3plus.color.text(d3plus.shape.color(d,vars))
        }
      })
      .attr("x",x_pos)
      .attr("y",y_pos)

    if (wrap) {

      text
        .each(function(t){

          if (t.text) {

            d3plus.utils.wordwrap({
              "text": vars.format(t.text*100,"share")+"%",
              "parent": this,
              "width": t.w*scale-label.padding,
              "height": t.h*scale-label.padding,
              "resize": t.resize,
              "font_min": 9/scale,
              "font_max": 70*scale
            })

          }
          else {

            if (vars.style.labels.align != "middle") {
              var height = t.h-t.share
            }
            else {
              var height = t.h
            }

            d3plus.utils.wordwrap({
              "text": t.names,
              "parent": this,
              "width": t.w*scale,
              "height": height*scale,
              "font_max": 40*scale,
              "font_min": 9/scale,
              "resize": t.resize
            })

          }

        })
        .attr("x",x_pos)
        .attr("y",y_pos)

    }

    text
      .attr("transform",function(t){
        var a = t.angle || 0,
            x = t.translate && t.translate.x || 0,
            y = t.translate && t.translate.y || 0

        return "rotate("+a+","+x+","+y+")scale("+1/scale+")"
      })
      .selectAll("tspan")
        .attr("x",x_pos)
  }

  //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  // Loop through each selection and analyze the labels
  //----------------------------------------------------------------------------
  if (vars.labels.value) {

    selection.each(function(d){

      var disabled = d.d3plus && "label" in d.d3plus && !d.d3plus.label,
          stat = d.d3plus && "static" in d.d3plus && d.d3plus.static
          label = d.d3plus_label,
          share = d.d3plus_share,
          names = label && label.names ? label.names : d3plus.variable.text(vars,d),
          group = d3.select(this),
          share_size = 0,
          fill = d3plus.apps[vars.type.value].fill

      if (["line","area"].indexOf(vars.shape.value) >= 0) {
        var background = true
      }
      else {
        var active = vars.active.key ? d.d3plus[vars.active.key] : d.d3plus.active,
            temp = vars.temp.key ? d.d3plus[vars.temp.key] : d.d3plus.temp,
            total = vars.total.key ? d.d3plus[vars.total.key] : d.d3plus.total,
            background = (!temp && !active) || (active == total)
      }

      if (!disabled && (background || !fill) && !stat) {

        if (share && d.d3plus.share && vars.style.labels.align != "middle") {

          share.w -= (vars.style.labels.padding/scale)*2
          share.h -= (vars.style.labels.padding/scale)*2

          share.text = d.d3plus.share
          if (!("resize" in share)) {
            share.resize = true
          }

          var text = group.selectAll("text.d3plus_share")
            .data([share],function(t){
              return t.w+""+t.h+""+t.text
            })

          if (vars.timing) {

            text
              .transition().duration(vars.timing/2)
              .call(style)

            text.enter().append("text")
              .attr("font-size",vars.style.labels.font.size)
              .attr("class","d3plus_share")
              .attr("opacity",0)
              .call(style,true)
              .transition().duration(vars.timing/2)
              .delay(vars.timing/2)
              .attr("opacity",0.5)

          }
          else {

            text
              .attr("opacity",0.5)
              .call(style)

            text.enter().append("text")
              .attr("font-size",vars.style.labels.font.size)
              .attr("class","d3plus_share")
              .attr("opacity",0.5)
              .call(style,true)

          }

          share_size = text.node().getBBox().height

          text.exit().call(remove)

        }
        else {
          group.selectAll("text.d3plus_share")
            .call(remove)
        }

        label.padding = (vars.style.labels.padding/scale)*2

        if (label && label.w*scale-label.padding >= 20 && label.h*scale-label.padding >= 10 && names.length) {

          label.names = names
          if (!("resize" in label)) {
            label.resize = true
          }

          label.share = share_size

          var text = group.selectAll("text.d3plus_label")
            .data([label],function(t){
              if (!t) return false
              return t.w+"_"+t.h+"_"+t.x+"_"+t.y+"_"+t.names.join("_")
            })

          if (vars.timing) {

            text
              .transition().duration(vars.timing/2)
              .call(style)

            text.enter().append("text")
              .attr("font-size",vars.style.labels.font.size)
              .attr("class","d3plus_label")
              .attr("opacity",0)
              .call(style,true)
              .transition().duration(vars.timing/2)
              .delay(vars.timing/2)
              .attr("opacity",1)

          }
          else {

            text
              .attr("opacity",1)
              .call(style)

            text.enter().append("text")
              .attr("font-size",vars.style.labels.font.size)
              .attr("class","d3plus_label")
              .call(style,true)
              .attr("opacity",1)

          }

          text.exit().call(remove)

          if (text.size() == 0 || text.html() == "") {
            delete d.d3plus_label
            text.remove()
          }
          else {

            if (label.background) {

              var background_data = ["background"]

              var bounds = text.node().getBBox()

              bounds.width += vars.style.labels.padding
              bounds.height += vars.style.labels.padding
              bounds.x -= vars.style.labels.padding/2
              bounds.y -= vars.style.labels.padding/2

            }
            else {
              var background_data = [],
                  bounds = {}
            }

            var bg = group.selectAll("rect.d3plus_label_bg")
              .data(background_data)

            function bg_style(elem) {

              var color = vars.style.background == "transparent" ? "#ffffff" : vars.style.background,
                  fill = label.background === true ? color : label.background,
                  a = label.angle || 0,
                  x = label.translate ? bounds.x+bounds.width/2 : 0,
                  y = label.translate ? bounds.y+bounds.height/2 : 0,
                  transform = "scale("+1/scale+")rotate("+a+","+x+","+y+")"

              elem
                .attr("fill",fill)
                .attr(bounds)
                .attr("transform",transform)

            }

            if (vars.timing) {

              bg.exit().transition().duration(vars.timing)
                .attr("opacity",0)
                .remove()

              bg.transition().duration(vars.timing)
                .attr("opacity",1)
                .call(bg_style)

              bg.enter().insert("rect",".d3plus_label")
                .attr("class","d3plus_label_bg")
                .attr("opacity",0)
                .call(bg_style)
                .transition().duration(vars.timing)
                  .attr("opacity",1)

            }
            else {

              bg.exit().remove()

              bg.enter().insert("rect",".d3plus_label")
                .attr("class","d3plus_label_bg")

              bg.attr("opacity",0.5)
                .call(bg_style)

            }

          }

        }
        else {
          delete d.d3plus_label
          group.selectAll("text.d3plus_label, rect.d3plus_label_bg")
            .call(remove)
        }

      }
      else {
        delete d.d3plus_label
        group.selectAll("text.d3plus_label, rect.d3plus_label_bg")
          .call(remove)
      }
    })

  }
  else {

    selection.selectAll("text.d3plus_label, rect.d3plus_label_bg")
      .call(remove)

  }

}
<commit_msg>fixed label padding<commit_after>//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Draws "labels" using svg:text and d3plus.utils.wordwrap
//------------------------------------------------------------------------------
d3plus.shape.labels = function(vars,selection) {

  var scale = vars.zoom_behavior.scaleExtent()[1]

  //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  // Label Exiting
  //----------------------------------------------------------------------------
  remove = function(text) {

    if (vars.timing) {
      text
        .transition().duration(vars.timing)
        .attr("opacity",0)
        .remove()
    }
    else {
      text.remove()
    }

  }

  //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  // Label Styling
  //----------------------------------------------------------------------------
  style = function(text,wrap) {

    function x_pos(t) {

      var align = t.anchor || vars.style.labels.align,
          tspan = this.tagName == "tspan",
          share = tspan ? this.parentNode.className.baseVal == "d3plus_share" : this.className.baseVal == "d3plus_share",
          width = d3.select(this).node().getComputedTextLength()/scale

      if (align == "middle" || share) {
        var pos = t.x-width/2
      }
      else if ((align == "end" && !d3plus.rtl) || (align == "start" && d3plus.rtl)) {
        var pos = t.x+(t.w-t.padding)/2-width
      }
      else {
        var pos = t.x-(t.w-t.padding)/2
      }

      if (tspan) {
        var t_width = this.getComputedTextLength()/scale
        if (align == "middle") {
          if (d3plus.rtl) {
            pos -= (width-t_width)/2
          }
          else {
            pos += (width-t_width)/2
          }
        }
        else if (align == "end") {
          if (d3plus.rtl) {
            pos -= (width-t_width)
          }
          else {
            pos += (width-t_width)
          }
        }
      }

      if (d3plus.rtl) {
        pos += width
      }

      return pos*scale

    }

    function y_pos(t) {

      if (d3.select(this).select("tspan").empty()) {
        return 0
      }
      else {

        var align = vars.style.labels.align,
            height = d3.select(this).node().getBBox().height/scale,
            diff = (parseFloat(d3.select(this).style("font-size"),10)/5)/scale

        if (this.className.baseVal == "d3plus_share") {
          var data = d3.select(this.parentNode).datum()
          var pheight = data.d3plus.r ? data.d3plus.r*2 : data.d3plus.height
          pheight = pheight/scale
          if (align == "end") {
            var y = t.y-pheight/2+diff/2
          }
          else {
            var y = t.y+pheight/2-height-diff/2
          }
        }
        else {

          if (align == "middle" || t.valign == "center") {
            var y = t.y-height/2-diff/2
          }
          else if (align == "end") {
            var y = t.y+(t.h-t.padding)/2-height+diff/2
          }
          else {
            var y = t.y-(t.h-t.padding)/2-diff
          }

        }

        return y*scale

      }
    }

    text
      .style("font-weight",vars.style.font.weight)
      .attr("font-family",vars.style.font.family)
      .attr("text-anchor","start")
      .attr("fill", function(t){
        if (t.color) {
          return t.color
        }
        else {
          var d = d3.select(this.parentNode).datum()
          return d3plus.color.text(d3plus.shape.color(d,vars))
        }
      })
      .attr("x",x_pos)
      .attr("y",y_pos)

    if (wrap) {

      text
        .each(function(t){

          if (t.text) {

            d3plus.utils.wordwrap({
              "text": vars.format(t.text*100,"share")+"%",
              "parent": this,
              "width": t.w*scale-t.padding,
              "height": t.h*scale-t.padding,
              "resize": t.resize,
              "font_min": 9/scale,
              "font_max": 70*scale
            })

          }
          else {

            if (vars.style.labels.align != "middle") {
              var height = t.h-t.share
            }
            else {
              var height = t.h
            }

            d3plus.utils.wordwrap({
              "text": t.names,
              "parent": this,
              "width": t.w*scale-t.padding,
              "height": height*scale-t.padding,
              "font_max": 40*scale,
              "font_min": 9/scale,
              "resize": t.resize
            })

          }

        })
        .attr("x",x_pos)
        .attr("y",y_pos)

    }

    text
      .attr("transform",function(t){
        var a = t.angle || 0,
            x = t.translate && t.translate.x || 0,
            y = t.translate && t.translate.y || 0

        return "rotate("+a+","+x+","+y+")scale("+1/scale+")"
      })
      .selectAll("tspan")
        .attr("x",x_pos)
  }

  //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  // Loop through each selection and analyze the labels
  //----------------------------------------------------------------------------
  if (vars.labels.value) {

    selection.each(function(d){

      var disabled = d.d3plus && "label" in d.d3plus && !d.d3plus.label,
          stat = d.d3plus && "static" in d.d3plus && d.d3plus.static
          label = d.d3plus_label,
          share = d.d3plus_share,
          names = label && label.names ? label.names : d3plus.variable.text(vars,d),
          group = d3.select(this),
          share_size = 0,
          fill = d3plus.apps[vars.type.value].fill

      if (["line","area"].indexOf(vars.shape.value) >= 0) {
        var background = true
      }
      else {
        var active = vars.active.key ? d.d3plus[vars.active.key] : d.d3plus.active,
            temp = vars.temp.key ? d.d3plus[vars.temp.key] : d.d3plus.temp,
            total = vars.total.key ? d.d3plus[vars.total.key] : d.d3plus.total,
            background = (!temp && !active) || (active == total)
      }

      if (!disabled && (background || !fill) && !stat) {

        if (share && d.d3plus.share && vars.style.labels.align != "middle") {

          share.padding = (vars.style.labels.padding/scale)*2

          share.text = d.d3plus.share
          if (!("resize" in share)) {
            share.resize = true
          }

          var text = group.selectAll("text.d3plus_share")
            .data([share],function(t){
              return t.w+""+t.h+""+t.text
            })

          if (vars.timing) {

            text
              .transition().duration(vars.timing/2)
              .call(style)

            text.enter().append("text")
              .attr("font-size",vars.style.labels.font.size)
              .attr("class","d3plus_share")
              .attr("opacity",0)
              .call(style,true)
              .transition().duration(vars.timing/2)
              .delay(vars.timing/2)
              .attr("opacity",0.5)

          }
          else {

            text
              .attr("opacity",0.5)
              .call(style)

            text.enter().append("text")
              .attr("font-size",vars.style.labels.font.size)
              .attr("class","d3plus_share")
              .attr("opacity",0.5)
              .call(style,true)

          }

          share_size = text.node().getBBox().height

          text.exit().call(remove)

        }
        else {
          group.selectAll("text.d3plus_share")
            .call(remove)
        }

        if (label) {
          label.padding = (vars.style.labels.padding/scale)*2
        }

        if (label && label.w*scale-label.padding >= 20 && label.h*scale-label.padding >= 10 && names.length) {

          label.names = names
          if (!("resize" in label)) {
            label.resize = true
          }

          label.share = share_size

          var text = group.selectAll("text.d3plus_label")
            .data([label],function(t){
              if (!t) return false
              return t.w+"_"+t.h+"_"+t.x+"_"+t.y+"_"+t.names.join("_")
            })

          if (vars.timing) {

            text
              .transition().duration(vars.timing/2)
              .call(style)

            text.enter().append("text")
              .attr("font-size",vars.style.labels.font.size)
              .attr("class","d3plus_label")
              .attr("opacity",0)
              .call(style,true)
              .transition().duration(vars.timing/2)
              .delay(vars.timing/2)
              .attr("opacity",1)

          }
          else {

            text
              .attr("opacity",1)
              .call(style)

            text.enter().append("text")
              .attr("font-size",vars.style.labels.font.size)
              .attr("class","d3plus_label")
              .call(style,true)
              .attr("opacity",1)

          }

          text.exit().call(remove)

          if (text.size() == 0 || text.html() == "") {
            delete d.d3plus_label
            text.remove()
          }
          else {

            if (label.background) {

              var background_data = ["background"]

              var bounds = text.node().getBBox()

              bounds.width += vars.style.labels.padding
              bounds.height += vars.style.labels.padding
              bounds.x -= vars.style.labels.padding/2
              bounds.y -= vars.style.labels.padding/2

            }
            else {
              var background_data = [],
                  bounds = {}
            }

            var bg = group.selectAll("rect.d3plus_label_bg")
              .data(background_data)

            function bg_style(elem) {

              var color = vars.style.background == "transparent" ? "#ffffff" : vars.style.background,
                  fill = label.background === true ? color : label.background,
                  a = label.angle || 0,
                  x = label.translate ? bounds.x+bounds.width/2 : 0,
                  y = label.translate ? bounds.y+bounds.height/2 : 0,
                  transform = "scale("+1/scale+")rotate("+a+","+x+","+y+")"

              elem
                .attr("fill",fill)
                .attr(bounds)
                .attr("transform",transform)

            }

            if (vars.timing) {

              bg.exit().transition().duration(vars.timing)
                .attr("opacity",0)
                .remove()

              bg.transition().duration(vars.timing)
                .attr("opacity",1)
                .call(bg_style)

              bg.enter().insert("rect",".d3plus_label")
                .attr("class","d3plus_label_bg")
                .attr("opacity",0)
                .call(bg_style)
                .transition().duration(vars.timing)
                  .attr("opacity",1)

            }
            else {

              bg.exit().remove()

              bg.enter().insert("rect",".d3plus_label")
                .attr("class","d3plus_label_bg")

              bg.attr("opacity",0.5)
                .call(bg_style)

            }

          }

        }
        else {
          delete d.d3plus_label
          group.selectAll("text.d3plus_label, rect.d3plus_label_bg")
            .call(remove)
        }

      }
      else {
        delete d.d3plus_label
        group.selectAll("text.d3plus_label, rect.d3plus_label_bg")
          .call(remove)
      }
    })

  }
  else {

    selection.selectAll("text.d3plus_label, rect.d3plus_label_bg")
      .call(remove)

  }

}
<|endoftext|>


<commit_before>// @flow
export class JsonAPI {
  json: Object
  links: Object
  relationships: Object
  constructor(json: Object) {
    this.json = json
  }
  getAttributes() {
    return this.json.data.attributes
  }
  getType() {
    return this.json.data.type
  }
  getId() {
    return this.json.data.id
  }
  getFetchURL() {
    return this.json.links.self
  }
  getRelationships() {
    return this.json.data.relationships
  }
}

export class AuthAPI extends JsonAPI {
  json: Object

  isAuthenticated() {
    if (this.json.isAuthenticated === true) {
      return true
    }
    return false
  }

  getToken() {
    return this.json.token
  }

  getProvider() {
    return this.json.provider
  }

  getUser() {
    return this.json.user
  }
}

export class AuthenticatedUser extends JsonAPI {
  json: Object

  getFullName() {
    return `${this.json.data.attributes.first_name} ${
      this.json.data.attributes.last_name
    }`
  }

  getRoles() {
    if (this.json.roles) {
      // return the role and capitalize the first letter
      const role = this.json.roles[0].attributes.role
      return role.charAt(0).toUpperCase() + role.substr(1)
    } else {
      return "..."
    }
  }

  canOverwrite = id => {
    if (id === this.json.data.id || this.getRoles() === "Superuser") {
      return true
    } else {
      return null
    }
  }
}

export class PermissionAPI extends JsonAPI {
  json: Object

  getResources() {
    if (this.json.permissions) {
      this.json.permissions.forEach(item => {
        return item.attributes.resource
      })
    } else {
      return
    }
  }

  getPermissions() {
    if (this.json.permissions) {
      this.json.permissions.forEach(item => {
        return item.attributes.permission
      })
    } else {
      return
    }
  }

  verifyPermissions = (perm, resource) => {
    if (this.json.data.id && this.json.permissions) {
      return this.json.permissions.filter(
        item =>
          item.attributes.permission === "admin" ||
          (item.attributes.permission === perm &&
            item.attributes.resource === resource)
      )
    } else {
      return null
    }
  }
}

export class RoleAPI extends JsonAPI {
  json: Object

  getRoles() {
    if (this.json.roles) {
      this.json.roles.forEach(item => {
        return item.attributes.role
      })
    } else {
      return
    }
  }

  checkRoles = role => {
    if (this.json.data.id && this.json.roles) {
      return this.json.roles.filter(item => item.attributes.role === role)
    } else {
      return null
    }
  }
}

export class ContentAPI extends AuthenticatedUser {
  json: Object

  getUser() {
    return this.json.data.attributes.updated_by
  }
}
<commit_msg>add comments to describe api classes<commit_after>// @flow
export class JsonAPI {
  json: Object
  links: Object
  relationships: Object
  constructor(json: Object) {
    this.json = json
  }
  getAttributes() {
    return this.json.data.attributes
  }
  getId() {
    return this.json.data.id
  }
  getRelationships() {
    return this.json.data.relationships
  }
}

export class AuthAPI extends JsonAPI {
  json: Object

  // checks if user is currently authenticated
  isAuthenticated() {
    if (this.json.isAuthenticated === true) {
      return true
    }
    return false
  }

  // gets JWT from currently logged in user
  getToken() {
    return this.json.token
  }

  // gets provider (i.e. google) from logged in user
  getProvider() {
    return this.json.provider
  }

  // gets user data
  getUser() {
    return this.json.user
  }
}

export class AuthenticatedUser extends JsonAPI {
  json: Object

  // gets the first and last name of logged in user
  getFullName() {
    return `${this.json.data.attributes.first_name} ${
      this.json.data.attributes.last_name
    }`
  }

  // gets capitalized version of user's role
  getRoles() {
    if (this.json.roles) {
      // return the role and capitalize the first letter
      const role = this.json.roles[0].attributes.role
      return role.charAt(0).toUpperCase() + role.substr(1)
    } else {
      return "..."
    }
  }

  // checks if user can overwrite current content
  canOverwrite = id => {
    if (id === this.json.data.id || this.getRoles() === "Superuser") {
      return true
    } else {
      return null
    }
  }
}

export class PermissionAPI extends JsonAPI {
  json: Object

  // gets lists of all resources from user's permissions
  getResources() {
    if (this.json.permissions) {
      this.json.permissions.forEach(item => {
        return item.attributes.resource
      })
    } else {
      return
    }
  }

  // gets full list of user's permissions
  getPermissions() {
    if (this.json.permissions) {
      this.json.permissions.forEach(item => {
        return item.attributes.permission
      })
    } else {
      return
    }
  }

  // this verifies that the user has the right resource
  // and permission to edit content
  verifyPermissions = (perm, resource) => {
    if (this.json.data.id && this.json.permissions) {
      return this.json.permissions.filter(
        item =>
          item.attributes.permission === "admin" ||
          (item.attributes.permission === perm &&
            item.attributes.resource === resource)
      )
    } else {
      return null
    }
  }
}

export class RoleAPI extends JsonAPI {
  json: Object

  // get full list of user's roles
  getRoles() {
    if (this.json.roles) {
      this.json.roles.forEach(item => {
        return item.attributes.role
      })
    } else {
      return
    }
  }

  // checks if user has specified role
  checkRoles = role => {
    if (this.json.data.id && this.json.roles) {
      return this.json.roles.filter(item => item.attributes.role === role)
    } else {
      return null
    }
  }
}

export class ContentAPI extends AuthenticatedUser {
  json: Object

  // gets the user ID for person who last updated this content
  getUser() {
    return this.json.data.attributes.updated_by
  }
}
<|endoftext|>


<commit_before>import {spring as motionSpring} from 'react-motion';

export default function spring(val, config) {
    return motionSpring(val, config);
}
<commit_msg>Used fat arrow to avoid spring name clash<commit_after>import {spring} from 'react-motion';

export default (val, config) => spring(val, config);

<|endoftext|>


<commit_before>/*
 * jQuery throttle / debounce - v1.1 - 3/7/2010
 * http://benalman.com/projects/jquery-throttle-debounce-plugin/
 *
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */
(function(b,c){var $=b.jQuery||b.Cowboy||(b.Cowboy={}),a;$.throttle=a=function(e,f,j,i){var h,d=0;if(typeof f!=="boolean"){i=j;j=f;f=c}function g(){var o=this,m=+new Date()-d,n=arguments;function l(){d=+new Date();j.apply(o,n)}function k(){h=c}if(i&&!h){l()}h&&clearTimeout(h);if(i===c&&m>e){l()}else{if(f!==true){h=setTimeout(i?k:l,i===c?e-m:e)}}}if($.guid){g.guid=j.guid=j.guid||$.guid++}return g};$.debounce=function(d,e,f){return f===c?a(d,e,false):a(d,f,e!==false)}})(this);

/*
 * Front page things
 */
(function () {

    /*
     * SVG map
     */
    function highlight(href, add) {
        var regionShapeLinks = document.getElementById('svgmap').getElementsByTagName('a');
        for (var i = 0; i < regionShapeLinks.length; i++) {
            if ('/regions/GB' === href || regionShapeLinks[i].getAttributeNS('http://www.w3.org/1999/xlink', 'href') === href) {
                if (add) {
                    regionShapeLinks[i].className += 'highlight';
                } else {
                    regionShapeLinks[i].className = '';
                }
            }
        }
    }

    var regionNameLinks = document.getElementById('regions').getElementsByTagName('a');

    for (var i = 0; i < regionNameLinks.length; i++) {
        regionNameLinks[i].onmouseover = regionNameLinks[i].onfocus = function(e) {
            highlight(this.getAttribute('href'), true);
        };
        regionNameLinks[i].onmouseout = regionNameLinks[i].onblur = function(e) {
            highlight(this.getAttribute('href'), false);
        };
    }

    /*
     * 'Search places' form
     */
    $(document.getElementById('q')).on('keypress', $.debounce(250, function (e) {
        var resultsElement = document.getElementById('results');
        if (this.value === '') {
            resultsElement.innerHTML = '';
        } else {
            $.get('/search.json', {
                q: this.value,
            }, function(data) {
                var output = '';
                for (var i = 0; i < data.length; i++) {
                    output += '
' + data[i].name + '';
                }
                resultsElement.innerHTML = output;
            }, 'json');
        }
    }));
    $(document.getElementById('search')).on('submit', function (e) {
        e.preventDefault();
    });

})();
<commit_msg>some kind of fix for the SVG map hover behaviour<commit_after>/*
 * jQuery throttle / debounce - v1.1 - 3/7/2010
 * http://benalman.com/projects/jquery-throttle-debounce-plugin/
 *
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */
(function(b,c){var $=b.jQuery||b.Cowboy||(b.Cowboy={}),a;$.throttle=a=function(e,f,j,i){var h,d=0;if(typeof f!=="boolean"){i=j;j=f;f=c}function g(){var o=this,m=+new Date()-d,n=arguments;function l(){d=+new Date();j.apply(o,n)}function k(){h=c}if(i&&!h){l()}h&&clearTimeout(h);if(i===c&&m>e){l()}else{if(f!==true){h=setTimeout(i?k:l,i===c?e-m:e)}}}if($.guid){g.guid=j.guid=j.guid||$.guid++}return g};$.debounce=function(d,e,f){return f===c?a(d,e,false):a(d,f,e!==false)}})(this);

/*
 * Front page things
 */
(function () {

    /*
     * SVG map
     */
    function highlight(href, add) {
        var regionShapeLinks = document.getElementById('svgmap').getElementsByTagName('a');
        for (var i = 0; i < regionShapeLinks.length; i++) {
            if ('/regions/GB' === href || regionShapeLinks[i].getAttributeNS('http://www.w3.org/1999/xlink', 'href') === href) {
                if (add) {
                    $(regionShapeLinks[i]).attr('class', 'highlight');
                } else {
                    $(regionShapeLinks[i]).attr('class', '');
                }
            }
        }
    }

    var regionNameLinks = document.getElementById('regions').getElementsByTagName('a');

    for (var i = 0; i < regionNameLinks.length; i++) {
        regionNameLinks[i].onmouseover = regionNameLinks[i].onfocus = function(e) {
            highlight(this.getAttribute('href'), true);
        };
        regionNameLinks[i].onmouseout = regionNameLinks[i].onblur = function(e) {
            highlight(this.getAttribute('href'), false);
        };
    }

    /*
     * 'Search places' form
     */
    $(document.getElementById('q')).on('keypress', $.debounce(250, function (e) {
        var resultsElement = document.getElementById('results');
        if (this.value === '') {
            resultsElement.innerHTML = '';
        } else {
            $.get('/search.json', {
                q: this.value,
            }, function(data) {
                var output = '';
                for (var i = 0; i < data.length; i++) {
                    output += '
' + data[i].name + '';
                }
                resultsElement.innerHTML = output;
            }, 'json');
        }
    }));
    $(document.getElementById('search')).on('submit', function (e) {
        e.preventDefault();
    });

})();
<|endoftext|>