Пример #1
0
        addEventHandlers: function addEventHandlers() {
            if (!vhSupport) {
                this.$window.on('resize', throttle(this.setHeight, 250).bind(this));
            }

            this.$window.on('keyup', throttle(this.keyCapture, 250).bind(this));
        },
Пример #2
0
                    fastdom.write(function () {
                        /**
                         * Set the item styles before creating the Sly instance
                         */
                        this.updateItemStyles();

                        /**
                         * Magic!
                         */
                        this.sly = new Sly(this.$frame, this.config.options);

                        /**
                         * Set up callbacks for Sly
                         * Note: The throttle count can be high because if the event is touch or drag based, the event
                         * can fire lots of times consecutively
                         */
                        this.sly.on('change', debounce(this.slideChanged, 250).bind(this));
                        this.sly.on('moveStart', throttle(this.lockCarousel, 250).bind(this));
                        this.sly.on('moveEnd', throttle(this.unlockCarousel, 250).bind(this));

                        this.sly.init();

                        /**
                         * Set the state of the navigation buttons
                         */
                        if (this.config.pageNav) {
                            this.setPageNavigationStates();
                        }
                    }.bind(this));
Пример #3
0
            events: function events () {
                this.$window.on('resize', throttle(this.resizeHandler, 250).bind(this));

                if (this.config.pageNav) {
                    this.$frame.on('click.pageNav', '.js-carousel-page-left, .js-carousel-page-right', this.pageNavigation);
                }
            },
Пример #4
0
  buildActiveRequests (grid) {
    const activeRequests = grid.set(3, 7, 6, 5, contrib.sparkline, {
      label: 'Active requests queued',
      tags: true,
      style: {
        fg: 'blue',
      },
    });

    let maxRequests = {};

    this.emitter.on('activeRequests', (requests) => {
      this.activeRequests = requests;
    });

    this.emitter.on('activeRequests', throttle(function(requests) {
      let titles = Object.keys(requests).map((k) => {
        let latest = requests[k][requests[k].length - 1];

        if (!maxRequests[k] || latest > maxRequests[k]) {
          maxRequests[k] = latest;
        }

        return `${k} [${latest}] (M: ${maxRequests[k]})`;
      });

      activeRequests.setData(
        titles,
        Object.values(requests)
      );
    }, 500));
  }
Пример #5
0
  return store => next => {
    const throttled = throttle(next, wait, options);

    return action => {
      if (types.indexOf(action.type) === -1) {
        return next(action);
      }
      return throttled(action);
    }
  }
Пример #6
0
export function stopScroll(elClass, delay=50) {
  return throttle(function stopScroll(e) {
    let touchMoveAllowed = false;
    let target = e.target;

    while (target !== null) {
      if (target.classList && target.classList.contains(elClass)) {
        if (elementCanScroll(target)) {
          touchMoveAllowed = true;
        }
        break;
      }

      target = target.parentNode;
    }

    if (!touchMoveAllowed) {
      e.preventDefault();
    }
  }, delay);
}
Пример #7
0
        events: function events() {
            gmaps.event.addDomListener(window, 'resize', throttle(this.handleResize, 250).bind(this));

            this.$toolbar.on('click', '.js-change-travel-mode', $.proxy(this.handleChangeTravelMode, this)).on('keyup', '.js-change-location', throttle($.proxy(this.handleChangeUserLocation, this))).on('submit click', '.js-submit-directions', $.proxy(this.handleFormSubmit, this));
        },
Пример #8
0
function advanced( editor ) {
	var button, updateVisibleState;

	function isAdvancedVisible() {
		return !! PreferencesStore.get( 'editorAdvancedVisible' );
	}

	function toggleAdvancedVisible() {
		PreferencesActions.set( 'editorAdvancedVisible', ! isAdvancedVisible() );
	}

	updateVisibleState = throttle( function() {
		var toolbars = editor.theme.panel.find( '.toolbar:not(.menubar)' ),
			isSmallViewport = isWithinBreakpoint( '<960px' ),
			containerPadding = 0;

		toolbars.each( function( toolbar, i ) {
			var isToolbarVisible = isSmallViewport || i === 0 || isAdvancedVisible();

			toolbar.visible( isToolbarVisible );

			if ( isAdvancedVisible ) {
				if ( isSmallViewport ) {
					containerPadding = Math.max( containerPadding, toolbar.getEl().clientHeight );
				} else {
					containerPadding += toolbar.getEl().clientHeight;
				}
			}
		} );

		tinymce.DOM.setStyles( editor.getContainer(), {
			'padding-top': containerPadding
		} );

		if ( button ) {
			button.active( isAdvancedVisible() );
		}
	}, 500 );

	editor.addButton( 'wpcom_advanced', {
		text: 'Toggle Advanced',
		tooltip: 'Toggle Advanced',
		classes: 'btn advanced',
		cmd: 'WPCOM_ToggleAdvancedVisible',
		onPostRender: function() {
			button = this;
		}
	} );

	editor.addCommand( 'WPCOM_ToggleAdvancedVisible', toggleAdvancedVisible );

	editor.on( 'init', function() {
		PreferencesActions.fetch();
	} );

	editor.on( 'preInit', function() {
		editor.shortcuts.add( 'access+z', '', 'WPCOM_ToggleAdvancedVisible' );
	} );

	editor.on( 'init show', updateVisibleState );

	window.addEventListener( 'resize', updateVisibleState );

	PreferencesStore.on( 'change', function() {
		updateVisibleState();
	} );
}
Пример #9
0
  // Send the process info to the dashboard so it can monitor CPU / Memory usage.
  if (dashboard) {
    dashboard.setProcesses(processes);
  }

  console.log(`listening on ${config.port} on ${config.processes} processes (pids: master: ${process.pid}, workers: ${processes.join(',')}).`);

  if (config.keys.length === 1 && config.keys[0] === 'lambeosaurus') {
    console.warn('WARNING: Using default security keys.');
  }

  let activeRequests = {};

  let sendRequests = throttle(function(requests) {
    if (requests) {
      statsd.increment('activeRequests', requests);
    }
  }, 10000);

  // To communicate between worker threads and the master thread, specifically
  // for the dashboard, we have to send messages; so we bind to `Server` events
  // below, and fire them through the process to here. The dashboard, if running,
  // can then do things with the data sent in.
  cluster.on('message', function(message) {
    if (message.type) {
      switch (message.type) {
        case 'log:request':
          if (dashboard) {
            return dashboard.logRequest(message.args);
          }
Пример #10
0
 componentWillMount() {
   this.changeVolumeThrottled = throttle(this.changeVolume, 200);
 }
Пример #11
0
 moretime: function(ctrl) {
   if (game.moretimeable(ctrl.data)) return m('a.moretime.hint--bottom-left', {
     'data-hint': ctrl.trans('giveNbSeconds', ctrl.data.clock.moretime),
     onclick: throttle(partial(ctrl.socket.send, 'moretime', null), 600)
   }, m('span[data-icon=O]'));
 },
Пример #12
0
define((require) => {
    /**
     * A module for creating embeddable Google Maps
     *
     * @module map
     * @author Sean McEmerson
     * @version 0.4.0
     * @requires lib/stampit
     * @requires lib/fastdom
     * @requires lib/lodash/object/merge
     * @requires lib/lodash/function/throttle
     * @requires lib/jquery
     * @requires modules/ui/currentLayout
     * @requires modules/maps/gmaps
     *
     * @example <caption>Include the module</caption>
     *  let map = require('modules/maps/map');
     *
     * @example <caption>Instantiate the module</caption>
     *  map.init({...config});
     *
     * @example <caption>or...</caption>
     *  let myMap = map();
     *  myMap.init({...config});
     *
     * @example <caption>Container element markup</caption>
     *  <div class="map-embed">
     *      <div id="map-canvas" class="map-embed__canvas"></div>
     *  </div>
     */

    const stampit = require('stampit');
    const fastdom = require('fastdom');
    const merge = require('lodash/object/merge');
    const throttle = require('lodash/function/throttle');
    const currentLayout = require('modules/ui/current-layout');
    const gmaps = require('modules/maps/gmaps');


    const map = stampit()
        .state({
            config: {
                container: {},
                host: {
                    latlng: [],
                    marker: true,
                    markerImage: false,
                    markerTitle: ''
                },
                options: {
                    disableDefaultUI: true,
                    panControl: false,
                    scaleControl: false,
                    scrollwheel: false,
                    zoom: 13,
                    zoomControl: true
                },
                type: 'interactive'
            },
            currentMapType: ''
        })
        .methods({
            /**
             * Hello, world
             * @method init
             */
            init (userConfig) {
                this.config = merge({}, this.config, userConfig);

                /**
                 * Exit if there is no 'host' location to show or the container doesn't exist
                 */
                if (!this.config.host.latlng.length || !this.config.container.length) {
                    return;
                }

                fastdom.write(() => {
                    this.events();
                    this.embedMap();
                });
            },

            /**
             * Add event listeners for the map instance
             * @method events
             */
            events () {
                gmaps.event.addDomListener(
                    window,
                    'resize',
                    throttle(this.handleResize, 250).bind(this)
                );
            },

            /**
             * Embed the appropriate map based on config/env settings
             * @method embedMap
             */
            embedMap () {
                /**
                 * Only embed the map if the layout is not mobile otherwise force the use of a static background image
                 */
                if (this.config.type === 'interactive' && currentLayout.not('~mobile')) {
                    this.embedInteractiveMap();
                } else {
                    this.embedStaticMap();
                }
            },

            /**
             * Embed an interactive Google Map instance.
             * @method embedInteractiveMap
             */
            embedInteractiveMap () {
                this.currentMapType = 'interactive';

                /**
                 * Create our latlng instance if it doesn't exist
                 */
                if (!this.config.host.latlngObject) {
                    this.setLatLng(this.config.host.latlng);
                }

                fastdom.write(() => {
                    /**
                     * Get the target element by using the jQuery object selector value
                     */
                    this.map = new gmaps.Map(
                        document.getElementById(this.config.container.selector.replace('#', '')),
                        this.config.options
                    );

                    /**
                     * Add our custom marker for the host
                     */
                    if (this.config.host.marker) {
                        this.addMarker(
                            this.map,
                            this.config.host.latlngObject,
                            this.config.host.markerTitle
                        );
                    }
                });
            },

            /**
             * Embed a static Google Map image
             * @method embedStaticMap
             */
            embedStaticMap () {
                this.currentMapType = 'static';
                let customMarker = '';

                /**
                 * If a custom marker is defined then add the required param values
                 */
                if (this.config.host.markerImage) {
                    customMarker = 'icon:' + this.config.host.markerImage + '|';
                }

                let image = 'https://maps.google.com/maps/api/staticmap?' +
                    'center=' + this.config.host.latlng[0] + ',' + this.config.host.latlng[1] +
                    '&markers=' + customMarker + this.config.host.latlng[0] + ',' + this.config.host.latlng[1] +
                    '&sensor=true' +
                    '&size=' + this.config.container.outerWidth() + 'x' + this.config.container.outerHeight() +
                    '&zoom=' + this.config.options.zoom;

                fastdom.write(() => {
                    /**
                     * Set style the attribute directly so we can override any styling applied to the element
                     */
                    this.config.container.attr('style', 'background-image: url(' + image + ') !important; background-position: center center !important; background-size: cover !important;');
                });
            },

            /**
             * Handle events when the window is resized.
             * @method handleResize
             */
            handleResize () {
                /**
                 * Embed the map if the layout is no longer mobile
                 */
                if (this.config.type === 'interactive' &&
                    currentLayout.not('~mobile') &&
                    this.currentMapType === 'static') {
                    this.embedInteractiveMap();
                }

                fastdom.write(() => {
                    this.centerMap();
                });
            },

            /**
             * Resize the layout and center the host location after the window is resized.
             * @method centerMap
             */
            centerMap () {
                if (this.map) {
                    gmaps.event.trigger(this.map, 'resize');

                    if (this.config.host.latlngObject) {
                        this.map.setCenter(this.config.host.latlngObject);
                    }
                }
            },

            /**
             * Create a Google Map LatLng instance from the configuration options.
             * @method setLatLng
             * @param {Array} latlng - An array with latitude longitude values
             */
            setLatLng (latlng) {
                /**
                 * Convert values into a LatLng object
                 */
                this.config.host.latlngObject = new gmaps.LatLng(latlng[0], latlng[1]);

                /**
                 * Update the saved center location
                 */
                this.config.options.center = this.config.host.latlngObject;
            },

            /**
             * Add a marker to an interactive map.
             * @param {object} map - a Google Maps instance
             * @param {(array|object)} latlng - Either a Goolge Maps LatLng object or an array with latitude and longitude
             * @param {string} [title] - A title for the marker
             * @method addMarker
             */
            addMarker (_map, latlng, title) {
                /**
                 * If the latlng is not a Google Maps object then it needs to be converted
                 */
                if (!this.config.host.latlngObject) {
                    this.setLatLng(this.config.host.latlng);
                }

                let marker = new gmaps.Marker({
                    animation: gmaps.Animation.DROP,
                    map: _map,
                    position: latlng,
                    title: title
                });

                return marker;
            }
        });


    return map;
});
Пример #13
0
export default function setAppEvents(app, hasHistAndBindLinks, render, $body) {
  app.on('route:desktop', function(route) {
    const options = {};

    const date = new Date();
    date.setFullYear(date.getFullYear() + 2);
    options.expires = date;

    if (window.location.host.indexOf('localhost') === -1) {
      const domain = `.${window.bootstrap.config.reddit}`
        .match(/https?:\/\/(.+)/)[1]
        .split('.')
        .splice(1,2)
        .join('.');

      options.domain = domain;
    }

    cookies.set('__cf_mob_redir', '0', options);

    if (route.indexOf('?') === -1) {
      route += '?ref_source=mweb';
    } else {
      route += '&ref_source=mweb';
    }

    window.location = `https://www.reddit.com${route}`;
  });

  app.on(constants.COMPACT_TOGGLE, function(compact) {
    app.setState('compact', compact);
  });

  app.on(constants.TOGGLE_OVER_18, function(val) {
    cookies.set('over18', val);
  });

  app.on('notification', function(notification) {
    app.setNotification(cookies, notification);
  });

  app.on('pageview', function() {
    // reset notifications once the page loads
    cookies.set('notifications');

    // update the scroll position when data finishes loading
    app.postRender(app.fullPathName())();
  });

  app.on(constants.HIDE_GLOBAL_MESSAGE, function(message) {
    const options = {
      expires: new Date(message.expires),
    };
    cookies.set(message.key, 'globalMessageSeen', options);
  });

  const stopScrollForMenu = stopScroll(constants.OVERLAY_MENU_CSS_CLASS);

  app.on(constants.OVERLAY_MENU_OPEN, function(open) {
    if (!$body.classList) {
      return;
    }

    // Scrolling on Safari is weird, possibly iOS 9. Overflow hidden doesn't
    // prevent the page background from scrolling as you'd expect.
    // When we're on Safari we do a fancy check to stop touchmove events
    // from scrolling the background.
    // We don't use position: fixed becuase the repaint from changing position
    // is slow in safari. Plus there's extra bookkeeping for preserving the
    // scroll position.
    if (open) {
      if ($body.classList.contains(constants.OVERLAY_MENU_VISIBLE_CSS_CLASS)) {
        return;
      }

      $body.classList.add(constants.OVERLAY_MENU_VISIBLE_CSS_CLASS);
      $body.addEventListener('touchmove', stopScrollForMenu);
    } else {
      $body.classList.remove(constants.OVERLAY_MENU_VISIBLE_CSS_CLASS);
      $body.removeEventListener('touchmove', stopScrollForMenu);
    }
  });

  app.on(constants.SET_META_COLOR, setMetaColor);

  let initialUrl = app.fullPathName();
  if (hasHistAndBindLinks) {
    $body.addEventListener('click', function(e) {
      let $link = e.target;

      if ($link.tagName !== 'A') {
        $link = findLinkParent($link);

        if (!$link) {
          return;
        }
      }

      const href = $link.getAttribute('href');
      if (!href) {
        logMissingHref($link, app);
        return;
      }

      // If it has a target=_blank, or an 'external' data attribute, or it's
      // an absolute url, let the browser route rather than forcing a capture.
      if (
        ($link.target === '_blank' || $link.dataset.noRoute === 'true') ||
        href.indexOf('//') > -1
      ) {
        return;
      }

      // If the href contains script ignore it
      if (/^javascript:/.test(href)) {
        return;
      }

      e.preventDefault();

      const currentUrl = app.fullPathName();
      app.scrollCache[currentUrl] = window.scrollY;

      if (href.indexOf('#') === 0) {
        return;
      }

      initialUrl = href;

      // Update the referrer before navigation
      const a = document.createElement('a');
      a.href = currentUrl;
      app.setState('referrer', a.href);

      // Let app.redirect do the heavy lifting. It has the the fancy
      // check for login / register
      app.redirect(href);
    });

    // for initial safari popstate check.
    let ignoredInitialPopState = false;

    window.addEventListener('popstate', function() {
      const href = app.fullPathName();
      if (href === initialUrl && !ignoredInitialPopState) {
        ignoredInitialPopState = true;
        return;
      }

      app.scrollCache[initialUrl] = window.scrollY;

      render(app, href, false, app.modifyContext).then(app.postRender(href));

      initialUrl = href;
    });
  }

  /* Window events */
  window.addEventListener('click', function(e) {
    if (!elementInOtherEl(e.target, constants.DROPDOWN_CSS_CLASS)) {
      // close any opened dropdown by faking another dropdown opening
      app.emit(constants.DROPDOWN_OPEN);
    }
  });

  window.addEventListener('scroll', throttle(function() {
    app.emit(constants.SCROLL);

    // Preseve scroll position if you scroll while waiting for content to load
    const href = app.fullPathName();
    app.scrollCache[href] = window.scrollY;
  }, 100));

  let _lastWinWidth = 0;
  const winWidth = window.innerWidth;

  window.addEventListener('resize', throttle(function() {
    // Prevent resize from firing when chrome shows/hides nav bar
    if (winWidth !== _lastWinWidth) {
      _lastWinWidth = winWidth;
      app.emit(constants.RESIZE);
    }
  }, 100));
}
Пример #14
0
  var MIN_IN_12_HOURS = 720;
  var deltaMinutes = MIN_IN_12_HOURS * percentDelta;

  var now = moment();
  now.add(deltaMinutes, 'm');

  // Round to quarter hour
  var minutes = now.minutes();
  now.add(timeUtils.roundToQuarterHour(minutes) - minutes, 'm');

  appState.setTime(now);

  renderApp();
}

var updateTimeAsPercentThrottled = throttle(updateTimeAsPercent, 100);


function json(res) {
  return res.json();
}
function saveTeamInfo(info) {

  info._csrf = appState.getCSRF();

  var options = {
    method: 'PUT',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
Пример #15
0
define((require) => {
    /**
     * A module for queueing animate.css animations to fire after xx delay, or programmatically.
     *
     * @module currentLayout
     * @author Sean McEmerson
     * @version 0.1.0
     * @requires lib/jquery
     * @requires lib/lodash/function/throttle
     * @requires lib/stampit
     * @requires modules/generic/modernizr
     *
     * @example <caption>Include the module</caption>
     *  let currentLayout = require('modules/ui/current-layout');
     *
     * @example <caption>Add event listener for window resizes</caption>
     *  currentLayout.init();
     *
     * @example <caption>Get current layout</caption>
     *  currentLayout.layout();
     *
     * @example <caption>Test if the current layout contains a breakpoint (note use of tilde)</caption>
     *  let isMobile = currentLayout.is('~mobile');
     *
     * @example <caption>Test if the current layout equals a specific breakpoint</caption>
     *  let isSmallerMobile = currentLayout.is('mobile-small');
     *
     * @example <caption>Test if the current layout is not a breakpoint (note use of tilde)</caption>
     *  let notMobile = currentLayout.not('~mobile');
     *
     * @example <caption>Test if the current layout is not a breakpoint</caption>
     *  let notSmallMobile = currentLayout.not('mobile-small');
     */

    const $ = require('jquery');
    const throttle = require('lodash/function/throttle');
    const stampit = require('stampit');
    const Modernizr = require('modernizr');

    const currentLayout = stampit()
        .state({
            currentLayout: ''
        })
        .methods({
            /**
             * Save current layout and add event listener to window
             * @method init
             */
            init () {
                this.update();

                $(window).on('resize.currentLayout', throttle(this.update, 250).bind(this));
            },

            /**
             * Check whether the current layout matches an expected breakpoint.
             * @method is
             * @returns {Boolean} - Returns true/false if current layout matches
             */
            is (breakpoint) {
                let is = false;

                if (!breakpoint || (typeof breakpoint) !== 'string') {
                    is = false;
                } else if (breakpoint.charAt(0) === '~') {
                    is = this.currentLayout.indexOf(breakpoint.slice(1)) !== -1;
                } else {
                    is = this.currentLayout === breakpoint;
                }

                return is;
            },

            /**
             * Return the current layout
             * @method layout
             * @returns {String} the name of the current layout
             */
            layout () {
                /**
                 * Update the layout if it is not yet defined
                 */
                if ((typeof this.currentLayout) === 'undefined' || !this.currentLayout) {
                    this.update();
                }

                return this.currentLayout;
            },

            /**
             * Check whether the current layout does not match an expected breakpoint
             * @method not
             * @returns {Boolean} - Returns true/false if current layout does not match
             */
            not (breakpoint) {
                return !this.is(breakpoint);
            },

            /**
             * Updates the current layout based on current CSS breakpoint
             * @method updated
             * @returns {String} the name of the current layout
             */
            update () {
                /**
                 * Test for media queries: if not supported, show desktop for older browsers
                 */
                let mqSupport = true;

                if ((typeof Modernizr) !== 'undefined' && !Modernizr.mq('only all')) {
                    mqSupport = false;
                }

                if (mqSupport) {
                    this.currentLayout = window.getComputedStyle(document.body, ':before').getPropertyValue('content').replace(/["']/g, '');

                    /**
                     * If the layout cannot be read then default to desktop
                     * @ignore
                     */
                    if ((typeof this.currentLayout) !== 'string') {
                        this.currentLayout = 'desktop';
                    }
                } else {
                    this.currentLayout = 'desktop';
                }

                return this.currentLayout;
            }
        })
        .create();

    return currentLayout;
});
Пример #16
0
var throttle = require('lodash/function/throttle');

// #FIXME jQuery crap here

var element;

var reload = throttle(function(ctrl) {
  var route = ctrl.data.player.spectator ? ctrl.router.Round.watcherText(ctrl.data.game.id, ctrl.data.player.color) : ctrl.router.Round.playerText(ctrl.data.game.id + ctrl.data.player.id);
  $(element).load(route.url, function() {
    $(this).find('form').submit(function() {
      var text = $(this).find('.move').val();
      var move = {
        from: text.substring(0, 2),
        to: text.substring(2, 4),
        promotion: text.substring(4, 5)
      };
      ctrl.socket.send("move", move, {
        ackable: true
      });
      return false;
    }).find('.move').focus();
  });
}, 1000);

module.exports = {
  reload: reload,
  init: function(el, ctrl) {
    element = el;
    reload(ctrl);
  }
};