<commit_before>/* eslint no-param-reassign: "off" */
import $ from '../../utils/dom';
import { extend, now, deleteProps } from '../../utils/utils';
import { getSupport } from '../../utils/get-support';
import { getDevice } from '../../utils/get-device';
import { getBrowser } from '../../utils/get-browser';

import modular from './modular';
import eventsEmitter from './events-emitter';

import update from './update/index';
import translate from './translate/index';
import transition from './transition/index';
import slide from './slide/index';
import loop from './loop/index';
import grabCursor from './grab-cursor/index';
import manipulation from './manipulation/index';
import events from './events/index';
import breakpoints from './breakpoints/index';
import classes from './classes/index';
import images from './images/index';
import checkOverflow from './check-overflow/index';

import defaults from './defaults';

const prototypes = {
  modular,
  eventsEmitter,
  update,
  translate,
  transition,
  slide,
  loop,
  grabCursor,
  manipulation,
  events,
  breakpoints,
  checkOverflow,
  classes,
  images,
};

const extendedDefaults = {};

class Swiper {
  constructor(...args) {
    let el;
    let params;
    if (args.length === 1 && args[0].constructor && args[0].constructor === Object) {
      params = args[0];
    } else {
      [el, params] = args;
    }
    if (!params) params = {};

    params = extend({}, params);
    if (el && !params.el) params.el = el;

    // Swiper Instance
    const swiper = this;
    swiper.support = getSupport();
    swiper.device = getDevice({ userAgent: params.userAgent });
    swiper.browser = getBrowser();

    swiper.eventsListeners = {};
    swiper.eventsAnyListeners = [];

    Object.keys(prototypes).forEach((prototypeGroup) => {
      Object.keys(prototypes[prototypeGroup]).forEach((protoMethod) => {
        if (!Swiper.prototype[protoMethod]) {
          Swiper.prototype[protoMethod] = prototypes[prototypeGroup][protoMethod];
        }
      });
    });

    if (typeof swiper.modules === 'undefined') {
      swiper.modules = {};
    }
    Object.keys(swiper.modules).forEach((moduleName) => {
      const module = swiper.modules[moduleName];
      if (module.params) {
        const moduleParamName = Object.keys(module.params)[0];
        const moduleParams = module.params[moduleParamName];
        if (typeof moduleParams !== 'object' || moduleParams === null) return;
        if (!(moduleParamName in params && 'enabled' in moduleParams)) return;
        if (params[moduleParamName] === true) {
          params[moduleParamName] = { enabled: true };
        }
        if (
          typeof params[moduleParamName] === 'object' &&
          !('enabled' in params[moduleParamName])
        ) {
          params[moduleParamName].enabled = true;
        }
        if (!params[moduleParamName]) params[moduleParamName] = { enabled: false };
      }
    });

    // Extend defaults with modules params
    const swiperParams = extend({}, defaults);
    swiper.useParams(swiperParams);

    // Extend defaults with passed params
    swiper.params = extend({}, swiperParams, extendedDefaults, params);
    swiper.originalParams = extend({}, swiper.params);
    swiper.passedParams = extend({}, params);

    // add event listeners
    if (swiper.params && swiper.params.on) {
      Object.keys(swiper.params.on).forEach((eventName) => {
        swiper.on(eventName, swiper.params.on[eventName]);
      });
    }

    // Save Dom lib
    swiper.$ = $;

    // Find el
    const $el = $(swiper.params.el);
    el = $el[0];

    if (!el) {
      return undefined;
    }

    if ($el.length > 1) {
      const swipers = [];
      $el.each((containerEl) => {
        const newParams = extend({}, params, { el: containerEl });
        swipers.push(new Swiper(newParams));
      });
      return swipers;
    }

    el.swiper = swiper;

    // Find Wrapper
    let $wrapperEl;
    if (el && el.shadowRoot && el.shadowRoot.querySelector) {
      $wrapperEl = $(el.shadowRoot.querySelector(`.${swiper.params.wrapperClass}`));
      // Children needs to return slot items
      $wrapperEl.children = (options) => $el.children(options);
    } else {
      $wrapperEl = $el.children(`.${swiper.params.wrapperClass}`);
    }
    // Extend Swiper
    extend(swiper, {
      $el,
      el,
      $wrapperEl,
      wrapperEl: $wrapperEl[0],

      // Classes
      classNames: [],

      // Slides
      slides: $(),
      slidesGrid: [],
      snapGrid: [],
      slidesSizesGrid: [],

      // isDirection
      isHorizontal() {
        return swiper.params.direction === 'horizontal';
      },
      isVertical() {
        return swiper.params.direction === 'vertical';
      },
      // RTL
      rtl: el.dir.toLowerCase() === 'rtl' || $el.css('direction') === 'rtl',
      rtlTranslate:
        swiper.params.direction === 'horizontal' &&
        (el.dir.toLowerCase() === 'rtl' || $el.css('direction') === 'rtl'),
      wrongRTL: $wrapperEl.css('display') === '-webkit-box',

      // Indexes
      activeIndex: 0,
      realIndex: 0,

      //
      isBeginning: true,
      isEnd: false,

      // Props
      translate: 0,
      previousTranslate: 0,
      progress: 0,
      velocity: 0,
      animating: false,

      // Locks
      allowSlideNext: swiper.params.allowSlideNext,
      allowSlidePrev: swiper.params.allowSlidePrev,

      // Touch Events
      touchEvents: (function touchEvents() {
        const touch = ['touchstart', 'touchmove', 'touchend', 'touchcancel'];
        let desktop = ['mousedown', 'mousemove', 'mouseup'];
        if (swiper.support.pointerEvents) {
          desktop = ['pointerdown', 'pointermove', 'pointerup'];
        }
        swiper.touchEventsTouch = {
          start: touch[0],
          move: touch[1],
          end: touch[2],
          cancel: touch[3],
        };
        swiper.touchEventsDesktop = {
          start: desktop[0],
          move: desktop[1],
          end: desktop[2],
        };
        return swiper.support.touch || !swiper.params.simulateTouch
          ? swiper.touchEventsTouch
          : swiper.touchEventsDesktop;
      })(),
      touchEventsData: {
        isTouched: undefined,
        isMoved: undefined,
        allowTouchCallbacks: undefined,
        touchStartTime: undefined,
        isScrolling: undefined,
        currentTranslate: undefined,
        startTranslate: undefined,
        allowThresholdMove: undefined,
        // Form elements to match
        formElements: 'input, select, option, textarea, button, video, label',
        // Last click time
        lastClickTime: now(),
        clickTimeout: undefined,
        // Velocities
        velocities: [],
        allowMomentumBounce: undefined,
        isTouchEvent: undefined,
        startMoving: undefined,
      },

      // Clicks
      allowClick: true,

      // Touches
      allowTouchMove: swiper.params.allowTouchMove,

      touches: {
        startX: 0,
        startY: 0,
        currentX: 0,
        currentY: 0,
        diff: 0,
      },

      // Images
      imagesToLoad: [],
      imagesLoaded: 0,
    });

    // Install Modules
    swiper.useModules();

    swiper.emit('_swiper', swiper);

    // Init
    if (swiper.params.init) {
      swiper.init();
    }

    // Return app instance
    return swiper;
  }

  emitContainerClasses() {
    const swiper = this;
    if (!swiper.params._emitClasses || !swiper.el) return;
    swiper.emit('_containerClasses', swiper.el.className);
  }

  emitSlidesClasses() {
    const swiper = this;
    if (!swiper.params._emitClasses || !swiper.el) return;
    swiper.slides.each((slideEl) => {
      swiper.emit('_slideClass', slideEl, slideEl.className);
    });
  }

  slidesPerViewDynamic() {
    const swiper = this;
    const { params, slides, slidesGrid, size: swiperSize, activeIndex } = swiper;
    let spv = 1;
    if (params.centeredSlides) {
      let slideSize = slides[activeIndex].swiperSlideSize;
      let breakLoop;
      for (let i = activeIndex + 1; i < slides.length; i += 1) {
        if (slides[i] && !breakLoop) {
          slideSize += slides[i].swiperSlideSize;
          spv += 1;
          if (slideSize > swiperSize) breakLoop = true;
        }
      }
      for (let i = activeIndex - 1; i >= 0; i -= 1) {
        if (slides[i] && !breakLoop) {
          slideSize += slides[i].swiperSlideSize;
          spv += 1;
          if (slideSize > swiperSize) breakLoop = true;
        }
      }
    } else {
      for (let i = activeIndex + 1; i < slides.length; i += 1) {
        if (slidesGrid[i] - slidesGrid[activeIndex] < swiperSize) {
          spv += 1;
        }
      }
    }
    return spv;
  }

  update() {
    const swiper = this;
    if (!swiper || swiper.destroyed) return;
    const { snapGrid, params } = swiper;
    // Breakpoints
    if (params.breakpoints) {
      swiper.setBreakpoint();
    }
    swiper.updateSize();
    swiper.updateSlides();
    swiper.updateProgress();
    swiper.updateSlidesClasses();

    function setTranslate() {
      const translateValue = swiper.rtlTranslate ? swiper.translate * -1 : swiper.translate;
      const newTranslate = Math.min(
        Math.max(translateValue, swiper.maxTranslate()),
        swiper.minTranslate(),
      );
      swiper.setTranslate(newTranslate);
      swiper.updateActiveIndex();
      swiper.updateSlidesClasses();
    }
    let translated;
    if (swiper.params.freeMode) {
      setTranslate();
      if (swiper.params.autoHeight) {
        swiper.updateAutoHeight();
      }
    } else {
      if (
        (swiper.params.slidesPerView === 'auto' || swiper.params.slidesPerView > 1) &&
        swiper.isEnd &&
        !swiper.params.centeredSlides
      ) {
        translated = swiper.slideTo(swiper.slides.length - 1, 0, false, true);
      } else {
        translated = swiper.slideTo(swiper.activeIndex, 0, false, true);
      }
      if (!translated) {
        setTranslate();
      }
    }
    if (params.watchOverflow && snapGrid !== swiper.snapGrid) {
      swiper.checkOverflow();
    }
    swiper.emit('update');
  }

  changeDirection(newDirection, needUpdate = true) {
    const swiper = this;
    const currentDirection = swiper.params.direction;
    if (!newDirection) {
      // eslint-disable-next-line
      newDirection = currentDirection === 'horizontal' ? 'vertical' : 'horizontal';
    }
    if (
      newDirection === currentDirection ||
      (newDirection !== 'horizontal' && newDirection !== 'vertical')
    ) {
      return swiper;
    }

    swiper.$el
      .removeClass(`${swiper.params.containerModifierClass}${currentDirection}`)
      .addClass(`${swiper.params.containerModifierClass}${newDirection}`);
    swiper.emitContainerClasses();

    swiper.params.direction = newDirection;

    swiper.slides.each((slideEl) => {
      if (newDirection === 'vertical') {
        slideEl.style.width = '';
      } else {
        slideEl.style.height = '';
      }
    });

    swiper.emit('changeDirection');
    if (needUpdate) swiper.update();

    return swiper;
  }

  init() {
    const swiper = this;
    if (swiper.initialized) return;

    swiper.emit('beforeInit');

    // Set breakpoint
    if (swiper.params.breakpoints) {
      swiper.setBreakpoint();
    }

    // Add Classes
    swiper.addClasses();

    // Create loop
    if (swiper.params.loop) {
      swiper.loopCreate();
    }

    // Update size
    swiper.updateSize();

    // Update slides
    swiper.updateSlides();

    if (swiper.params.watchOverflow) {
      swiper.checkOverflow();
    }

    // Set Grab Cursor
    if (swiper.params.grabCursor) {
      swiper.setGrabCursor();
    }

    if (swiper.params.preloadImages) {
      swiper.preloadImages();
    }

    // Slide To Initial Slide
    if (swiper.params.loop) {
      swiper.slideTo(
        swiper.params.initialSlide + swiper.loopedSlides,
        0,
        swiper.params.runCallbacksOnInit,
      );
    } else {
      swiper.slideTo(swiper.params.initialSlide, 0, swiper.params.runCallbacksOnInit);
    }

    // Attach events
    swiper.attachEvents();

    // Init Flag
    swiper.initialized = true;

    // Emit
    swiper.emit('init');
  }

  destroy(deleteInstance = true, cleanStyles = true) {
    const swiper = this;
    const { params, $el, $wrapperEl, slides } = swiper;

    if (typeof swiper.params === 'undefined' || swiper.destroyed) {
      return null;
    }

    swiper.emit('beforeDestroy');

    // Init Flag
    swiper.initialized = false;

    // Detach events
    swiper.detachEvents();

    // Destroy loop
    if (params.loop) {
      swiper.loopDestroy();
    }

    // Cleanup styles
    if (cleanStyles) {
      swiper.removeClasses();
      $el.removeAttr('style');
      $wrapperEl.removeAttr('style');
      if (slides && slides.length) {
        slides
          .removeClass(
            [
              params.slideVisibleClass,
              params.slideActiveClass,
              params.slideNextClass,
              params.slidePrevClass,
            ].join(' '),
          )
          .removeAttr('style')
          .removeAttr('data-swiper-slide-index');
      }
    }

    swiper.emit('destroy');

    // Detach emitter events
    Object.keys(swiper.eventsListeners).forEach((eventName) => {
      swiper.off(eventName);
    });

    if (deleteInstance !== false) {
      swiper.$el[0].swiper = null;
      deleteProps(swiper);
    }
    swiper.destroyed = true;

    return null;
  }

  static extendDefaults(newDefaults) {
    extend(extendedDefaults, newDefaults);
  }

  static get extendedDefaults() {
    return extendedDefaults;
  }

  static get defaults() {
    return defaults;
  }

  static installModule(module) {
    if (!Swiper.prototype.modules) Swiper.prototype.modules = {};
    const name = module.name || `${Object.keys(Swiper.prototype.modules).length}_${now()}`;
    Swiper.prototype.modules[name] = module;
  }

  static use(module) {
    if (Array.isArray(module)) {
      module.forEach((m) => Swiper.installModule(m));
      return Swiper;
    }
    Swiper.installModule(module);
    return Swiper;
  }
}

export default Swiper;
<commit_msg>Core: Emit only related classes<commit_after>/* eslint no-param-reassign: "off" */
import $ from '../../utils/dom';
import { extend, now, deleteProps } from '../../utils/utils';
import { getSupport } from '../../utils/get-support';
import { getDevice } from '../../utils/get-device';
import { getBrowser } from '../../utils/get-browser';

import modular from './modular';
import eventsEmitter from './events-emitter';

import update from './update/index';
import translate from './translate/index';
import transition from './transition/index';
import slide from './slide/index';
import loop from './loop/index';
import grabCursor from './grab-cursor/index';
import manipulation from './manipulation/index';
import events from './events/index';
import breakpoints from './breakpoints/index';
import classes from './classes/index';
import images from './images/index';
import checkOverflow from './check-overflow/index';

import defaults from './defaults';

const prototypes = {
  modular,
  eventsEmitter,
  update,
  translate,
  transition,
  slide,
  loop,
  grabCursor,
  manipulation,
  events,
  breakpoints,
  checkOverflow,
  classes,
  images,
};

const extendedDefaults = {};

class Swiper {
  constructor(...args) {
    let el;
    let params;
    if (args.length === 1 && args[0].constructor && args[0].constructor === Object) {
      params = args[0];
    } else {
      [el, params] = args;
    }
    if (!params) params = {};

    params = extend({}, params);
    if (el && !params.el) params.el = el;

    // Swiper Instance
    const swiper = this;
    swiper.support = getSupport();
    swiper.device = getDevice({ userAgent: params.userAgent });
    swiper.browser = getBrowser();

    swiper.eventsListeners = {};
    swiper.eventsAnyListeners = [];

    Object.keys(prototypes).forEach((prototypeGroup) => {
      Object.keys(prototypes[prototypeGroup]).forEach((protoMethod) => {
        if (!Swiper.prototype[protoMethod]) {
          Swiper.prototype[protoMethod] = prototypes[prototypeGroup][protoMethod];
        }
      });
    });

    if (typeof swiper.modules === 'undefined') {
      swiper.modules = {};
    }
    Object.keys(swiper.modules).forEach((moduleName) => {
      const module = swiper.modules[moduleName];
      if (module.params) {
        const moduleParamName = Object.keys(module.params)[0];
        const moduleParams = module.params[moduleParamName];
        if (typeof moduleParams !== 'object' || moduleParams === null) return;
        if (!(moduleParamName in params && 'enabled' in moduleParams)) return;
        if (params[moduleParamName] === true) {
          params[moduleParamName] = { enabled: true };
        }
        if (
          typeof params[moduleParamName] === 'object' &&
          !('enabled' in params[moduleParamName])
        ) {
          params[moduleParamName].enabled = true;
        }
        if (!params[moduleParamName]) params[moduleParamName] = { enabled: false };
      }
    });

    // Extend defaults with modules params
    const swiperParams = extend({}, defaults);
    swiper.useParams(swiperParams);

    // Extend defaults with passed params
    swiper.params = extend({}, swiperParams, extendedDefaults, params);
    swiper.originalParams = extend({}, swiper.params);
    swiper.passedParams = extend({}, params);

    // add event listeners
    if (swiper.params && swiper.params.on) {
      Object.keys(swiper.params.on).forEach((eventName) => {
        swiper.on(eventName, swiper.params.on[eventName]);
      });
    }

    // Save Dom lib
    swiper.$ = $;

    // Find el
    const $el = $(swiper.params.el);
    el = $el[0];

    if (!el) {
      return undefined;
    }

    if ($el.length > 1) {
      const swipers = [];
      $el.each((containerEl) => {
        const newParams = extend({}, params, { el: containerEl });
        swipers.push(new Swiper(newParams));
      });
      return swipers;
    }

    el.swiper = swiper;

    // Find Wrapper
    let $wrapperEl;
    if (el && el.shadowRoot && el.shadowRoot.querySelector) {
      $wrapperEl = $(el.shadowRoot.querySelector(`.${swiper.params.wrapperClass}`));
      // Children needs to return slot items
      $wrapperEl.children = (options) => $el.children(options);
    } else {
      $wrapperEl = $el.children(`.${swiper.params.wrapperClass}`);
    }
    // Extend Swiper
    extend(swiper, {
      $el,
      el,
      $wrapperEl,
      wrapperEl: $wrapperEl[0],

      // Classes
      classNames: [],

      // Slides
      slides: $(),
      slidesGrid: [],
      snapGrid: [],
      slidesSizesGrid: [],

      // isDirection
      isHorizontal() {
        return swiper.params.direction === 'horizontal';
      },
      isVertical() {
        return swiper.params.direction === 'vertical';
      },
      // RTL
      rtl: el.dir.toLowerCase() === 'rtl' || $el.css('direction') === 'rtl',
      rtlTranslate:
        swiper.params.direction === 'horizontal' &&
        (el.dir.toLowerCase() === 'rtl' || $el.css('direction') === 'rtl'),
      wrongRTL: $wrapperEl.css('display') === '-webkit-box',

      // Indexes
      activeIndex: 0,
      realIndex: 0,

      //
      isBeginning: true,
      isEnd: false,

      // Props
      translate: 0,
      previousTranslate: 0,
      progress: 0,
      velocity: 0,
      animating: false,

      // Locks
      allowSlideNext: swiper.params.allowSlideNext,
      allowSlidePrev: swiper.params.allowSlidePrev,

      // Touch Events
      touchEvents: (function touchEvents() {
        const touch = ['touchstart', 'touchmove', 'touchend', 'touchcancel'];
        let desktop = ['mousedown', 'mousemove', 'mouseup'];
        if (swiper.support.pointerEvents) {
          desktop = ['pointerdown', 'pointermove', 'pointerup'];
        }
        swiper.touchEventsTouch = {
          start: touch[0],
          move: touch[1],
          end: touch[2],
          cancel: touch[3],
        };
        swiper.touchEventsDesktop = {
          start: desktop[0],
          move: desktop[1],
          end: desktop[2],
        };
        return swiper.support.touch || !swiper.params.simulateTouch
          ? swiper.touchEventsTouch
          : swiper.touchEventsDesktop;
      })(),
      touchEventsData: {
        isTouched: undefined,
        isMoved: undefined,
        allowTouchCallbacks: undefined,
        touchStartTime: undefined,
        isScrolling: undefined,
        currentTranslate: undefined,
        startTranslate: undefined,
        allowThresholdMove: undefined,
        // Form elements to match
        formElements: 'input, select, option, textarea, button, video, label',
        // Last click time
        lastClickTime: now(),
        clickTimeout: undefined,
        // Velocities
        velocities: [],
        allowMomentumBounce: undefined,
        isTouchEvent: undefined,
        startMoving: undefined,
      },

      // Clicks
      allowClick: true,

      // Touches
      allowTouchMove: swiper.params.allowTouchMove,

      touches: {
        startX: 0,
        startY: 0,
        currentX: 0,
        currentY: 0,
        diff: 0,
      },

      // Images
      imagesToLoad: [],
      imagesLoaded: 0,
    });

    // Install Modules
    swiper.useModules();

    swiper.emit('_swiper', swiper);

    // Init
    if (swiper.params.init) {
      swiper.init();
    }

    // Return app instance
    return swiper;
  }

  emitContainerClasses() {
    const swiper = this;
    if (!swiper.params._emitClasses || !swiper.el) return;
    const classes = swiper.el.className.split(' ').filter((className) => {
      return (
        className.indexOf('swiper-container') === 0 ||
        className.indexOf(swiper.params.containerModifierClass) === 0
      );
    });
    swiper.emit('_containerClasses', classes.join(' '));
  }

  emitSlidesClasses() {
    const swiper = this;
    if (!swiper.params._emitClasses || !swiper.el) return;
    swiper.slides.each((slideEl) => {
      const classes = slideEl.className.split(' ').filter((className) => {
        return (
          className.indexOf('swiper-slide') === 0 ||
          className.indexOf(swiper.params.slideClass) === 0
        );
      });
      swiper.emit('_slideClass', slideEl, classes.join(' '));
    });
  }

  slidesPerViewDynamic() {
    const swiper = this;
    const { params, slides, slidesGrid, size: swiperSize, activeIndex } = swiper;
    let spv = 1;
    if (params.centeredSlides) {
      let slideSize = slides[activeIndex].swiperSlideSize;
      let breakLoop;
      for (let i = activeIndex + 1; i < slides.length; i += 1) {
        if (slides[i] && !breakLoop) {
          slideSize += slides[i].swiperSlideSize;
          spv += 1;
          if (slideSize > swiperSize) breakLoop = true;
        }
      }
      for (let i = activeIndex - 1; i >= 0; i -= 1) {
        if (slides[i] && !breakLoop) {
          slideSize += slides[i].swiperSlideSize;
          spv += 1;
          if (slideSize > swiperSize) breakLoop = true;
        }
      }
    } else {
      for (let i = activeIndex + 1; i < slides.length; i += 1) {
        if (slidesGrid[i] - slidesGrid[activeIndex] < swiperSize) {
          spv += 1;
        }
      }
    }
    return spv;
  }

  update() {
    const swiper = this;
    if (!swiper || swiper.destroyed) return;
    const { snapGrid, params } = swiper;
    // Breakpoints
    if (params.breakpoints) {
      swiper.setBreakpoint();
    }
    swiper.updateSize();
    swiper.updateSlides();
    swiper.updateProgress();
    swiper.updateSlidesClasses();

    function setTranslate() {
      const translateValue = swiper.rtlTranslate ? swiper.translate * -1 : swiper.translate;
      const newTranslate = Math.min(
        Math.max(translateValue, swiper.maxTranslate()),
        swiper.minTranslate(),
      );
      swiper.setTranslate(newTranslate);
      swiper.updateActiveIndex();
      swiper.updateSlidesClasses();
    }
    let translated;
    if (swiper.params.freeMode) {
      setTranslate();
      if (swiper.params.autoHeight) {
        swiper.updateAutoHeight();
      }
    } else {
      if (
        (swiper.params.slidesPerView === 'auto' || swiper.params.slidesPerView > 1) &&
        swiper.isEnd &&
        !swiper.params.centeredSlides
      ) {
        translated = swiper.slideTo(swiper.slides.length - 1, 0, false, true);
      } else {
        translated = swiper.slideTo(swiper.activeIndex, 0, false, true);
      }
      if (!translated) {
        setTranslate();
      }
    }
    if (params.watchOverflow && snapGrid !== swiper.snapGrid) {
      swiper.checkOverflow();
    }
    swiper.emit('update');
  }

  changeDirection(newDirection, needUpdate = true) {
    const swiper = this;
    const currentDirection = swiper.params.direction;
    if (!newDirection) {
      // eslint-disable-next-line
      newDirection = currentDirection === 'horizontal' ? 'vertical' : 'horizontal';
    }
    if (
      newDirection === currentDirection ||
      (newDirection !== 'horizontal' && newDirection !== 'vertical')
    ) {
      return swiper;
    }

    swiper.$el
      .removeClass(`${swiper.params.containerModifierClass}${currentDirection}`)
      .addClass(`${swiper.params.containerModifierClass}${newDirection}`);
    swiper.emitContainerClasses();

    swiper.params.direction = newDirection;

    swiper.slides.each((slideEl) => {
      if (newDirection === 'vertical') {
        slideEl.style.width = '';
      } else {
        slideEl.style.height = '';
      }
    });

    swiper.emit('changeDirection');
    if (needUpdate) swiper.update();

    return swiper;
  }

  init() {
    const swiper = this;
    if (swiper.initialized) return;

    swiper.emit('beforeInit');

    // Set breakpoint
    if (swiper.params.breakpoints) {
      swiper.setBreakpoint();
    }

    // Add Classes
    swiper.addClasses();

    // Create loop
    if (swiper.params.loop) {
      swiper.loopCreate();
    }

    // Update size
    swiper.updateSize();

    // Update slides
    swiper.updateSlides();

    if (swiper.params.watchOverflow) {
      swiper.checkOverflow();
    }

    // Set Grab Cursor
    if (swiper.params.grabCursor) {
      swiper.setGrabCursor();
    }

    if (swiper.params.preloadImages) {
      swiper.preloadImages();
    }

    // Slide To Initial Slide
    if (swiper.params.loop) {
      swiper.slideTo(
        swiper.params.initialSlide + swiper.loopedSlides,
        0,
        swiper.params.runCallbacksOnInit,
      );
    } else {
      swiper.slideTo(swiper.params.initialSlide, 0, swiper.params.runCallbacksOnInit);
    }

    // Attach events
    swiper.attachEvents();

    // Init Flag
    swiper.initialized = true;

    // Emit
    swiper.emit('init');
  }

  destroy(deleteInstance = true, cleanStyles = true) {
    const swiper = this;
    const { params, $el, $wrapperEl, slides } = swiper;

    if (typeof swiper.params === 'undefined' || swiper.destroyed) {
      return null;
    }

    swiper.emit('beforeDestroy');

    // Init Flag
    swiper.initialized = false;

    // Detach events
    swiper.detachEvents();

    // Destroy loop
    if (params.loop) {
      swiper.loopDestroy();
    }

    // Cleanup styles
    if (cleanStyles) {
      swiper.removeClasses();
      $el.removeAttr('style');
      $wrapperEl.removeAttr('style');
      if (slides && slides.length) {
        slides
          .removeClass(
            [
              params.slideVisibleClass,
              params.slideActiveClass,
              params.slideNextClass,
              params.slidePrevClass,
            ].join(' '),
          )
          .removeAttr('style')
          .removeAttr('data-swiper-slide-index');
      }
    }

    swiper.emit('destroy');

    // Detach emitter events
    Object.keys(swiper.eventsListeners).forEach((eventName) => {
      swiper.off(eventName);
    });

    if (deleteInstance !== false) {
      swiper.$el[0].swiper = null;
      deleteProps(swiper);
    }
    swiper.destroyed = true;

    return null;
  }

  static extendDefaults(newDefaults) {
    extend(extendedDefaults, newDefaults);
  }

  static get extendedDefaults() {
    return extendedDefaults;
  }

  static get defaults() {
    return defaults;
  }

  static installModule(module) {
    if (!Swiper.prototype.modules) Swiper.prototype.modules = {};
    const name = module.name || `${Object.keys(Swiper.prototype.modules).length}_${now()}`;
    Swiper.prototype.modules[name] = module;
  }

  static use(module) {
    if (Array.isArray(module)) {
      module.forEach((m) => Swiper.installModule(m));
      return Swiper;
    }
    Swiper.installModule(module);
    return Swiper;
  }
}

export default Swiper;
<|endoftext|>


<commit_before>'use strict';

/**
 * @ngdoc overview
 * @name tinkApp
 * @description
 * # tinkApp
 *
 * Main module of the application.
 */
 angular
 .module('tinkApp', [
   'ngAnimate',
   'ngCookies',
   'ngResource',
   'ngRoute',
   'ngSanitize',
   'ngTouch'
   ])
 .config(function ($routeProvider) { /*, $locationProvider */
  $routeProvider
  .when('/', {
    templateUrl: 'views/main.html',
    // controller: 'MainCtrl'
  })
  .when('/start', {
    templateUrl: 'views/start.html',
    controller: 'StartCtrl'
  })
  .when('/docs', {
    redirectTo: '/start',
  })
  .when('/docs/ui', {
    redirectTo: '/docs/ui/grid',
  })
  .when('/docs/:subpage', {
    templateUrl: 'views/docs.html',
    controller: 'DocsCtrl'
  })
  .when('/docs/:subpage/:subsubpage', {
    templateUrl: 'views/docs.html',
    controller: 'DocsCtrl'
  })
  .when('/changelog', {
    templateUrl: 'views/changelog.html',
    controller: 'ChangelogCtrl'
  })
  .when('/faq', {
    templateUrl: 'views/faq.html',
  })
  .when('/shame', {
    templateUrl: 'views/shame.html',
    controller: 'ShameCtrl'
  })
  .otherwise({
    redirectTo: '/'
  });

	// $locationProvider.html5Mode(true);
	// $locationProvider.hashPrefix('!');
});//.run(function($rootScope) {
//   var versionFileTinkProp = '1.2.6';
//   $rootScope.themes = {
//     digipolis:['tink.'+versionFileTinkProp+'.min.css','default.'+versionFileTinkProp+'.min.css','styleguide.'+versionFileTinkProp+'.min.css'],
//     stad:['tink-stad.'+versionFileTinkProp+'.min.css','default-stad.'+versionFileTinkProp+'.min.css','styleguide-stad.'+versionFileTinkProp+'.min.css'],
//     ocmw:['tink-ocmw.'+versionFileTinkProp+'.min.css','default-ocmw.'+versionFileTinkProp+'.min.css','styleguide-ocmw.'+versionFileTinkProp+'.min.css'],
//     politie:['tink-politie.'+versionFileTinkProp+'.min.css','default-politie.'+versionFileTinkProp+'.min.css','styleguide-politie.'+versionFileTinkProp+'.min.css']
//   };

//   $rootScope.theme = {
//     active: 'digipolis',
//     text: 'Tink',
//     html: 'Tink'
//   };
// });
<commit_msg>module load fix<commit_after>'use strict';

/**
 * @ngdoc overview
 * @name tinkApp
 * @description
 * # tinkApp
 *
 * Main module of the application.
 */
 angular
 .module('tinkApp', [
   'ngAnimate',
   'ngCookies',
   'ngResource',
   'ngRoute',
   'ngSanitize',
   'ngTouch',
   'tink.tinkApi',
   'tink.navigation'
   ])
 .config(function ($routeProvider) { /*, $locationProvider */
  $routeProvider
  .when('/', {
    templateUrl: 'views/main.html',
    // controller: 'MainCtrl'
  })
  .when('/start', {
    templateUrl: 'views/start.html',
    controller: 'StartCtrl'
  })
  .when('/docs', {
    redirectTo: '/start',
  })
  .when('/docs/ui', {
    redirectTo: '/docs/ui/grid',
  })
  .when('/docs/:subpage', {
    templateUrl: 'views/docs.html',
    controller: 'DocsCtrl'
  })
  .when('/docs/:subpage/:subsubpage', {
    templateUrl: 'views/docs.html',
    controller: 'DocsCtrl'
  })
  .when('/changelog', {
    templateUrl: 'views/changelog.html',
    controller: 'ChangelogCtrl'
  })
  .when('/faq', {
    templateUrl: 'views/faq.html',
  })
  .when('/shame', {
    templateUrl: 'views/shame.html',
    controller: 'ShameCtrl'
  })
  .otherwise({
    redirectTo: '/'
  });

	// $locationProvider.html5Mode(true);
	// $locationProvider.hashPrefix('!');
});//.run(function($rootScope) {
//   var versionFileTinkProp = '1.2.6';
//   $rootScope.themes = {
//     digipolis:['tink.'+versionFileTinkProp+'.min.css','default.'+versionFileTinkProp+'.min.css','styleguide.'+versionFileTinkProp+'.min.css'],
//     stad:['tink-stad.'+versionFileTinkProp+'.min.css','default-stad.'+versionFileTinkProp+'.min.css','styleguide-stad.'+versionFileTinkProp+'.min.css'],
//     ocmw:['tink-ocmw.'+versionFileTinkProp+'.min.css','default-ocmw.'+versionFileTinkProp+'.min.css','styleguide-ocmw.'+versionFileTinkProp+'.min.css'],
//     politie:['tink-politie.'+versionFileTinkProp+'.min.css','default-politie.'+versionFileTinkProp+'.min.css','styleguide-politie.'+versionFileTinkProp+'.min.css']
//   };

//   $rootScope.theme = {
//     active: 'digipolis',
//     text: 'Tink',
//     html: 'Tink'
//   };
// });
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import {
  Provider,
  Banner,
  Heading,
  Lead,
  Container,
  Flex,
  Box,
  Text,
  Subhead,
  Absolute,
  ButtonOutline
} from 'rebass'
import theme, { colors, mx } from '../theme'
import { Head, Link } from 'react-static'
import Features from '../components/Features'
import Stat from '../components/Stat'

const css = `
  body { background-color: #000; }
  *::selection {
    color: #fff;
    background-color: ${colors.green[6]};
  }
  #root > div, #features *, #stats span {
    color: ${colors.green[6]} !important;
    font-family: ${theme.monospace} !important;
    letter-spacing: -.02em;
  }
  h1, h2, a:hover, #stats span {
    text-shadow: 0 0 2px ${colors.green[4]};
  }
  h3 {
    text-shadow: 0 0 1px ${colors.green[4]};
  }
  a:hover {
    box-shadow: inset 0 0 4px ${colors.green[4]};
  }
  a {
    transition: text-shadow box-shadow;
    transition-duration: 0.5s;
  }
  #features > div > div {
    background-color: #000;
    border: 1px solid ${colors.green[6]};
    border-radius: 0;
  }
  #features img { display: none !important; }
  #features * {
    font-size: ${theme.fontSizes[2]};
  }
  #stats > div {
    padding-left: .5rem;
    padding-right: .5rem;
  }
  #stats p {
    color: ${colors.green[8]};
    text-shadow: none;
  }
  #stats span { font-weight: 400; }
`

const Header = Flex.extend.attrs({
  is: 'header',
  align: 'center',
  justify: 'center',
  direction: 'column',
  px: [3, 0],
  py: [5, 3]
})`
  background: #000 url('/map-repl.svg') no-repeat;
  background-size: cover;
  background-position: 33% top;
  border-bottom: 1px solid ${colors.green[9]};
  text-align: center;
  ${mx[0]} {
    background-position: center top;
    min-height: 75vh !important;
  }
`
const Section = Box.extend.attrs({ is: 'section', py: 4 })`
  border-bottom: 1px solid ${colors.green[9]};
  text-align: center;
`
const Footer = Box.extend.attrs({
  is: 'footer',
  py: 4,
  f: 2
})`text-align: center;`

const Tagline = Text.extend.attrs({
  f: 3,
  mb: 2
})`
  text-align: center;
  text-transform: uppercase;
`
const Headline = Heading.extend.attrs({
  is: 'h1',
  f: 6,
  mb: 2
})`line-height: 1.125;`
const Subheadline = Heading.extend.attrs({
  f: 5,
  mt: 4,
  px: 3
})``

const CTA = Box.extend.attrs({
  is: 'a',
  color: colors.green[6],
  px: [2, 3, 4],
  py: [2, 3],
  mx: 2,
  f: [3, 4]
})`
  border: 2px solid ${colors.green[6]};
  line-height: 1;
  text-decoration: none;
  text-transform: uppercase;
  cursor: pointer;
`

class ReplAnalytics extends Component {
  componentDidUpdate() {
    const paramString = decodeURI(this.props.paramString)
    const paramArray = paramString.split(/\?|&/)
    paramArray.forEach(param => {
      let kv = param.split('=')
      if (kv[0] == 'i') {
        window.analytics.identify(kv[1])

        const cValue = `replit_user_id=${kv[1]}`
        const cPath = 'path=/'
        document.cookie = `${cValue}; ${cPath}`
      }
    })
  }

  render() {
    return ''
  }
}

class StartRepl extends Component {
  constructor(props) {
    super(props)

    this.state = {
      paramString: ''
    }
  }

  componentDidMount() {
    if (!window) {
      return
    }

    this.setState({
      paramString: window.location.search
    })
  }

  render() {
    const { paramString } = this.state

    return (
      <Provider theme={theme}>

          <title>Repl.it – Hack Club</title>
          <link
            rel="stylesheet"
            href="//brick.a.ssl.fastly.net/Roboto+Mono:400:700"
          />

        <ReplAnalytics paramString={paramString} />


<commit_before>/**
 * @author Titus Wormer
 * @copyright 2015 Titus Wormer
 * @license MIT
 * @module list-item-indent
 * @fileoverview
 *   Warn when the spacing between a list item’s bullet and its content violates
 *   a given style.
 *
 *   Options: `'tab-size'`, `'mixed'`, or `'space'`, default: `'tab-size'`.
 *
 *   ## Fix
 *
 *   [`remark-stringify`](https://github.com/remarkjs/remark/tree/HEAD/packages/remark-stringify)
 *   uses `'tab-size'` (named `'tab'` there) by default to ensure Markdown is
 *   seen the same way across vendors.
 *   This can be configured with the
 *   [`listItemIndent`](https://github.com/remarkjs/remark/tree/HEAD/packages/remark-stringify#optionslistitemindent)
 *   option.
 *   This rule’s `'space'` option is named `'1'` there.
 *
 *   See [Using remark to fix your Markdown](https://github.com/remarkjs/remark-lint#using-remark-to-fix-your-markdown)
 *   on how to automatically fix warnings for this rule.
 *
 * @example
 *   {"name": "ok.md"}
 *
 *   *···List
 *   ····item.
 *
 *   Paragraph.
 *
 *   11.·List
 *   ····item.
 *
 *   Paragraph.
 *
 *   *···List
 *   ····item.
 *
 *   *···List
 *   ····item.
 *
 * @example
 *   {"name": "ok.md", "setting": "mixed"}
 *
 *   *·List item.
 *
 *   Paragraph.
 *
 *   11.·List item
 *
 *   Paragraph.
 *
 *   *···List
 *   ····item.
 *
 *   *···List
 *   ····item.
 *
 * @example
 *   {"name": "ok.md", "setting": "space"}
 *
 *   *·List item.
 *
 *   Paragraph.
 *
 *   11.·List item
 *
 *   Paragraph.
 *
 *   *·List
 *   ··item.
 *
 *   *·List
 *   ··item.
 *
 * @example
 *   {"name": "not-ok.md", "setting": "space", "label": "input"}
 *
 *   *···List
 *   ····item.
 *
 * @example
 *   {"name": "not-ok.md", "setting": "space", "label": "output"}
 *
 *    1:5: Incorrect list-item indent: remove 2 spaces
 *
 * @example
 *   {"name": "not-ok.md", "setting": "tab-size", "label": "input"}
 *
 *   *·List
 *   ··item.
 *
 * @example
 *   {"name": "not-ok.md", "setting": "tab-size", "label": "output"}
 *
 *    1:3: Incorrect list-item indent: add 2 spaces
 *
 * @example
 *   {"name": "not-ok.md", "setting": "mixed", "label": "input"}
 *
 *   *···List item.
 *
 * @example
 *   {"name": "not-ok.md", "setting": "mixed", "label": "output"}
 *
 *    1:5: Incorrect list-item indent: remove 2 spaces
 *
 * @example
 *   {"name": "not-ok.md", "setting": "💩", "label": "output", "positionless": true}
 *
 *    1:1: Incorrect list-item indent style `💩`: use either `'tab-size'`, `'space'`, or `'mixed'`
 */

/**
 * @typedef {import('mdast').Root} Root
 * @typedef {'tab-size'|'space'|'mixed'} Options
 */

import {lintRule} from 'unified-lint-rule'
import plural from 'pluralize'
import {visit} from 'unist-util-visit'
import {pointStart} from 'unist-util-position'
import {generated} from 'unist-util-generated'

const remarkLintListItemIndent = lintRule(
  'remark-lint:list-item-indent',
  /** @type {import('unified-lint-rule').Rule<Root, Options>} */
  (tree, file, option = 'tab-size') => {
    const value = String(file)

    if (option !== 'tab-size' && option !== 'space' && option !== 'mixed') {
      file.fail(
        'Incorrect list-item indent style `' +
          option +
          "`: use either `'tab-size'`, `'space'`, or `'mixed'`"
      )
    }

    visit(tree, 'list', (node) => {
      if (generated(node)) return

      // @ts-expect-error: legacy.
      const spread = Boolean(node.spread || node.loose)
      let index = -1

      while (++index < node.children.length) {
        const item = node.children[index]
        const head = item.children[0]
        const final = pointStart(head)

        const marker = value
          .slice(pointStart(item).offset, final.offset)
          .replace(/\[[x ]?]\s*$/i, '')

        const bulletSize = marker.replace(/\s+$/, '').length

        const style =
          option === 'tab-size' || (option === 'mixed' && spread)
            ? Math.ceil(bulletSize / 4) * 4
            : bulletSize + 1

        if (marker.length !== style) {
          const diff = style - marker.length
          const abs = Math.abs(diff)

          file.message(
            'Incorrect list-item indent: ' +
              (diff > 0 ? 'add' : 'remove') +
              ' ' +
              abs +
              ' ' +
              plural('space', abs),
            final
          )
        }
      }
    })
  }
)

export default remarkLintListItemIndent
<commit_msg>Remove support for ancient `loose` field<commit_after>/**
 * @author Titus Wormer
 * @copyright 2015 Titus Wormer
 * @license MIT
 * @module list-item-indent
 * @fileoverview
 *   Warn when the spacing between a list item’s bullet and its content violates
 *   a given style.
 *
 *   Options: `'tab-size'`, `'mixed'`, or `'space'`, default: `'tab-size'`.
 *
 *   ## Fix
 *
 *   [`remark-stringify`](https://github.com/remarkjs/remark/tree/HEAD/packages/remark-stringify)
 *   uses `'tab-size'` (named `'tab'` there) by default to ensure Markdown is
 *   seen the same way across vendors.
 *   This can be configured with the
 *   [`listItemIndent`](https://github.com/remarkjs/remark/tree/HEAD/packages/remark-stringify#optionslistitemindent)
 *   option.
 *   This rule’s `'space'` option is named `'1'` there.
 *
 *   See [Using remark to fix your Markdown](https://github.com/remarkjs/remark-lint#using-remark-to-fix-your-markdown)
 *   on how to automatically fix warnings for this rule.
 *
 * @example
 *   {"name": "ok.md"}
 *
 *   *···List
 *   ····item.
 *
 *   Paragraph.
 *
 *   11.·List
 *   ····item.
 *
 *   Paragraph.
 *
 *   *···List
 *   ····item.
 *
 *   *···List
 *   ····item.
 *
 * @example
 *   {"name": "ok.md", "setting": "mixed"}
 *
 *   *·List item.
 *
 *   Paragraph.
 *
 *   11.·List item
 *
 *   Paragraph.
 *
 *   *···List
 *   ····item.
 *
 *   *···List
 *   ····item.
 *
 * @example
 *   {"name": "ok.md", "setting": "space"}
 *
 *   *·List item.
 *
 *   Paragraph.
 *
 *   11.·List item
 *
 *   Paragraph.
 *
 *   *·List
 *   ··item.
 *
 *   *·List
 *   ··item.
 *
 * @example
 *   {"name": "not-ok.md", "setting": "space", "label": "input"}
 *
 *   *···List
 *   ····item.
 *
 * @example
 *   {"name": "not-ok.md", "setting": "space", "label": "output"}
 *
 *    1:5: Incorrect list-item indent: remove 2 spaces
 *
 * @example
 *   {"name": "not-ok.md", "setting": "tab-size", "label": "input"}
 *
 *   *·List
 *   ··item.
 *
 * @example
 *   {"name": "not-ok.md", "setting": "tab-size", "label": "output"}
 *
 *    1:3: Incorrect list-item indent: add 2 spaces
 *
 * @example
 *   {"name": "not-ok.md", "setting": "mixed", "label": "input"}
 *
 *   *···List item.
 *
 * @example
 *   {"name": "not-ok.md", "setting": "mixed", "label": "output"}
 *
 *    1:5: Incorrect list-item indent: remove 2 spaces
 *
 * @example
 *   {"name": "not-ok.md", "setting": "💩", "label": "output", "positionless": true}
 *
 *    1:1: Incorrect list-item indent style `💩`: use either `'tab-size'`, `'space'`, or `'mixed'`
 */

/**
 * @typedef {import('mdast').Root} Root
 * @typedef {'tab-size'|'space'|'mixed'} Options
 */

import {lintRule} from 'unified-lint-rule'
import plural from 'pluralize'
import {visit} from 'unist-util-visit'
import {pointStart} from 'unist-util-position'
import {generated} from 'unist-util-generated'

const remarkLintListItemIndent = lintRule(
  'remark-lint:list-item-indent',
  /** @type {import('unified-lint-rule').Rule<Root, Options>} */
  (tree, file, option = 'tab-size') => {
    const value = String(file)

    if (option !== 'tab-size' && option !== 'space' && option !== 'mixed') {
      file.fail(
        'Incorrect list-item indent style `' +
          option +
          "`: use either `'tab-size'`, `'space'`, or `'mixed'`"
      )
    }

    visit(tree, 'list', (node) => {
      if (generated(node)) return

      const spread = node.spread
      let index = -1

      while (++index < node.children.length) {
        const item = node.children[index]
        const head = item.children[0]
        const final = pointStart(head)

        const marker = value
          .slice(pointStart(item).offset, final.offset)
          .replace(/\[[x ]?]\s*$/i, '')

        const bulletSize = marker.replace(/\s+$/, '').length

        const style =
          option === 'tab-size' || (option === 'mixed' && spread)
            ? Math.ceil(bulletSize / 4) * 4
            : bulletSize + 1

        if (marker.length !== style) {
          const diff = style - marker.length
          const abs = Math.abs(diff)

          file.message(
            'Incorrect list-item indent: ' +
              (diff > 0 ? 'add' : 'remove') +
              ' ' +
              abs +
              ' ' +
              plural('space', abs),
            final
          )
        }
      }
    })
  }
)

export default remarkLintListItemIndent
<|endoftext|>


<commit_before>const start = ["a lazy", "a stupid", "an insecure", "an idiotic", "a slimy", "a slutty", "a smelly", "a pompous", "a communist", "a dicknose", "a pie-eating", "a racist", "an elitist", "a white trash", "a drug-loving", "a butterface", "a tone deaf", "a ugly", "a creepy", "an artless", "a bawdy", "a beslubbering", "a bootless", "a churlish", "a cockered", "a clouted", "a craven", "a currish", "a dankish", "a dissembling", "a droning", "an errant", "a fawning", "a fobbing", "a frothy", "a gleeking", "a goatfish", "a gorbellied", "an impertinent", "an infectious", "a jarring", "a loggerheaded", "a lumpish", "a mammering", "a mangled", "a mewling", "a paunchy", "a pribbling", "a puking", "a puny", "a qualling", "a rank", "a reeky", "a roguish", "a ruttish", "a saucy", "a spleeny", "a spongy", "a surly", "a tottering", "an unmuzzled", "a vain", "a venomed", "a villainous", "a warped", "a wayward", "a weedy", "a yeasty", "a lilly-livered", "a rotten", "a stinky", "a lame", "a dim-witted", "a funky", "a crusty", "a steamy", "a drizzly", "a grizzly", "a squirty", "an uptight", "a hairy", "a husky", "an arrogant", "a nippy", "a chunky", "a smelly", "a drooling", "a crusty", "a decrepic", "a stupid", "a moronic", "a greasy", "a poxy", "an ugly", "a smelly", "a putrid", "a shitty", "an assinine", "a sickening"];

const middle = ["douche", "ass", "turd", "rectum", "butt", "cock", "shit", "crotch", "bitch", "turd", "prick", "slut", "taint", "fuck", "dick", "boner", "shart", "nut", "sphincter", "base-court", "bat-fowling", "beef-witted", "beetle-headed", "boil-brained", "clapper-clawed", "clay-brained", "common-kissing", "crook-pated", "dismal-dreaming", "dizzy-eyed", "doghearted", "dread-bolted", "earth-vexing", "elf-skinned", "fat-kidneyed", "fen-sucked", "flap-mouthed", "fly-bitten", "folly-fallen", "fool-born", "full-gorged", "guts-gripping", "half-faced", "hasty-witted", "hedge-born", "hell-hated", "idle-headed", "ill-breeding", "ill-nurtured", "knotty-pated", "milk-livered", "motly-minded", "onion-eyed", "plume-plucked", "pottle-deep", "pox-marked", "reeling-ripe", "rough-hewn", "rude-growing", "rump-red", "shard-borne", "sheep-biting", "spur-galled", "swag-bellied", "tardy-gaited", "tickle-brained", "toad-spotted", "unchin-snouted", "weather-bitten", "hiney", "poop", "toot", "wedgie", "stool", "fudge", "bum", "potty", "dookie", "pudding", "sphincter", "booger", "feces", "snot", "crust", "badonk-a", "crud", "sludge", "tool", "shit-kicking", "monkey-licking", "butt-munching", "crotch-sniffing", "donkey-spanking", "fashion-illiterate", "worm-ridden", "grub-fucking", "lathered-up", "pasty-waisted", "snot-flicking", "fart-eating"];

const end = ["pilot", "canoe", "captain", "pirate", "hammer", "knob", "box", "jockey", "nazi", "waffle", "goblin", "blossom", "biscuit", "clown", "socket", "monster", "hound", "dragon", "balloon", "apple-john", "baggage", "barnacle", "bladder", "boar-pig", "bugbear", "bum-bailey", "canker-blossom", "clack-dish", "clotpole", "coxcomb", "codpiece", "death-token", "dewberry", "flap-dragon", "flax-wench", "flirt-gill", "foot-licker", "fustilarian", "giglet", "gudgeon", "haggard", "harpy", "hedge-pig", "horn-beast", "hugger-mugger", "joithead", "lewdster", "lout", "maggot-pie", "malt-worm", "mammet", "measle", "minnow", "miscreant", "moldwarp", "mumble-news", "nut-hook", "pigeon-egg", "pignut", "puttock", "pumpion", "ratsbane", "scut", "skinsmate", "strumpet", "varlot", "vassal", "whey-face", "wagtail", "squeegee", "turtle", "cabbage", "bomb", "sniffer", "binkie", "stump", "nugget", "whistle", "twig", "knuckle", "burger", "hotdog", "loaf", "freckle", "soldier", "kernal", "shingle", "warrior", "hemorrhoid", "fuckface", "asshole", "scumbucket", "toerag", "hackwack", "imbecile", "stunodigan", "maggot", "hipster", "gargabe", "jerkstore"];

exports.run = (client, msg, [user]) => {
    msg.delete().then(() =>
        msg.channel.sendMessage(`${user}, you know what? you're nothing but ${start[Math.floor(Math.random() * start.length)]} ${middle[Math.floor(Math.random() * middle.length)]} ${end[Math.floor(Math.random() * end.length)]}.`)).catch(error => console.log(error.stack));
};

exports.conf = {
    enabled: true,
    guildOnly: false,
    aliases: [],
    permLevel: 0,
    botPerms: [],
    requiredFuncs: []
};

exports.help = {
    name: "insult",
    description: "Insults who you mention",
    usage: "<user:mention>",
    usageDelim: ""
};
<commit_msg>Fix botPerms<commit_after>const start = ["a lazy", "a stupid", "an insecure", "an idiotic", "a slimy", "a slutty", "a smelly", "a pompous", "a communist", "a dicknose", "a pie-eating", "a racist", "an elitist", "a white trash", "a drug-loving", "a butterface", "a tone deaf", "a ugly", "a creepy", "an artless", "a bawdy", "a beslubbering", "a bootless", "a churlish", "a cockered", "a clouted", "a craven", "a currish", "a dankish", "a dissembling", "a droning", "an errant", "a fawning", "a fobbing", "a frothy", "a gleeking", "a goatfish", "a gorbellied", "an impertinent", "an infectious", "a jarring", "a loggerheaded", "a lumpish", "a mammering", "a mangled", "a mewling", "a paunchy", "a pribbling", "a puking", "a puny", "a qualling", "a rank", "a reeky", "a roguish", "a ruttish", "a saucy", "a spleeny", "a spongy", "a surly", "a tottering", "an unmuzzled", "a vain", "a venomed", "a villainous", "a warped", "a wayward", "a weedy", "a yeasty", "a lilly-livered", "a rotten", "a stinky", "a lame", "a dim-witted", "a funky", "a crusty", "a steamy", "a drizzly", "a grizzly", "a squirty", "an uptight", "a hairy", "a husky", "an arrogant", "a nippy", "a chunky", "a smelly", "a drooling", "a crusty", "a decrepic", "a stupid", "a moronic", "a greasy", "a poxy", "an ugly", "a smelly", "a putrid", "a shitty", "an assinine", "a sickening"];

const middle = ["douche", "ass", "turd", "rectum", "butt", "cock", "shit", "crotch", "bitch", "turd", "prick", "slut", "taint", "fuck", "dick", "boner", "shart", "nut", "sphincter", "base-court", "bat-fowling", "beef-witted", "beetle-headed", "boil-brained", "clapper-clawed", "clay-brained", "common-kissing", "crook-pated", "dismal-dreaming", "dizzy-eyed", "doghearted", "dread-bolted", "earth-vexing", "elf-skinned", "fat-kidneyed", "fen-sucked", "flap-mouthed", "fly-bitten", "folly-fallen", "fool-born", "full-gorged", "guts-gripping", "half-faced", "hasty-witted", "hedge-born", "hell-hated", "idle-headed", "ill-breeding", "ill-nurtured", "knotty-pated", "milk-livered", "motly-minded", "onion-eyed", "plume-plucked", "pottle-deep", "pox-marked", "reeling-ripe", "rough-hewn", "rude-growing", "rump-red", "shard-borne", "sheep-biting", "spur-galled", "swag-bellied", "tardy-gaited", "tickle-brained", "toad-spotted", "unchin-snouted", "weather-bitten", "hiney", "poop", "toot", "wedgie", "stool", "fudge", "bum", "potty", "dookie", "pudding", "sphincter", "booger", "feces", "snot", "crust", "badonk-a", "crud", "sludge", "tool", "shit-kicking", "monkey-licking", "butt-munching", "crotch-sniffing", "donkey-spanking", "fashion-illiterate", "worm-ridden", "grub-fucking", "lathered-up", "pasty-waisted", "snot-flicking", "fart-eating"];

const end = ["pilot", "canoe", "captain", "pirate", "hammer", "knob", "box", "jockey", "nazi", "waffle", "goblin", "blossom", "biscuit", "clown", "socket", "monster", "hound", "dragon", "balloon", "apple-john", "baggage", "barnacle", "bladder", "boar-pig", "bugbear", "bum-bailey", "canker-blossom", "clack-dish", "clotpole", "coxcomb", "codpiece", "death-token", "dewberry", "flap-dragon", "flax-wench", "flirt-gill", "foot-licker", "fustilarian", "giglet", "gudgeon", "haggard", "harpy", "hedge-pig", "horn-beast", "hugger-mugger", "joithead", "lewdster", "lout", "maggot-pie", "malt-worm", "mammet", "measle", "minnow", "miscreant", "moldwarp", "mumble-news", "nut-hook", "pigeon-egg", "pignut", "puttock", "pumpion", "ratsbane", "scut", "skinsmate", "strumpet", "varlot", "vassal", "whey-face", "wagtail", "squeegee", "turtle", "cabbage", "bomb", "sniffer", "binkie", "stump", "nugget", "whistle", "twig", "knuckle", "burger", "hotdog", "loaf", "freckle", "soldier", "kernal", "shingle", "warrior", "hemorrhoid", "fuckface", "asshole", "scumbucket", "toerag", "hackwack", "imbecile", "stunodigan", "maggot", "hipster", "gargabe", "jerkstore"];

exports.run = (client, msg, [user]) => {
    msg.delete().then(() =>
        msg.channel.sendMessage(`${user}, you know what? you're nothing but ${start[Math.floor(Math.random() * start.length)]} ${middle[Math.floor(Math.random() * middle.length)]} ${end[Math.floor(Math.random() * end.length)]}.`)).catch(error => console.log(error.stack));
};

exports.conf = {
    enabled: true,
    guildOnly: false,
    aliases: [],
    permLevel: 0,
    botPerms: ["MANAGE_MESSAGES"],
    requiredFuncs: []
};

exports.help = {
    name: "insult",
    description: "Insults who you mention",
    usage: "<user:mention>",
    usageDelim: ""
};
<|endoftext|>


<commit_before>var _ = require('lodash'),
    chalk = require('chalk'),
    log = require('./log'),
    parseArgs = require('minimist'),
    pkg = require('../package.json');

var bannerText = [
    '',
    '==========================================================================',
    '================================  ========================================',
    '================================  ========================================',
    '=============  =================  ====================  ==================',
    '==   ===  ==    ===   ====   ===  ======   ====   ===    ===   ===  =   ==',
    '=  =  =======  ===  =  ==  =  ==    ===     ==     ===  ===  =  ==    =  =',
    '==  ====  ===  ===     ===  ====  =  ==  =  ==  =  ===  ===     ==  ======',
    '===  ===  ===  ===  =======  ===  =  ==  =  ==  =  ===  ===  =====  ======',
    '=  =  ==  ===  ===  =  ==  =  ==  =  ==  =  ==  =  ===  ===  =  ==  ======',
    '==   ===  ===   ===   ====   ===  =  ===   ====   ====   ===   ===  ======',
    '==========================================================================',
    '',
    'Siteshooter                                                     v' + pkg.version,
    'Maintainer                                                      ' + pkg.author.name + ' <' + pkg.author.email + '>',
    '                                                                ' + pkg.author.url,
    '',
    'Usage: siteshooter [options]',
    '',
    'OPTIONS',
    '___________________________________________________________________________________________________________',
    '-c --config            Show configuration',
    '-C --cwd               Set working directory, which will load a siteshooter.yml file in the specified path',
    '-e --debug             Output exceptions',
    '-h --help              Print this help',
    '-i --init              Create siteshooter.yml template file in working directory',
    '-p --pdf               Generate PDFs, by defined viewports, based on screenshots created via Siteshooter',
    '-q --quiet             Only return final output',
    '-s --screenshots       Generate screenshots, by defined viewports, based on local sitemap.xml file',
    '-S --sitemap           Crawl domain name specified in siteshooter.yml file and generate a local sitemap.xml file',
    '-v --version           Print version number',
    '-V --verbose           Verbose output',
    '-w --website           Report on website information based on Siteshooter crawled results',
    '_____________________________________________________________________________________________________________',
    '',
].join('\n');

var aliases = {
    c: 'config',
    C: 'cwd',
    e: 'debug',
    h: 'help',
    i: 'init',
    p: 'pdf',
    q: 'quiet',
    s: 'screenshots',
    S: 'sitemap',
    v: 'version',
    V: 'verbose',
    w: 'website'
};

function checkForCommand(options) {

    var commands = [
            'pdf',
            'screenshots',
            'sitemap',
            'website'
        ],
        hasCommand = commands.filter(function(item) {
            return (options[item]);
        });

    return hasCommand.length;
}

module.exports = {
    config: function() {
        log.log.apply(null, arguments);
    },
    help: function() {
        log.log(chalk.yellow.bold(bannerText));
    },
    parse: function(argv) {

        var options = {
            commands: parseArgs(argv, {
                alias: aliases,
                boolean: true
            }),
            invalidArgument: false
        };

        var flattenAliases = Object.entries(aliases).join().split(','),
            flattenCommands = Object.keys(options.commands).filter(function(item) {
                return item !== '_';
            });

        // check for arguments without preceeding --
        if( options.commands._.length > 0 ){
            options.invalidArgument = options.commands._[0];
            return options;
        }

        // check for invalid arguments
        _.forEach(flattenCommands, function(command) {
            if( flattenAliases.indexOf(command) === -1 ){
                options.invalidArgument = command;
                return false;
            }
        });

        // if 0 commands were passed, run the following in sequence
        if ( !options.invalidArgument && checkForCommand(options.commands) === 0 ) {
            options.commands.sitemap = true;
            options.commands.screenshots = true;
            options.commands.pdf = true;
            options.commands.website = true;
        }

        return options;
    },
    version: function() {
        log.log('v' + pkg.version);
    }
};
<commit_msg>fix(CLI): Use lodash entires function for node v6 support<commit_after>var _ = require('lodash'),
    chalk = require('chalk'),
    log = require('./log'),
    parseArgs = require('minimist'),
    pkg = require('../package.json');

var bannerText = [
    '',
    '==========================================================================',
    '================================  ========================================',
    '================================  ========================================',
    '=============  =================  ====================  ==================',
    '==   ===  ==    ===   ====   ===  ======   ====   ===    ===   ===  =   ==',
    '=  =  =======  ===  =  ==  =  ==    ===     ==     ===  ===  =  ==    =  =',
    '==  ====  ===  ===     ===  ====  =  ==  =  ==  =  ===  ===     ==  ======',
    '===  ===  ===  ===  =======  ===  =  ==  =  ==  =  ===  ===  =====  ======',
    '=  =  ==  ===  ===  =  ==  =  ==  =  ==  =  ==  =  ===  ===  =  ==  ======',
    '==   ===  ===   ===   ====   ===  =  ===   ====   ====   ===   ===  ======',
    '==========================================================================',
    '',
    'Siteshooter                                                     v' + pkg.version,
    'Maintainer                                                      ' + pkg.author.name + ' <' + pkg.author.email + '>',
    '                                                                ' + pkg.author.url,
    '',
    'Usage: siteshooter [options]',
    '',
    'OPTIONS',
    '___________________________________________________________________________________________________________',
    '-c --config            Show configuration',
    '-C --cwd               Set working directory, which will load a siteshooter.yml file in the specified path',
    '-e --debug             Output exceptions',
    '-h --help              Print this help',
    '-i --init              Create siteshooter.yml template file in working directory',
    '-p --pdf               Generate PDFs, by defined viewports, based on screenshots created via Siteshooter',
    '-q --quiet             Only return final output',
    '-s --screenshots       Generate screenshots, by defined viewports, based on local sitemap.xml file',
    '-S --sitemap           Crawl domain name specified in siteshooter.yml file and generate a local sitemap.xml file',
    '-v --version           Print version number',
    '-V --verbose           Verbose output',
    '-w --website           Report on website information based on Siteshooter crawled results',
    '_____________________________________________________________________________________________________________',
    '',
].join('\n');

var aliases = {
    c: 'config',
    C: 'cwd',
    e: 'debug',
    h: 'help',
    i: 'init',
    p: 'pdf',
    q: 'quiet',
    s: 'screenshots',
    S: 'sitemap',
    v: 'version',
    V: 'verbose',
    w: 'website'
};

function checkForCommand(options) {

    var commands = [
            'pdf',
            'screenshots',
            'sitemap',
            'website'
        ],
        hasCommand = commands.filter(function(item) {
            return (options[item]);
        });

    return hasCommand.length;
}

module.exports = {
    config: function() {
        log.log.apply(null, arguments);
    },
    help: function() {
        log.log(chalk.yellow.bold(bannerText));
    },
    parse: function(argv) {

        var options = {
            commands: parseArgs(argv, {
                alias: aliases,
                boolean: true
            }),
            invalidArgument: false
        };

        var flattenAliases = _.entries(aliases).join().split(','),
            flattenCommands = Object.keys(options.commands).filter(function(item) {
                return item !== '_';
            });

        // check for arguments without preceeding --
        if( options.commands._.length > 0 ){
            options.invalidArgument = options.commands._[0];
            return options;
        }

        // check for invalid arguments
        _.forEach(flattenCommands, function(command) {
            if( flattenAliases.indexOf(command) === -1 ){
                options.invalidArgument = command;
                return false;
            }
        });

        // if 0 commands were passed, run the following in sequence
        if ( !options.invalidArgument && checkForCommand(options.commands) === 0 ) {
            options.commands.sitemap = true;
            options.commands.screenshots = true;
            options.commands.pdf = true;
            options.commands.website = true;
        }

        return options;
    },
    version: function() {
        log.log('v' + pkg.version);
    }
};
<|endoftext|>


<commit_before>#!/usr/bin/env node

var mqtt      = require('../')
  , path      = require('path')
  , fs        = require('fs')
  , concat    = require('concat-stream')
  , helpMe    = require('help-me')({
      dir: path.join(__dirname, '..', 'doc')
    })
  , minimist  = require('minimist');

function send(args) {
}

function start(args) {
  args = minimist(args, {
    string: ['host', 'username', 'password', 'key', 'cert'],
    integer: ['port', 'qos', 'keepAlive'],
    boolean: ['stdin', 'help', 'clean'],
    alias: {
      port: 'p',
      host: 'h',
      topic: 't',
      qos: 'q',
      clean: 'c',
      keepAlive: 'k',
      clientId: ['i', 'id'],
      username: 'u',
      password: 'P',
      protocol: 'C',
      verbose: 'v',
      help: '-h'
    },
    default: {
      host: 'localhost',
      port: 1883,
      qos: 0,
      retain: false,
      clean: true,
      keepAlive: 30 // 30 sec
    }
  })

  if (args.help) {
    return helpMe.toStdout('subscribe');
  }

  args.topic = args.topic || args._.shift();

  if (!args.topic) {
    console.error('missing topic\n')
    return helpMe.toStdout('subscribe');
  }

  if (args.key) {
    args.key = fs.readFileSync(key);
  }

  if (args.cert) {
    args.cert = fs.readFileSync(cert);
  }

  if (args.ca) {
    args.ca = fs.readFileSync(ca);
  }

  if (args.key && args.cert && !args.protocol) {
    args.protocol = 'mqtts'
  }

  if (args['will-topic']) {
    args.will = {};
    args.will.topic = args['will-topic'];
    args.will.payload = args['will-message'];
    args.will.qos = args['will-qos'];
    args.will.retain = args['will-retain'];
  }

  args.keepAlive = args['keep-alive'];

  var client = mqtt.connect(args);
  client.subscribe(args.topic)

  client.on('message', function(topic, payload) {
    if (args.verbose) {
      console.log(topic, payload)
    } else {
      console.log(payload)
    }
  })
}

module.exports = start;

if (require.main === module) {
  start(process.argv.slice(2))
}
<commit_msg>Subscribe during the 'connect' event in sub CLI, to support reconnections<commit_after>#!/usr/bin/env node

var mqtt      = require('../')
  , path      = require('path')
  , fs        = require('fs')
  , concat    = require('concat-stream')
  , helpMe    = require('help-me')({
      dir: path.join(__dirname, '..', 'doc')
    })
  , minimist  = require('minimist');

function send(args) {
}

function start(args) {
  args = minimist(args, {
    string: ['host', 'username', 'password', 'key', 'cert'],
    integer: ['port', 'qos', 'keepAlive'],
    boolean: ['stdin', 'help', 'clean'],
    alias: {
      port: 'p',
      host: 'h',
      topic: 't',
      qos: 'q',
      clean: 'c',
      keepAlive: 'k',
      clientId: ['i', 'id'],
      username: 'u',
      password: 'P',
      protocol: 'C',
      verbose: 'v',
      help: '-h'
    },
    default: {
      host: 'localhost',
      port: 1883,
      qos: 0,
      retain: false,
      clean: true,
      keepAlive: 30 // 30 sec
    }
  })

  if (args.help) {
    return helpMe.toStdout('subscribe');
  }

  args.topic = args.topic || args._.shift();

  if (!args.topic) {
    console.error('missing topic\n')
    return helpMe.toStdout('subscribe');
  }

  if (args.key) {
    args.key = fs.readFileSync(key);
  }

  if (args.cert) {
    args.cert = fs.readFileSync(cert);
  }

  if (args.ca) {
    args.ca = fs.readFileSync(ca);
  }

  if (args.key && args.cert && !args.protocol) {
    args.protocol = 'mqtts'
  }

  if (args['will-topic']) {
    args.will = {};
    args.will.topic = args['will-topic'];
    args.will.payload = args['will-message'];
    args.will.qos = args['will-qos'];
    args.will.retain = args['will-retain'];
  }

  args.keepAlive = args['keep-alive'];

  var client = mqtt.connect(args);

  client.on('connect', function() {
    client.subscribe(args.topic);
  });

  client.on('message', function(topic, payload) {
    if (args.verbose) {
      console.log(topic, payload)
    } else {
      console.log(payload)
    }
  });
}

module.exports = start;

if (require.main === module) {
  start(process.argv.slice(2))
}
<|endoftext|>


<commit_before>angular.module( 'countryCapitalsAppModel', [ 'geonamesLibrary' ] )

// getCapitalInfo( countryObject )
// extend a country with additional information about the capital
.factory( 'countryCapitalsModel', [ 'geonames', 'SEARCH_CODE_CAPITAL',
                           function( geonames,   SEARCH_CODE_CAPITAL ) {

	return ({
		listCountries: function() {
			return geonames.listCountries();
		},
		getCountry: function( countryCode ) {
			return geonames.getCountry( countryCode ).then(function( country ) {
				// prep for extending capital info
				if ( typeof country === 'object' ) {
					country.capital = { name: country.capital };
				}
				return country;
			});
		},
		extendCountryInfoWithCapital: function( country ) {
			return geonames.search( country.capital.name, SEARCH_CODE_CAPITAL ).then(function( data ) {
				// parse lat/long as floats
				data.geonames[ 0 ].lat = parseFloat( data.geonames[ 0 ].lat );
				data.geonames[ 0 ].lng = parseFloat( data.geonames[ 0 ].lng );
				angular.extend( country.capital, data.geonames[ 0 ]);
			});
		},
		getCountryNeighbours: function( country ) {
			return geonames.listNeighbours( country );
		}
	});
}])
;
<commit_msg>handle missing capital (fixes #3)<commit_after>angular.module( 'countryCapitalsAppModel', [ 'geonamesLibrary' ] )

// getCapitalInfo( countryObject )
// extend a country with additional information about the capital
.factory( 'countryCapitalsModel', [ 'geonames', 'SEARCH_CODE_CAPITAL', '$q',
                           function( geonames,   SEARCH_CODE_CAPITAL,   $q ) {

	return ({
		listCountries: function() {
			return geonames.listCountries();
		},
		getCountry: function( countryCode ) {
			return geonames.getCountry( countryCode ).then(function( country ) {
				// prep for extending capital info
				if ( typeof country === 'object' && country.capital ) {
					country.capital = { name: country.capital };
				}
				return country;
			});
		},
		extendCountryInfoWithCapital: function( country ) {
			if ( ! country.capital ) {
				return $q.defer().promise;
			}
			return geonames.search( country.capital.name, SEARCH_CODE_CAPITAL ).then(function( data ) {
				// parse lat/long as floats
				data.geonames[ 0 ].lat = parseFloat( data.geonames[ 0 ].lat );
				data.geonames[ 0 ].lng = parseFloat( data.geonames[ 0 ].lng );
				angular.extend( country.capital, data.geonames[ 0 ]);
			});
		},
		getCountryNeighbours: function( country ) {
			return geonames.listNeighbours( country );
		}
	});
}])
;
<|endoftext|>


<commit_before>import React from 'react';
import {
  Row,
  Column,
  FlexVideo
} from 'react-foundation';

export const FlexVideoDocs = () => (

    <Row>
      <Column large={12}>

Flex Video

          <FlexVideo>

          </FlexVideo>
          <FlexVideo isWidescreen>

          </FlexVideo>
          <FlexVideo isWidescreen isVimeo>

          </FlexVideo>

      </Column>
    </Row>

);

export default FlexVideoDocs;
<commit_msg>Use protocol-independent URL for the video player (fixes #1)<commit_after>import React from 'react';
import {
  Row,
  Column,
  FlexVideo
} from 'react-foundation';

export const FlexVideoDocs = () => (

    <Row>
      <Column large={12}>

Flex Video

          <FlexVideo>

          </FlexVideo>
          <FlexVideo isWidescreen>

          </FlexVideo>
          <FlexVideo isWidescreen isVimeo>

          </FlexVideo>

      </Column>
    </Row>

);

export default FlexVideoDocs;
<|endoftext|>


<commit_before><commit_msg>not pass onChange to SelectableGroup wrapper<commit_after><|endoftext|>


<commit_before>import { connect } from 'react-redux'
import ErrorBoundary from '../components/ErrorBoundary'
import Footer from '@twreporter/react-components/lib/footer'
import Header from '@twreporter/universal-header/lib/containers/header'
import mq from '@twreporter/core/lib/utils/media-query'
import PropTypes from 'prop-types'
import React from 'react'
import WebPush from '../components/web-push'
import styled from 'styled-components'
import twreporterRedux from '@twreporter/redux'
import uiConst from '../constants/ui'
import uiManager from '../managers/ui-manager'

// lodash
import get from 'lodash/get'
import values from 'lodash/values'

const _ = {
  get,
  values,
}

const { reduxStateFields } = twreporterRedux

const AppBox = styled.div`
  background-color: ${props => props.backgroundColor};
`

const ContentBlock = styled.div`
  position: relative;
`

const TransparentHeader = styled.div`
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 1;
  ${mq.mobileOnly`
    position: relative;
  `}
`

// TODO add `pink` theme to universal-header
const PinkBackgroundHeader = styled.div`
  position: relative;
  background-color: #fabcf0;
`

const renderFooter = footerType => {
  switch (footerType) {
    case uiConst.footer.none: {
      return null
    }
    case uiConst.footer.default:
    default: {
      return <Footer />
    }
  }
}

const renderHeader = (headerType, releaseBranch) => {
  switch (headerType) {
    case uiConst.header.none: {
      return null
    }
    case uiConst.header.pink: {
      return (
        <PinkBackgroundHeader>
          <Header
            theme="transparent"
            releaseBranch={releaseBranch}
            isLinkExternal={false}
          />
        </PinkBackgroundHeader>
      )
    }
    case uiConst.header.photo: {
      return (
        <Header
          theme="photography"
          releaseBranch={releaseBranch}
          isLinkExternal={false}
        />
      )
    }
    case uiConst.header.transparent: {
      return (
        <TransparentHeader>
          <Header
            theme="transparent"
            releaseBranch={releaseBranch}
            isLinkExternal={false}
          />
        </TransparentHeader>
      )
    }
    default: {
      return (
        <Header
          theme="normal"
          releaseBranch={releaseBranch}
          isLinkExternal={false}
        />
      )
    }
  }
}

class AppShell extends React.PureComponent {
  static propTypes = {
    apiOrigin: PropTypes.string,
    backgroundColor: PropTypes.string,
    footerType: PropTypes.oneOf(_.values(uiConst.footer)),
    headerType: PropTypes.oneOf(_.values(uiConst.header)),
    releaseBranch: PropTypes.string.isRequired,
    userId: PropTypes.string,
    children: PropTypes.oneOfType([
      PropTypes.arrayOf(PropTypes.node),
      PropTypes.node,
    ]),
  }

  static defaultProps = {
    headerType: uiConst.header.default,
    footerType: uiConst.footer.default,
    backgroundColor: '#f1f1f1',
  }

  render() {
    const {
      apiOrigin,
      headerType,
      footerType,
      backgroundColor,
      releaseBranch,
      children,
      userId,
    } = this.props

    return (
      <ErrorBoundary>
        <AppBox backgroundColor={backgroundColor}>
          <ContentBlock>
            <WebPush apiOrigin={apiOrigin} userId={userId} />
            {renderHeader(headerType, releaseBranch)}
            {children}
            {renderFooter(footerType)}
          </ContentBlock>
        </AppBox>
      </ErrorBoundary>
    )
  }
}

function mapStateToProps(state, ownProps) {
  return Object.assign(
    {
      apiOrigin: _.get(state, [reduxStateFields.origins, 'api'], ''),
      userId: _.get(state, [reduxStateFields.auth, 'userInfo.id']),
    },
    uiManager.getLayoutObj(state, ownProps.location)
  )
}

export default connect(mapStateToProps)(AppShell)
<commit_msg>fix: update footer when host or pathname changes<commit_after>import { connect } from 'react-redux'
import ErrorBoundary from '../components/ErrorBoundary'
import Footer from '@twreporter/react-components/lib/footer'
import Header from '@twreporter/universal-header/lib/containers/header'
import mq from '@twreporter/core/lib/utils/media-query'
import PropTypes from 'prop-types'
import React from 'react'
import WebPush from '../components/web-push'
import styled from 'styled-components'
import twreporterRedux from '@twreporter/redux'
import uiConst from '../constants/ui'
import uiManager from '../managers/ui-manager'

// lodash
import get from 'lodash/get'
import values from 'lodash/values'

const _ = {
  get,
  values,
}

const { reduxStateFields } = twreporterRedux

const AppBox = styled.div`
  background-color: ${props => props.backgroundColor};
`

const ContentBlock = styled.div`
  position: relative;
`

const TransparentHeader = styled.div`
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 1;
  ${mq.mobileOnly`
    position: relative;
  `}
`

// TODO add `pink` theme to universal-header
const PinkBackgroundHeader = styled.div`
  position: relative;
  background-color: #fabcf0;
`

const renderFooter = (footerType, pathname = '', host = '') => {
  switch (footerType) {
    case uiConst.footer.none: {
      return null
    }
    case uiConst.footer.default:
    default: {
      return <Footer host={host} pathname={pathname} />
    }
  }
}

const renderHeader = (headerType, releaseBranch) => {
  switch (headerType) {
    case uiConst.header.none: {
      return null
    }
    case uiConst.header.pink: {
      return (
        <PinkBackgroundHeader>
          <Header
            theme="transparent"
            releaseBranch={releaseBranch}
            isLinkExternal={false}
          />
        </PinkBackgroundHeader>
      )
    }
    case uiConst.header.photo: {
      return (
        <Header
          theme="photography"
          releaseBranch={releaseBranch}
          isLinkExternal={false}
        />
      )
    }
    case uiConst.header.transparent: {
      return (
        <TransparentHeader>
          <Header
            theme="transparent"
            releaseBranch={releaseBranch}
            isLinkExternal={false}
          />
        </TransparentHeader>
      )
    }
    default: {
      return (
        <Header
          theme="normal"
          releaseBranch={releaseBranch}
          isLinkExternal={false}
        />
      )
    }
  }
}

class AppShell extends React.PureComponent {
  static propTypes = {
    apiOrigin: PropTypes.string,
    backgroundColor: PropTypes.string,
    footerType: PropTypes.oneOf(_.values(uiConst.footer)),
    headerType: PropTypes.oneOf(_.values(uiConst.header)),
    releaseBranch: PropTypes.string.isRequired,
    userId: PropTypes.string,
    children: PropTypes.oneOfType([
      PropTypes.arrayOf(PropTypes.node),
      PropTypes.node,
    ]),
    pathname: PropTypes.string.isRequired,
    host: PropTypes.string.isRequired,
  }

  static defaultProps = {
    headerType: uiConst.header.default,
    footerType: uiConst.footer.default,
    backgroundColor: '#f1f1f1',
  }

  render() {
    const {
      apiOrigin,
      headerType,
      footerType,
      backgroundColor,
      releaseBranch,
      children,
      userId,
      pathname,
      host,
    } = this.props

    return (
      <ErrorBoundary>
        <AppBox backgroundColor={backgroundColor}>
          <ContentBlock>
            <WebPush apiOrigin={apiOrigin} userId={userId} />
            {renderHeader(headerType, releaseBranch)}
            {children}
            {renderFooter(footerType, pathname, host)}
          </ContentBlock>
        </AppBox>
      </ErrorBoundary>
    )
  }
}

function mapStateToProps(state, ownProps) {
  return Object.assign(
    {
      apiOrigin: _.get(state, [reduxStateFields.origins, 'api'], ''),
      userId: _.get(state, [reduxStateFields.auth, 'userInfo.id']),
      pathname: _.get(ownProps.location, 'pathname', ''),
      host: _.get(ownProps.location, 'host', ''),
    },
    uiManager.getLayoutObj(state, ownProps.location)
  )
}

export default connect(mapStateToProps)(AppShell)
<|endoftext|>


<commit_before>// Copyright 2013 Google Inc. All Rights Reserved.

/**
 * @fileoverview
 * Provides methods for the utility methods needed to render the Google+
 * Sign-In button.
 *
 * @author dhermes@google.com (Danny Hermes)
 */

/** google global namespace for Google projects. */
var google = google || {};

/** devrel namespace for Google Developer Relations projects. */
google.devrel = google.devrel || {};

/** samples namespace for DevRel sample code. */
google.devrel.samples = google.devrel.samples || {};

/** TicTacToe namespace for this sample. */
google.devrel.samples.ttt = google.devrel.samples.ttt || {};

/**
 * Client ID of the application (from the APIs Console).
 * @type {string}
 */
google.devrel.samples.ttt.CLIENT_ID =
    'YOUR-CLIENT-ID';

/**
 * Scopes used by the application.
 * @type {string}
 */
google.devrel.samples.ttt.SCOPES =
    'https://www.googleapis.com/auth/userinfo.email ' +
    'https://www.googleapis.com/auth/plus.login';

/**
 * Parses email from the claim set of a JWT ID token.
 *
 * NOTE: We are not validating the ID token since from a trusted source.
 *       We are simply parsed the value from the JWT.
 *
 * See http://www.tbray.org/ongoing/When/201x/2013/04/04/ID-Tokens
 * or
 * http://openid.net/specs/openid-connect-messages-1_0.html#StandardClaims
 * for more info.
 *
 * @param {string} idToken A base64 JWT containing a user ID token.
 * @return {string} The email parsed from the claim set, else undefined
 *                  if one can't be parsed.
 */
google.devrel.samples.ttt.getEmailFromIDToken = function(idToken) {
  if (typeof idToken !== 'string') {
    return;
  }

  var segments = idToken.split('.');
  if segments.length !== 3 {
    return;
  }

  try {
    var claimSet = JSON.parse(atob(claimSet));
  } catch (e) {
    return;
  }

  if (claimSet.email && typeof claimSet.email === 'string') {
    return claimSet.email;
  }
}

/**
 * Handles the Google+ Sign In response.
 *
 * Success calls google.devrel.samples.ttt.init. Failure makes the Sign-In
 * button visible.
 *
 * @param {Object} authResult The contents returned from the Google+
 *                            Sign In attempt.
 */
google.devrel.samples.ttt.signinCallback = function(authResult) {
  var tokenEmail = google.devrel.samples.ttt.getEmailFromIDToken(
      authResult.id_token);
  if (authResult.access_token && tokenEmail) {
    google.devrel.samples.ttt.init('//' + window.location.host + '/_ah/api',
                                   tokenEmail);

    document.getElementById('signinButtonContainer').classList.remove(
        'visible');
    document.getElementById('signedInStatus').classList.add('visible');
  } else {
    document.getElementById('signinButtonContainer').classList.add('visible');
    document.getElementById('signedInStatus').classList.remove('visible');

    if (!authResult.error) {
      console.log('Unexpected result');
      console.log(authResult);
    } else if (authResult.error !== 'immediate_failed') {
      console.log('Unexpected error occured: ' + authResult.error);
    } else {
      console.log('Immediate mode failed, user needs to click Sign In.');
    }
  }
};

/**
 * Renders the Google+ Sign-in button using auth parameters.
 */
google.devrel.samples.ttt.render = function() {
  gapi.signin.render('signinButton', {
    'callback': google.devrel.samples.ttt.signinCallback,
    'clientid': google.devrel.samples.ttt.CLIENT_ID,
    'cookiepolicy': 'single_host_origin',
    'requestvisibleactions': 'http://schemas.google.com/AddActivity',
    'scope': google.devrel.samples.ttt.SCOPES
  });
};
// A quirk of the JSONP callback of the plusone client makes it so
// our callback must exist as an element in window.
window['google.devrel.samples.ttt.render'] = google.devrel.samples.ttt.render;

// Recommended code to load Google+ JS library.
(function() {
  var newScriptElement = document.createElement('script');
  newScriptElement.type = 'text/javascript';
  newScriptElement.async = true;
  newScriptElement.src = 'https://apis.google.com/js/client:plusone.js' +
                         '?onload=google.devrel.samples.ttt.render';
  var firstScriptElement = document.getElementsByTagName('script')[0];
  firstScriptElement.parentNode.insertBefore(newScriptElement,
                                             firstScriptElement);
})();
<commit_msg>fix syntax; fix idToken parsing<commit_after>// Copyright 2013 Google Inc. All Rights Reserved.

/**
 * @fileoverview
 * Provides methods for the utility methods needed to render the Google+
 * Sign-In button.
 *
 * @author dhermes@google.com (Danny Hermes)
 */

/** google global namespace for Google projects. */
var google = google || {};

/** devrel namespace for Google Developer Relations projects. */
google.devrel = google.devrel || {};

/** samples namespace for DevRel sample code. */
google.devrel.samples = google.devrel.samples || {};

/** TicTacToe namespace for this sample. */
google.devrel.samples.ttt = google.devrel.samples.ttt || {};

/**
 * Client ID of the application (from the APIs Console).
 * @type {string}
 */
google.devrel.samples.ttt.CLIENT_ID =
    'YOUR-CLIENT-ID';

/**
 * Scopes used by the application.
 * @type {string}
 */
google.devrel.samples.ttt.SCOPES =
    'https://www.googleapis.com/auth/userinfo.email ' +
    'https://www.googleapis.com/auth/plus.login';

/**
 * Parses email from the claim set of a JWT ID token.
 *
 * NOTE: We are not validating the ID token since from a trusted source.
 *       We are simply parsed the value from the JWT.
 *
 * See http://www.tbray.org/ongoing/When/201x/2013/04/04/ID-Tokens
 * or
 * http://openid.net/specs/openid-connect-messages-1_0.html#StandardClaims
 * for more info.
 *
 * @param {string} idToken A base64 JWT containing a user ID token.
 * @return {string} The email parsed from the claim set, else undefined
 *                  if one can't be parsed.
 */
google.devrel.samples.ttt.getEmailFromIDToken = function(idToken) {
  if (typeof idToken !== 'string') {
    return;
  }

  var segments = idToken.split('.');
  if (segments.length !== 3) {
    return;
  }

  try {
    var claimSet = JSON.parse(atob(segments[1]));
  } catch (e) {
    return;
  }

  if (claimSet.email && typeof claimSet.email === 'string') {
    return claimSet.email;
  }
}

/**
 * Handles the Google+ Sign In response.
 *
 * Success calls google.devrel.samples.ttt.init. Failure makes the Sign-In
 * button visible.
 *
 * @param {Object} authResult The contents returned from the Google+
 *                            Sign In attempt.
 */
google.devrel.samples.ttt.signinCallback = function(authResult) {
  var tokenEmail = google.devrel.samples.ttt.getEmailFromIDToken(
      authResult.id_token);
  if (authResult.access_token && tokenEmail) {
    google.devrel.samples.ttt.init('//' + window.location.host + '/_ah/api',
                                   tokenEmail);

    document.getElementById('signinButtonContainer').classList.remove(
        'visible');
    document.getElementById('signedInStatus').classList.add('visible');
  } else {
    document.getElementById('signinButtonContainer').classList.add('visible');
    document.getElementById('signedInStatus').classList.remove('visible');

    if (!authResult.error) {
      console.log('Unexpected result');
      console.log(authResult);
    } else if (authResult.error !== 'immediate_failed') {
      console.log('Unexpected error occured: ' + authResult.error);
    } else {
      console.log('Immediate mode failed, user needs to click Sign In.');
    }
  }
};

/**
 * Renders the Google+ Sign-in button using auth parameters.
 */
google.devrel.samples.ttt.render = function() {
  gapi.signin.render('signinButton', {
    'callback': google.devrel.samples.ttt.signinCallback,
    'clientid': google.devrel.samples.ttt.CLIENT_ID,
    'cookiepolicy': 'single_host_origin',
    'requestvisibleactions': 'http://schemas.google.com/AddActivity',
    'scope': google.devrel.samples.ttt.SCOPES
  });
};
// A quirk of the JSONP callback of the plusone client makes it so
// our callback must exist as an element in window.
window['google.devrel.samples.ttt.render'] = google.devrel.samples.ttt.render;

// Recommended code to load Google+ JS library.
(function() {
  var newScriptElement = document.createElement('script');
  newScriptElement.type = 'text/javascript';
  newScriptElement.async = true;
  newScriptElement.src = 'https://apis.google.com/js/client:plusone.js' +
                         '?onload=google.devrel.samples.ttt.render';
  var firstScriptElement = document.getElementsByTagName('script')[0];
  firstScriptElement.parentNode.insertBefore(newScriptElement,
                                             firstScriptElement);
})();
<|endoftext|>


<commit_before>import React from 'react'
import PropTypes from 'prop-types'
import {storiesOf} from '@storybook/react'
import {action} from '@storybook/addon-actions'
import {withKnobs, boolean} from '@storybook/addon-knobs'

import Select from './'
import {Select as Raw} from './Select'

const options = [
  {key: 1, display: 'Option 1'},
  {key: 2, display: 'Option 2'},
  {key: 3, display: 'Option 3'},
  {key: 4, display: 'Option 4'},
  {key: 5, display: 'Option 5'}
]

export class SelectStory extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      isLoading: false,
      options: null,
      value: [{key: 3, display: 'Option 3'}],
      moreOptionsAvailable: false,
      tooltips: {}
    }
  }

  fetchOptions = () => {
    if (this.state.options === null) {
      this.setState({...this.state, options: null, isLoading: true})
      setTimeout(() => { this.setState({...this.state, options, isLoading: false}) }, this.props.delay || 0)
    }
  }

  searchOptions = () => {
    this.setState({...this.state, options: null, isLoading: true})
    setTimeout(() => {
      this.setState({
        ...this.state,
        options: options.filter((e, idx) => idx % 2 === 0),
        isLoading: false,
        moreOptionsAvailable: true
      })
    }, this.props.delay || 0)
  }

  setValue = value => {
    this.setState({...this.state, value})
  }

  loadToolTip = key => {
    if (!this.state.tooltips[key]) {
      this.setState({...this.state, tooltips: {...this.state.tooltips, [key]: `TOOL TIP ${key}`}})
    }
  }

  render() {
    return (

        <Select
          isMulti={this.props.isMulti}
          fetchOptions={this.fetchOptions}
          searchOptions={this.searchOptions}
          options={this.state.options}
          isLoading={this.state.isLoading}
          onChange={this.setValue}
          value={this.state.value}
          noResultsText="No more options."
          moreOptionsAvailable={this.state.moreOptionsAvailable}
          moreOptionsAvailableText="More options available"
          openAdvancedSearch={action('open advanced search')}
          tooltips={this.state.tooltips}
          loadTooltip={this.loadToolTip}
        />

    )
  }
}

SelectStory.propTypes = {
  isMulti: PropTypes.bool,
  delay: PropTypes.number
}

storiesOf('Select', module)
  .addDecorator(withKnobs)
  .add(
    'Select',
    () => <SelectStory isMulti={boolean('isMulti', true)} delay={2000} action={action}/>,
    {info: {propTables: [Raw], propTablesExclude: [SelectStory], source: false}}
  )
<commit_msg>refactor(tocco-ui): extend story of Select<commit_after>import React from 'react'
import PropTypes from 'prop-types'
import {storiesOf} from '@storybook/react'
import {action} from '@storybook/addon-actions'
import {withKnobs, boolean} from '@storybook/addon-knobs'

import Select from './'
import {Select as Raw} from './Select'

const options = [
  {key: 1, display: 'Option 1'},
  {key: 2, display: 'Option 2'},
  {key: 3, display: 'Option 3'},
  {key: 4, display: 'Option 4'},
  {key: 5, display: 'Option 5'}
]

export class SelectStory extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      isLoading: false,
      options: null,
      value: [{key: 3, display: 'Option 3'}],
      moreOptionsAvailable: false,
      tooltips: {}
    }
  }

  fetchOptions = () => {
    if (this.state.options === null) {
      this.setState({...this.state, options: null, isLoading: true})
      setTimeout(() => { this.setState({...this.state, options, isLoading: false}) }, this.props.delay || 0)
    }
  }

  searchOptions = () => {
    this.setState({...this.state, options: null, isLoading: true})
    setTimeout(() => {
      this.setState({
        ...this.state,
        options: options.filter((e, idx) => idx % 2 === 0),
        isLoading: false,
        moreOptionsAvailable: true
      })
    }, this.props.delay || 0)
  }

  setValue = value => {
    this.setState({...this.state, value})
  }

  loadToolTip = key => {
    if (!this.state.tooltips[key]) {
      this.setState({...this.state, tooltips: {...this.state.tooltips, [key]: `TOOL TIP ${key}`}})
    }
  }

  render() {
    return (

        <Select
          fetchOptions={this.fetchOptions}
          isLoading={this.state.isLoading}
          isMulti={this.props.isMulti}
          loadTooltip={this.loadToolTip}
          moreOptionsAvailable={this.state.moreOptionsAvailable}
          moreOptionsAvailableText="More options available"
          noResultsText="No more options."
          onChange={this.setValue}
          openAdvancedSearch={action('open advanced search')}
          options={this.state.options}
          readOnly={this.props.readOnly}
          searchOptions={this.searchOptions}
          tooltips={this.state.tooltips}
          value={this.state.value}
        />

    )
  }
}

SelectStory.propTypes = {
  delay: PropTypes.number,
  isMulti: PropTypes.bool,
  readOnly: PropTypes.bool
}

storiesOf('Select', module)
  .addDecorator(withKnobs)
  .add(
    'Select',
    () =>
      <SelectStory
        action={action}
        delay={2000}
        isMulti={boolean('isMulti', true)}
        readOnly={boolean('readOnly', true)}
      />,
    {info: {propTables: [Raw], propTablesExclude: [SelectStory], source: false}}
  )
<|endoftext|>


<commit_before>/*
 * Copyright 2010 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

addScriptToInject(function() {

chrome_comp.CompDetect.declareDetector(

'table_cellspacing_border_collapse',

chrome_comp.CompDetect.ScanDomBaseDetector,

null, // constructor

function checkNode(node, context) {
  if (Node.ELEMENT_NODE != node.nodeType)
    return;

  if (context.isDisplayNone())
    return;

  var computedStyle = chrome_comp.getComputedStyle(node);
  var display = computedStyle.display;
  if (display == 'table' || display == 'inline-table') {
    var borderCollapse = computedStyle.borderCollapse;
    switch (borderCollapse) {
      case 'collapse':
        if (node.hasAttribute('cellspacing')
            && parseInt(node.getAttribute('cellspacing'),10) > 0
            && node.childElementCount > 0 ){
            this.addProblem('RX1008', [node]);
        }
        break;
      case 'separate':
        var hSpacing =
          parseInt(computedStyle.WebkitBorderHorizontalSpacing, 10)|0;
        var vSpacing =
          parseInt(computedStyle.WebkitBorderVerticalSpacing, 10)|0;

        if (node.tagName == 'TABLE'){
          if (node.hasAttribute('cellspacing')) {
            var spacing = parseInt(node.getAttribute('cellspacing',10))|0;
            if ( (hSpacing && hSpacing != spacing) ||
               (vSpacing && vSpacing != spacing)){
              this.addProblem('RE1020', [node]);
              return;
            }
           } else {
           // 2px is talbe tag default table-cell space in chrome
            if (hSpacing != 0 || vSpacing != 0 ){
              this.addProblem('RE1020', [node]);
              return;
            }
          }
        }
        // other html tag set display:table and display:inline-table
        if (node.tagName != 'TABLE' && (hSpacing || vSpacing) )
           this.addProblem('RE1020', [node]);
        break;
    }
  }
}
); // declareDetector

});
<commit_msg>将检测宽容度提高2px，避免报出后无明显显示差异。<commit_after>/*
 * Copyright 2010 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

addScriptToInject(function() {

chrome_comp.CompDetect.declareDetector(

'table_cellspacing_border_collapse',

chrome_comp.CompDetect.ScanDomBaseDetector,

null, // constructor

function checkNode(node, context) {
  if (Node.ELEMENT_NODE != node.nodeType)
    return;

  if (context.isDisplayNone())
    return;

  var computedStyle = chrome_comp.getComputedStyle(node);
  var display = computedStyle.display;
  if (display == 'table' || display == 'inline-table') {
    var borderCollapse = computedStyle.borderCollapse;
    switch (borderCollapse) {
      case 'collapse':
        if (node.hasAttribute('cellspacing')
            && parseInt(node.getAttribute('cellspacing'),10) > 0
            && node.childElementCount > 0 ){
            this.addProblem('RX1008', [node]);
        }
        break;
      case 'separate':
        var hSpacing =
          parseInt(computedStyle.WebkitBorderHorizontalSpacing, 10)|0;
        var vSpacing =
          parseInt(computedStyle.WebkitBorderVerticalSpacing, 10)|0;

        if (node.tagName == 'TABLE'){
          if (node.hasAttribute('cellspacing')) {
            var spacing = parseInt(node.getAttribute('cellspacing',10))|0;
            if ( (hSpacing && hSpacing != spacing) ||
               (vSpacing && vSpacing != spacing)){
              this.addProblem('RE1020', [node]);
              return;
            }
           } else {
           // 2px is talbe tag default table-cell space in chrome
            if (hSpacing > 2 || vSpacing > 2 ){
              this.addProblem('RE1020', [node]);
              return;
            }
          }
        }
        // other html tag set display:table and display:inline-table
        if (node.tagName != 'TABLE' && (hSpacing || vSpacing) )
           this.addProblem('RE1020', [node]);
        break;
    }
  }
}
); // declareDetector

});
<|endoftext|>