<commit_before>import $ from 'jquery';

class Core {

  /**
   * Initialize Papi core class.
   */
  static init() {
    const core = new Core();

    core.binds();
    core.setEqualBoxHeights();
    core.setSelectedMenuItem();
    core.addCurrentClassToMenuItem();
  }

  /**
   * Autosave fields on heartbeat.
   *
   * @param {object} e
   * @param {object} xhr
   * @param {object} options
   */
  autosave(e, xhr, options) {
    const fields = jQuery('[name*="papi_"]');
    const data = {};
    const reg = /action\=(.+?)\&/;
    const val = reg.exec(options.data);
    const id  = /post_id\=\d+/.exec(options.data);

    if (val !== null && val.length && val[1] === 'heartbeat' && id != null && id.length) {
        fields.each(function () {
          const $this = $(this);

          data[$this.attr('name')] = $this.val();
      });

      options.data += '&' + jQuery.param(data);
    }
  }

  /**
   * Bind elements with functions.
   */
  binds() {
    $('.papi-box-list > li > p').on('click', this.redirect);
    $('input[name="add-new-page-search"]').on('keyup', this.search);
    $('[data-papi-href]').on('click touchstart', this.redirect);
    $(window).resize(this.setEqualBoxHeights);

    if ('select2' in $.fn) {
      $('.inside .papi-table tr .papi-component-select2').select2();
    }

    $('.papi-meta-type-term button.handlediv').on('click', this.handlediv);

    // Autosave fields on heartbeat.
    $(document).ajaxSend(this.autosave);
  }

  /**
   * Add current class to menu item.
   */
  addCurrentClassToMenuItem() {
    let $submenu = $('.wp-has-current-submenu .wp-submenu');
    let $menuitem = $submenu.find('a[href*="papi-add-new-page"]').parent();

    if (!$menuitem.hasClass('current') && !$submenu.find('li.current').length) {
      $menuitem.addClass('current');
    }
  }

  /**
   * Handle expanded postbox div.
   *
   * @param  {object} e
   */
  handlediv(e) {
    e.preventDefault();

    const $this   = $(this);
    const $parent = $this.parent();
    const $inside = $parent.find('.inside');

    $parent.parent().toggleClass('closed');
    $inside.toggleClass('papi-hide');
    $this.attr('aria-expanded', !$inside.hasClass('papi-hide'));
  }

  /**
   * Redirect to location from `papi-href` data attribute
   * or closest tag with href attribute.
   *
   * @param {object} e
   */
  redirect(e) {
    e.preventDefault();
    let $this    = $(this);
    let papiHref = $this.data().papiHref;

    if (papiHref !== undefined) {
      window.location = papiHref;
    } else {
      window.location = $(this).closest('[href]').attr('href');
    }
  }

  /**
   * Search in page types box list.
   *
   * @param {object} e
   */
  search(e) {
    e.preventDefault();

    let $this = $(this);
    let $list = $('.papi-box-list');
    let val   = $this.val();

    $list.find('.papi-box-item').each(function() {
      let $item = $(this);
      $item[$item.text().toLowerCase().indexOf(val) === -1 ? 'addClass' : 'removeClass']('papi-hide');
    });
  }

  /**
   * Set equal height on page type boxes.
   */
  setEqualBoxHeights() {
    let $boxItems  = $('.papi-box-item');
    let thumbnails = $boxItems.find('.papi-post-type-screenshot').length > 0;
    let boxMaxHeight = 0;

    if (!thumbnails) {
      $boxItems = $('.papi-post-type-info');
    }

    $boxItems.each(function () {
      let $this  = $(this);

      if (thumbnails) {
        $this.find('.papi-post-type-info').removeAttr('style');
      } else {
        $this.removeAttr('style');
      }

      let height = $this.height();
      boxMaxHeight = height > boxMaxHeight ? height : boxMaxHeight;
    });

    $boxItems.each(function () {
      let $this  = $(this);
      let height = boxMaxHeight;

      if (thumbnails) {
        let $thumb = $this.find('.papi-post-type-screenshot');

        if ($thumb.length) {
          height = height - $thumb.height();
        } else {
          height += 5;
        }

        $this.find('.papi-post-type-info').height(height);
      } else {
        $this.height(height);
      }
    });
  }

  /**
   * Set selected menu item if it isn't selected.
   */
  setSelectedMenuItem() {
    let href = typeof window.location === 'string' ? window.location : window.location.href;
    let $adminmenu = $('#adminmenu');

    if (!$adminmenu.find('li.current > a.current').length) {
      href = href.substr(href.lastIndexOf('/') + 1);
      href = href.replace(/\%2F/g, '/');
      $('a[href="' + href + '"]', $adminmenu).addClass('current').parent().addClass('current');
    }
  }
}

export default Core;
<commit_msg>Fix equal box hight when no thumbnail exists<commit_after>import $ from 'jquery';

class Core {

  /**
   * Initialize Papi core class.
   */
  static init() {
    const core = new Core();

    core.binds();
    core.setEqualBoxHeights();
    core.setSelectedMenuItem();
    core.addCurrentClassToMenuItem();
  }

  /**
   * Autosave fields on heartbeat.
   *
   * @param {object} e
   * @param {object} xhr
   * @param {object} options
   */
  autosave(e, xhr, options) {
    const fields = jQuery('[name*="papi_"]');
    const data = {};
    const reg = /action\=(.+?)\&/;
    const val = reg.exec(options.data);
    const id  = /post_id\=\d+/.exec(options.data);

    if (val !== null && val.length && val[1] === 'heartbeat' && id != null && id.length) {
        fields.each(function () {
          const $this = $(this);

          data[$this.attr('name')] = $this.val();
      });

      options.data += '&' + jQuery.param(data);
    }
  }

  /**
   * Bind elements with functions.
   */
  binds() {
    $('.papi-box-list > li > p').on('click', this.redirect);
    $('input[name="add-new-page-search"]').on('keyup', this.search);
    $('[data-papi-href]').on('click touchstart', this.redirect);
    $(window).resize(this.setEqualBoxHeights);

    if ('select2' in $.fn) {
      $('.inside .papi-table tr .papi-component-select2').select2();
    }

    $('.papi-meta-type-term button.handlediv').on('click', this.handlediv);

    // Autosave fields on heartbeat.
    $(document).ajaxSend(this.autosave);
  }

  /**
   * Add current class to menu item.
   */
  addCurrentClassToMenuItem() {
    let $submenu = $('.wp-has-current-submenu .wp-submenu');
    let $menuitem = $submenu.find('a[href*="papi-add-new-page"]').parent();

    if (!$menuitem.hasClass('current') && !$submenu.find('li.current').length) {
      $menuitem.addClass('current');
    }
  }

  /**
   * Handle expanded postbox div.
   *
   * @param  {object} e
   */
  handlediv(e) {
    e.preventDefault();

    const $this   = $(this);
    const $parent = $this.parent();
    const $inside = $parent.find('.inside');

    $parent.parent().toggleClass('closed');
    $inside.toggleClass('papi-hide');
    $this.attr('aria-expanded', !$inside.hasClass('papi-hide'));
  }

  /**
   * Redirect to location from `papi-href` data attribute
   * or closest tag with href attribute.
   *
   * @param {object} e
   */
  redirect(e) {
    e.preventDefault();
    let $this    = $(this);
    let papiHref = $this.data().papiHref;

    if (papiHref !== undefined) {
      window.location = papiHref;
    } else {
      window.location = $(this).closest('[href]').attr('href');
    }
  }

  /**
   * Search in page types box list.
   *
   * @param {object} e
   */
  search(e) {
    e.preventDefault();

    let $this = $(this);
    let $list = $('.papi-box-list');
    let val   = $this.val();

    $list.find('.papi-box-item').each(function() {
      let $item = $(this);
      $item[$item.text().toLowerCase().indexOf(val) === -1 ? 'addClass' : 'removeClass']('papi-hide');
    });
  }

  /**
   * Set equal height on page type boxes.
   */
  setEqualBoxHeights() {
    let $boxItems  = $('.papi-box-item');
    let thumbnails = $boxItems.find('.papi-post-type-screenshot').length > 0;
    let boxMaxHeight = 0;

    if (!thumbnails) {
      $boxItems = $('.papi-page-type-info');
    }

    $boxItems.each(function () {
      let $this  = $(this);

      if (thumbnails) {
        $this.find('.papi-post-type-info').removeAttr('style');
      } else {
        $this.removeAttr('style');
      }

      let height = $this.height();
      boxMaxHeight = height > boxMaxHeight ? height : boxMaxHeight;
    });

    $boxItems.each(function () {
      let $this  = $(this);
      let height = boxMaxHeight;

      if (thumbnails) {
        let $thumb = $this.find('.papi-post-type-screenshot');

        if ($thumb.length) {
          height = height - $thumb.height();
        } else {
          height += 5;
        }

        $this.find('.papi-post-type-info').height(height);
      } else {
        $this.height(height);
      }
    });
  }

  /**
   * Set selected menu item if it isn't selected.
   */
  setSelectedMenuItem() {
    let href = typeof window.location === 'string' ? window.location : window.location.href;
    let $adminmenu = $('#adminmenu');

    if (!$adminmenu.find('li.current > a.current').length) {
      href = href.substr(href.lastIndexOf('/') + 1);
      href = href.replace(/\%2F/g, '/');
      $('a[href="' + href + '"]', $adminmenu).addClass('current').parent().addClass('current');
    }
  }
}

export default Core;
<|endoftext|>


<commit_before>var mainApp = angular.module('mainApp', ['ui.bootstrap']);

mainApp.config(function ($routeProvider) {

    $routeProvider
        .when('/', {
            templateUrl: 'views/main.html',
            controller: 'MainCtrl',
            resolve: { user: mainApp.resolveUser }
        })
        .when('/dashboard', {
            templateUrl: 'views/dashboard.html',
            controller: 'DashboardCtrl',
            resolve: { user: mainApp.resolveUser }
        })
        .when('/word-lookup', {
            templateUrl: 'views/word-lookup.html',
            controller: 'WordLookupCtrl',
            resolve: { user: mainApp.resolveUser }
        })
        .when('/activity', {
            templateUrl: 'views/activity.html',
            controller: 'ActivityCtrl',
            resolve: { user: mainApp.resolveUser }
        })
        .when('/login', {
            templateUrl: 'views/login.html',
            controller: 'LoginCtrl'
        })
        .when('/logout', {
            templateUrl: 'views/logout.html',
            controller: 'LoginCtrl'
        })
        .otherwise({
            redirectTo: '/'
        });
});

mainApp.resolveUser = function($q, $route, $location){
    var defer = $q.defer();
    chrome.storage.local.get('user', function (result) {
        // if not, redirect him to login page
        if(result.user == null){
            $location.path('/login');
            defer.reject();
            return;
        }
        defer.resolve(result.user);
    });
    return defer.promise;
}

mainApp.filter('oneZeroToYesNo', function() {
    return function(input) {
        return input == 1 ? 'Yes' : 'No';
    };
});<commit_msg>new route - register<commit_after>var mainApp = angular.module('mainApp', ['ui.bootstrap']);

mainApp.config(function ($routeProvider) {

    $routeProvider
        .when('/', {
            templateUrl: 'views/main.html',
            controller: 'MainCtrl',
            resolve: { user: mainApp.resolveUser }
        })
        .when('/dashboard', {
            templateUrl: 'views/dashboard.html',
            controller: 'DashboardCtrl',
            resolve: { user: mainApp.resolveUser }
        })
        .when('/word-lookup', {
            templateUrl: 'views/word-lookup.html',
            controller: 'WordLookupCtrl',
            resolve: { user: mainApp.resolveUser }
        })
        .when('/activity', {
            templateUrl: 'views/activity.html',
            controller: 'ActivityCtrl',
            resolve: { user: mainApp.resolveUser }
        })
        .when('/login', {
            templateUrl: 'views/login.html',
            controller: 'LoginCtrl'
        })
        .when('/logout', {
            templateUrl: 'views/logout.html',
            controller: 'LoginCtrl'
        })
        .when('/register', {
            templateUrl: 'views/register.html',
            controller: 'RegisterCtrl'
        })
        .otherwise({
            redirectTo: '/'
        });
});

mainApp.resolveUser = function($q, $route, $location){
    var defer = $q.defer();
    chrome.storage.local.get('user', function (result) {
        // if not, redirect him to login page
        if(result.user == null){
            $location.path('/login');
            defer.reject();
            return;
        }
        defer.resolve(result.user);
    });
    return defer.promise;
}

mainApp.filter('oneZeroToYesNo', function() {
    return function(input) {
        return input == 1 ? 'Yes' : 'No';
    };
});<|endoftext|>


<commit_before>import moment from 'moment'
import { getItems, replaceItems } from 'feathers-hooks-common'

export function marshall (hook) {
  let items = getItems(hook)
  items = (Array.isArray(items) ? items : [items])

  items.forEach(item => {
    item.runTime = new Date(item.runTime.format())
    item.forecastTime = new Date(item.forecastTime.format())
  })

  replaceItems(hook, items)
}

export function unmarshall (hook) {
  let items = getItems(hook)
  items = (Array.isArray(items) ? items : [items])

  items.forEach(item => {
    // Take care to field selection that might remove some
    if (item.runTime) item.runTime = moment.utc(item.runTime.toISOString())
    if (item.forecastTime) item.forecastTime = moment.utc(item.forecastTime.toISOString())
  })

  replaceItems(hook, items)
}
<commit_msg>Added comments<commit_after>import moment from 'moment'
import { getItems, replaceItems } from 'feathers-hooks-common'

// Need to convert from server side types (moment dates) to basic JS types when "writing" to DB adapters
export function marshall (hook) {
  let items = getItems(hook)
  items = (Array.isArray(items) ? items : [items])

  items.forEach(item => {
    item.runTime = new Date(item.runTime.format())
    item.forecastTime = new Date(item.forecastTime.format())
  })

  replaceItems(hook, items)
}

// Need to convert back to server side types (moment dates) from basic JS types when "reading" from DB adapters
export function unmarshall (hook) {
  let items = getItems(hook)
  items = (Array.isArray(items) ? items : [items])

  items.forEach(item => {
    // Take care to field selection that might remove some
    if (item.runTime) item.runTime = moment.utc(item.runTime.toISOString())
    if (item.forecastTime) item.forecastTime = moment.utc(item.forecastTime.toISOString())
  })

  replaceItems(hook, items)
}
<|endoftext|>


<commit_before>const _ = require('underscore');

class AbilityTargetCard {
    constructor(name, properties, ability) {
        this.name = name;
        this.properties = _.omit(properties, 'ringCondition');
        this.properties.ringCondition = (ring, context) => {
            let contextCopy = context.copy();
            contextCopy.rings[this.name] = ring;
            if(this.name === 'target') {
                contextCopy.ring = ring;
            }
            return (properties.gameAction.length === 0 || properties.gameAction.some(gameAction => gameAction.hasLegalTarget(context))) &&
                   properties.ringCondition(ring, context) && context.ability.canPayCosts(context) && this.checkDependentTarget(context);
        };
        for(let gameAction of this.properties.gameAction) {
            gameAction.getDefaultTargets = context => context.rings[name];
        }
        this.checkDependentTarget = context => true; // eslint-disable-line no-unused-vars
        if(this.properties.dependsOn) {
            let dependsOnTarget = ability.targets.find(target => target.name === this.properties.dependsOn);
            dependsOnTarget.checkDependentTarget = context => this.hasLegalTarget(context);
        }
    }

    canResolve(context) {
        return !!this.properties.dependsOn || this.hasLegalTarget(context);
    }

    hasLegalTarget(context) {
        return _.any(context.game.rings, ring => this.properties.ringCondition(ring, context));
    }

    getGameAction(context) {
        return this.properties.gameAction.filter(gameAction => gameAction.hasLegalTarget(context));
    }

    getAllLegalTargets(context) {
        return _.filter(context.game.rings, ring => this.properties.ringCondition(ring, context));
    }

    resolve(context, noCostsFirstButton = false) {
        let result = { resolved: false, name: this.name, value: null, costsFirst: false, mode: 'ring' };
        let player = context.player;
        if(this.properties.player && this.properties.player === 'opponent') {
            if(context.stage === 'pretarget') {
                result.costsFirst = true;
                return result;
            }
            player = player.opponent;
        }
        let buttons = [];
        let waitingPromptTitle = '';
        if(this.properties.optional) {
            buttons.push({ text: 'No more targets', arg: 'noMoreTargets' });
        }
        if(context.stage === 'pretarget') {
            if(!noCostsFirstButton) {
                buttons.push({ text: 'Pay costs first', arg: 'costsFirst' });
            }
            buttons.push({ text: 'Cancel', arg: 'cancel' });
            if(context.ability.abilityType === 'action') {
                waitingPromptTitle = 'Waiting for opponent to take an action or pass';
            } else {
                waitingPromptTitle = 'Waiting for opponent';
            }
        }
        let promptProperties = {
            waitingPromptTitle: waitingPromptTitle,
            context: context,
            buttons: buttons,
            onSelect: (player, ring) => {
                result.resolved = true;
                result.value = ring;
                context.rings[this.name] = ring;
                return true;
            },
            onCancel: () => {
                result.resolved = true;
                return true;
            },
            onMenuCommand: (player, arg) => {
                if(arg === 'costsFirst') {
                    result.costsFirst = true;
                    return true;
                }
                result.resolved = true;
                result.value = arg;
                return true;
            }
        };
        context.game.promptForRingSelect(player, _.extend(promptProperties, this.properties));
        return result;
    }

    checkTarget(context) {
        return this.properties.ringCondition(context.rings[this.name], context);
    }
}

module.exports = AbilityTargetCard;
<commit_msg>AbilityTargetRing bugfix<commit_after>const _ = require('underscore');

class AbilityTargetCard {
    constructor(name, properties, ability) {
        this.name = name;
        this.properties = _.omit(properties, 'ringCondition');
        this.properties.ringCondition = (ring, context) => {
            let contextCopy = context.copy();
            contextCopy.rings[this.name] = ring;
            if(this.name === 'target') {
                contextCopy.ring = ring;
            }
            return (properties.gameAction.length === 0 || properties.gameAction.some(gameAction => gameAction.hasLegalTarget(contextCopy))) &&
                   properties.ringCondition(ring, contextCopy) && context.ability.canPayCosts(contextCopy) && this.checkDependentTarget(contextCopy);
        };
        for(let gameAction of this.properties.gameAction) {
            gameAction.getDefaultTargets = context => context.rings[name];
        }
        this.checkDependentTarget = context => true; // eslint-disable-line no-unused-vars
        if(this.properties.dependsOn) {
            let dependsOnTarget = ability.targets.find(target => target.name === this.properties.dependsOn);
            dependsOnTarget.checkDependentTarget = context => this.hasLegalTarget(context);
        }
    }

    canResolve(context) {
        return !!this.properties.dependsOn || this.hasLegalTarget(context);
    }

    hasLegalTarget(context) {
        return _.any(context.game.rings, ring => this.properties.ringCondition(ring, context));
    }

    getGameAction(context) {
        return this.properties.gameAction.filter(gameAction => gameAction.hasLegalTarget(context));
    }

    getAllLegalTargets(context) {
        return _.filter(context.game.rings, ring => this.properties.ringCondition(ring, context));
    }

    resolve(context, noCostsFirstButton = false) {
        let result = { resolved: false, name: this.name, value: null, costsFirst: false, mode: 'ring' };
        let player = context.player;
        if(this.properties.player && this.properties.player === 'opponent') {
            if(context.stage === 'pretarget') {
                result.costsFirst = true;
                return result;
            }
            player = player.opponent;
        }
        let buttons = [];
        let waitingPromptTitle = '';
        if(this.properties.optional) {
            buttons.push({ text: 'No more targets', arg: 'noMoreTargets' });
        }
        if(context.stage === 'pretarget') {
            if(!noCostsFirstButton) {
                buttons.push({ text: 'Pay costs first', arg: 'costsFirst' });
            }
            buttons.push({ text: 'Cancel', arg: 'cancel' });
            if(context.ability.abilityType === 'action') {
                waitingPromptTitle = 'Waiting for opponent to take an action or pass';
            } else {
                waitingPromptTitle = 'Waiting for opponent';
            }
        }
        let promptProperties = {
            waitingPromptTitle: waitingPromptTitle,
            context: context,
            buttons: buttons,
            onSelect: (player, ring) => {
                result.resolved = true;
                result.value = ring;
                context.rings[this.name] = ring;
                return true;
            },
            onCancel: () => {
                result.resolved = true;
                return true;
            },
            onMenuCommand: (player, arg) => {
                if(arg === 'costsFirst') {
                    result.costsFirst = true;
                    return true;
                }
                result.resolved = true;
                result.value = arg;
                return true;
            }
        };
        context.game.promptForRingSelect(player, _.extend(promptProperties, this.properties));
        return result;
    }

    checkTarget(context) {
        return this.properties.ringCondition(context.rings[this.name], context);
    }
}

module.exports = AbilityTargetCard;
<|endoftext|>


<commit_before>import $ from 'jquery';

class Core {

  /**
   * Initialize Papi core class.
   */
  static init() {
    const core = new Core();

    core.addCurrentClassToMenuItem();
    core.binds();
    core.pageTypeSwitcher();
    core.prepareBoxes();
    core.setSelectedMenuItem();
  }

  /**
   * Autosave fields on heartbeat.
   *
   * @param {object} e
   * @param {object} xhr
   * @param {object} options
   */
  autosave(e, xhr, options) {
    const fields = $('[name*="papi_"]');
    const data = {};
    const reg = /action=(.+?)&/;
    const val = reg.exec(options.data);
    const id  = /post_id=\d+/.exec(options.data);

    if (val !== null && val.length && val[1] === 'heartbeat' && id != null && id.length) {
      fields.each(function () {
        const $this = $(this);

        data[$this.attr('name')] = $this.val();
      });

      options.data += '&' + $.param(data);
    }
  }

  /**
   * Bind elements with functions.
   */
  binds() {
    $('.papi-box-list > li > p').on('click', this.redirect);
    $('input[name="add-new-page-search"]').on('keyup', this.search);
    $('[data-papi-href]').on('click touchstart', this.redirect);

    if ('select2' in $.fn) {
      $('.inside .papi-table tr .papi-component-select2').select2();
    }

    $('.papi-meta-type-term button.handlediv').on('click', this.handlediv);

    // Autosave fields on heartbeat.
    $(document).ajaxSend(this.autosave);
  }

  /**
   * Add current class to menu item.
   */
  addCurrentClassToMenuItem() {
    let $submenu = $('.wp-has-current-submenu .wp-submenu');
    let $menuitem = $submenu.find('a[href*="papi-add-new-page"]').parent();

    if (!$menuitem.hasClass('current') && !$submenu.find('li.current').length) {
      $menuitem.addClass('current');
    }
  }

  /**
   * Handle expanded postbox div.
   *
   * @param  {object} e
   */
  handlediv(e) {
    e.preventDefault();

    const $this   = $(this);
    const $parent = $this.parent();
    const $inside = $parent.find('.inside');

    $parent.parent().toggleClass('closed');
    $inside.toggleClass('papi-hide');
    $this.attr('aria-expanded', !$inside.hasClass('papi-hide'));
  }

  /**
   * Page type switcher.
   */
  pageTypeSwitcher() {
    $('.misc-pub-section.curtime.misc-pub-section-last').removeClass('misc-pub-section-last');
    $('#papi-page-type-switcher-edit').on('click', function(e) {
      e.preventDefault();
      $(this).hide();
      $('.papi-page-type-switcher > div').slideDown();
    });
    $('#papi-page-type-switcher-save').on('click', function(e) {
      e.preventDefault();
      $('.papi-page-type-switcher > div').slideUp();
      $('#papi-page-type-switcher-edit').show();
      $('.papi-page-type-switcher > span').text($('.papi-page-type-switcher select :selected').text());
    });
    $('#papi-page-type-switcher-cancel').on('click', function(e) {
      e.preventDefault();
      $('.papi-page-type-switcher > div').slideUp();
      $('#papi-page-type-switcher-edit').show();
    });
  }

  /**
   * Redirect to location from `papi-href` data attribute
   * or closest tag with href attribute.
   *
   * @param {object} e
   */
  redirect(e) {
    e.preventDefault();
    let $this    = $(this);
    let papiHref = $this.data().papiHref;

    if (papiHref !== undefined) {
      window.location = papiHref;
    } else {
      window.location = $(this).closest('[href]').attr('href');
    }
  }

  /**
   * Search in page types box list.
   *
   * @param {object} e
   */
  search(e) {
    e.preventDefault();

    let $this = $(this);
    let $list = $('.papi-box-list');
    let val   = $this.val();

    // Destroy masonry before searching the list.
    $('.papi-box-list').masonry('destroy');

    $list.find('.papi-box-item').each(function() {
      let $item = $(this);

      if ($item.text().toLowerCase().indexOf(val) === -1) {
        $item.addClass('papi-hide');
      } else {
        $item.removeClass('papi-hide');
      }
    });

    // Enable masonry after searching the list.
    $('.papi-box-list').masonry({
      itemSelector: '.papi-box-item:not(.papi-hide)',
      isResizable: true
    });
  }

  /**
   * Prepare boxes with equal height.
   */
  prepareBoxes() {
    let $boxItems = $('.papi-box-item');
    let thumbnails = $boxItems.find('.papi-page-type-screenshot').length;
    let boxMaxHeight = 0;

    if (!thumbnails) {
      $boxItems = $('.papi-page-type-info');
    }

    $boxItems.each(function () {
      let $this  = $(this);

      if (thumbnails) {
        $this.find('.papi-post-type-info').removeAttr('style');
      } else {
        $this.removeAttr('style');
      }

      let height = $this.height();
      boxMaxHeight = height > boxMaxHeight ? height : boxMaxHeight;
    });

    $boxItems.each(function () {
      let $this  = $(this);
      let height = boxMaxHeight;

      if (thumbnails) {
        let $thumb = $this.find('.papi-page-type-screenshot');

        if ($thumb.length) {
          height = height - $thumb.height();
        } else {
          height += 5;
        }

        $this.find('.papi-page-type-info').height(height);
      } else {
        $this.height(height);
      }
    });

    // Enable masonry after setting equal height.
    $('.papi-box-list').masonry({
      itemSelector: '.papi-box-item:not(.papi-hide)',
      isResizable: true
    });
  }

  /**
   * Set selected menu item if it isn't selected.
   */
  setSelectedMenuItem() {
    let href = typeof window.location === 'string' ? window.location : window.location.href;
    let $adminmenu = $('#adminmenu');

    if (!$adminmenu.find('li.current > a.current').length) {
      href = href.substr(href.lastIndexOf('/') + 1);
      href = href.replace(/%2F/g, '/');
      $('a[href="' + href + '"]', $adminmenu).addClass('current').parent().addClass('current');
    }
  }
}

export default Core;
<commit_msg>Fix issue with browsers where selected attribute is not removed correct<commit_after>import $ from 'jquery';

class Core {

  /**
   * Initialize Papi core class.
   */
  static init() {
    const core = new Core();

    core.addCurrentClassToMenuItem();
    core.binds();
    core.pageTypeSwitcher();
    core.prepareBoxes();
    core.setSelectedMenuItem();
  }

  /**
   * Autosave fields on heartbeat.
   *
   * @param {object} e
   * @param {object} xhr
   * @param {object} options
   */
  autosave(e, xhr, options) {
    const fields = $('[name*="papi_"]');
    const data = {};
    const reg = /action=(.+?)&/;
    const val = reg.exec(options.data);
    const id  = /post_id=\d+/.exec(options.data);

    if (val !== null && val.length && val[1] === 'heartbeat' && id != null && id.length) {
      fields.each(function () {
        const $this = $(this);

        data[$this.attr('name')] = $this.val();
      });

      options.data += '&' + $.param(data);
    }
  }

  /**
   * Bind elements with functions.
   */
  binds() {
    $('.papi-box-list > li > p').on('click', this.redirect);
    $('input[name="add-new-page-search"]').on('keyup', this.search);
    $('[data-papi-href]').on('click touchstart', this.redirect);

    if ('select2' in $.fn) {
      $('.inside .papi-table tr .papi-component-select2').select2();

      // Fix issue with browsers where selected attribute is not removed correct.
      $(document.body).on('change', 'select.papi-component-select2', function () {
        $(this).find('option[selected]').removeAttr('selected');
      });
    }

    $('.papi-meta-type-term button.handlediv').on('click', this.handlediv);

    // Autosave fields on heartbeat.
    $(document).ajaxSend(this.autosave);
  }

  /**
   * Add current class to menu item.
   */
  addCurrentClassToMenuItem() {
    let $submenu = $('.wp-has-current-submenu .wp-submenu');
    let $menuitem = $submenu.find('a[href*="papi-add-new-page"]').parent();

    if (!$menuitem.hasClass('current') && !$submenu.find('li.current').length) {
      $menuitem.addClass('current');
    }
  }

  /**
   * Handle expanded postbox div.
   *
   * @param  {object} e
   */
  handlediv(e) {
    e.preventDefault();

    const $this   = $(this);
    const $parent = $this.parent();
    const $inside = $parent.find('.inside');

    $parent.parent().toggleClass('closed');
    $inside.toggleClass('papi-hide');
    $this.attr('aria-expanded', !$inside.hasClass('papi-hide'));
  }

  /**
   * Page type switcher.
   */
  pageTypeSwitcher() {
    $('.misc-pub-section.curtime.misc-pub-section-last').removeClass('misc-pub-section-last');
    $('#papi-page-type-switcher-edit').on('click', function(e) {
      e.preventDefault();
      $(this).hide();
      $('.papi-page-type-switcher > div').slideDown();
    });
    $('#papi-page-type-switcher-save').on('click', function(e) {
      e.preventDefault();
      $('.papi-page-type-switcher > div').slideUp();
      $('#papi-page-type-switcher-edit').show();
      $('.papi-page-type-switcher > span').text($('.papi-page-type-switcher select :selected').text());
    });
    $('#papi-page-type-switcher-cancel').on('click', function(e) {
      e.preventDefault();
      $('.papi-page-type-switcher > div').slideUp();
      $('#papi-page-type-switcher-edit').show();
    });
  }

  /**
   * Redirect to location from `papi-href` data attribute
   * or closest tag with href attribute.
   *
   * @param {object} e
   */
  redirect(e) {
    e.preventDefault();
    let $this    = $(this);
    let papiHref = $this.data().papiHref;

    if (papiHref !== undefined) {
      window.location = papiHref;
    } else {
      window.location = $(this).closest('[href]').attr('href');
    }
  }

  /**
   * Search in page types box list.
   *
   * @param {object} e
   */
  search(e) {
    e.preventDefault();

    let $this = $(this);
    let $list = $('.papi-box-list');
    let val   = $this.val();

    // Destroy masonry before searching the list.
    $('.papi-box-list').masonry('destroy');

    $list.find('.papi-box-item').each(function() {
      let $item = $(this);

      if ($item.text().toLowerCase().indexOf(val) === -1) {
        $item.addClass('papi-hide');
      } else {
        $item.removeClass('papi-hide');
      }
    });

    // Enable masonry after searching the list.
    $('.papi-box-list').masonry({
      itemSelector: '.papi-box-item:not(.papi-hide)',
      isResizable: true
    });
  }

  /**
   * Prepare boxes with equal height.
   */
  prepareBoxes() {
    let $boxItems = $('.papi-box-item');
    let thumbnails = $boxItems.find('.papi-page-type-screenshot').length;
    let boxMaxHeight = 0;

    if (!thumbnails) {
      $boxItems = $('.papi-page-type-info');
    }

    $boxItems.each(function () {
      let $this  = $(this);

      if (thumbnails) {
        $this.find('.papi-post-type-info').removeAttr('style');
      } else {
        $this.removeAttr('style');
      }

      let height = $this.height();
      boxMaxHeight = height > boxMaxHeight ? height : boxMaxHeight;
    });

    $boxItems.each(function () {
      let $this  = $(this);
      let height = boxMaxHeight;

      if (thumbnails) {
        let $thumb = $this.find('.papi-page-type-screenshot');

        if ($thumb.length) {
          height = height - $thumb.height();
        } else {
          height += 5;
        }

        $this.find('.papi-page-type-info').height(height);
      } else {
        $this.height(height);
      }
    });

    // Enable masonry after setting equal height.
    $('.papi-box-list').masonry({
      itemSelector: '.papi-box-item:not(.papi-hide)',
      isResizable: true
    });
  }

  /**
   * Set selected menu item if it isn't selected.
   */
  setSelectedMenuItem() {
    let href = typeof window.location === 'string' ? window.location : window.location.href;
    let $adminmenu = $('#adminmenu');

    if (!$adminmenu.find('li.current > a.current').length) {
      href = href.substr(href.lastIndexOf('/') + 1);
      href = href.replace(/%2F/g, '/');
      $('a[href="' + href + '"]', $adminmenu).addClass('current').parent().addClass('current');
    }
  }
}

export default Core;
<|endoftext|>


<commit_before>(function ()
{
    'use strict';

    document.documentElement.className = 'js';

    // Detect whether jQuery v2 features required, otherwise use jQuery v1 for higher compatibility.

    var jqueryVersion = '1.12.2';

    if (typeof JSON !== 'undefined' && 'querySelector' in document && 'addEventListener' in window) {
        jqueryVersion = '2.2.2';
    }

    requirejs.config({
        paths:
        {
            'jquery': 'https://ajax.googleapis.com/ajax/libs/jquery/'+jqueryVersion+'/jquery.min',
            'jqueryui': 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min',
            'flowplayer': 'flowplayer/flowplayer.min'
        },
        shim:
        {
            'cookie': ['jquery'],
            'jqueryui': ['jquery']
        }
    });

    // Detect whether user enabled 'Do No Track' in their browser, and honour it.

    define('track', function ()
    {
        return {
            allow : navigator.doNotTrack !== 'yes' && navigator.doNotTrack !== '1' && navigator.doNotTrack !== 1
        };
    });

    require(['jquery'], function ($)
    {
        // Load objects as variables.

        var code = $('code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code'),
            fields = $('textarea'),
            player = $('.videoplayer'),
            slider = $('.slider');

        // Syntax highlighting, via 'Prism'.
        // Applies syntax highlighting to `code` HTML elements.
        // More info - http://prismjs.com.

        if (code.length) {
            require(['prism'], function ()
            {
                Prism.highlightAll();
            });
        }

        // Auto-growing textareas, via 'Autosize'.
        // Allows dynamic resizing of textarea height, so that it grows as based
        // on visitor input. More info - https://github.com/jackmoore/autosize.

        if (fields.length) {
            require(['autosize'], function (autosize)
            {
                autosize(fields);
            });
        }

        // HTML5 videos (with Flash fallback), via 'Flowplayer'.
        // More info - https://github.com/flowplayer/flowplayer.

        if (player.length) {
            require(['flowplayer'], function ()
            {
                player.flowplayer({
                    splash: true
                });
            });
        }

        // Slider, via 'Lory'.
        // More info - https://github.com/meandmax/lory.

        if (slider.length) {
            require(['slick'], function ()
            {
                slider.slick({
                    //accessibility: true,
                    //adaptiveHeight: false,
                    //appendArrows: $(element),
                    //appendDots: $(element),
                    //arrows: true,
                    //asNavFor: null,
                    //prevArrow: '<button type="button" data-role="none" class="slick-prev" aria-label="Previous" tabindex="0" role="button">Previous</button>',
                    //nextArrow: '<button type="button" data-role="none" class="slick-next" aria-label="Next" tabindex="0" role="button">Next</button>',
                    //autoplay: false,
                    //autoplaySpeed: 3000,
                    //centerMode: false,
                    //centerPadding: '50px',
                    //cssEase: 'ease',
                    //customPaging: function(slider, i) {
                    //    return '<button type="button" data-role="none" role="button" aria-required="false" tabindex="0">' + (i + 1) + '</button>';
                    //},
                    dots: true,
                    //dotsClass: 'slick-dots',
                    //draggable: true,
                    easing: 'swing',
                    //edgeFriction: 0.35,
                    //fade: false,
                    //focusOnSelect: false,
                    //infinite: true,
                    //initialSlide: 0,
                    //lazyLoad: 'ondemand',
                    //mobileFirst: false,
                    //pauseOnHover: true,
                    //pauseOnDotsHover: false,
                    //respondTo: 'window',
                    //responsive: null,
                    //rows: 1,
                    //rtl: false,
                    //slide: '',
                    //slidesPerRow: 1,
                    //slidesToShow: 1,
                    //slidesToScroll: 1,
                    speed: 300
                    //swipe: true,
                    //swipeToSlide: false,
                    //touchMove: true,
                    //touchThreshold: 5,
                    //useCSS: true,
                    //useTransform: false,
                    //variableWidth: false,
                    //vertical: false,
                    //verticalSwiping: false,
                    //waitForAnimate: true,
                    //zIndex: 1000
                });
            });
        }

    });

    // Responsive navigation menu, via 'Responsive Nav'.
    // More info - https://github.com/viljamis/responsive-nav.js.

    require(['responsivenav'], function ()
    {
        responsiveNav('.site-navigation', {
            transition: 400,
            insert: 'after',
            navClass: 'site-navigation'
        });
    });

    // `picture` tag and/or `img` tag with `srcset` and `sizes` attributes polyfill, via 'Picturefill'.
    // More info - https://github.com/scottjehl/picturefill.

    require(['jquery'], function ($)
    {
        if ($('img[srcset], img[sizes], picture').length) {
            require(['picturefill']);
        }
    });

    // EU-cookie disclaimer, via 'jquery.cookie'.
    // More info - https://github.com/carhartl/jquery-cookie.

    require(['jquery', 'cookie'], function ($)
    {
        if (!$.cookie('acceptedCookies')) {
            var disclaimer = $('

This website uses cookies to enhance your experience. By continuing to use this website you agree to cookies being placed on your computer. If you wish to use this website but do not wish for cookies to be placed on your computer you can change the settings in your internet browser. Close.

');
            $('body').prepend(disclaimer);
            $.cookie('acceptedCookies', 1, {expires: 1461});

            disclaimer.find('a').on('click', function (e)
            {
                e.preventDefault();

                disclaimer.slideUp('fast', function ()
                {
                    disclaimer.remove();
                });
            });
        }
    });

    // Google+ '+1' button.

    require(['jquery'], function ($)
    {
        if ($('.g-plusone').length) {
            require(['https://apis.google.com/js/platform.js']);
        }
    });

    // Twitter 'Tweet' button.

    require(['jquery'], function ($)
    {
        if ($('.twitter-share-button').length) {
            require(['https://platform.twitter.com/widgets.js']);
        }
    });

    // Google Analytics - remember to amend the user account ID number!

    require(['track'], function(track)
    {
        if (track.allow) {
            window._gaq = window._gaq || [];
            window._gaq.push(['_setAccount', 'UA-xxxxxxxx-x', 'auto']);
            window._gaq.push(['_setDomainName', 'none']);
            window._gaq.push(['_gat._anonymizeIp']);
            window._gaq.push(['_setVisitorCookieTimeout', 0]);
            window._gaq.push(['_setSessionCookieTimeout', 0]);
            window._gaq.push(['_setCampaignCookieTimeout', 0]);
            window._gaq.push(['_trackPageview']);
            require(['https://www.google-analytics.com/ga.js']);
        }
    });

})();
<commit_msg>Update jQuery<commit_after>(function ()
{
    'use strict';

    document.documentElement.className = 'js';

    // Detect whether jQuery v2 features required, otherwise use jQuery v1 for higher compatibility.

    var jqueryVersion = '1.12.3';

    if (typeof JSON !== 'undefined' && 'querySelector' in document && 'addEventListener' in window) {
        jqueryVersion = '2.2.3';
    }

    requirejs.config({
        paths:
        {
            'jquery': 'https://ajax.googleapis.com/ajax/libs/jquery/'+jqueryVersion+'/jquery.min',
            'jqueryui': 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min',
            'flowplayer': 'flowplayer/flowplayer.min'
        },
        shim:
        {
            'cookie': ['jquery'],
            'jqueryui': ['jquery']
        }
    });

    // Detect whether user enabled 'Do No Track' in their browser, and honour it.

    define('track', function ()
    {
        return {
            allow : navigator.doNotTrack !== 'yes' && navigator.doNotTrack !== '1' && navigator.doNotTrack !== 1
        };
    });

    require(['jquery'], function ($)
    {
        // Load objects as variables.

        var code = $('code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code'),
            fields = $('textarea'),
            player = $('.videoplayer'),
            slider = $('.slider');

        // Syntax highlighting, via 'Prism'.
        // Applies syntax highlighting to `code` HTML elements.
        // More info - http://prismjs.com.

        if (code.length) {
            require(['prism'], function ()
            {
                Prism.highlightAll();
            });
        }

        // Auto-growing textareas, via 'Autosize'.
        // Allows dynamic resizing of textarea height, so that it grows as based
        // on visitor input. More info - https://github.com/jackmoore/autosize.

        if (fields.length) {
            require(['autosize'], function (autosize)
            {
                autosize(fields);
            });
        }

        // HTML5 videos (with Flash fallback), via 'Flowplayer'.
        // More info - https://github.com/flowplayer/flowplayer.

        if (player.length) {
            require(['flowplayer'], function ()
            {
                player.flowplayer({
                    splash: true
                });
            });
        }

        // Slider, via 'Lory'.
        // More info - https://github.com/meandmax/lory.

        if (slider.length) {
            require(['slick'], function ()
            {
                slider.slick({
                    //accessibility: true,
                    //adaptiveHeight: false,
                    //appendArrows: $(element),
                    //appendDots: $(element),
                    //arrows: true,
                    //asNavFor: null,
                    //prevArrow: '<button type="button" data-role="none" class="slick-prev" aria-label="Previous" tabindex="0" role="button">Previous</button>',
                    //nextArrow: '<button type="button" data-role="none" class="slick-next" aria-label="Next" tabindex="0" role="button">Next</button>',
                    //autoplay: false,
                    //autoplaySpeed: 3000,
                    //centerMode: false,
                    //centerPadding: '50px',
                    //cssEase: 'ease',
                    //customPaging: function(slider, i) {
                    //    return '<button type="button" data-role="none" role="button" aria-required="false" tabindex="0">' + (i + 1) + '</button>';
                    //},
                    dots: true,
                    //dotsClass: 'slick-dots',
                    //draggable: true,
                    easing: 'swing',
                    //edgeFriction: 0.35,
                    //fade: false,
                    //focusOnSelect: false,
                    //infinite: true,
                    //initialSlide: 0,
                    //lazyLoad: 'ondemand',
                    //mobileFirst: false,
                    //pauseOnHover: true,
                    //pauseOnDotsHover: false,
                    //respondTo: 'window',
                    //responsive: null,
                    //rows: 1,
                    //rtl: false,
                    //slide: '',
                    //slidesPerRow: 1,
                    //slidesToShow: 1,
                    //slidesToScroll: 1,
                    speed: 300
                    //swipe: true,
                    //swipeToSlide: false,
                    //touchMove: true,
                    //touchThreshold: 5,
                    //useCSS: true,
                    //useTransform: false,
                    //variableWidth: false,
                    //vertical: false,
                    //verticalSwiping: false,
                    //waitForAnimate: true,
                    //zIndex: 1000
                });
            });
        }

    });

    // Responsive navigation menu, via 'Responsive Nav'.
    // More info - https://github.com/viljamis/responsive-nav.js.

    require(['responsivenav'], function ()
    {
        responsiveNav('.site-navigation', {
            transition: 400,
            insert: 'after',
            navClass: 'site-navigation'
        });
    });

    // `picture` tag and/or `img` tag with `srcset` and `sizes` attributes polyfill, via 'Picturefill'.
    // More info - https://github.com/scottjehl/picturefill.

    require(['jquery'], function ($)
    {
        if ($('img[srcset], img[sizes], picture').length) {
            require(['picturefill']);
        }
    });

    // EU-cookie disclaimer, via 'jquery.cookie'.
    // More info - https://github.com/carhartl/jquery-cookie.

    require(['jquery', 'cookie'], function ($)
    {
        if (!$.cookie('acceptedCookies')) {
            var disclaimer = $('

This website uses cookies to enhance your experience. By continuing to use this website you agree to cookies being placed on your computer. If you wish to use this website but do not wish for cookies to be placed on your computer you can change the settings in your internet browser. Close.

');
            $('body').prepend(disclaimer);
            $.cookie('acceptedCookies', 1, {expires: 1461});

            disclaimer.find('a').on('click', function (e)
            {
                e.preventDefault();

                disclaimer.slideUp('fast', function ()
                {
                    disclaimer.remove();
                });
            });
        }
    });

    // Google+ '+1' button.

    require(['jquery'], function ($)
    {
        if ($('.g-plusone').length) {
            require(['https://apis.google.com/js/platform.js']);
        }
    });

    // Twitter 'Tweet' button.

    require(['jquery'], function ($)
    {
        if ($('.twitter-share-button').length) {
            require(['https://platform.twitter.com/widgets.js']);
        }
    });

    // Google Analytics - remember to amend the user account ID number!

    require(['track'], function(track)
    {
        if (track.allow) {
            window._gaq = window._gaq || [];
            window._gaq.push(['_setAccount', 'UA-xxxxxxxx-x', 'auto']);
            window._gaq.push(['_setDomainName', 'none']);
            window._gaq.push(['_gat._anonymizeIp']);
            window._gaq.push(['_setVisitorCookieTimeout', 0]);
            window._gaq.push(['_setSessionCookieTimeout', 0]);
            window._gaq.push(['_setCampaignCookieTimeout', 0]);
            window._gaq.push(['_trackPageview']);
            require(['https://www.google-analytics.com/ga.js']);
        }
    });

})();
<|endoftext|>


<commit_before>const DrawCard = require('../../../drawcard.js');

class CrownOfGold extends DrawCard {
    setupCardAbilities(ability) {
        this.whileAttached({
            effect: [
                ability.effects.addTrait('King'),
                ability.effects.modifyStrength(-4),
                ability.effects.killByStrength
            ]
        });
    }
}

CrownOfGold.code = '02034';

module.exports = CrownOfGold;
<commit_msg>make sure Crown of Gold can only be attached to characters (#984)<commit_after>const DrawCard = require('../../../drawcard.js');

class CrownOfGold extends DrawCard {
    setupCardAbilities(ability) {
        this.whileAttached({
            effect: [
                ability.effects.addTrait('King'),
                ability.effects.modifyStrength(-4),
                ability.effects.killByStrength
            ]
        });
    }

    canAttach(player, card) {
        if(card.getType() !== 'character') {
            return false;
        }

        return super.canAttach(player, card);
    }
}

CrownOfGold.code = '02034';

module.exports = CrownOfGold;
<|endoftext|>


<commit_before>(function ()
{
    'use strict';

    document.documentElement.className = 'js';

    requirejs.config({
        paths:
        {
            'jquery': '//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min',
            'jqueryui': '//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min',
            'flowplayer': 'flowplayer/flowplayer.min'
        },
        shim:
        {
            'autosize': ['jquery'],
            'cookie': ['jquery'],
            'details': ['jquery'],
            'flowplayer': ['jquery'],
            'jqueryui': ['jquery'],
            'placeholder': ['jquery'],
            'stellar': ['jquery']
        }
    });

    define('feature', function ()
    {
        return {
            svg: function ()
            {
                return document.createElementNS || document.createElementNS('http://www.w3.org/2000/svg', 'svg').createSVGRect;
            }
        };
    });

    define('track', function ()
    {
        return {
            allow : navigator.doNotTrack !== 'yes' && navigator.doNotTrack !== '1' && navigator.doNotTrack !== 1
        };
    });

    require(['jquery', 'autosize'], function ($)
    {
        $('form textarea').autosize();
    });

    require(['jquery'], function ($)
    {
        var details = $('details'),
            placeholder = $('textarea[placeholder], input[placeholder]'),
            code = $('pre code'),
            stellar = $('.parallax');

        // Details polyfill.

        if (details.length)
        {
            require(['details'], function ()
            {
                details.details();
                $('html').addClass($.fn.details.support ? 'details' : 'no-details');
            });
        }

        // Placeholder polyfill.

        if (placeholder.length)
        {
            require(['placeholder'], function ()
            {
                placeholder.placeholder();
            });
        }

        // Syntax highlighting.

        if (code.length)
        {
            code.parent().addClass('prettyprint');

            require(['prettify'], function ()
            {
                prettyPrint();
            });
        }

        // Parallax backgrounds.

        if (stellar.length)
        {
            require(['stellar'], function ()
            {
                $.stellar({
                    horizontalScrolling: false
                });
            });
        }
    });

    // If no SVG support, replace SVGs with PNGs.

    require(['jquery', 'feature'], function ($, supports)
    {
        if (!supports.svg) {
            $('img.svg').attr('src', function ()
            {
                return $(this).attr('src').replace('.svg', '.png');
            });
        }
    });

    // Responsive navigation.

    require(['responsivenav'], function ()
    {
        responsiveNav('.nav-collapse', {
            transition: 400
        });
    });

    // EU-cookie disclaimer.

    require(['jquery', 'cookie'], function ($)
    {
        if (!$.cookie('acceptedCookies'))
        {
            var disclaimer = $('

This website uses cookies to enhance your experience. By continuing to use this website you agree to cookies being placed on your computer. If you wish to use this website but do not wish for cookies to be placed on your computer you can change the settings in your internet browser. Close.

');
            $('body').prepend(disclaimer);
            $.cookie('acceptedCookies', 1, {expires: 1461});

            disclaimer.find('a').on('click', function (e)
            {
                e.preventDefault();

                disclaimer.slideUp('fast', function ()
                {
                    disclaimer.remove();
                });
            });
        }
    });

    // ResponsiveSlides.

    require(['jquery'], function ($)
    {
        var slider = $('.rslides');

        if (slider.length)
        {
            require(['responsiveslides'], function ()
            {
                slider.responsiveSlides({
                    auto: true,             // Boolean: Animate automatically, true or false
                    speed: 1200,            // Integer: Speed of the transition, in milliseconds
                    timeout: 4800,          // Integer: Time between slide transitions, in milliseconds
                    pager: true,            // Boolean: Show pager, true or false
                    nav: true,              // Boolean: Show navigation, true or false
                    random: false,          // Boolean: Randomize the order of the slides, true or false
                    pause: false,           // Boolean: Pause on hover, true or false
                    pauseControls: false,   // Boolean: Pause when hovering controls, true or false
                    prevText: '←',    // String: Text for the "previous" button
                    nextText: '→',    // String: Text for the "next" button
                    maxwidth: '',           // Integer: Max-width of the slideshow, in pixels
                    navContainer: '',       // Selector: Where auto generated controls should be appended to, default is after the

                    manualControls: '',     // Selector: Declare custom pager navigation
                    namespace: 'rslides',   // String: change the default namespace used
                    before: function () {}, // Function: Before callback
                    after: function () {}   // Function: After callback
                });
            });
        }
    });

    // Flowplayer.

    require(['jquery'], function ($)
    {
        var player = $('.videoplayer');

        if (player.length)
        {
            require(['flowplayer'], function ()
            {
                player.flowplayer({
                    splash: true,
                    ratio: 0.417
                });
            });
        }
    });

    // Google+ '+1' button.

    require(['jquery'], function ($)
    {
        if ($('.g-plusone').length)
        {
            require(['//apis.google.com/js/plusone.js']);
        }
    });

    // Twitter 'Tweet' button.

    require(['jquery'], function ($)
    {
        if ($('.twitter-share-button').length)
        {
            require(['//platform.twitter.com/widgets.js']);
        }
    });

    require(['track'], function(track)
    {
        if (track.allow) {
            // Analytics.

            window._gaq = window._gaq || [];
            window._gaq.push(['_setAccount', 'UA-xxxxxxxx-x']);
            window._gaq.push(['_setDomainName', 'none']);
            window._gaq.push(['_gat._anonymizeIp']);
            window._gaq.push(['_setVisitorCookieTimeout', 0]);
            window._gaq.push(['_setSessionCookieTimeout', 0]);
            window._gaq.push(['_setCampaignCookieTimeout', 0]);
            window._gaq.push(['_trackPageview']);
            require(['//www.google-analytics.com/ga.js']);
        }
    });

})();
<commit_msg>Add comment to autosize script for clarity<commit_after>(function ()
{
    'use strict';

    document.documentElement.className = 'js';

    requirejs.config({
        paths:
        {
            'jquery': '//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min',
            'jqueryui': '//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min',
            'flowplayer': 'flowplayer/flowplayer.min'
        },
        shim:
        {
            'autosize': ['jquery'],
            'cookie': ['jquery'],
            'details': ['jquery'],
            'flowplayer': ['jquery'],
            'jqueryui': ['jquery'],
            'placeholder': ['jquery'],
            'stellar': ['jquery']
        }
    });

    define('feature', function ()
    {
        return {
            svg: function ()
            {
                return document.createElementNS || document.createElementNS('http://www.w3.org/2000/svg', 'svg').createSVGRect;
            }
        };
    });

    define('track', function ()
    {
        return {
            allow : navigator.doNotTrack !== 'yes' && navigator.doNotTrack !== '1' && navigator.doNotTrack !== 1
        };
    });

    require(['jquery'], function ($)
    {
        var details = $('details'),
            placeholder = $('textarea[placeholder], input[placeholder]'),
            code = $('pre code'),
            stellar = $('.parallax');

        // Details polyfill.

        if (details.length)
        {
            require(['details'], function ()
            {
                details.details();
                $('html').addClass($.fn.details.support ? 'details' : 'no-details');
            });
        }

        // Placeholder polyfill.

        if (placeholder.length)
        {
            require(['placeholder'], function ()
            {
                placeholder.placeholder();
            });
        }

        // Syntax highlighting.

        if (code.length)
        {
            code.parent().addClass('prettyprint');

            require(['prettify'], function ()
            {
                prettyPrint();
            });
        }

        // Parallax backgrounds.

        if (stellar.length)
        {
            require(['stellar'], function ()
            {
                $.stellar({
                    horizontalScrolling: false
                });
            });
        }
    });

    // Auto-growing textareas.

    require(['jquery', 'autosize'], function ($)
    {
        $('form textarea').autosize();
    });

    // If no SVG support, replace SVGs with PNGs.

    require(['jquery', 'feature'], function ($, supports)
    {
        if (!supports.svg) {
            $('img.svg').attr('src', function ()
            {
                return $(this).attr('src').replace('.svg', '.png');
            });
        }
    });

    // Responsive navigation.

    require(['responsivenav'], function ()
    {
        responsiveNav('.nav-collapse', {
            transition: 400
        });
    });

    // EU-cookie disclaimer.

    require(['jquery', 'cookie'], function ($)
    {
        if (!$.cookie('acceptedCookies'))
        {
            var disclaimer = $('

This website uses cookies to enhance your experience. By continuing to use this website you agree to cookies being placed on your computer. If you wish to use this website but do not wish for cookies to be placed on your computer you can change the settings in your internet browser. Close.

');
            $('body').prepend(disclaimer);
            $.cookie('acceptedCookies', 1, {expires: 1461});

            disclaimer.find('a').on('click', function (e)
            {
                e.preventDefault();

                disclaimer.slideUp('fast', function ()
                {
                    disclaimer.remove();
                });
            });
        }
    });

    // ResponsiveSlides.

    require(['jquery'], function ($)
    {
        var slider = $('.rslides');

        if (slider.length)
        {
            require(['responsiveslides'], function ()
            {
                slider.responsiveSlides({
                    auto: true,             // Boolean: Animate automatically, true or false
                    speed: 1200,            // Integer: Speed of the transition, in milliseconds
                    timeout: 4800,          // Integer: Time between slide transitions, in milliseconds
                    pager: true,            // Boolean: Show pager, true or false
                    nav: true,              // Boolean: Show navigation, true or false
                    random: false,          // Boolean: Randomize the order of the slides, true or false
                    pause: false,           // Boolean: Pause on hover, true or false
                    pauseControls: false,   // Boolean: Pause when hovering controls, true or false
                    prevText: '←',    // String: Text for the "previous" button
                    nextText: '→',    // String: Text for the "next" button
                    maxwidth: '',           // Integer: Max-width of the slideshow, in pixels
                    navContainer: '',       // Selector: Where auto generated controls should be appended to, default is after the

                    manualControls: '',     // Selector: Declare custom pager navigation
                    namespace: 'rslides',   // String: change the default namespace used
                    before: function () {}, // Function: Before callback
                    after: function () {}   // Function: After callback
                });
            });
        }
    });

    // Flowplayer.

    require(['jquery'], function ($)
    {
        var player = $('.videoplayer');

        if (player.length)
        {
            require(['flowplayer'], function ()
            {
                player.flowplayer({
                    splash: true,
                    ratio: 0.417
                });
            });
        }
    });

    // Google+ '+1' button.

    require(['jquery'], function ($)
    {
        if ($('.g-plusone').length)
        {
            require(['//apis.google.com/js/plusone.js']);
        }
    });

    // Twitter 'Tweet' button.

    require(['jquery'], function ($)
    {
        if ($('.twitter-share-button').length)
        {
            require(['//platform.twitter.com/widgets.js']);
        }
    });

    require(['track'], function(track)
    {
        if (track.allow) {
            // Analytics.

            window._gaq = window._gaq || [];
            window._gaq.push(['_setAccount', 'UA-xxxxxxxx-x']);
            window._gaq.push(['_setDomainName', 'none']);
            window._gaq.push(['_gat._anonymizeIp']);
            window._gaq.push(['_setVisitorCookieTimeout', 0]);
            window._gaq.push(['_setSessionCookieTimeout', 0]);
            window._gaq.push(['_setCampaignCookieTimeout', 0]);
            window._gaq.push(['_trackPageview']);
            require(['//www.google-analytics.com/ga.js']);
        }
    });

})();
<|endoftext|>


<commit_before>/********************************************************************
 *
 * Shared classes for most scripts.
 *
 * @public {class} sbCommonUtils
 * @public {class} sbDataSource
 * @public {class} sbShortcut
 *
 *******************************************************************/

Components.utils.import("resource://scrapbook-modules/common.jsm");
Components.utils.import("resource://scrapbook-modules/datasource.jsm");
Components.utils.import("resource://scrapbook-modules/shortcut.jsm");

/* javascript polyfill */
if (!String.prototype.startsWith) {
    String.prototype.startsWith = function (searchString, position) {
        position = position || 0;
        return this.substr(position, searchString.length) === searchString;
    };
}
<commit_msg>core: add polyfill String.endsWith<commit_after>/********************************************************************
 *
 * Shared classes for most scripts.
 *
 * @public {class} sbCommonUtils
 * @public {class} sbDataSource
 * @public {class} sbShortcut
 *
 *******************************************************************/

Components.utils.import("resource://scrapbook-modules/common.jsm");
Components.utils.import("resource://scrapbook-modules/datasource.jsm");
Components.utils.import("resource://scrapbook-modules/shortcut.jsm");

/* javascript polyfill */
if (!String.prototype.startsWith) {
    String.prototype.startsWith = function (searchString, position) {
        position = position || 0;
        return this.substr(position, searchString.length) === searchString;
    };
}

if (!String.prototype.endsWith) {
    String.prototype.endsWith = function(searchString, position) {
        var subjectString = this.toString();
        if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) {
            position = subjectString.length;
        }
        return subjectString.slice(position-searchString.length, position) == searchString;
    };
}<|endoftext|>


<commit_before>$(function() {
  // start the icon carousel
  $('#icon-carousel').carousel({
    interval: 5000
  });

  // Filter icons
  if($('#filter-by').length) {
    var $filter_val = $('#filter-val');
    var $filter = $('#filter');
    var $other = $('#new, #web-application, #form-control, #medical, #currency, #text-editor, #directional, #video-player, #brand, #file-type, #spinner, #payment, #chart');
    var $clear = $('#filter-clear');
    var $no_results = $('#no-search-results');

    var $icons = $('.filter-icon', $filter);

    $clear.click(function(e) {
      e.preventDefault();
      $('#filter-by').val('').trigger('keyup').focus();
    });

    $('#filter-by').keyup(function() {
      var $this = $(this);
      var val = $this.val();
      $filter.toggle(!!val);
      $other.toggle(!val);
      $clear.toggleClass('gone', !val);
      $filter_val.text(val);

      if(!val) return;

      var resultsCount = 0;
      $icons.each(function() {
        var filter = $(this).attr('data-filter').split('|');
        var show = inFilter(val, filter);
        if (!show) {
          if (val.slice(-1) === 's') {
            // Try to be smart. Make plural terms singular.
            show = inFilter(val.slice(0, -1), filter);
          }
        }
        if (show) resultsCount++;
        $(this).toggle(!!show);
      });

      if( resultsCount == 0 && val.length != 0 ) {
        $no_results.find('span').text(val);
        $no_results.show();
      } else {
        $no_results.hide();
      }
    }).trigger('keyup');
  }

  function inFilter(val, filter) {
    var found = false;
    for (var i = 0; i < filter.length; i++) {
      if (filter[i].match(val)) {
        found = true;
        break;
      }
    }
    return found;
  }

  // make code pretty
//  $('pre').addClass('prettyprint');
//  window.prettyPrint && prettyPrint();

  // Disable links with href="#" inside <section>, so users can click on them
  // to preview :active state without being scrolled up to the top of the page.
//  $('section a[href="#"]').click(function(e) {
//    e.preventDefault();
//    e.stopPropagation();
//  });

//  // inject twitter & github counts
//  $.ajax({
//    url: 'http://api.twitter.com/1/users/show.json',
//    data: {screen_name: 'fortaweso_me'},
//    dataType: 'jsonp',
//    success: function(data) {
//      $('#followers').html(data.followers_count);
//    }
//  });
//  $.ajax({
//    url: 'https://api.github.com/repos/fortawesome/Font-Awesome',
//    dataType: 'jsonp',
//    success: function(data) {
//      $('#watchers').html(data.data.watchers);
//      $('#forks').html(data.data.forks);
//    }
//  });
});
<commit_msg>Improved icon search inFilter function code.<commit_after>$(function() {
  // start the icon carousel
  $('#icon-carousel').carousel({
    interval: 5000
  });

  // Filter icons
  if($('#filter-by').length) {
    var $filter_val = $('#filter-val');
    var $filter = $('#filter');
    var $other = $('#new, #web-application, #form-control, #medical, #currency, #text-editor, #directional, #video-player, #brand, #file-type, #spinner, #payment, #chart');
    var $clear = $('#filter-clear');
    var $no_results = $('#no-search-results');

    var $icons = $('.filter-icon', $filter);

    $clear.click(function(e) {
      e.preventDefault();
      $('#filter-by').val('').trigger('keyup').focus();
    });

    $('#filter-by').keyup(function() {
      var $this = $(this);
      var val = $this.val();
      $filter.toggle(!!val);
      $other.toggle(!val);
      $clear.toggleClass('gone', !val);
      $filter_val.text(val);

      if(!val) return;

      var resultsCount = 0;
      $icons.each(function() {
        var filter = $(this).attr('data-filter').split('|');
        var show = inFilter(val, filter);
        if (!show) {
          if (val.slice(-1) === 's') {
            // Try to be smart. Make plural terms singular.
            show = inFilter(val.slice(0, -1), filter);
          }
        }
        if (show) resultsCount++;
        $(this).toggle(!!show);
      });

      if( resultsCount == 0 && val.length != 0 ) {
        $no_results.find('span').text(val);
        $no_results.show();
      } else {
        $no_results.hide();
      }
    }).trigger('keyup');
  }

  function inFilter(val, filter) {
    for (var i = 0; i < filter.length; i++) {
      if (filter[i].match(val)) return true;
    }
    return false;
  }

  // make code pretty
//  $('pre').addClass('prettyprint');
//  window.prettyPrint && prettyPrint();

  // Disable links with href="#" inside <section>, so users can click on them
  // to preview :active state without being scrolled up to the top of the page.
//  $('section a[href="#"]').click(function(e) {
//    e.preventDefault();
//    e.stopPropagation();
//  });

//  // inject twitter & github counts
//  $.ajax({
//    url: 'http://api.twitter.com/1/users/show.json',
//    data: {screen_name: 'fortaweso_me'},
//    dataType: 'jsonp',
//    success: function(data) {
//      $('#followers').html(data.followers_count);
//    }
//  });
//  $.ajax({
//    url: 'https://api.github.com/repos/fortawesome/Font-Awesome',
//    dataType: 'jsonp',
//    success: function(data) {
//      $('#watchers').html(data.data.watchers);
//      $('#forks').html(data.data.forks);
//    }
//  });
});
<|endoftext|>


<commit_before>var intercom = {
    loginUserWithUserAttributes: function(options, success, error) {
        cordova.exec(success, error, 'Intercom', 'loginUserWithUserAttributes', [options]);
    },

    loginUnidentifiedUser: function(options, success, error) {
        cordova.exec(success, error, 'Intercom', 'loginUnidentifiedUser', []);
    },

    logout: function(success, error) {
        cordova.exec(success, error, 'Intercom', 'logout', []);
    },

    setUserHash: function(secureHash, success, error) {
        cordova.exec(success, error, 'Intercom', 'setUserHash', [secureHash]);
    },

    updateUser: function(attributes, success, error) {
        cordova.exec(success, error, 'Intercom', 'updateUser', [attributes]);
    },

    logEvent: function(eventName, metaData, success, error) {
        cordova.exec(success, error, 'Intercom', 'logEvent', [eventName, metaData]);
    },

    displayMessenger: function(success, error) {
        cordova.exec(success, error, 'Intercom', 'displayMessenger', []);
    },

    displayMessageComposer: function(initialMessage, success, error) {
        cordova.exec(success, error, 'Intercom', 'displayMessageComposer', [initialMessage]);
    },

    displayHelpCenter: function(success, error) {
        cordova.exec(success, error, 'Intercom', 'displayHelpCenter', []);
    },

    fetchHelpCenterCollections: function(success, error) {
        cordova.exec(success, error, 'Intercom', 'fetchHelpCenterCollections', []);
    },

    searchHelpCenter: function(searchTerm, success, error) {
        cordova.exec(success, error, 'Intercom', 'searchHelpCenter', [searchTerm]);
    },

    fetchHelpCenterCollection: function(collectionId, success, error) {
        cordova.exec(success, error, 'Intercom', 'fetchHelpCenterCollection', [collectionId]);
    },

    displayHelpCenterCollections: function(collectionIds, success, error) {
            cordova.exec(success, error, 'Intercom', 'displayHelpCenterCollections', [collectionIds]);
    },

    unreadConversationCount: function(success, error) {
        cordova.exec(success, error, 'Intercom', 'unreadConversationCount', []);
    },

    VISIBLE : "VISIBLE",
    GONE    : "GONE",

    setLauncherVisibility: function(visibility, success, error) {
        cordova.exec(success, error, 'Intercom', 'setLauncherVisibility', [visibility]);
    },

    setInAppMessageVisibility: function(visibility, success, error) {
        cordova.exec(success, error, 'Intercom', 'setInAppMessageVisibility', [visibility]);
    },

    hideIntercom: function(success, error) {
        cordova.exec(success, error, 'Intercom', 'hideIntercom', []);
    },

    registerForPush: function(success, error) {
        cordova.exec(success, error, 'Intercom', 'registerForPush', []);
    },

    sendPushTokenToIntercom: function(token, success, error) {
        cordova.exec(success, error, 'Intercom', 'sendPushTokenToIntercom', [token]);
    },

    displayCarousel: function(carouselId, success, error) {
        cordova.exec(success, error, 'Intercom', 'displayCarousel', [carouselId]);
    },

    displayArticle: function(articleId, success, error) {
        cordova.exec(success, error, 'Intercom', 'displayArticle', [articleId]);
    },

    displaySurvey: function(surveyId, success, error) {
        cordova.exec(success, error, 'Intercom', 'displaySurvey', [surveyId]);
    },

    setBottomPadding: function(bottomPadding, success, error) {
        cordova.exec(success, error, 'Intercom', 'setBottomPadding', [bottomPadding]);
    }
}

module.exports = intercom;
<commit_msg>Update intercom.js<commit_after>var intercom = {

    registerIdentifiedUser: function(options, success, error) {
        cordova.exec(success, error, 'Intercom', 'loginUserWithUserAttributes', [options]);
        console.warn('registerIdentifiedUser() is deprecated and will be removed in a future release. Please use loginUserWithUserAttributes()');
    },

    loginUserWithUserAttributes: function(options, success, error) {
        cordova.exec(success, error, 'Intercom', 'loginUserWithUserAttributes', [options]);
    },

    registerUnidentifiedUser: function(options, success, error) {
        cordova.exec(success, error, 'Intercom', 'loginUnidentifiedUser', []);
        console.warn('registerUnidentifiedUser() is deprecated and will be removed in a future release. Please use loginUnidentifiedUser()');
    },

    loginUnidentifiedUser: function(options, success, error) {
        cordova.exec(success, error, 'Intercom', 'loginUnidentifiedUser', []);
    },

    reset: function(success, error) {
        cordova.exec(success, error, 'Intercom', 'logout', []);
        console.warn('reset() is deprecated and will be removed in a future release. Please use logout()');
    },

    logout: function(success, error) {
        cordova.exec(success, error, 'Intercom', 'logout', []);
    },

    setUserHash: function(secureHash, success, error) {
        cordova.exec(success, error, 'Intercom', 'setUserHash', [secureHash]);
    },

    updateUser: function(attributes, success, error) {
        cordova.exec(success, error, 'Intercom', 'updateUser', [attributes]);
    },

    logEvent: function(eventName, metaData, success, error) {
        cordova.exec(success, error, 'Intercom', 'logEvent', [eventName, metaData]);
    },

    displayMessenger: function(success, error) {
        cordova.exec(success, error, 'Intercom', 'displayMessenger', []);
    },

    displayMessageComposer: function(success, error) {
        cordova.exec(success, error, 'Intercom', 'displayMessageComposer', []);
        console.warn('displayMessageComposer() is deprecated and will be removed in a future release. Please use displayMessageComposer(initialMessage)')
    },

    displayMessageComposerWithInitialMessage: function(initialMessage, success, error) {
        cordova.exec(success, error, 'Intercom', 'displayMessageComposer', [initialMessage]);
        console.warn('displayMessageComposerWithInitialMessage(initialMessage) is deprecated and will be removed in a future release. Please use displayMessageComposer(initialMessage)')
    },

    displayMessageComposer: function(initialMessage, success, error) {
        cordova.exec(success, error, 'Intercom', 'displayMessageComposer', [initialMessage]);
    },

    displayHelpCenter: function(success, error) {
        cordova.exec(success, error, 'Intercom', 'displayHelpCenter', []);
    },

    fetchHelpCenterCollections: function(success, error) {
        cordova.exec(success, error, 'Intercom', 'fetchHelpCenterCollections', []);
    },

    searchHelpCenter: function(searchTerm, success, error) {
        cordova.exec(success, error, 'Intercom', 'searchHelpCenter', [searchTerm]);
    },

    fetchHelpCenterCollection: function(collectionId, success, error) {
        cordova.exec(success, error, 'Intercom', 'fetchHelpCenterCollection', [collectionId]);
    },

    displayHelpCenterCollections: function(collectionIds, success, error) {
            cordova.exec(success, error, 'Intercom', 'displayHelpCenterCollections', [collectionIds]);
    },

    unreadConversationCount: function(success, error) {
        cordova.exec(success, error, 'Intercom', 'unreadConversationCount', []);
    },

    VISIBLE : "VISIBLE",
    GONE    : "GONE",

    setLauncherVisibility: function(visibility, success, error) {
        cordova.exec(success, error, 'Intercom', 'setLauncherVisibility', [visibility]);
    },

    setInAppMessageVisibility: function(visibility, success, error) {
        cordova.exec(success, error, 'Intercom', 'setInAppMessageVisibility', [visibility]);
    },

    hideIntercom: function(success, error) {
        cordova.exec(success, error, 'Intercom', 'hideIntercom', []);
    },

    registerForPush: function(success, error) {
        cordova.exec(success, error, 'Intercom', 'registerForPush', []);
    },

    sendPushTokenToIntercom: function(token, success, error) {
        cordova.exec(success, error, 'Intercom', 'sendPushTokenToIntercom', [token]);
    },

    displayCarousel: function(carouselId, success, error) {
        cordova.exec(success, error, 'Intercom', 'displayCarousel', [carouselId]);
    },

    displayArticle: function(articleId, success, error) {
        cordova.exec(success, error, 'Intercom', 'displayArticle', [articleId]);
    },

    displaySurvey: function(surveyId, success, error) {
        cordova.exec(success, error, 'Intercom', 'displaySurvey', [surveyId]);
    },

    setBottomPadding: function(bottomPadding, success, error) {
        cordova.exec(success, error, 'Intercom', 'setBottomPadding', [bottomPadding]);
    }
}

module.exports = intercom;
<|endoftext|>


<commit_before>import { mount } from '@vue/test-utils';
import ChannelEditor from './../../views/ChannelEditor.vue';
import { localStore, mockFunctions } from './../data.js';
require('handlebars/helpers'); // Needed for image uploader

let testChannel = {
  'name': 'channel',
  'description': "description",
  'language': 'en',
}

function makeWrapper(props = {}) {
  let testChannel = {
    ...testChannel,
    ...props
  }
  localStore.commit('channel_list/SET_ACTIVE_CHANNEL', testChannel)
  return mount(ChannelEditor, {
    store: localStore
  })
}

describe('channelMetadataSection', () => {
  let wrapper;
  beforeEach(() => {
    wrapper = makeWrapper();
  });

  describe('on load', () => {
    it('changed is false', () => {
      expect(wrapper.vm.changed).toBe(false);
    });
    it('thumbnail is shown', () => {
      let thumbnailWrapper = makeWrapper({'thumbnail_url': 'thumbnail.png'})
      thumbnailWrapper.vm.$nextTick(() => {
        expect(thumbnailWrapper.find('img').attributes('src')).toContain('thumbnail.png')
      })
    });
    it('default thumbnail is shown if channel has no thumbnail', () => {
      wrapper.vm.$nextTick(() => {
        expect(wrapper.find('img').attributes('src')).toContain('kolibri_placeholder.png')
      })
    });
    it('.channel-name is set to channel.name', () => {
      expect(wrapper.find('.channel-name').element.value).toEqual(testChannel.name);
    });
    it('.channel-description is set to channel.description', () => {
      expect(wrapper.find('.channel-description').element.value).toEqual(testChannel.description);
    });
    it('#select-language is set to channel.language_id', () => {
      expect(wrapper.find('#select-language').element.value).toEqual(testChannel.language);
    });
  })
  describe('changes registered', () => {
    it('setChannelThumbnail sets channel.thumbnail', () => {
      let thumbnail = 'newthumbnail.png'
      wrapper.vm.setChannelThumbnail(thumbnail, {'new encoding': thumbnail}, thumbnail, thumbnail)
      expect(wrapper.vm.changed).toBe(true);
      expect(wrapper.vm.channel.thumbnail).toEqual(thumbnail);
      expect(wrapper.vm.channel.thumbnail_encoding).toEqual({'new encoding': thumbnail});
    });
    it('removeChannelThumbnail removes channel.thumbnail', () => {
      let thumbnailWrapper = makeWrapper({'thumbnail': 'thumbnail.png', 'thumbnail_encoding': {'test': 'test'}})
      thumbnailWrapper.vm.removeChannelThumbnail();
      expect(wrapper.vm.changed).toBe(true);
      expect(wrapper.vm.channel.thumbnail).toEqual("");
      expect(wrapper.vm.channel.thumbnail_encoding).toEqual({});
    });
    it('typing in .channel-name sets channel.name', () => {
      let nameInput = wrapper.find('.channel-name');
      nameInput.element.value = 'new channel name';
      nameInput.trigger('input');
      expect(wrapper.vm.changed).toBe(true);
      expect(wrapper.vm.channel.name).toEqual('new channel name');
    });
    it('setting .channel-description sets channel.description', () => {
      let descriptionInput = wrapper.find('.channel-description');
      descriptionInput.element.value = 'new channel description';
      descriptionInput.trigger('input');
      expect(wrapper.vm.changed).toBe(true);
      expect(wrapper.vm.channel.description).toEqual('new channel description');
    });
    it('setting #select-language sets channel.language_id', () => {
      expect(true).toBeTruthy();
    });
  })

  it('clicking CANCEL cancels edits', () => {
    let nameInput = wrapper.find('.channel-name');
    nameInput.element.value = 'new channel name';
    nameInput.trigger('input');

    // Cancel changes
    wrapper.find(".cancel-edits").trigger('click');
    expect(wrapper.vm.changed).toBe(false);
    expect(wrapper.vm.channel.name).toEqual('channel');
    expect(wrapper.emitted().cancelEdit).toBeTruthy();
  });

  it('clicking SAVE saves edits', () => {
    wrapper.find('.save-channel').trigger('click');
    expect(mockFunctions.saveChannel).toHaveBeenCalled();
    wrapper.vm.$nextTick(() => {
      expect(wrapper.emitted('submitChanges')).toBeTruthy();
    });
  });
});
<commit_msg>Fixed test<commit_after>import { mount } from '@vue/test-utils';
import ChannelEditor from './../../views/ChannelEditor.vue';
import { localStore, mockFunctions } from './../data.js';
require('handlebars/helpers'); // Needed for image uploader

let testChannel = {
  'name': 'channel',
  'description': "description",
  'language': 'en',
}

function makeWrapper(props = {}) {
  localStore.commit('channel_list/SET_ACTIVE_CHANNEL', {
    ...testChannel,
    ...props
  })
  return mount(ChannelEditor, {
    store: localStore
  })
}

describe('channelMetadataSection', () => {
  let wrapper;
  beforeEach(() => {
    wrapper = makeWrapper();
  });

  describe('on load', () => {
    it('changed is false', () => {
      expect(wrapper.vm.changed).toBe(false);
    });
    it('thumbnail is shown', () => {
      let thumbnailWrapper = makeWrapper({'thumbnail_url': 'thumbnail.png'})
      thumbnailWrapper.vm.$nextTick(() => {
        expect(thumbnailWrapper.find('img').attributes('src')).toContain('thumbnail.png')
      })
    });
    it('default thumbnail is shown if channel has no thumbnail', () => {
      wrapper.vm.$nextTick(() => {
        expect(wrapper.find('img').attributes('src')).toContain('kolibri_placeholder.png')
      })
    });
    it('.channel-name is set to channel.name', () => {
      expect(wrapper.find('.channel-name').element.value).toEqual(testChannel.name);
    });
    it('.channel-description is set to channel.description', () => {
      expect(wrapper.find('.channel-description').element.value).toEqual(testChannel.description);
    });
    it('#select-language is set to channel.language_id', () => {
      expect(wrapper.find('#select-language').element.value).toEqual(testChannel.language);
    });
  })
  describe('changes registered', () => {
    it('setChannelThumbnail sets channel.thumbnail', () => {
      let thumbnail = 'newthumbnail.png'
      wrapper.vm.setChannelThumbnail(thumbnail, {'new encoding': thumbnail}, thumbnail, thumbnail)
      expect(wrapper.vm.changed).toBe(true);
      expect(wrapper.vm.channel.thumbnail).toEqual(thumbnail);
      expect(wrapper.vm.channel.thumbnail_encoding).toEqual({'new encoding': thumbnail});
    });
    it('removeChannelThumbnail removes channel.thumbnail', () => {
      let thumbnailWrapper = makeWrapper({'thumbnail': 'thumbnail.png', 'thumbnail_encoding': {'test': 'test'}})
      thumbnailWrapper.vm.removeChannelThumbnail();
      expect(wrapper.vm.changed).toBe(true);
      expect(wrapper.vm.channel.thumbnail).toEqual("");
      expect(wrapper.vm.channel.thumbnail_encoding).toEqual({});
    });
    it('typing in .channel-name sets channel.name', () => {
      let nameInput = wrapper.find('.channel-name');
      nameInput.element.value = 'new channel name';
      nameInput.trigger('input');
      expect(wrapper.vm.changed).toBe(true);
      expect(wrapper.vm.channel.name).toEqual('new channel name');
    });
    it('setting .channel-description sets channel.description', () => {
      let descriptionInput = wrapper.find('.channel-description');
      descriptionInput.element.value = 'new channel description';
      descriptionInput.trigger('input');
      expect(wrapper.vm.changed).toBe(true);
      expect(wrapper.vm.channel.description).toEqual('new channel description');
    });
    it('setting #select-language sets channel.language_id', () => {
      expect(true).toBeTruthy();
    });
  })

  it('clicking CANCEL cancels edits', () => {
    let nameInput = wrapper.find('.channel-name');
    nameInput.element.value = 'new channel name';
    nameInput.trigger('input');

    // Cancel changes
    wrapper.find(".cancel-edits").trigger('click');
    expect(wrapper.vm.changed).toBe(false);
    expect(wrapper.vm.channel.name).toEqual('channel');
    expect(wrapper.emitted().cancelEdit).toBeTruthy();
  });

  it('clicking SAVE saves edits', () => {
    wrapper.find('.save-channel').trigger('click');
    expect(mockFunctions.saveChannel).toHaveBeenCalled();
    wrapper.vm.$nextTick(() => {
      expect(wrapper.emitted('submitChanges')).toBeTruthy();
    });
  });
});
<|endoftext|>


<commit_before>import React from 'react'
import { Scrollbars } from 'react-custom-scrollbars-2'

import styled from 'styled'
import { Page, Section, ActionButton } from 'components'
import { ArrowForward, FileDownload } from 'icons'
import cover from './cover.jpg'
import './styles.css'
import apps from './data'

const matchDimensions = str => {
  const regex = /r(\d+)x(\d+)/g
  const matches = regex.exec(str)
  return matches && matches.slice(1, 3).map(x => +x)
}

const dimensions = str => {
  const matches = matchDimensions(str)

  const baseHeight = 400

  let scaledWidth = 240
  let scaledHeight = baseHeight

  if (matches) {
    const width = matches[0]
    const height = matches[1]
    scaledWidth = (width / height) * baseHeight
    scaledHeight = baseHeight
  }
  return {
    width: scaledWidth,
    height: scaledHeight
  }
}

const totalWidth = entries => {
  const widths = entries.map(entry => dimensions(entry[0]).width + 8)
  const sum = widths.reduce((acc, curr) => acc + curr, 32 - 8)
  return sum
}

const AppsPage = () => (
  <Page
    Apps
    title="Apps - Przemysław Zalewski - Ciunkos"
    description="Sandtime.io, Promegle, Testy Prawo Jazdy, Store ᴾᴿᴼ, MusicTube and more..."
  >

Apps

          ))}
        </styled.AppList>

    {Object.values(apps).map(app => (

            </styled.AppHeader>

{app.description}

        {app.screenshots && (

                ))}

              </styled.Screenshots>
            </Scrollbars>
          </styled.ScreenshotsView>
        )}

        {app.link ? (
          <ActionButton
            download={app.download}
            href={app.link}
            icon={app.download ? <FileDownload /> : <ArrowForward />}
            name={app.label || 'See more'}
            rel="noopener noreferrer"
            target="_blank"
          />
        ) : (

        )}

    ))}
  </Page>
)

export default AppsPage
<commit_msg>Enable lazy apps images loading<commit_after>import React from 'react'
import { Scrollbars } from 'react-custom-scrollbars-2'

import styled from 'styled'
import { Page, Section, ActionButton } from 'components'
import { ArrowForward, FileDownload } from 'icons'
import cover from './cover.jpg'
import './styles.css'
import apps from './data'

const matchDimensions = str => {
  const regex = /r(\d+)x(\d+)/g
  const matches = regex.exec(str)
  return matches && matches.slice(1, 3).map(x => +x)
}

const dimensions = str => {
  const matches = matchDimensions(str)

  const baseHeight = 400

  let scaledWidth = 240
  let scaledHeight = baseHeight

  if (matches) {
    const width = matches[0]
    const height = matches[1]
    scaledWidth = (width / height) * baseHeight
    scaledHeight = baseHeight
  }
  return {
    width: scaledWidth,
    height: scaledHeight
  }
}

const totalWidth = entries => {
  const widths = entries.map(entry => dimensions(entry[0]).width + 8)
  const sum = widths.reduce((acc, curr) => acc + curr, 32 - 8)
  return sum
}

const AppsPage = () => (
  <Page
    Apps
    title="Apps - Przemysław Zalewski - Ciunkos"
    description="Sandtime.io, Promegle, Testy Prawo Jazdy, Store ᴾᴿᴼ, MusicTube and more..."
  >

Apps

          ))}
        </styled.AppList>

    {Object.values(apps).map(app => (

            </styled.AppHeader>

{app.description}

        {app.screenshots && (

                ))}

              </styled.Screenshots>
            </Scrollbars>
          </styled.ScreenshotsView>
        )}

        {app.link ? (
          <ActionButton
            download={app.download}
            href={app.link}
            icon={app.download ? <FileDownload /> : <ArrowForward />}
            name={app.label || 'See more'}
            rel="noopener noreferrer"
            target="_blank"
          />
        ) : (

        )}

    ))}
  </Page>
)

export default AppsPage
<|endoftext|>


<commit_before>export default function(area) {
  return function (data) {
    var x = area.x();
    var y0 = area.y0();
    var y1 = area.y1();

    console.log(this.getBBox()) // We can measure the text aspect ratio from here.
    console.log(data) // We can access the area polygon from here, with `area`

    var d = data[0];
    console.log(x(d), y0(d), y1(d));

    // This is how we could set the x, y, and font-size
    d3.select(this)
      .attr('x', 300 + Math.random() * 200)
      .attr('y', 200 + Math.random() * 200)
      .attr('font-size', Math.random() * 40 + 'px');
  }
};
<commit_msg>Sketch out bits of the algorithm<commit_after>function getAspectRatio(textNode) {
  var box = textNode.getBBox();
  return box.width / box.height;
}

export default function(area) {
  var x = area.x();
  var y0 = area.y0();
  var y1 = area.y1();
  var bisectorX = d3.bisector(x);

  // Returns true if there is at least one rectangle
  // of the given aspect ratio and scale
  // that fits somewhere within the area.
  function fits(data, aspect, scale) {
    var x0,
        x1,
        i0,
        i1,
        j,
        d,
        top,
        bottom,
        width = scale * aspect,
        height = scale / aspect;

    for(i0 = 0; i0 < data.length; i0++) {
      d = data[i0];
      x0 = x(d);
      x1 = x0 + width;
      i1 = bisectorX.right(data, x1);

      console.log("width " + width);
      console.log("height " + height);
      console.log("x0 " + x0);
      console.log("x1 " + x1);
      console.log("i0 " + i0);
      console.log("i1 " + i1);

      // TODO compute top and bottom,
      // TODO return true if (top-bottom) <= height
      //if(test(data, x0, x1, h
      //top = y0(d);
      //bottom = y1(d);
      //j = i;
      //while(x(d) < x1 && j < data.length) {
      //  d = data[j]
      //  j++;
      //}

      return false;
    }
  }

  return function (data) {
    var aspect = getAspectRatio(this);
    var scale = 5;

    console.log(fits(data, aspect, scale));

    //var d = data[0];
    //console.log(x(d), y0(d), y1(d));

    // This is how we could set the x, y, and font-size
    d3.select(this)
      .attr('x', 300 + Math.random() * 200)
      .attr('y', 200 + Math.random() * 200)
      .attr('font-size', Math.random() * 40 + 'px');
  }
};
<|endoftext|>


<commit_before>function xconcat () {
  var arg
  var len = arguments.length
  var i = -1
  var target = []

  while (++i < len) {
    arg = arguments[i]
    if (!arg) continue

    target[i] = arg
  }

  return target
}

module.exports = xconcat<commit_msg>lint array/xcat — lint testing over<commit_after>function xconcat () {
  var arg
  var len = arguments.length
  var i = -1
  var target = []

  while (++i < len) {
    arg = arguments[i]
    if (!arg) continue

    target[i] = arg
  }

  return target
}

module.exports = xconcat
<|endoftext|>