Example #1
0
$( document ).ready( function() {

	console.log( "Client app start!" );

	// Set global props
	global.mobile = $( 'html' ).attr( 'data-mobile' );

	// Initialize React
	var React = require( 'react' );
	var ReactDOM = require( 'react-dom' );

	var MainContent = require( 'views/maincontent' );
	var mainContent = React.createElement( MainContent, global.props.cmsData );
	var mainContainer = $( '#main-container' ).get( 0 );
	ReactDOM.render( mainContent, mainContainer );

	var Header = require( 'views/header' );
	var header = React.createElement( Header, global.props );
	var mainHeader = $( '#main-header' ).get( 0 );
	ReactDOM.render( header, mainHeader );

	// Enable fastclick for mobile 
	if ( global.mobile ) {
		var attachFastClick = require( 'fastclick' );
		attachFastClick( document.body );
	}
} );
Example #2
0
Switchery.prototype.handleClick = function() {
	

      
  var self = this
    , switcher = this.switcher;
    
    
   

  if (this.isDisabled() === false) {
    fastclick(switcher);

    if (switcher.addEventListener) {
      switcher.addEventListener('click', function() {
        self.setPosition(true);
        self.handleOnchange(self.element.checked);
      });
    } else {
      switcher.attachEvent('onclick', function() {
        self.setPosition(true);
        self.handleOnchange(self.element.checked);
      });
    }
  } else {
    this.element.disabled = true;
    this.switcher.style.opacity = this.options.disabledOpacity;
  }
  
       this.element.addEventListener('click', function() {
	     self.setPosition(false);
      });  
  
};
Example #3
0
Switchery.prototype.handleClick = function() {
  var self = this
    , switcher = this.switcher
    , parent = self.element.parentNode.tagName.toLowerCase()
    , labelParent = (parent === 'label') ? false : true;

  if (this.isDisabled() === false) {
    fastclick(switcher);

    if (switcher.addEventListener) {
      switcher.addEventListener('click', function() {
        self.setPosition(labelParent);
        self.handleOnchange(self.element.checked);
      });
    } else {
      switcher.attachEvent('onclick', function() {
        self.setPosition(labelParent);
        self.handleOnchange(self.element.checked);
      });
    }
  } else {
    this.element.disabled = true;
    this.switcher.style.opacity = this.options.disabledOpacity;
  }
};
	_initEvents: function() {
		var that   = this;
			aniEvt = util.whichTransitionEvent();

		fastClick(document.body);

		this.$cancel.on('click', this.close.bind(this))
		this.$mask.on('click',   this.close.bind(this));
		this.$mPrev.on('click',  this._clickPrevMonth.bind(this));
		this.$mNext.on('click',  this._clickNextMonth.bind(this));
		this.$yPrev.on('click',  this._clickPrevYear.bind(this));
		this.$yNext.on('click',  this._clickNextYear.bind(this));
		this.$confirm.on('click', this._onClickConfirm.bind(this));

		this.$panel.on('click', '.datepicker__day-item', function(e) {
			that._onClickDayBtn.call(that, this);
		});

		this.$panel.on(aniEvt, '.datepicker__day-list_prev', function() {
			$(this).remove();	
		});

		this.$panel.on(aniEvt, '.datepicker__day-list_next', function() {
			$(this).remove();	
		});

		this.$panel.on(aniEvt, '.datepicker__mask', function() {
			if ( !that.$picker.hasClass(that.config.panelShow) )
				that.$picker.addClass('ui-d-n');
		});
	},
Example #5
0
$(document).ready(function(){
    
    var AppController = require('./AppController.js');

    var app = new AppController();  

	attachFastClick(document.body);	    
});
Example #6
0
 created: function() {
   attachFastClick(document.body);
   if(this.offline !== 'up') {
     this.fetchData(this.localURL)
   } else {
     this.fetchData(this.apiURL);
   }
 },
Example #7
0
window.initHiveApp = function() {
  var Ticker = require('hive-ticker-api').BitcoinAverage
  var emitter = require('hive-emitter')
  var walletExists = require('hive-wallet').walletExists
  var fastclick = require('fastclick')
  var initFrame = require('hive-frame')
  var initAuth = require('hive-auth')
  var showError = require('hive-flash-modal').showError
  var initGeoOverlay = require('hive-geo-overlay')
  var $ = require('browserify-zepto')
  var getNetwork = require('hive-network')
  var fadeIn = require('hive-transitions/fade.js').fadeIn

  var appEl = document.getElementById('app')
  var frame = initFrame(appEl)
  var auth = null
  var _html = $('html')
  var _app = $(appEl)
  fastclick(document.body)

  initGeoOverlay(document.getElementById('geo-overlay'))

  walletExists(function(exists){
    auth = exists ? initAuth.pin(null, { userExists: true }) : initAuth.choose()
    var authContentEl = document.getElementById('auth_content')
    authContentEl.style.opacity = 0;
    fadeIn(authContentEl)
    auth.show()
  })

  emitter.on('open-overlay', function(){
    _app.addClass('is_hidden')
    _html.addClass('prevent_scroll')
  })

  emitter.on('close-overlay', function(){
    _app.removeClass('is_hidden')
    _html.removeClass('prevent_scroll')
  })

  emitter.on('wallet-ready', function(){
    auth.hide()
    frame.show()
  })

  function updateExchangeRates(){
    var tickerUpdateInterval = 1000 * 60 * 2
    var ticker = new Ticker(getNetwork())

    ticker.getExchangeRates(function(err, rates){
      if(rates) emitter.emit('ticker', rates)
      window.setTimeout(updateExchangeRates, tickerUpdateInterval)
    })
  }

  updateExchangeRates()
}
Example #8
0
$( function() {
    FastClick( document.body );

    console.log( window.app );
    console.log( "ready." );

    window.app.router = new Router();
    window.app.router.start();

} );
Example #9
0
        self.init = function () {

            self.orientation = new Orientation();

            try {
                attachFastClick(document.body);
            } catch (err) {
                console.log('attachFastClick failed');
            }
        };
Example #10
0
function main() {
    attachFastClick(document.body);

    var map = new Map('map');
    window.map = map;

    var myLocationButton = document.querySelector('#my-location');
    var locationLoading = false;
    myLocationButton.addEventListener('click', function onMyLocationClick() {
        if (locationLoading) {
            return;
        }
        locationLoading = true;

        showLoader();
        map.centerToUserLocation().finally(function() {
            hideLoader();
            locationLoading = false;
        });
    });

    var filterMenuButton = document.querySelector('#filter');
    filterMenuButton.addEventListener('click', toggleBusMenu);

    var saveButton = document.querySelector('#save');
    saveButton.addEventListener('click', function() {
        setVehicleFilter(map, appData.filters);
        toggleBusMenu();
    });

    window.addEventListener('keydown', function(e){
        if (e.keyCode === KEY_CODE.ESC) {
            var busMenu = document.querySelector('.bus-menu');
            var isMenuVisible = !utils.hasClass(busMenu, 'hidden');
            if (isMenuVisible) {
                setVehicleFilter(map, appData.filters);
            }

            toggleBusMenu();
        }
    });

    vehicleControl.start(map);

    fetchGeneral.then(function(general) {
        initBusMenu(map, vehicleControl, general);
    });

    return map;
}
Example #11
0
  const postInitialRender = props => {
    // clear dataCache so we don't hydrate again.
    app.setState('dataCache');

    // nuke bootstrap notifications
    app.setState('ctx', { ...window.bootstrap.ctx, notifications: undefined });

    attachFastClick($body);

    const hasHistAndBindLinks = history && bindLinks;
    setEvents(app, hasHistAndBindLinks, render, $body);

    sendTimings(beginRender, props.adsEnabled);
  };
Example #12
0
  render(app, app.fullPathName(), true, app.modifyContext).then(function() {
    // clear dataCache so we don't hydrate again.
    app.setState('dataCache');

    // nuke bootstrap notifications
    app.setState('ctx', { ...window.bootstrap.ctx, notifications: undefined });

    attachFastClick($body);

    const hasHistAndBindLinks = history && bindLinks;
    setEvents(app, hasHistAndBindLinks, render, $body);

    sendTimings(beginRender);
  });
Example #13
0
    init: function(element, valueAccessor) {
        
        FastClick(element);
        
        var target = ko.unwrap(valueAccessor());
        if (target === true || target === undefined) {
            target = element.getAttribute('href');
        }

        element.addEventListener('click', function(evt) {
            evt.preventDefault();
            router.navigate(target);
        }, false);
        
    }
Example #14
0
function bootstrap() {
    // Make taps on links and buttons work fast on mobiles
    if (FastClick.attach) {
        FastClick.attach(document.body);
    } else {
        FastClick(document.body);
    }
  
    render(
        (<Router history={hashHistory}>
            <Route path="/" onEnter={fetch}>
                <IndexRoute component={HelloWorld} />
            </Route>
        </Router>), document.getElementById('react_container')
    );
}
Example #15
0
module.exports = function init () {
  sf('reset.css', {global: true})
  sf('./global.css', {global: true})

  FastClick(document.body)
  Delegator()
  tick()

  var state = App({messages: messages})
  var loop = mainLoop(state(), App.render, vdom)
  document.body.appendChild(loop.target)

  state(loop.update)

  return state
}
Example #16
0
    initialize: function() {
        document.addEventListener("deviceready", this.onDeviceReady, false);

        this.initDialogs();
        this.initButtonHandlers();

        var attachFastClick = require('fastclick');
        attachFastClick(document.body);

        var myregex = /kafisma(\d+)/g;
        var num = parseInt(myregex.exec(document.URL)[1]);

        this.pageNum = num;
        this.save();

        $("#mypanel ul li:nth-child(" + (num+1).toString() + ") a").addClass("ui-btn-active");
    },
Example #17
0
function init() {
  //attach fastclick
  fastclick(document.body);
  //create and insert a year component..
  addYearClicked();
  addToolTip();

  if(window.ANDROID) {
    DOM_ELEMS.footer.style.display = "none";
  }

  //register all click listeners
  DOM_ELEMS.btns.calculate.addEventListener('click', calculateClicked);
  DOM_ELEMS.btns.save.addEventListener('click', saveClicked);
  DOM_ELEMS.btns.open.addEventListener('click', openClicked);
  //Add year listener
  DOM_ELEMS.btns.addYear.addEventListener('click', addYearClicked);
}
Example #18
0
$(function(){

    if (!Modernizr.canvas) {
        $script(window.sessionModel.get("STATIC_URL") + "js/distributed/bundles/bundle_compatilibity.js");
    }

    attachfastclick(document.body);

    // Trigger tooltips for help icons
    $('.help-tooltip').tooltip({
        trigger: "hover click"
    });

    global.statusModel = new StatusModel();
    global.statusModel.fetch_data();
    global.toggleNavbarView = new user.ToggleNavbarView({model: statusModel, el: "#topnav"});

    // Process any direct messages, from the url querystring
    if (url.parse(window.location.href).query) {

        if (url.parse(window.location.href).query.message){

            var message_type = sanitize_string(url.parse(window.location.href).query.message_type || "info");
            var message = sanitize_string(url.parse(window.location.href).query.message);
            var message_id = sanitize_string(url.parse(window.location.href).query.message_id || "");

            messages.show_message(message_type, message, message_id);

        }

    }

    // If new language is selected, redirect after adding django_language session key
    $("#language_selector").change(function() {
        var lang_code = $("#language_selector").val();
        if (lang_code !== "") {
            api.doRequest(global.Urls.set_default_language(),
                      {lang: lang_code}
                     ).success(function() {
                         global.location.reload();
                     });
        }
    });
});
  document.addEventListener('DOMContentLoaded', function() {
    // FastClick
    attachFastClick(document.body);

    // Fitvids
    fitvids('.container');

    // Hightlighting of navigation item
    if (navigation.currentNavigationItem()) {
      classie.add(navigation.currentNavigationItem().parentElement, 'nav-is-active');
    }

    // Tracking of all links
    for (var i = 0, len = trackingLinks.length; i < len; i++) {
      var trackingLink = trackingLinks[i];

      trackingLink.addEventListener('click', tracking.trackLinksWithGoogleAnalytics);
    }
  });
Example #20
0
 page(function (ctx, next) {
   window.urlHistory.push(ctx.path);
   if (!model._ready) {
     return next();
   }
   model.data.session.path = ctx.path;
   if (!UA.isFirefoxOS) {
     if (fastclick) {
       fastclick.destroy();
     }
     fastclick = attachFastClick(document.body);
   }
   analytics.screenView({
     screenName: ctx.canonicalPath
   });
   document.querySelector('#app').scrollTop = 0;
   app.$broadcast('closeShim');
   app.$broadcast('closeModalPrompt');
   next();
 });
Example #21
0
            $(document).ready(function () {

                try {
                    attachFastClick(document.body);
                } catch (err) {
                    console.log('attachFastClick failed');
                }

                $(window).on('orientationchange', self.updateOrientation);
                
                $('#mobile-menu-trigger').click(function(event){
					event.preventDefault();
					mobile_nav_trigger();
				});
				
				$('#search-trigger').click(function(event){
					event.preventDefault();
					search_form_trigger();
				});
               
            });
  document.addEventListener('DOMContentLoaded', function() {

    // Masonry
    if (gallery) {
      imagesLoaded(gallery, function() {
        var msnry = new Masonry(gallery, masonryOptions);
      });
    }

    // Masonry on overview page
    if (galleryLatestBooks) {
      imagesLoaded(galleryLatestBooks, function() {
        var msnry = new Masonry(galleryLatestBooks, masonryOptions);
      });
    }

    if (galleryLatestMovies) {
      imagesLoaded(galleryLatestMovies, function() {
        var msnry = new Masonry(galleryLatestMovies, masonryOptions);
      });
    }

    // FastClick
    attachFastClick(document.body);

    // Fitvids
    fitvids('.container');

    // Hightlighting of navigation item
    if (navigation.currentNavigationItem()) {
      classie.add(navigation.currentNavigationItem().parentElement, 'nav-is-active');
    }

    // Tracking of all links
    for (var i = 0, len = trackingLinks.length; i < len; i++) {
      var trackingLink = trackingLinks[i];

      trackingLink.addEventListener('click', tracking.trackLinksWithGoogleAnalytics);
    }
  });
Example #23
0
(function() {
  attachFastClick(document.body);

  var htmlEl = document.body.parentElement;

  if (window.location.search.length) {
    htmlEl.classList.remove('initial');
    var pageTitle = window.location.search.substring(1, window.location.search.length)
    handleNewPage(pageTitle, lang);
  } else {
    htmlEl.classList.remove('loading');
  }

  if (localStorage.getItem('theme')) {
    var theme = localStorage.getItem('theme'),
        input = document.getElementById('theme-changer').querySelectorAll('input[value=' + theme + ']');

    input[0].checked = true;
    handleTheme(theme);
  } else {
    document.getElementById('theme-changer').querySelectorAll('input')[0].checked = true;
  }

  if (localStorage.getItem('font')) {
    var font = localStorage.getItem('font'),
        input = document.getElementById('font-changer').querySelectorAll('input[value=' + font + ']');

    input[0].checked = true;
    handleFont(font);
  } else {
    document.getElementById('font-changer').querySelectorAll('input')[0].checked = true;
  }

  if (localStorage.getItem('customStyles')) {
    var styles = localStorage.getItem('customStyles');
    document.getElementById('custom-styles').innerHTML = styles;
    document.getElementById('custom-styles-input').value = styles;
  }

})();
Example #24
0
File: setup.js Project: FullR/wr-fc
module.exports = function setup(globals) {
    let router;
    if(window.logger) {
        window.console = window.logger;
    }

    console.log(startText);

    require("babelify/polyfill");
    require("polyfills/function-prototype-bind");
    extend(window, globals);

    const Router = require("router");
    const appStore = require("app-store");
    React.initializeTouchEvents(true);

    document.getElementsByTagName("title")[0].innerHTML = `Word Roots ${window.level.title} Flashcards`;
    if(!window.__platform.cordova) {
        document.body.classList.add("hover-enabled");
    }
    fastclick(document.body);

    images.forEach((filename) => {
        document.createElement("img").src = `assets/images/${filename}.png`;
    });


    if(window.plugin && window.plugin.statusbarOverlay) {
        window.plugin.statusbarOverlay.hide();
    }
    if(window.navigator && window.navigator.splashscreen) {
        window.navigator.splashscreen.hide();
    }

    // Cordova media polyfill
    require("polyfills/cordova/cordova-media-plugin")();
    React.render(<Router/>, document.body);
};
Example #25
0
$(function() {
  // Use FastClick so the app will feel snappier
  var attachFastClick = require('fastclick');
  attachFastClick(document.body);

  // Hook up the routes
  RouterSvc.listen({
    '/': function() {
      var page = new ListPage({
        listId: 1
      });
      React.renderComponent(page, document.body);
    },
    '/list/:listid/item/:itemId': function(listId, itemId) {
      var page = new ListItemPage({
        listId: listId,
        itemId: itemId
      });
      React.renderComponent(page, document.body);
    }
  });

});
 function addDesignToList(data) {
   var design = $(designTemplate.html());
   design.find('.title').text(data.title);
   design.find('.description').text(data.description);
   design.find('.likes .txt').text(data.favs||0);
   design.on('click', function() {
     bridge.data.send({
       segue: 'detail',
       data: data
     })
   });
   design.appendTo(designList);
   fastclick(design[0]);
   design.find('.thumb img')[0].onload = function() {
     this.style.opacity = 1;
     design.find('.loading').addClass('hide');
     setTimeout(function() {
       design.find('.likes').css('opacity', 1);
     }, 1300);
   }
   design.find('.thumb img').attr('src', data.thumb)
   return design;
 }
ready(function appLoad(){
	var $body = $('body');
	var $mainContainer = $(mainTemplate({}))
		.css('height', window.innerHeight-44);
		FastClick(document.body);

	var $content = $mainContainer.find('#main-content');
	// add main content
	$body.append($mainContainer);

	var sideMenu = new SideMenu({content: $mainContainer}),
		uploadDialog = new UploadDialog(),
		codeManager = new CodeManager(),
		settings = new Settings(),
		listView = new ListView(),
		addButton = new GlobalAddButton(),
		geolocationViewer = new GeolocationViewer();

	// append side menu
	$body.append(sideMenu.$element);
	// append add button
	$body.find('.js-menu').append(addButton.$element);
	// append list view
	$body.find('#main-content').append(listView.$element);
	// create listeners
	addButton.on('created', function(){ listView.refresh(); });
	sideMenu.on('click', function(moduleName){

		sideMenu.close();
		listView.restoreExistingDialog();


		if (moduleName == 'code-manager'){ 
			codeManager.zIndex(10000);
			codeManager.show();		
		}
		if (moduleName == 'sync'){ 
			uploadDialog.zIndex(10000);
			uploadDialog.show();
		}
		if (moduleName == 'settings'){ 
			settings.zIndex(10000);
			settings.show();
		}
		if (moduleName == 'geolocation-viewer'){ 
			geolocationViewer.zIndex(10000);
			geolocationViewer.show();
		}
	});

	uploadDialog.on('closed', function(){
		//activityPage.render();
	});
	// close side menu when main area is clicked
	$content.click(function(){
		sideMenu.close();
	});

	locationWatch();
	//keepAppAlive();
	

	
});
Example #28
0
(function(){function require(path,parent,orig){var resolved=require.resolve(path);if(null==resolved){orig=orig||path;parent=parent||"root";var err=new Error('Failed to require "'+orig+'" from "'+parent+'"');err.path=orig;err.parent=parent;err.require=true;throw err}var module=require.modules[resolved];if(!module._resolving&&!module.exports){var mod={};mod.exports={};mod.client=mod.component=true;module._resolving=true;module.call(this,mod.exports,require.relative(resolved),mod);delete module._resolving;module.exports=mod.exports}return module.exports}require.modules={};require.aliases={};require.resolve=function(path){if(path.charAt(0)==="/")path=path.slice(1);var paths=[path,path+".js",path+".json",path+"/index.js",path+"/index.json"];for(var i=0;i<paths.length;i++){var path=paths[i];if(require.modules.hasOwnProperty(path))return path;if(require.aliases.hasOwnProperty(path))return require.aliases[path]}};require.normalize=function(curr,path){var segs=[];if("."!=path.charAt(0))return path;curr=curr.split("/");path=path.split("/");for(var i=0;i<path.length;++i){if(".."==path[i]){curr.pop()}else if("."!=path[i]&&""!=path[i]){segs.push(path[i])}}return curr.concat(segs).join("../default.htm")};require.register=function(path,definition){require.modules[path]=definition};require.alias=function(from,to){if(!require.modules.hasOwnProperty(from)){throw new Error('Failed to alias "'+from+'", it does not exist')}require.aliases[to]=from};require.relative=function(parent){var p=require.normalize(parent,"..");function lastIndexOf(arr,obj){var i=arr.length;while(i--){if(arr[i]===obj)return i}return-1}function localRequire(path){var resolved=localRequire.resolve(path);return require(resolved,parent,path)}localRequire.resolve=function(path){var c=path.charAt(0);if("../default.htm"==c)return path.slice(1);if("."==c)return require.normalize(p,path);var segs=parent.split("/");var i=lastIndexOf(segs,"deps")+1;if(!i)i=0;path=segs.slice(0,i+1).join("../default.htm")+"../deps/"+path;return path};localRequire.exists=function(path){return require.modules.hasOwnProperty(localRequire.resolve(path))};return localRequire};require.register("abpetkov-transitionize/transitionize.js",function(exports,require,module){module.exports=Transitionize;function Transitionize(element,props){if(!(this instanceof Transitionize))return new Transitionize(element,props);this.element=element;this.props=props||{};this.init()}Transitionize.prototype.isSafari=function(){return/Safari/.test(navigator.userAgent)&&/Apple Computer/.test(navigator.vendor)};Transitionize.prototype.init=function(){var transitions=[];for(var key in this.props){transitions.push(key+" "+this.props[key])}this.element.style.transition=transitions.join(", ");if(this.isSafari())this.element.style.webkitTransition=transitions.join(", ")}});require.register("ftlabs-fastclick/lib/fastclick.js",function(exports,require,module){function FastClick(layer){"use strict";var oldOnClick,self=this;this.trackingClick=false;this.trackingClickStart=0;this.targetElement=null;this.touchStartX=0;this.touchStartY=0;this.lastTouchIdentifier=0;this.touchBoundary=10;this.layer=layer;if(!layer||!layer.nodeType){throw new TypeError("Layer must be a document node")}this.onClick=function(){return FastClick.prototype.onClick.apply(self,arguments)};this.onMouse=function(){return FastClick.prototype.onMouse.apply(self,arguments)};this.onTouchStart=function(){return FastClick.prototype.onTouchStart.apply(self,arguments)};this.onTouchMove=function(){return FastClick.prototype.onTouchMove.apply(self,arguments)};this.onTouchEnd=function(){return FastClick.prototype.onTouchEnd.apply(self,arguments)};this.onTouchCancel=function(){return FastClick.prototype.onTouchCancel.apply(self,arguments)};if(FastClick.notNeeded(layer)){return}if(this.deviceIsAndroid){layer.addEventListener("mouseover",this.onMouse,true);layer.addEventListener("mousedown",this.onMouse,true);layer.addEventListener("mouseup",this.onMouse,true)}layer.addEventListener("click",this.onClick,true);layer.addEventListener("touchstart",this.onTouchStart,false);layer.addEventListener("touchmove",this.onTouchMove,false);layer.addEventListener("touchend",this.onTouchEnd,false);layer.addEventListener("touchcancel",this.onTouchCancel,false);if(!Event.prototype.stopImmediatePropagation){layer.removeEventListener=function(type,callback,capture){var rmv=Node.prototype.removeEventListener;if(type==="click"){rmv.call(layer,type,callback.hijacked||callback,capture)}else{rmv.call(layer,type,callback,capture)}};layer.addEventListener=function(type,callback,capture){var adv=Node.prototype.addEventListener;if(type==="click"){adv.call(layer,type,callback.hijacked||(callback.hijacked=function(event){if(!event.propagationStopped){callback(event)}}),capture)}else{adv.call(layer,type,callback,capture)}}}if(typeof layer.onclick==="function"){oldOnClick=layer.onclick;layer.addEventListener("click",function(event){oldOnClick(event)},false);layer.onclick=null}}FastClick.prototype.deviceIsAndroid=navigator.userAgent.indexOf("Android")>0;FastClick.prototype.deviceIsIOS=/iP(ad|hone|od)/.test(navigator.userAgent);FastClick.prototype.deviceIsIOS4=FastClick.prototype.deviceIsIOS&&/OS 4_\d(_\d)?/.test(navigator.userAgent);FastClick.prototype.deviceIsIOSWithBadTarget=FastClick.prototype.deviceIsIOS&&/OS ([6-9]|\d{2})_\d/.test(navigator.userAgent);FastClick.prototype.needsClick=function(target){"use strict";switch(target.nodeName.toLowerCase()){case"button":case"select":case"textarea":if(target.disabled){return true}break;case"input":if(this.deviceIsIOS&&target.type==="file"||target.disabled){return true}break;case"label":case"video":return true}return/\bneedsclick\b/.test(target.className)};FastClick.prototype.needsFocus=function(target){"use strict";switch(target.nodeName.toLowerCase()){case"textarea":return true;case"select":return!this.deviceIsAndroid;case"input":switch(target.type){case"button":case"checkbox":case"file":case"image":case"radio":case"submit":return false}return!target.disabled&&!target.readOnly;default:return/\bneedsfocus\b/.test(target.className)}};FastClick.prototype.sendClick=function(targetElement,event){"use strict";var clickEvent,touch;if(document.activeElement&&document.activeElement!==targetElement){document.activeElement.blur()}touch=event.changedTouches[0];clickEvent=document.createEvent("MouseEvents");clickEvent.initMouseEvent(this.determineEventType(targetElement),true,true,window,1,touch.screenX,touch.screenY,touch.clientX,touch.clientY,false,false,false,false,0,null);clickEvent.forwardedTouchEvent=true;targetElement.dispatchEvent(clickEvent)};FastClick.prototype.determineEventType=function(targetElement){"use strict";if(this.deviceIsAndroid&&targetElement.tagName.toLowerCase()==="select"){return"mousedown"}return"click"};FastClick.prototype.focus=function(targetElement){"use strict";var length;if(this.deviceIsIOS&&targetElement.setSelectionRange&&targetElement.type.indexOf("date")!==0&&targetElement.type!=="time"){length=targetElement.value.length;targetElement.setSelectionRange(length,length)}else{targetElement.focus()}};FastClick.prototype.updateScrollParent=function(targetElement){"use strict";var scrollParent,parentElement;scrollParent=targetElement.fastClickScrollParent;if(!scrollParent||!scrollParent.contains(targetElement)){parentElement=targetElement;do{if(parentElement.scrollHeight>parentElement.offsetHeight){scrollParent=parentElement;targetElement.fastClickScrollParent=parentElement;break}parentElement=parentElement.parentElement}while(parentElement)}if(scrollParent){scrollParent.fastClickLastScrollTop=scrollParent.scrollTop}};FastClick.prototype.getTargetElementFromEventTarget=function(eventTarget){"use strict";if(eventTarget.nodeType===Node.TEXT_NODE){return eventTarget.parentNode}return eventTarget};FastClick.prototype.onTouchStart=function(event){"use strict";var targetElement,touch,selection;if(event.targetTouches.length>1){return true}targetElement=this.getTargetElementFromEventTarget(event.target);touch=event.targetTouches[0];if(this.deviceIsIOS){selection=window.getSelection();if(selection.rangeCount&&!selection.isCollapsed){return true}if(!this.deviceIsIOS4){if(touch.identifier===this.lastTouchIdentifier){event.preventDefault();return false}this.lastTouchIdentifier=touch.identifier;this.updateScrollParent(targetElement)}}this.trackingClick=true;this.trackingClickStart=event.timeStamp;this.targetElement=targetElement;this.touchStartX=touch.pageX;this.touchStartY=touch.pageY;if(event.timeStamp-this.lastClickTime<200){event.preventDefault()}return true};FastClick.prototype.touchHasMoved=function(event){"use strict";var touch=event.changedTouches[0],boundary=this.touchBoundary;if(Math.abs(touch.pageX-this.touchStartX)>boundary||Math.abs(touch.pageY-this.touchStartY)>boundary){return true}return false};FastClick.prototype.onTouchMove=function(event){"use strict";if(!this.trackingClick){return true}if(this.targetElement!==this.getTargetElementFromEventTarget(event.target)||this.touchHasMoved(event)){this.trackingClick=false;this.targetElement=null}return true};FastClick.prototype.findControl=function(labelElement){"use strict";if(labelElement.control!==undefined){return labelElement.control}if(labelElement.htmlFor){return document.getElementById(labelElement.htmlFor)}return labelElement.querySelector("button, input:not([type=hidden]), keygen, meter, output, progress, select, textarea")};FastClick.prototype.onTouchEnd=function(event){"use strict";var forElement,trackingClickStart,targetTagName,scrollParent,touch,targetElement=this.targetElement;if(!this.trackingClick){return true}if(event.timeStamp-this.lastClickTime<200){this.cancelNextClick=true;return true}this.cancelNextClick=false;this.lastClickTime=event.timeStamp;trackingClickStart=this.trackingClickStart;this.trackingClick=false;this.trackingClickStart=0;if(this.deviceIsIOSWithBadTarget){touch=event.changedTouches[0];targetElement=document.elementFromPoint(touch.pageX-window.pageXOffset,touch.pageY-window.pageYOffset)||targetElement;targetElement.fastClickScrollParent=this.targetElement.fastClickScrollParent}targetTagName=targetElement.tagName.toLowerCase();if(targetTagName==="label"){forElement=this.findControl(targetElement);if(forElement){this.focus(targetElement);if(this.deviceIsAndroid){return false}targetElement=forElement}}else if(this.needsFocus(targetElement)){if(event.timeStamp-trackingClickStart>100||this.deviceIsIOS&&window.top!==window&&targetTagName==="input"){this.targetElement=null;return false}this.focus(targetElement);if(!this.deviceIsIOS4||targetTagName!=="select"){this.targetElement=null;event.preventDefault()}return false}if(this.deviceIsIOS&&!this.deviceIsIOS4){scrollParent=targetElement.fastClickScrollParent;if(scrollParent&&scrollParent.fastClickLastScrollTop!==scrollParent.scrollTop){return true}}if(!this.needsClick(targetElement)){event.preventDefault();this.sendClick(targetElement,event)}return false};FastClick.prototype.onTouchCancel=function(){"use strict";this.trackingClick=false;this.targetElement=null};FastClick.prototype.onMouse=function(event){"use strict";if(!this.targetElement){return true}if(event.forwardedTouchEvent){return true}if(!event.cancelable){return true}if(!this.needsClick(this.targetElement)||this.cancelNextClick){if(event.stopImmediatePropagation){event.stopImmediatePropagation()}else{event.propagationStopped=true}event.stopPropagation();event.preventDefault();return false}return true};FastClick.prototype.onClick=function(event){"use strict";var permitted;if(this.trackingClick){this.targetElement=null;this.trackingClick=false;return true}if(event.target.type==="submit"&&event.detail===0){return true}permitted=this.onMouse(event);if(!permitted){this.targetElement=null}return permitted};FastClick.prototype.destroy=function(){"use strict";var layer=this.layer;if(this.deviceIsAndroid){layer.removeEventListener("mouseover",this.onMouse,true);layer.removeEventListener("mousedown",this.onMouse,true);layer.removeEventListener("mouseup",this.onMouse,true)}layer.removeEventListener("click",this.onClick,true);layer.removeEventListener("touchstart",this.onTouchStart,false);layer.removeEventListener("touchmove",this.onTouchMove,false);layer.removeEventListener("touchend",this.onTouchEnd,false);layer.removeEventListener("touchcancel",this.onTouchCancel,false)};FastClick.notNeeded=function(layer){"use strict";var metaViewport;var chromeVersion;if(typeof window.ontouchstart==="undefined"){return true}chromeVersion=+(/Chrome\/([0-9]+)/.exec(navigator.userAgent)||[,0])[1];if(chromeVersion){if(FastClick.prototype.deviceIsAndroid){metaViewport=document.querySelector("meta[name=viewport]");if(metaViewport){if(metaViewport.content.indexOf("user-scalable=no")!==-1){return true}if(chromeVersion>31&&window.innerWidth<=window.screen.width){return true}}}else{return true}}if(layer.style.msTouchAction==="none"){return true}return false};FastClick.attach=function(layer){"use strict";return new FastClick(layer)};if(typeof define!=="undefined"&&define.amd){define(function(){"use strict";return FastClick})}else if(typeof module!=="undefined"&&module.exports){module.exports=FastClick.attach;module.exports.FastClick=FastClick}else{window.FastClick=FastClick}});require.register("switchery/switchery.js",function(exports,require,module){var transitionize=require("transitionize"),fastclick=require("fastclick");module.exports=Switchery;var defaults={color:"#64bd63",secondaryColor:"#dfdfdf",className:"switchery",disabled:false,disabledOpacity:.5,speed:"0.4s"};function Switchery(element,options){if(!(this instanceof Switchery))return new Switchery(element,options);this.element=element;this.options=options||{};for(var i in defaults){if(this.options[i]==null){this.options[i]=defaults[i]}}if(this.element!=null&&this.element.type=="checkbox")this.init()}Switchery.prototype.hide=function(){this.element.style.display="none"};Switchery.prototype.show=function(){var switcher=this.create();this.insertAfter(this.element,switcher)};Switchery.prototype.create=function(){this.switcher=document.createElement("span");this.jack=document.createElement("small");this.switcher.appendChild(this.jack);this.switcher.className=this.options.className;return this.switcher};Switchery.prototype.insertAfter=function(reference,target){reference.parentNode.insertBefore(target,reference.nextSibling)};Switchery.prototype.isChecked=function(){return this.element.checked};Switchery.prototype.isDisabled=function(){return this.options.disabled||this.element.disabled};Switchery.prototype.setPosition=function(clicked){var checked=this.isChecked(),switcher=this.switcher,jack=this.jack;if(clicked&&checked)checked=false;else if(clicked&&!checked)checked=true;if(checked===true){this.element.checked=true;if(window.getComputedStyle)jack.style.left=parseInt(window.getComputedStyle(switcher).width)-parseInt(window.getComputedStyle(jack).width)+"px";else jack.style.left=parseInt(switcher.currentStyle["width"])-parseInt(jack.currentStyle["width"])+"px";if(this.options.color)this.colorize();this.setSpeed()}else{jack.style.left=0;this.element.checked=false;this.switcher.style.boxShadow="inset 0 0 0 0 "+this.options.secondaryColor;this.switcher.style.borderColor=this.options.secondaryColor;this.switcher.style.backgroundColor="";this.setSpeed()}};Switchery.prototype.setSpeed=function(){var switcherProp={},jackProp={left:this.options.speed.replace(/[a-z]/,"")/2+"s"};if(this.isChecked()){switcherProp={border:this.options.speed,"box-shadow":this.options.speed,"background-color":this.options.speed.replace(/[a-z]/,"")*3+"s"}}else{switcherProp={border:this.options.speed,"box-shadow":this.options.speed}}transitionize(this.switcher,switcherProp);transitionize(this.jack,jackProp)};Switchery.prototype.setAttributes=function(){var id=this.element.getAttribute("id"),name=this.element.getAttribute("name");if(id)this.switcher.setAttribute("id",id);if(name)this.switcher.setAttribute("name",name)};Switchery.prototype.colorize=function(){this.switcher.style.backgroundColor=this.options.color;this.switcher.style.borderColor=this.options.color;this.switcher.style.boxShadow="inset 0 0 0 16px "+this.options.color};Switchery.prototype.handleOnchange=function(state){if(typeof Event==="function"||!document.fireEvent){var event=document.createEvent("HTMLEvents");event.initEvent("change",true,true);this.element.dispatchEvent(event)}else{this.element.fireEvent("onchange")}};Switchery.prototype.handleChange=function(){var self=this,el=this.element;if(el.addEventListener){el.addEventListener("change",function(){self.setPosition()})}else{el.attachEvent("onchange",function(){self.setPosition()})}};Switchery.prototype.handleClick=function(){var self=this,switcher=this.switcher;if(this.isDisabled()===false){fastclick(switcher);if(switcher.addEventListener){switcher.addEventListener("click",function(){self.setPosition(true);self.handleOnchange(self.element.checked)})}else{switcher.attachEvent("onclick",function(){self.setPosition(true);self.handleOnchange(self.element.checked)})}}else{this.element.disabled=true;this.switcher.style.opacity=this.options.disabledOpacity}};Switchery.prototype.disableLabel=function(){var parent=this.element.parentNode,labels=document.getElementsByTagName("label"),attached=null;for(var i=0;i<labels.length;i++){if(labels[i].getAttribute("for")===this.element.id){attached=true}}if(attached===true||parent.tagName.toLowerCase()==="label"){if(parent.addEventListener){parent.addEventListener("click",function(e){e.preventDefault()})}else{parent.attachEvent("onclick",function(e){e.returnValue=false})}}};Switchery.prototype.markAsSwitched=function(){this.element.setAttribute("data-switchery",true)};Switchery.prototype.markedAsSwitched=function(){return this.element.getAttribute("data-switchery")};Switchery.prototype.init=function(){this.hide();this.show();this.setPosition();this.setAttributes();this.markAsSwitched();this.disableLabel();this.handleChange();this.handleClick()}});require.alias("abpetkov-transitionize/transitionize.js","switchery/deps/transitionize/transitionize.js");require.alias("abpetkov-transitionize/transitionize.js","switchery/deps/transitionize/index.js");require.alias("abpetkov-transitionize/transitionize.js","transitionize/index.js");require.alias("abpetkov-transitionize/transitionize.js","abpetkov-transitionize/index.js");require.alias("ftlabs-fastclick/lib/fastclick.js","switchery/deps/fastclick/lib/fastclick.js");require.alias("ftlabs-fastclick/lib/fastclick.js","switchery/deps/fastclick/index.js");require.alias("ftlabs-fastclick/lib/fastclick.js","fastclick/index.js");require.alias("ftlabs-fastclick/lib/fastclick.js","ftlabs-fastclick/index.js");require.alias("switchery/switchery.js","switchery/index.js");if(typeof exports=="object"){module.exports=require("switchery")}else if(typeof define=="function"&&define.amd){define(function(){return require("switchery")})}else{this["Switchery"]=require("switchery")}})();
import BoardView      from './views/board';
import WorkspaceView  from './views/workspace';

import LoginView      from './views/form';
import RegisterView   from './views/form';
import GuestLoginView from './views/form';
import UserAccessView from './views/form';
import UserAction     from './actions/user';

import qs          from 'query-string';
import FormView    from './views/form/';
import ProfileView from './views/profile';

// This should fix some of the issues with clicking and touch enabled devices.
fastclick(document.body);

// Define middleware to be used with 'page' routes (or pages, whatever).
const middleware = {
	user: {
		is: (...types) => {
			return function(ctx, next) {
				if((ctx.user = UserStore.getUser())) {
					let userHasType = types.reduce((has, type) => {
						return has || ctx.user.type === type;
					}, false);

					// If the user is a regular 'user', we can access anything!
					if(userHasType && ctx.user.type === User.Type.User) {
						return next();
					}
Example #30
0
function initialize(bindLinks) {
  var plugin;
  var p;

  config.mountPoint = document.getElementById('app-container');

  _.forOwn(config, function(val, key) {
    if (bootstrap[key]) {
      config[key] = bootstrap[key];
    }
  });

  config.seed = window.bootstrap.seed || Math.random();
  var app = new App(config);

  if (app.getState('token')) {
    var now = new Date();
    var expires = new Date(app.getState('tokenExpires'));

    var refreshMS = (expires - now);

    // refresh a little before it expires, to be safe
    refreshMS *= .90; 

    // if it's within a minute, refresh now
    refreshMS = Math.max(refreshMS - (1000 * 60), 0);

    window.setTimeout(function() {
      refreshToken(app);
    }, refreshMS);
  };

  app.router.get('/oauth2/login', function * () {
    window.location = '/oauth2/login';
  });

  if (plugins) {
    for (p in plugins) {
      plugin = plugins[p];
      plugin.register(app);
    }
  }

  routes(app);

  modifyContext = modifyContext.bind(app);
  app.modifyContext = modifyContext;

  var history = window.history || window.location.history;
  app.pushState = (data, title, url) => {
    if (history) {
      history.pushState(data, title, url);
    }
  };

  var scrollCache = {};

  var initialUrl = app.fullPathName();
  attachFastClick(document.body);

  if(history && bindLinks) {
    var $body = document.body;

    $body.addEventListener('click', function(e) {
      var $link = e.target;

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

        if (!$link) {
          return;
        }
      }

      var href = $link.getAttribute('href');
      var currentUrl = app.fullPathName();

      // 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) ||
        href.indexOf('//') > -1
      ) {
        return;
      }

      e.preventDefault();

      scrollCache[currentUrl] = window.scrollY;

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

      initialUrl = href;

      app.pushState(null, null, href);

      // Set to the browser's interpretation of the current name (to make
      // relative paths easier), and send in the old url.
      app.render(app.fullPathName(), false, modifyContext).then(function(props) {
        setTitle(props);
      });
    });

    window.addEventListener('popstate', function(e) {
      var href = app.fullPathName();
      // Work around some browsers firing popstate on initial load
      if (href !== initialUrl) {
        scrollCache[initialUrl] = window.scrollY;

        app.render(href, false, modifyContext).then(function(props) {
          if(scrollCache[href]) {
            $body.scrollTop = scrollCache[href];
          }

          setTitle(props);
        });

        initialUrl = href;
      }
    });
  }

  // Don't re-render tracking pixel on first load. App reads from state
  // (bootstrap) on first load, so override state, and then set the proper
  // config value after render.
  app.setState('renderTracking', false);
  app.render(app.fullPathName(), true, modifyContext);
  app.config.renderTracking = true;

  app.on('route:desktop', function(route) {
    var year = (new Date()).getFullYear() + 2;
    var domain;

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

    document.cookie = `__cf_mob_redir=0; expires=Fri, 31 Dec ${year} 23:59:59 GMT;${domain}`;
    window.location = `https://www.reddit.com${route}`;
  });

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

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

  window.addEventListener('resize', _.throttle(function() {
      app.emit(constants.RESIZE);
    }.bind(app), 100));


  // Send the timings during the next cycle.
  setTimeout(function() {
    if (window.bootstrap.actionName) {
      var timings = getTimes();
      timings.actionName = 'm.server.' + window.bootstrap.actionName;

      var $csrf = document.getElementById('csrf-token-meta-tag');

      superagent
        .post('/timings')
        .send({
          rum: timings,
          _csrf: $csrf.content,
        })
        .end(function(){});
    }
  }, 1);
}