<commit_before>/**
 * Map of nested bottles by index => name
 *
 * @type Array
 */
var nestedBottles = [];

/**
 * Map of provider constructors by index => name
 *
 * @type Array
 */
var providerMap = [];

/**
 * Used to process decorators in the provider
 *
 * @param Object instance
 * @param Function func
 * @return Mixed
 */
var reducer = function reducer(instance, func) {
    return func(instance);
};

/**
 * Register a provider.
 *
 * @param String fullname
 * @param Function Provider
 * @return Bottle
 */
var provider = function provider(fullname, Provider) {
    var parts, providers, providerName, name, id, factory;
    id = this.id;
    providers = get(providerMap, id);
    parts = fullname.split('.');
    if (providers[fullname] && parts.length === 1) {
        providerName = fullname + 'Provider';
        if (this.container[providerName] === undefined) {
            return console.error(fullname + ' provider already instantiated.');
        }
    }
    providers[fullname] = true;

    name = parts.shift();
    factory = parts.length ? createSubProvider : createProvider;

    return factory.call(this, name, Provider, fullname, parts);
};

/**
 * Create the provider properties on the container
 *
 * @param String fullname
 * @param String name
 * @param Function Provider
 * @return Bottle
 */
var createProvider = function createProvider(name, Provider) {
    var providerName, properties, container, id;

    id = this.id;
    container = this.container;
    providerName = name + 'Provider';

    properties = Object.create(null);
    properties[providerName] = {
        configurable : true,
        enumerable : true,
        get : function getProvider() {
            var instance = new Provider();
            delete container[providerName];
            container[providerName] = instance;
            return instance;
        }
    };

    properties[name] = {
        configurable : true,
        enumerable : true,
        get : function getService() {
            var provider = container[providerName];
            var instance;
            if (provider) {
                delete container[providerName];
                delete container[name];

                // filter through decorators
                instance = getAllWithMapped(decorators, id, name)
                    .reduce(reducer, provider.$get(container));
            }
            return instance === undefined ? instance : applyMiddleware(id, name, instance, container);
        }
    };

    Object.defineProperties(container, properties);
    return this;
};

/**
 * Creates a bottle container on the current bottle container, and registers
 * the provider under the sub container.
 *
 * @param String name
 * @param Function Provider
 * @param String fullname
 * @param Array parts
 * @return Bottle
 */
var createSubProvider = function createSubProvider(name, Provider, fullname, parts) {
    var bottle, bottles, subname, id;

    id = this.id;
    bottles = get(nestedBottles, id);
    bottle = bottles[name];
    if (!bottle) {
        this.container[name] = (bottle = bottles[name] = Bottle.pop()).container;
    }
    subname = parts.join('.');
    bottle.provider(subname, Provider);

    set(fullnameMap, bottle.id, subname, { fullname : fullname, id : id });

    return this;
};
<commit_msg>Removed `providerName` variable in favor of inline condition.<commit_after>/**
 * Map of nested bottles by index => name
 *
 * @type Array
 */
var nestedBottles = [];

/**
 * Map of provider constructors by index => name
 *
 * @type Array
 */
var providerMap = [];

/**
 * Used to process decorators in the provider
 *
 * @param Object instance
 * @param Function func
 * @return Mixed
 */
var reducer = function reducer(instance, func) {
    return func(instance);
};

/**
 * Register a provider.
 *
 * @param String fullname
 * @param Function Provider
 * @return Bottle
 */
var provider = function provider(fullname, Provider) {
    var parts, providers, name, id, factory;
    id = this.id;
    providers = get(providerMap, id);
    parts = fullname.split('.');
    if (providers[fullname] && parts.length === 1 && !this.container[fullname + 'Provider']) {
        return console.error(fullname + ' provider already instantiated.');
    }
    providers[fullname] = true;

    name = parts.shift();
    factory = parts.length ? createSubProvider : createProvider;

    return factory.call(this, name, Provider, fullname, parts);
};

/**
 * Create the provider properties on the container
 *
 * @param String fullname
 * @param String name
 * @param Function Provider
 * @return Bottle
 */
var createProvider = function createProvider(name, Provider) {
    var providerName, properties, container, id;

    id = this.id;
    container = this.container;
    providerName = name + 'Provider';

    properties = Object.create(null);
    properties[providerName] = {
        configurable : true,
        enumerable : true,
        get : function getProvider() {
            var instance = new Provider();
            delete container[providerName];
            container[providerName] = instance;
            return instance;
        }
    };

    properties[name] = {
        configurable : true,
        enumerable : true,
        get : function getService() {
            var provider = container[providerName];
            var instance;
            if (provider) {
                delete container[providerName];
                delete container[name];

                // filter through decorators
                instance = getAllWithMapped(decorators, id, name)
                    .reduce(reducer, provider.$get(container));
            }
            return instance === undefined ? instance : applyMiddleware(id, name, instance, container);
        }
    };

    Object.defineProperties(container, properties);
    return this;
};

/**
 * Creates a bottle container on the current bottle container, and registers
 * the provider under the sub container.
 *
 * @param String name
 * @param Function Provider
 * @param String fullname
 * @param Array parts
 * @return Bottle
 */
var createSubProvider = function createSubProvider(name, Provider, fullname, parts) {
    var bottle, bottles, subname, id;

    id = this.id;
    bottles = get(nestedBottles, id);
    bottle = bottles[name];
    if (!bottle) {
        this.container[name] = (bottle = bottles[name] = Bottle.pop()).container;
    }
    subname = parts.join('.');
    bottle.provider(subname, Provider);

    set(fullnameMap, bottle.id, subname, { fullname : fullname, id : id });

    return this;
};
<|endoftext|>


<commit_before>import React from 'react'
import styled, { css } from 'styled-components'
import { Box, Flex, Heading, Image, Text, theme } from '@hackclub/design-system'
import Layout from 'components/Layout'
import { Helmet } from 'react-helmet'
import Nav from 'components/Nav'
import Sheet from 'components/Sheet'
import Footer from 'components/Footer'
import { random } from 'lodash'
import { Lead } from 'components/Content'

const Hero = styled(Flex.withComponent('article')).attrs({ align: 'center' })`
  background-image: ${theme.gradient('dark', 'darker')};
  min-height: 100vh;
  position: relative;
  overflow: hidden;
`

const Megaline = styled(Heading.h1).attrs({
  color: 'white',
  fontSize: [6, 7, 8],
  pt: 1
})`
  line-height: 1;
  @supports (-webkit-background-clip: text) {
    background-image: ${theme.gradient('pink.5', 'red.5', 'red.6')};
    background-repeat: no-repeat;
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
  }
  ${theme.mediaQueries.md} {
    line-height: 0.875;
  }
`

const Article = styled(Sheet).attrs({
  maxWidth: 32,
  align: 'center',
  mx: 'auto'
})`
  z-index: 2;
  @supports (-webkit-backdrop-filter: none) or (backdrop-filter: none) {
    background-color: rgba(0, 0, 0, 0.75);
    -webkit-backdrop-filter: saturate(180%) blur(16px);
  }
  ${theme.mediaQueries.reduceTransparency} {
    -webkit-backdrop-filter: auto !important;
  }
`

const Grid = styled(Box).attrs({ px: 3, py: [0, 6] })`
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(128px, 1fr));
  grid-template-rows: repeat(auto-fit, minmax(128px, 1fr));
  grid-gap: ${theme.space[4]}px;
  position: absolute;
  width: 100%;
  height: 100%;
  ${theme.mediaQueries.md} {
    grid-gap: ${theme.space[6]}px;
  }
`

const Sticker = styled(Image).attrs({ width: 1 })`
  object-fit: contain;
  margin: auto;
  transform: rotate(${(props) => random(-12, 16)}deg);
  ${(props) =>
    props.cols &&
    css`
      grid-column: span ${props.cols};
    `}
  ${(props) =>
    props.rows &&
    css`
      grid-row: span ${props.rows};
    `}
`

const title = 'Hack Club Secret Santa – Holiday 2018'
const desc = 'Find your holiday zen this year with Hack Club’s Secret Santa.'
const img = 'https://hackclub.com/cards/santa.png'

export default () => (
  <Layout>
    <Helmet
      title={title}
      meta={[
        { name: 'description', content: desc },
        { name: 'twitter:title', content: title },
        { name: 'twitter:description', content: desc },
        { name: 'twitter:image', content: img },
        { property: 'og:title', content: title },
        { property: 'og:description', content: desc },
        { property: 'og:image', content: img },
        { property: 'og:url', content: 'https://hackclub.com/santa' }
      ]}
    />
    <Nav dark fixed />
    <Hero py={[4, 5]}>
      <Grid>
        <Sticker rows={2} alt="Classic Macintosh" src="/stickers/mac.svg" />
        <Sticker alt="Pride" src="/stickers/pride.svg" />
        <Sticker cols={2} alt="Enjoy Hack Club" src="/stickers/enjoy.svg" />
        <Sticker
          cols={2}
          alt="Stranger Hacks"
          src="/stickers/stranger_hacks.png"
        />
        <Sticker alt="Hack Club" src="/stickers/h.svg" />
        <Sticker
          cols={2}
          rows={2}
          alt="Holiday 2018"
          src="/stickers/holidays.svg"
        />
        <Sticker cols={2} alt="Undertale" src="/stickers/undertale.svg" />
        <Sticker
          rows={2}
          cols={2}
          alt="Hack Strikes Back"
          src="/stickers/strikes_back.svg"
        />
      </Grid>
      <Article>
        <Text color="muted" fontSize={[3, 4]} bold caps>
          Stick to it
        </Text>
        <Megaline>Unparalleled stickers.</Megaline>
        <Lead fontSize={[3, null, 4]} color="smoke" maxWidth={48} my={3} mx={0}>
          Every season, we design another of our renowned stickers. Collect them
          all & stick them everywhere!
        </Lead>
      </Article>
    </Hero>
    <Footer dark />
  </Layout>
)
<commit_msg>Delete stickers.js<commit_after><|endoftext|>


<commit_before>window.onload = function() {
	/**
	 * make accordion headings clickable, not only the link inside them
	 */
	var accordionTitles = document.getElementsByClassName('panel-heading');
	for (var i=0; i<accordionTitles.length; i++) {
		var accordionTitle = accordionTitles[i];
		accordionTitle.className = accordionTitle.className + ' clickable';
		accordionTitle.addEventListener('click', function(event) {
			var accordionLink = accordionTitle.querySelectorAll('[data-toggle="collapse"]')[0];
			accordionLink.click();
		});
	}

	/**
	 * shortcuts
	 * - Shift+D: open/close the toolbar
	 * - Escape:  close the toolbar
	 */
	window.addEventListener('keydown', function(event) {
		if (event.ctrlKey == false && event.altKey == false && event.shiftKey && event.keyCode == 68) {
			event.preventDefault();
			top.window.closeDebugDetails();
		}
		if (event.ctrlKey == false && event.altKey == false && event.shiftKey == false && event.keyCode == 27) {
			event.preventDefault();
			top.window.closeDebugDetails();
		}
	});
}
<commit_msg>help ignite tabbed navigation<commit_after>window.onload = function() {
	/**
	 * help tabbed navigation inside the iframe
	 */
	setTimeout(function() {
		window.focus();
	}, 100);

	/**
	 * make accordion headings clickable, not only the link inside them
	 */
	var accordionTitles = document.getElementsByClassName('panel-heading');
	for (var i=0; i<accordionTitles.length; i++) {
		var accordionTitle = accordionTitles[i];
		accordionTitle.className = accordionTitle.className + ' clickable';
		accordionTitle.addEventListener('click', function(event) {
			var accordionLink = accordionTitle.querySelectorAll('[data-toggle="collapse"]')[0];
			accordionLink.click();
		});
	}

	/**
	 * shortcuts
	 * - Shift+D: open/close the toolbar
	 * - Escape:  close the toolbar
	 */
	window.addEventListener('keydown', function(event) {
		if (event.ctrlKey == false && event.altKey == false && event.shiftKey && event.keyCode == 68) {
			event.preventDefault();
			top.window.closeDebugDetails();
		}
		if (event.ctrlKey == false && event.altKey == false && event.shiftKey == false && event.keyCode == 27) {
			event.preventDefault();
			top.window.closeDebugDetails();
		}
	});
}
<|endoftext|>


<commit_before>'use strict';

/**
 * @ngdoc function
 * @name Pear2Pear.controller:BottomNavbarCtrl
 * @description
 * # BottomNavbarCtrl
 * Controller of the Pear2Pear
 */
angular.module('Pear2Pear')
  .controller('BottomNavbarCtrl', ['$scope', '$location', '$window', function ($scope, $location, $window) {
    $scope.context = 'news';
    $scope.timeline = function () {
      //TODO timeline of the community
      $location.path('/timeline/');
    };
    $scope.projects = function () {
      //TODO projects of the community
      $location.path('/projects/');
    };
    $scope.tasks = function () {
      //TODO tasks of the user
      $location.path('/my_tasks/:1/tasks/');
    };

    $scope.contextIs = function (ctx) {
      return $location.path().split('/')[1] === ctx;
    };
    $scope.$watch(function () {
      return $window.innerHeight;
    }, function(value) {
      console.log(value);
    });

    $window.addEventListener('resize', function () {
      $scope.$apply(function () {
        $scope.$parent.height = window.innerHeight;
      });
    }, true);
  }]);
<commit_msg>do not log irrelevant message<commit_after>'use strict';

/**
 * @ngdoc function
 * @name Pear2Pear.controller:BottomNavbarCtrl
 * @description
 * # BottomNavbarCtrl
 * Controller of the Pear2Pear
 */
angular.module('Pear2Pear')
  .controller('BottomNavbarCtrl', ['$scope', '$location', '$window', function ($scope, $location, $window) {
    $scope.context = 'news';
    $scope.timeline = function () {
      //TODO timeline of the community
      $location.path('/timeline/');
    };
    $scope.projects = function () {
      //TODO projects of the community
      $location.path('/projects/');
    };
    $scope.tasks = function () {
      //TODO tasks of the user
      $location.path('/my_tasks/:1/tasks/');
    };

    $scope.contextIs = function (ctx) {
      return $location.path().split('/')[1] === ctx;
    };
    $scope.$watch(function () {
      return $window.innerHeight;
    }, function(value) {
    });

    $window.addEventListener('resize', function () {
      $scope.$apply(function () {
        $scope.$parent.height = window.innerHeight;
      });
    }, true);
  }]);
<|endoftext|>


<commit_before>/**
 * Created by wermerbalazs on 06/12/15.
 */
(function () {
  'use strict';

  angular
    .module('app')
    .factory('cartService', cartService);

  cartService.$inject = ['$log'];

  /* @ngInject */
  function cartService($log) {
    var cart = [];
    var service = {
      add: add,
      addOne: addOne,
      removeOne: removeOne,
      remove: remove,
      clear: clear,
      getCart: getCart
    };
    return service;

    ////////////////

    function add(obj) {
      var contains = false;
      $.each(cart, function () {
        if ($(this)[0].name == obj.name) {
          $log.info('Cart already contains the product. Adding amount.');
          $(this)[0].amount += obj.amount;
          contains = true;
        }
      });

      if (!contains) {
        cart.push(obj);
        $log.info('Added product: ', obj);
      }
      console.log(cart);
    }

    function addOne(obj) {
      $.each(cart, function () {
        if (obj.name == $(this)[0].name) {
          $(this)[0].amount++;
          $log.info('Increased product amount by one. Product:', $(this)[0]);
        }
      });

    }

    function removeOne(obj) {
      $.each(cart, function () {
        if (obj.name == $(this)[0].name) {
          $(this)[0].amount--;
          $log.info('Decreased product amount by one. Product:', $(this)[0]);
        }
      });
    }

    function remove(obj) {
      var index = cart.indexOf(obj);
      cart.splice(index, 1);
      $log.info('Removed product from cart. Product:', obj);
    }

    function clear() {
      cart = [];
      $log.info('Emptied cart.');
    }

    function getCart() {
      $log.info('Getting cart content.');
      return cart;
    }
  }

})();

<commit_msg>cleanup<commit_after>/**
 * Created by wermerbalazs on 06/12/15.
 */
(function () {
  'use strict';

  angular
    .module('app')
    .factory('cartService', cartService);

  cartService.$inject = ['$log'];

  /* @ngInject */
  function cartService($log) {
    var cart = [];
    var service = {
      add: add,
      addOne: addOne,
      removeOne: removeOne,
      remove: remove,
      clear: clear,
      getCart: getCart
    };
    return service;

    ////////////////

    function add(obj) {
      var contains = false;
      $.each(cart, function () {
        if ($(this)[0].name == obj.name) {
          $log.info('Cart already contains the product. Adding amount.');
          $(this)[0].amount += obj.amount;
          contains = true;
        }
      });

      if (!contains) {
        cart.push(obj);
        $log.info('Added product: ', obj);
      }
    }

    function addOne(obj) {
      $.each(cart, function () {
        if (obj.name == $(this)[0].name) {
          $(this)[0].amount++;
          $log.info('Increased product amount by one. Product:', $(this)[0]);
        }
      });

    }

    function removeOne(obj) {
      $.each(cart, function () {
        if (obj.name == $(this)[0].name) {
          $(this)[0].amount--;
          $log.info('Decreased product amount by one. Product:', $(this)[0]);
        }
      });
    }

    function remove(obj) {
      var index = cart.indexOf(obj);
      cart.splice(index, 1);
      $log.info('Removed product from cart. Product:', obj);
    }

    function clear() {
      cart = [];
      $log.info('Emptied cart.');
    }

    function getCart() {
      $log.info('Getting cart content.');
      return cart;
    }
  }

})();

<|endoftext|>


<commit_before>/**
 * ------------------------------------------
 * 平台配置信息接口实现文件
 *  window.NEJ_CONF = {
 *      // resource root
 *      // defalut value -> '/res/'
 *      root : '/nej/'
 *      // blank image for ie6-ie7
 *      // default value -> $root+'nej_blank.gif'
 *      blank : '/res/nej_blank.gif'
 *      // localstorage flash
 *      // default value -> $root+'nej_storage.swf'
 *      storage : '/res/nej_storage.swf'
 *      // clipboard flash
 *      // default value -> $root+'nej_clipboard.swf'
 *      clipboard : '/res/nej_clipboard.swf'
 *      // https request proxy
 *      // default value -> $root+'nej_proxy_flash.swf'
 *      ajax : '/res/nej_proxy_flash.swf'
 *      // portrait root
 *      // default value -> $root+'portrait/'
 *      portrait : '/res/portrait/'
 *      // cross domain xhr request for ie6-ie9
 *      // if path not start with http[s]://
 *      // will use /res/nej_proxy_frame.html as default
 *      p_frame:['http://c.d.com/html/nej_proxy_frame.html']
 *      // flash crossdomain.xml file path
 *      // default value -> http://a.b.com/crossdomain.xml
 *      p_flash:['http://a.b.com/proxy/crossdomain.xml']
 *      // CSRF cookie name and parameter name
 *      // default value -> {cookie:'',param:''}
 *      p_csrf:{cookie:'',param:''}
 *  };
 * @version  1.0
 * @author   genify(caijf@corp.netease.com)
 * ------------------------------------------
 */
var f = function(){
    var _c = NEJ.P('nej.c'),
        _cache = {};
    /*
     * URL地址转源信息
     * http://a.b.com:8080/a/bc/ -> http://a.b.com:8080
     * @param  {String} URL地址
     * @return {String} 源信息
     */
    var _url2host = (function(){
        var _reg = /^([\w]+?:\/\/.*?(?=\/|$))/i;
        return function(_url){
            _url = _url||'';
            if (_reg.test(_url))
                return RegExp.$1;
            return location.protocol+'//'+location.host;
        };
    })();
    /*
     * 初始化配置信息
     * @param  {Object} 配置信息
     * @return {Void}
     */
    var _doInit = (function(){
        var _doInitProxy = function(_list,_map){
            if (!_list||!_list.length) return;
            for(var i=0,l=_list.length,_path;i<l;i++){
                _path = _list[i];
                if (_path.indexOf('://')>0)
                    _map[_url2host(_path)] = _path;
            }
        };
        return function(_config){
            // root
            _c.__set('root',_config.root||'/res/');
            // portrait root
            _c.__set('portrait',_config.portrait||
                    (_c._$get('root')+'portrait/'));
            // ajax by flash proxy
            _c.__set('ajax.swf',_config.ajax||
                    (_c._$get('root')+'nej_proxy_flash.swf'));
            // clipboard flash
            _c.__set('clipboard.swf',_config.clipboard||
                    (_c._$get('root')+'nej_clipboard.swf'));
            // chart flash
            _c.__set('chart.swf',_config.chart||
                    (_c._$get('root')+'nej_flex_chart.swf'));
            // csrf config
            _c.__set('csrf',NEJ.EX({
                cookie:'p_info',
                param:'csrf_token'
            },_config.p_csrf));
            // ajax by frame proxy
            _cache.frames = {};
            _doInitProxy(_config.p_frame,_cache.frames);
            // ajax by flash proxy
            _cache.flashs = {};
            _doInitProxy(_config.p_flash,_cache.flashs);
        };
    })();
    /*
     * 设置NEJ配置信息
     * @param  {String}   _key   配置标识
     * @param  {Variable} _value 配置信息
     * @return {Void}
     */
    _c.__set = function(_key,_value){
        _cache[_key] = _value;
    };
    /**
     * 获取NEJ配置信息
     * @param  {String} _key 配置标识
     * @return {Variable}    配置信息
     */
    _c._$get = function(_key){
        return _cache[_key];
    };
    /**
     * 取Frame跨域Ajax代理文件
     * @param  {String} 请求地址或者域名
     * @return {String} 代理文件地址
     */
    _c._$getFrameProxy = function(_url){
        var _host = _url2host(_url);
        return _cache.frames[_host]||
              (_host+'/res/nej_proxy_frame.html');
    };
    /**
     * 取Flash跨域Ajax配置文件
     * @param  {String} 请求地址或者域名
     * @return {String} 代理文件地址
     */
    _c._$getFlashProxy = function(_url){
        return _cache.flashs[_url2host(_url)];
    };
    // init
    _doInit(window.NEJ_CONF||NEJ.O);
};
NEJ.define('{lib}patched/config.js',
          ['{lib}base/platform.js'],f);<commit_msg>anti csrf<commit_after>/**
 * ------------------------------------------
 * 平台配置信息接口实现文件
 *  window.NEJ_CONF = {
 *      // resource root
 *      // defalut value -> '/res/'
 *      root : '/nej/'
 *      // blank image for ie6-ie7
 *      // default value -> $root+'nej_blank.gif'
 *      blank : '/res/nej_blank.gif'
 *      // localstorage flash
 *      // default value -> $root+'nej_storage.swf'
 *      storage : '/res/nej_storage.swf'
 *      // clipboard flash
 *      // default value -> $root+'nej_clipboard.swf'
 *      clipboard : '/res/nej_clipboard.swf'
 *      // https request proxy
 *      // default value -> $root+'nej_proxy_flash.swf'
 *      ajax : '/res/nej_proxy_flash.swf'
 *      // portrait root
 *      // default value -> $root+'portrait/'
 *      portrait : '/res/portrait/'
 *      // cross domain xhr request for ie6-ie9
 *      // if path not start with http[s]://
 *      // will use /res/nej_proxy_frame.html as default
 *      p_frame:['http://c.d.com/html/nej_proxy_frame.html']
 *      // flash crossdomain.xml file path
 *      // default value -> http://a.b.com/crossdomain.xml
 *      p_flash:['http://a.b.com/proxy/crossdomain.xml']
 *      // CSRF cookie name and parameter name
 *      // default value -> {cookie:'',param:''}
 *      p_csrf:{cookie:'',param:''}
 *  };
 * @version  1.0
 * @author   genify(caijf@corp.netease.com)
 * ------------------------------------------
 */
var f = function(){
    var _c = NEJ.P('nej.c'),
        _cache = {};
    /*
     * URL地址转源信息
     * http://a.b.com:8080/a/bc/ -> http://a.b.com:8080
     * @param  {String} URL地址
     * @return {String} 源信息
     */
    var _url2host = (function(){
        var _reg = /^([\w]+?:\/\/.*?(?=\/|$))/i;
        return function(_url){
            _url = _url||'';
            if (_reg.test(_url))
                return RegExp.$1;
            return location.protocol+'//'+location.host;
        };
    })();
    /*
     * 初始化配置信息
     * @param  {Object} 配置信息
     * @return {Void}
     */
    var _doInit = (function(){
        var _doInitProxy = function(_list,_map){
            if (!_list||!_list.length) return;
            for(var i=0,l=_list.length,_path;i<l;i++){
                _path = _list[i];
                if (_path.indexOf('://')>0)
                    _map[_url2host(_path)] = _path;
            }
        };
        return function(_config){
            // root
            _c.__set('root',_config.root||'/res/');
            // portrait root
            _c.__set('portrait',_config.portrait||
                    (_c._$get('root')+'portrait/'));
            // ajax by flash proxy
            _c.__set('ajax.swf',_config.ajax||
                    (_c._$get('root')+'nej_proxy_flash.swf'));
            // clipboard flash
            _c.__set('clipboard.swf',_config.clipboard||
                    (_c._$get('root')+'nej_clipboard.swf'));
            // chart flash
            _c.__set('chart.swf',_config.chart||
                    (_c._$get('root')+'nej_flex_chart.swf'));
            // csrf config
            _c.__set('csrf',NEJ.EX({
                cookie:'AntiCSRF',
                param:'AntiCSRF'
            },_config.p_csrf));
            // ajax by frame proxy
            _cache.frames = {};
            _doInitProxy(_config.p_frame,_cache.frames);
            // ajax by flash proxy
            _cache.flashs = {};
            _doInitProxy(_config.p_flash,_cache.flashs);
        };
    })();
    /*
     * 设置NEJ配置信息
     * @param  {String}   _key   配置标识
     * @param  {Variable} _value 配置信息
     * @return {Void}
     */
    _c.__set = function(_key,_value){
        _cache[_key] = _value;
    };
    /**
     * 获取NEJ配置信息
     * @param  {String} _key 配置标识
     * @return {Variable}    配置信息
     */
    _c._$get = function(_key){
        return _cache[_key];
    };
    /**
     * 取Frame跨域Ajax代理文件
     * @param  {String} 请求地址或者域名
     * @return {String} 代理文件地址
     */
    _c._$getFrameProxy = function(_url){
        var _host = _url2host(_url);
        return _cache.frames[_host]||
              (_host+'/res/nej_proxy_frame.html');
    };
    /**
     * 取Flash跨域Ajax配置文件
     * @param  {String} 请求地址或者域名
     * @return {String} 代理文件地址
     */
    _c._$getFlashProxy = function(_url){
        return _cache.flashs[_url2host(_url)];
    };
    // init
    _doInit(window.NEJ_CONF||NEJ.O);
};
NEJ.define('{lib}patched/config.js',
          ['{lib}base/platform.js'],f);<|endoftext|>


<commit_before>L.Control.MiniMap = L.Control.extend({
	options: {
		position: 'bottomright',
		toggleDisplay: false,
		zoomLevelOffset: -5,
		zoomLevelFixed: false,
		zoomAnimation: false,
		autoToggleDisplay: false,
		width: 150,
		height: 150
	},
	//layer is the map layer to be shown in the minimap
	initialize: function (layer, options) {
		L.Util.setOptions(this, options);
		this._layer = layer;
	},

	onAdd: function (map) {

		this._mainMap = map;

		//Creating the container and stopping events from spilling through to the main map.
		this._container = L.DomUtil.create('div', 'leaflet-control-minimap');
		this._container.style.width = this.options.width + 'px';
		this._container.style.height = this.options.height + 'px';
		L.DomEvent.disableClickPropagation(this._container);
		L.DomEvent.on(this._container, 'mousewheel', L.DomEvent.stopPropagation);

		this._miniMap = new L.Map(this._container,
		{
			attributionControl: false,
			zoomControl: false,
			zoomAnimation: this.options.zoomAnimation,
			autoToggleDisplay: this.options.autoToggleDisplay,
			touchZoom: !this.options.zoomLevelFixed,
			scrollWheelZoom: !this.options.zoomLevelFixed,
			doubleClickZoom: !this.options.zoomLevelFixed,
			boxZoom: !this.options.zoomLevelFixed
		});
		//We make a copy so that the original layer object is untouched, this way we can add/remove multiple times
		this._miniMap.addLayer(L.Util.clone (this._layer));

		//These bools are used to prevent infinite loops of the two maps notifying each other that they've moved.
		this._mainMapMoving = false;
		this._miniMapMoving = false;

		//Keep a record of this to prevent auto toggling when the user explicitly doesn't want it.
		this._userToggledDisplay = false;
		this._minimized = false;

		if (this.options.toggleDisplay) {
			this._addToggleButton();
		}

		this._miniMap.whenReady(L.Util.bind(function () {
			this._aimingRect = L.rectangle(this._mainMap.getBounds(), {color: "#ff7800", weight: 1, clickable: false}).addTo(this._miniMap);
			this._mainMap.on('moveend', this._onMainMapMoved, this);
			this._mainMap.on('move', this._onMainMapMoving, this);
			this._miniMap.on('moveend', this._onMiniMapMoved, this);
		}, this));

		return this._container;
	},

	addTo: function (map) {
		L.Control.prototype.addTo.call(this, map);
		this._miniMap.setView(this._mainMap.getCenter(), this._decideZoom(true));
		this._setDisplay(this._decideMinimized());
		return this;
	},

	onRemove: function (map) {
		this._mainMap.off('moveend', this._onMainMapMoved, this);
		this._mainMap.off('move', this._onMainMapMoving, this);
		this._miniMap.off('moveend', this._onMiniMapMoved, this);

	},

	_addToggleButton: function () {
		this._toggleDisplayButton = this.options.toggleDisplay ? this._createButton(
		        '', 'Hide', 'leaflet-control-minimap-toggle-display', this._container, this._toggleDisplayButtonClicked, this) : undefined;
	},

	_createButton: function (html, title, className, container, fn, context) {
		var link = L.DomUtil.create('a', className, container);
		link.innerHTML = html;
		link.href = '#';
		link.title = title;

		var stop = L.DomEvent.stopPropagation;

		L.DomEvent
		    .on(link, 'click', stop)
		    .on(link, 'mousedown', stop)
		    .on(link, 'dblclick', stop)
		    .on(link, 'click', L.DomEvent.preventDefault)
		    .on(link, 'click', fn, context);

		return link;
	},

    _toggleDisplayButtonClicked: function () {
        this._userToggledDisplay = true;
        if (!this._minimized) {
            this._minimize();
        }
        else {
            this._restore();
        }
    },

    _setDisplay: function (minimize) {
        if (minimize != this._minimized) {
            if (!this._minimized) {
                this._minimize();
            }
            else {
                this._restore();
            }
        }
    },

    _minimize: function () {
        // hide the minimap
        if (this.options.toggleDisplay) {
            this._container.style.width = '19px';
            this._container.style.height = '19px';
            this._toggleDisplayButton.className += ' minimized';
        }
        else {
            this._container.style.display = 'none';
        }
        this._minimized = true;
    },

    _restore: function () {
        if (this.options.toggleDisplay) {
            this._container.style.width = this.options.width + 'px';
            this._container.style.height = this.options.height + 'px';
            this._toggleDisplayButton.className = this._toggleDisplayButton.className
				    .replace(/(?:^|\s)minimized(?!\S)/g, '');
        }
        else {
            this._container.style.display = 'block';
        }
        this._minimized = false;
    },

	_onMainMapMoved: function (e) {
		if (!this._miniMapMoving) {
			this._mainMapMoving = true;
			this._miniMap.setView(this._mainMap.getCenter(), this._decideZoom(true));
			this._setDisplay(this._decideMinimized());
		} else {
			this._miniMapMoving = false;
		}
		this._aimingRect.setBounds(this._mainMap.getBounds());
	},

	_onMainMapMoving: function (e) {
		this._aimingRect.setBounds(this._mainMap.getBounds());
	},

	_onMiniMapMoved: function (e) {
	    if (!this._mainMapMoving) {
			this._miniMapMoving = true;
			this._mainMap.setView(this._miniMap.getCenter(), this._decideZoom(false));
		} else {
			this._mainMapMoving = false;
		}
	},

	_decideZoom: function (fromMaintoMini) {
		if (!this.options.zoomLevelFixed) {
			if (fromMaintoMini)
				return this._mainMap.getZoom() + this.options.zoomLevelOffset;
			else
				return this._miniMap.getZoom() - this.options.zoomLevelOffset;
		} else {
			if (fromMaintoMini)
				return this.options.zoomLevelFixed;
			else
				return this._mainMap.getZoom();
		}
    },

    _decideMinimized: function () {
        if (this._userToggledDisplay) {
            return this._minimized;
        }

        if (this.options.autoToggleDisplay) {
            if (this._mainMap.getBounds().contains(this._miniMap.getBounds())) {
                return true;
            }
            return false;
        }

        return this._minimized;
    }
});

L.Map.mergeOptions({
	miniMapControl: false
});

L.Map.addInitHook(function () {
	if (this.options.miniMapControl) {
		this.miniMapControl = (new L.Control.MiniMap()).addTo(this);
	}
});

L.control.minimap = function (options) {
	return new L.Control.MiniMap(options);
};

//Simple helper function for cloning
L.Util.clone = function (o){
	if(o == null || typeof(o) != 'object')
		return o;

	var c = new o.constructor();
	//Deep clone recursively
	for(var k in o)
		c[k] = L.Util.clone(o[k]);

	return c;
};<commit_msg>Fix ws errors from recent contribs<commit_after>L.Control.MiniMap = L.Control.extend({
	options: {
		position: 'bottomright',
		toggleDisplay: false,
		zoomLevelOffset: -5,
		zoomLevelFixed: false,
		zoomAnimation: false,
		autoToggleDisplay: false,
		width: 150,
		height: 150
	},
	//layer is the map layer to be shown in the minimap
	initialize: function (layer, options) {
		L.Util.setOptions(this, options);
		this._layer = layer;
	},

	onAdd: function (map) {

		this._mainMap = map;

		//Creating the container and stopping events from spilling through to the main map.
		this._container = L.DomUtil.create('div', 'leaflet-control-minimap');
		this._container.style.width = this.options.width + 'px';
		this._container.style.height = this.options.height + 'px';
		L.DomEvent.disableClickPropagation(this._container);
		L.DomEvent.on(this._container, 'mousewheel', L.DomEvent.stopPropagation);

		this._miniMap = new L.Map(this._container,
		{
			attributionControl: false,
			zoomControl: false,
			zoomAnimation: this.options.zoomAnimation,
			autoToggleDisplay: this.options.autoToggleDisplay,
			touchZoom: !this.options.zoomLevelFixed,
			scrollWheelZoom: !this.options.zoomLevelFixed,
			doubleClickZoom: !this.options.zoomLevelFixed,
			boxZoom: !this.options.zoomLevelFixed
		});
		//We make a copy so that the original layer object is untouched, this way we can add/remove multiple times
		this._miniMap.addLayer(L.Util.clone (this._layer));

		//These bools are used to prevent infinite loops of the two maps notifying each other that they've moved.
		this._mainMapMoving = false;
		this._miniMapMoving = false;

		//Keep a record of this to prevent auto toggling when the user explicitly doesn't want it.
		this._userToggledDisplay = false;
		this._minimized = false;

		if (this.options.toggleDisplay) {
			this._addToggleButton();
		}

		this._miniMap.whenReady(L.Util.bind(function () {
			this._aimingRect = L.rectangle(this._mainMap.getBounds(), {color: "#ff7800", weight: 1, clickable: false}).addTo(this._miniMap);
			this._mainMap.on('moveend', this._onMainMapMoved, this);
			this._mainMap.on('move', this._onMainMapMoving, this);
			this._miniMap.on('moveend', this._onMiniMapMoved, this);
		}, this));

		return this._container;
	},

	addTo: function (map) {
		L.Control.prototype.addTo.call(this, map);
		this._miniMap.setView(this._mainMap.getCenter(), this._decideZoom(true));
		this._setDisplay(this._decideMinimized());
		return this;
	},

	onRemove: function (map) {
		this._mainMap.off('moveend', this._onMainMapMoved, this);
		this._mainMap.off('move', this._onMainMapMoving, this);
		this._miniMap.off('moveend', this._onMiniMapMoved, this);

	},

	_addToggleButton: function () {
		this._toggleDisplayButton = this.options.toggleDisplay ? this._createButton(
				'', 'Hide', 'leaflet-control-minimap-toggle-display', this._container, this._toggleDisplayButtonClicked, this) : undefined;
	},

	_createButton: function (html, title, className, container, fn, context) {
		var link = L.DomUtil.create('a', className, container);
		link.innerHTML = html;
		link.href = '#';
		link.title = title;

		var stop = L.DomEvent.stopPropagation;

		L.DomEvent
			.on(link, 'click', stop)
			.on(link, 'mousedown', stop)
			.on(link, 'dblclick', stop)
			.on(link, 'click', L.DomEvent.preventDefault)
			.on(link, 'click', fn, context);

		return link;
	},

	_toggleDisplayButtonClicked: function () {
		this._userToggledDisplay = true;
		if (!this._minimized) {
			this._minimize();
		}
		else {
			this._restore();
		}
	},

	_setDisplay: function (minimize) {
		if (minimize != this._minimized) {
			if (!this._minimized) {
				this._minimize();
			}
			else {
				this._restore();
			}
		}
	},

	_minimize: function () {
		// hide the minimap
		if (this.options.toggleDisplay) {
			this._container.style.width = '19px';
			this._container.style.height = '19px';
			this._toggleDisplayButton.className += ' minimized';
		}
		else {
			this._container.style.display = 'none';
		}
		this._minimized = true;
	},

	_restore: function () {
		if (this.options.toggleDisplay) {
			this._container.style.width = this.options.width + 'px';
			this._container.style.height = this.options.height + 'px';
			this._toggleDisplayButton.className = this._toggleDisplayButton.className
					.replace(/(?:^|\s)minimized(?!\S)/g, '');
		}
		else {
			this._container.style.display = 'block';
		}
		this._minimized = false;
	},

	_onMainMapMoved: function (e) {
		if (!this._miniMapMoving) {
			this._mainMapMoving = true;
			this._miniMap.setView(this._mainMap.getCenter(), this._decideZoom(true));
			this._setDisplay(this._decideMinimized());
		} else {
			this._miniMapMoving = false;
		}
		this._aimingRect.setBounds(this._mainMap.getBounds());
	},

	_onMainMapMoving: function (e) {
		this._aimingRect.setBounds(this._mainMap.getBounds());
	},

	_onMiniMapMoved: function (e) {
		if (!this._mainMapMoving) {
			this._miniMapMoving = true;
			this._mainMap.setView(this._miniMap.getCenter(), this._decideZoom(false));
		} else {
			this._mainMapMoving = false;
		}
	},

	_decideZoom: function (fromMaintoMini) {
		if (!this.options.zoomLevelFixed) {
			if (fromMaintoMini)
				return this._mainMap.getZoom() + this.options.zoomLevelOffset;
			else
				return this._miniMap.getZoom() - this.options.zoomLevelOffset;
		} else {
			if (fromMaintoMini)
				return this.options.zoomLevelFixed;
			else
				return this._mainMap.getZoom();
		}
	},

	_decideMinimized: function () {
		if (this._userToggledDisplay) {
			return this._minimized;
		}

		if (this.options.autoToggleDisplay) {
			if (this._mainMap.getBounds().contains(this._miniMap.getBounds())) {
				return true;
			}
			return false;
		}

		return this._minimized;
	}
});

L.Map.mergeOptions({
	miniMapControl: false
});

L.Map.addInitHook(function () {
	if (this.options.miniMapControl) {
		this.miniMapControl = (new L.Control.MiniMap()).addTo(this);
	}
});

L.control.minimap = function (options) {
	return new L.Control.MiniMap(options);
};

//Simple helper function for cloning
L.Util.clone = function (o){
	if(o == null || typeof(o) != 'object')
		return o;

	var c = new o.constructor();
	//Deep clone recursively
	for(var k in o)
		c[k] = L.Util.clone(o[k]);

	return c;
};<|endoftext|>


<commit_before>/* Copyright 2011 the Melange authors.
 *
 * 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.
 */
/**
 * @author Mario Ferraro
 */
(function () {
  /** @lends melange.dependency */

  if (window.melange === undefined) {
    throw new Error("Melange not loaded");
  }

  var melange = window.melange;

  /** Package that handles melange JS dependencies
    * Doesn't list jQuery, JSON, melange and melange.dependency
    * in any chain as they're dependencies of this own script,
    * and they will be then loaded anyway.
    * @name melange.dependency
    * @namespace melange.depencency
    * @borrows melange.logging.debugDecorator.log as log
    */
  melange.dependency = window.melange.dependency = function () {
    return new melange.dependency();
  };

  /** Shortcut to current package.
    * @private
    */
  var $m = melange.logging.debugDecorator(melange.dependency);

  melange.error.createErrors([
  ]);

  $m.templateWithContext = function (script_template, context) {
    this.script_template = script_template;
    this.context = context;
  };

  $m.cssFile = function (css) {
    this.css = css;
  };

  var script_dependencies_chains = {};

  var s = script_dependencies_chains;

  // Third party JS URL prefix
  var tpjs = "/js/" + melange.config.app_version + "/";

  // Melange packages URL prefix
  var mpjs = "/soc/content/js/" + melange.config.app_version + "/";

  if (melange.config.google_api_key !== undefined) {
    s.google = [
      "http://www.google.com/jsapi?key=" + melange.config.google_api_key
    ];
  }
  else {
    s.google = [
      "http://www.google.com/jsapi"
    ];
  }

  if (melange.config.is_local !== undefined && melange.config.is_local === true) {
    s.jquery = [
      tpjs + "jquery/jquery-1.5.js"
    ];
  }
  else {
    s.jquery = [
      "http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"
    ];
  }

  s.json = [
    tpjs + "json/json2.js"
  ];

  s.tinymce = [
    tpjs + "tiny_mce/tiny_mce.js"
  ];

  s.purr = [
    tpjs + "jquery/jquery-purr.js"
  ];

  s.spin = [
    tpjs + "jquery/jquery-spin-1.1.1.js"
  ];

  s.bgiframe = [
    tpjs + "jquery/jquery-bgiframe.js"
  ];

  s.ajaxQueue = [
    tpjs + "jquery/jquery-ajaxQueue.js"
  ];

  s.thickbox = [
    tpjs + "jquery/jquery-thickbox.js"
  ];

  s.progressbar = [
    tpjs + "jquery/jquery-progressbar.js"
  ];

  s.uniform = [
    tpjs + "jquery/jquery-uniform.js"
  ];

  s.jqueryui = {}

  if (melange.config.is_local !== undefined && melange.config.is_local === true) {
    s.jqueryui.core = [
      new $m.cssFile("/soc/content/css/jquery-ui/jquery.ui.all.css"),
      tpjs + "jquery/jquery-ui.core.js"
    ];
  }
  else {
    s.jqueryui.core = [
      new $m.cssFile("/soc/content/css/jquery-ui/jquery.ui.merged.css"),
      tpjs + "jquery/jquery-ui.core.js"
    ];
  }

  s.jqueryui.position = [
    s.jqueryui.core,
    null,
    tpjs + "jquery/jquery-ui.position.js"
  ];

  s.jqueryui.widget = [
    s.jqueryui.core,
    null,
    tpjs + "jquery/jquery-ui.widget.js"
  ];

  s.jqueryui.autocomplete = [
    s.jqueryui.position,
    s.jqueryui.widget,
    null,
    tpjs + "jquery/jquery-ui.autocomplete.js"
  ];

  s.jqgrid = [
    s.jqueryui.core,
    null,
    new $m.cssFile("/soc/content/css/v2/gsoc/ui.jqgrid.css"),
    tpjs + "jquery/jquery-jqgrid.locale-en.js",
    null,
    tpjs + "jquery/jquery-jqgrid.base.js",
    null,
    tpjs + "jquery/jquery-jqgrid.custom.js",
    tpjs + "jquery/jquery-jqgrid.setcolumns.js"
  ];

  s.jqgridediting = [
    s.jqgrid,
    null,
    tpjs + "jquery/jquery-jqgrid.common.js",
    tpjs + "jquery/jquery-jqgrid.formedit.js",
    null,
    tpjs + "jquery/jquery-jqgrid.searchFilter.js",
    tpjs + "jquery/jquery-jqgrid.inlinedit.js",
    null,
    tpjs + "jquery/jquery-jqgrid.jqDnR.js",
    null,
    tpjs + "jquery/jquery-jqgrid.jqModal.js"
  ];

  s.cookie = [
    tpjs + "jquery/jquery-cookie.js"
  ];

  s.jlinq = [
    tpjs + "jlinq/jLinq-2.2.1.js"
  ];

  /** Melange packages **/

  s.melange = {};

  s.melange.main = [
    s.google,
    null,
    mpjs + "melange.js"
  ];

  s.melange.datetimepicker = [
    s.jqueryui.core,
    null,
    tpjs + "jquery-ui.datetimepicker.js",
    null,
    mpjs + "datetimepicker.js",
    null,
    mpjs + "datetime-loader.js"
  ];

  s.melange.menu = [
    s.cookie,
    null,
    mpjs + "menu.js"
  ];

  s.melange.duplicates = [
    s.progressbar,
    null,
    mpjs + "duplicate-slots.js"
  ];

  s.melange.form = [
  ];

  s.melange.list = [
    s.jqgrid,
    s.jlinq,
    null,
    s.jqgridediting,
    null,
    mpjs + "melange.list.js"
  ];

  s.melange.tooltip = [
    s.purr,
    null
  ];

  s.melange.autocomplete = [
    s.jqueryui.autocomplete,
    null,
    mpjs + "melange.autocomplete.js"
  ];

  s.melange.graph = [
    s.google,
    null,
    mpjs + "melange.graph.js"
  ];

  s.melange.uploadform = [
    mpjs + "upload-form.js"
  ];

  s.melange.blog = [
    s.google,
    null,
    mpjs + "melange.blog.js"
  ];

  $m.s = s;

  var unpack = function (orig_array) {
    var array_to_return = [];
    for (var i = 0, len = orig_array.length; i < len; i++) {
      var current_element = orig_array[i];
      if (typeof current_element === 'object' && current_element instanceof
          Array) {
        var unpacks = unpack(current_element);
        array_to_return = array_to_return.concat(unpacks);
      }
      else {
        array_to_return.push(current_element);
      }
    }
    return array_to_return;
  };

  $m.loadScripts = function(requested_packages) {
    var _tempqueue = unpack(requested_packages);

    /* Remove duplicates from the queue, as allowDuplicates with LAB
     * fails randomly at least in Safari and Chrome
     */
    var _queue = [];

    for (var i = 0, len = _tempqueue.length; i < len; i++) {
      var temp_val = _tempqueue[i];
      if (typeof temp_val == "string") {
        if (jQuery.inArray(temp_val, _queue) === -1) {
          _queue.push(temp_val);
        }
      } else {
        _queue.push(temp_val);
      }
    }

    for (var i=0, len=_queue.length; i<len; i++) {
      if (typeof _queue[i] == "string") { // script string source found
          $LAB = $LAB.script(_queue[i]);
      }
      else if (!_queue[i]) { // null/false found
          $LAB = $LAB.wait();
      }
      else if (typeof _queue[i] == "object" && _queue[i] instanceof $m.templateWithContext) {
          $LAB = $LAB.script(_queue[i].script_template).wait(
            function (context_to_send) {
              return function () {
                melange.templates.setContextToLast(context_to_send);
              }
            }(_queue[i].context)
          ).wait();
      }
      else if (typeof _queue[i] == "object" && _queue[i] instanceof $m.cssFile) {
        jQuery("<link>", {
          href: _queue[i].css,
          media: "screen",
          rel: "stylesheet",
          type: "text/css"
        }).appendTo("head");
      }
      else if (typeof _queue[i] == "function") { // inline function found
          $LAB = $LAB.wait(_queue[i]);
      }
    }
  };

}());
<commit_msg>jQuery Rating plugin added to Melange Dependencies.<commit_after>/* Copyright 2011 the Melange authors.
 *
 * 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.
 */
/**
 * @author Mario Ferraro
 */
(function () {
  /** @lends melange.dependency */

  if (window.melange === undefined) {
    throw new Error("Melange not loaded");
  }

  var melange = window.melange;

  /** Package that handles melange JS dependencies
    * Doesn't list jQuery, JSON, melange and melange.dependency
    * in any chain as they're dependencies of this own script,
    * and they will be then loaded anyway.
    * @name melange.dependency
    * @namespace melange.depencency
    * @borrows melange.logging.debugDecorator.log as log
    */
  melange.dependency = window.melange.dependency = function () {
    return new melange.dependency();
  };

  /** Shortcut to current package.
    * @private
    */
  var $m = melange.logging.debugDecorator(melange.dependency);

  melange.error.createErrors([
  ]);

  $m.templateWithContext = function (script_template, context) {
    this.script_template = script_template;
    this.context = context;
  };

  $m.cssFile = function (css) {
    this.css = css;
  };

  var script_dependencies_chains = {};

  var s = script_dependencies_chains;

  // Third party JS URL prefix
  var tpjs = "/js/" + melange.config.app_version + "/";

  // Melange packages URL prefix
  var mpjs = "/soc/content/js/" + melange.config.app_version + "/";

  if (melange.config.google_api_key !== undefined) {
    s.google = [
      "http://www.google.com/jsapi?key=" + melange.config.google_api_key
    ];
  }
  else {
    s.google = [
      "http://www.google.com/jsapi"
    ];
  }

  if (melange.config.is_local !== undefined && melange.config.is_local === true) {
    s.jquery = [
      tpjs + "jquery/jquery-1.5.js"
    ];
  }
  else {
    s.jquery = [
      "http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"
    ];
  }

  s.json = [
    tpjs + "json/json2.js"
  ];

  s.tinymce = [
    tpjs + "tiny_mce/tiny_mce.js"
  ];

  s.purr = [
    tpjs + "jquery/jquery-purr.js"
  ];

  s.spin = [
    tpjs + "jquery/jquery-spin-1.1.1.js"
  ];

  s.bgiframe = [
    tpjs + "jquery/jquery-bgiframe.js"
  ];

  s.ajaxQueue = [
    tpjs + "jquery/jquery-ajaxQueue.js"
  ];

  s.thickbox = [
    tpjs + "jquery/jquery-thickbox.js"
  ];

  s.progressbar = [
    tpjs + "jquery/jquery-progressbar.js"
  ];

  s.uniform = [
    tpjs + "jquery/jquery-uniform.js"
  ];

  s.raty = [
    tpjs + "jquery/jquery.raty.js"
    ];

  s.jqueryui = {}

  if (melange.config.is_local !== undefined && melange.config.is_local === true) {
    s.jqueryui.core = [
      new $m.cssFile("/soc/content/css/jquery-ui/jquery.ui.all.css"),
      tpjs + "jquery/jquery-ui.core.js"
    ];
  }
  else {
    s.jqueryui.core = [
      new $m.cssFile("/soc/content/css/jquery-ui/jquery.ui.merged.css"),
      tpjs + "jquery/jquery-ui.core.js"
    ];
  }

  s.jqueryui.position = [
    s.jqueryui.core,
    null,
    tpjs + "jquery/jquery-ui.position.js"
  ];

  s.jqueryui.widget = [
    s.jqueryui.core,
    null,
    tpjs + "jquery/jquery-ui.widget.js"
  ];

  s.jqueryui.autocomplete = [
    s.jqueryui.position,
    s.jqueryui.widget,
    null,
    tpjs + "jquery/jquery-ui.autocomplete.js"
  ];

  s.jqgrid = [
    s.jqueryui.core,
    null,
    new $m.cssFile("/soc/content/css/v2/gsoc/ui.jqgrid.css"),
    tpjs + "jquery/jquery-jqgrid.locale-en.js",
    null,
    tpjs + "jquery/jquery-jqgrid.base.js",
    null,
    tpjs + "jquery/jquery-jqgrid.custom.js",
    tpjs + "jquery/jquery-jqgrid.setcolumns.js"
  ];

  s.jqgridediting = [
    s.jqgrid,
    null,
    tpjs + "jquery/jquery-jqgrid.common.js",
    tpjs + "jquery/jquery-jqgrid.formedit.js",
    null,
    tpjs + "jquery/jquery-jqgrid.searchFilter.js",
    tpjs + "jquery/jquery-jqgrid.inlinedit.js",
    null,
    tpjs + "jquery/jquery-jqgrid.jqDnR.js",
    null,
    tpjs + "jquery/jquery-jqgrid.jqModal.js"
  ];

  s.cookie = [
    tpjs + "jquery/jquery-cookie.js"
  ];

  s.jlinq = [
    tpjs + "jlinq/jLinq-2.2.1.js"
  ];

  /** Melange packages **/

  s.melange = {};

  s.melange.main = [
    s.google,
    null,
    mpjs + "melange.js"
  ];

  s.melange.datetimepicker = [
    s.jqueryui.core,
    null,
    tpjs + "jquery-ui.datetimepicker.js",
    null,
    mpjs + "datetimepicker.js",
    null,
    mpjs + "datetime-loader.js"
  ];

  s.melange.menu = [
    s.cookie,
    null,
    mpjs + "menu.js"
  ];

  s.melange.duplicates = [
    s.progressbar,
    null,
    mpjs + "duplicate-slots.js"
  ];

  s.melange.form = [
  ];

  s.melange.list = [
    s.jqgrid,
    s.jlinq,
    null,
    s.jqgridediting,
    null,
    mpjs + "melange.list.js"
  ];

  s.melange.tooltip = [
    s.purr,
    null
  ];

  s.melange.autocomplete = [
    s.jqueryui.autocomplete,
    null,
    mpjs + "melange.autocomplete.js"
  ];

  s.melange.graph = [
    s.google,
    null,
    mpjs + "melange.graph.js"
  ];

  s.melange.uploadform = [
    mpjs + "upload-form.js"
  ];

  s.melange.blog = [
    s.google,
    null,
    mpjs + "melange.blog.js"
  ];

  $m.s = s;

  var unpack = function (orig_array) {
    var array_to_return = [];
    for (var i = 0, len = orig_array.length; i < len; i++) {
      var current_element = orig_array[i];
      if (typeof current_element === 'object' && current_element instanceof
          Array) {
        var unpacks = unpack(current_element);
        array_to_return = array_to_return.concat(unpacks);
      }
      else {
        array_to_return.push(current_element);
      }
    }
    return array_to_return;
  };

  $m.loadScripts = function(requested_packages) {
    var _tempqueue = unpack(requested_packages);

    /* Remove duplicates from the queue, as allowDuplicates with LAB
     * fails randomly at least in Safari and Chrome
     */
    var _queue = [];

    for (var i = 0, len = _tempqueue.length; i < len; i++) {
      var temp_val = _tempqueue[i];
      if (typeof temp_val == "string") {
        if (jQuery.inArray(temp_val, _queue) === -1) {
          _queue.push(temp_val);
        }
      } else {
        _queue.push(temp_val);
      }
    }

    for (var i=0, len=_queue.length; i<len; i++) {
      if (typeof _queue[i] == "string") { // script string source found
          $LAB = $LAB.script(_queue[i]);
      }
      else if (!_queue[i]) { // null/false found
          $LAB = $LAB.wait();
      }
      else if (typeof _queue[i] == "object" && _queue[i] instanceof $m.templateWithContext) {
          $LAB = $LAB.script(_queue[i].script_template).wait(
            function (context_to_send) {
              return function () {
                melange.templates.setContextToLast(context_to_send);
              }
            }(_queue[i].context)
          ).wait();
      }
      else if (typeof _queue[i] == "object" && _queue[i] instanceof $m.cssFile) {
        jQuery("<link>", {
          href: _queue[i].css,
          media: "screen",
          rel: "stylesheet",
          type: "text/css"
        }).appendTo("head");
      }
      else if (typeof _queue[i] == "function") { // inline function found
          $LAB = $LAB.wait(_queue[i]);
      }
    }
  };

}());
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');
var chalk = require('chalk');
var ssh = require('./lib/ssh.js');

module.exports = function(grunt){

    grunt.registerTask('ssh_setup', function(name){

        if (arguments.length === 0) {
            grunt.fatal([
                'You should provide an instance name.',
                'e.g: ' + chalk.yellow('grunt ssh_deploy:name')
            ].join('\n'));
        }
        // TODO nginx, users
        // TODO ssh-add the key in ec2_create_keypair so that rsync doesn't cough
        var done = this.async();
        var tasks = [[
            // setup rsync deployments
            'sudo mkdir -p /srv/rsync',
            'sudo chown ubuntu /srv/rsync' // TODO: create an rsync user, chown with him. AWS_RSYNC_USER
        ], [
            // install Node.js
            // TODO use node through a new user, too.
            'sudo apt-get install python-software-properties',
            'sudo add-apt-repository ppa:chris-lea/node.js -y',
            'sudo apt-get update',
            'sudo apt-get install nodejs -y'
        ]];

        var commands = _.flatten(tasks);
        ssh(commands, name, done);
    });
};
<commit_msg>removed TODO<commit_after>'use strict';

var _ = require('lodash');
var chalk = require('chalk');
var ssh = require('./lib/ssh.js');

module.exports = function(grunt){

    grunt.registerTask('ssh_setup', function(name){

        if (arguments.length === 0) {
            grunt.fatal([
                'You should provide an instance name.',
                'e.g: ' + chalk.yellow('grunt ssh_deploy:name')
            ].join('\n'));
        }
        // TODO nginx, users
        var done = this.async();
        var tasks = [[
            // setup rsync deployments
            'sudo mkdir -p /srv/rsync',
            'sudo chown ubuntu /srv/rsync' // TODO: create an rsync user, chown with him. AWS_RSYNC_USER
        ], [
            // install Node.js
            // TODO use node through a new user, too.
            'sudo apt-get install python-software-properties',
            'sudo add-apt-repository ppa:chris-lea/node.js -y',
            'sudo apt-get update',
            'sudo apt-get install nodejs -y'
        ]];

        var commands = _.flatten(tasks);
        ssh(commands, name, done);
    });
};
<|endoftext|>


<commit_before>import './polyfill';
import Delta from 'rich-text/lib/delta';
import Editor from './editor';
import Emitter from './emitter';
import Module from './module';
import Parchment from 'parchment';
import Selection, { Range } from './selection';
import extend from 'extend';
import logger from './logger';
import Theme from './theme';

let debug = logger('quill');

class Quill {
  static debug(limit) {
    logger.level(limit);
  }

  static import(name) {
    if (this.imports[name] == null) {
      debug.error(`Cannot import ${name}. Are you sure it was registered?`);
    }
    return this.imports[name];
  }

  static register(path, target, overwrite = false) {
    if (typeof path !== 'string') {
      let name = path.attrName || path.blotName;
      if (typeof name === 'string') {
        // register(Blot | Attributor, overwrite)
        this.register('formats/' + name, path, target);
      } else {
        Object.keys(path).forEach((key) => {
          this.register(key, path[key], target);
        });
      }
    } else {
      if (this.imports[path] != null && !overwrite) {
        debug.warn(`Overwriting ${path} with`, target);
      }
      this.imports[path] = target;
      if ((path.startsWith('blots/') || path.startsWith('formats/')) &&
          target.blotName !== 'abstract') {
        Parchment.register(target);
      }
    }
  }

  constructor(container, options = {}) {
    options = expandConfig(container, options);
    this.container = options.container;
    if (this.container == null) {
      return debug.error('Invalid Quill container', container);
    }
    if (options.debug) {
      Quill.debug(options.debug);
    }
    let html = this.container.innerHTML.trim();
    this.container.classList.add('ql-container');
    this.container.innerHTML = '';
    this.root = this.addContainer('ql-editor');
    this.emitter = new Emitter();
    this.emitter.on(Emitter.events.EDITOR_CHANGE, (type) => {
      if (type === Emitter.events.TEXT_CHANGE) {
        this.root.classList.toggle('ql-blank', this.editor.isBlank());
      }
    });
    this.scroll = Parchment.create(this.root, {
      emitter: this.emitter,
      whitelist: options.formats
    });
    this.editor = new Editor(this.scroll, this.emitter);
    this.selection = new Selection(this.scroll, this.emitter);
    this.theme = new options.theme(this, options);
    this.keyboard = this.theme.addModule('keyboard');
    this.clipboard = this.theme.addModule('clipboard');
    this.history = this.theme.addModule('history');
    this.theme.init();
    this.pasteHTML(`<div class='ql-editor' style="white-space: normal;">${html}<p><br></p></div>`);
    this.history.clear();
    if (options.readOnly) {
      this.disable();
    }
    if (options.placeholder) {
      this.root.dataset.placeholder = options.placeholder;
    }
  }

  addContainer(container, refNode = null) {
    if (typeof container === 'string') {
      let className = container;
      container = document.createElement('div');
      container.classList.add(className);
    }
    this.container.insertBefore(container, refNode);
    return container;
  }

  blur() {
    this.selection.setRange(null);
  }

  deleteText(index, length, source) {
    [index, length, , source] = overload(index, length, source);
    let range = this.getSelection();
    let change = this.editor.deleteText(index, length, source);
    range = shiftRange(range, index, -1*length, source);
    this.setSelection(range, Emitter.sources.SILENT);
    return change;
  }

  disable() {
    this.editor.enable(false);
  }

  enable(enabled = true) {
    this.editor.enable(enabled);
  }

  focus() {
    this.selection.focus();
    this.selection.scrollIntoView();
  }

  format(name, value, source = Emitter.sources.API) {
    let range = this.getSelection(true);
    let change = new Delta();
    if (range == null) return change;
    if (Parchment.query(name, Parchment.Scope.BLOCK)) {
      change = this.formatLine(range, name, value, source);
    } else if (range.length === 0) {
      this.selection.format(name, value);
      return change;
    } else {
      change = this.formatText(range, name, value, source);
    }
    this.setSelection(range, Emitter.sources.SILENT);
    return change;
  }

  formatLine(index, length, name, value, source) {
    let formats;
    [index, length, formats, source] = overload(index, length, name, value, source);
    let range = this.getSelection();
    let change = this.editor.formatLine(index, length, formats, source);
    this.selection.setRange(range, true, Emitter.sources.SILENT);
    this.selection.scrollIntoView();
    return change;
  }

  formatText(index, length, name, value, source) {
    let formats;
    [index, length, formats, source] = overload(index, length, name, value, source);
    let range = this.getSelection();
    let change = this.editor.formatText(index, length, formats, source);
    this.selection.setRange(range, true, Emitter.sources.SILENT);
    this.selection.scrollIntoView();
    return change;
  }

  getBounds(index, length = 0) {
    if (typeof index === 'number') {
      return this.selection.getBounds(index, length);
    } else {
      return this.selection.getBounds(index.index, index.length);
    }
  }

  getContents(index = 0, length = this.getLength() - index) {
    [index, length] = overload(index, length);
    return this.editor.getContents(index, length);
  }

  getFormat(index = this.getSelection(), length = 0) {
    if (typeof index === 'number') {
      return this.editor.getFormat(index, length);
    } else {
      return this.editor.getFormat(index.index, index.length);
    }
  }

  getLength() {
    return this.scroll.length();
  }

  getModule(name) {
    return this.theme.modules[name];
  }

  getSelection(focus = false) {
    if (focus) this.focus();
    this.update();  // Make sure we access getRange with editor in consistent state
    return this.selection.getRange()[0];
  }

  getText(index = 0, length = this.getLength() - index) {
    [index, length] = overload(index, length);
    return this.editor.getText(index, length);
  }

  hasFocus() {
    return this.selection.hasFocus();
  }

  insertEmbed(index, embed, value, source = Quill.sources.API) {
    let range = this.getSelection();
    let change = this.editor.insertEmbed(index, embed, value, source);
    range = shiftRange(range, change, source);
    this.setSelection(range, Emitter.sources.SILENT);
    return change;
  }

  insertText(index, text, name, value, source) {
    let formats, range = this.getSelection();
    [index, , formats, source] = overload(index, 0, name, value, source);
    let change = this.editor.insertText(index, text, formats, source);
    range = shiftRange(range, index, text.length, source);
    this.setSelection(range, Emitter.sources.SILENT);
    return change;
  }

  off() {
    return this.emitter.off.apply(this.emitter, arguments);
  }

  on() {
    return this.emitter.on.apply(this.emitter, arguments);
  }

  once() {
    return this.emitter.once.apply(this.emitter, arguments);
  }

  pasteHTML(index, html, source = Emitter.sources.API) {
    if (typeof index === 'string') {
      return this.setContents(this.clipboard.convert(index), html);
    } else {
      let paste = this.clipboard.convert(html);
      return this.updateContents(new Delta().retain(index).concat(paste), source);
    }
  }

  removeFormat(index, length, source) {
    let range = this.getSelection();
    [index, length, , source] = overload(index, length, source);
    let change = this.editor.removeFormat(index, length, source);
    range = shiftRange(range, change, source);
    this.setSelection(range, Emitter.sources.SILENT);
    return change;
  }

  setContents(delta, source = Emitter.sources.API) {
    delta = new Delta(delta).slice();
    let lastOp = delta.ops[delta.ops.length - 1];
    // Quill contents must always end with newline
    if (lastOp == null || lastOp.insert[lastOp.insert.length-1] !== '\n') {
      delta.insert('\n');
    }
    delta.delete(this.getLength());
    return this.editor.applyDelta(delta, source);
  }

  setSelection(index, length, source) {
    if (index == null) {
      this.selection.setRange(null, length || Quill.sources.API);
    } else {
      [index, length, , source] = overload(index, length, source);
      this.selection.setRange(new Range(index, length), source);
    }
    this.selection.scrollIntoView();
  }

  setText(text, source = Emitter.sources.API) {
    let delta = new Delta().insert(text);
    return this.setContents(delta, source);
  }

  update(source = Emitter.sources.USER) {
    let change = this.scroll.update(source);   // Will update selection before selection.update() does if text changes
    this.selection.update(source);
    return change;
  }

  updateContents(delta, source = Emitter.sources.API) {
    let range = this.getSelection();
    if (Array.isArray(delta)) {
      delta = new Delta(delta.slice());
    }
    let change = this.editor.applyDelta(delta, source);
    if (range != null) {
      range = shiftRange(range, change, source);
      this.setSelection(range, Emitter.sources.SILENT);
    }
    return change;
  }
}
Quill.DEFAULTS = {
  bounds: document.body,
  formats: null,
  modules: {},
  placeholder: '',
  readOnly: false,
  theme: 'default'
};
Quill.events = Emitter.events;
Quill.sources = Emitter.sources;
Quill.version = typeof(QUILL_VERSION) === 'undefined' ? 'dev' : QUILL_VERSION;

Quill.imports = {
  'delta'       : Delta,
  'parchment'   : Parchment,
  'core/module' : Module,
  'core/theme'  : Theme
};

function expandConfig(container, userConfig) {
  userConfig = extend(true, {
    container: container,
    modules: {
      clipboard: true,
      keyboard: true,
      history: true
    }
  }, userConfig);
  if (userConfig.theme == null || userConfig.theme === Quill.DEFAULTS.theme) {
    userConfig.theme = Theme;
  } else {
    userConfig.theme = Quill.import(`themes/${userConfig.theme}`);
    if (userConfig.theme == null) {
      throw new Error(`Invalid theme ${userConfig.theme}. Did you register it?`);
    }
  }
  let themeConfig = extend(true, {}, userConfig.theme.DEFAULTS);
  [themeConfig, userConfig].forEach(function(config) {
    config.modules = config.modules || {};
    Object.keys(config.modules).forEach(function(module) {
      if (config.modules[module] === true) {
        config.modules[module] = {};
      }
    });
  });
  let moduleNames = Object.keys(themeConfig.modules).concat(Object.keys(userConfig.modules));
  let moduleConfig = moduleNames.reduce(function(config, name) {
    let moduleClass = Quill.import(`modules/${name}`);
    if (moduleClass == null) {
      debug.error(`Cannot load ${name} module. Are you sure you registered it?`);
    } else {
      config[name] = moduleClass.DEFAULTS || {};
    }
    return config;
  }, {});
  // Special case toolbar shorthand
  if (userConfig.modules != null && userConfig.modules.toolbar != null &&
      userConfig.modules.toolbar.constructor !== Object) {
    userConfig.modules.toolbar = {
      container: userConfig.modules.toolbar
    };
  }
  userConfig = extend(true, {}, Quill.DEFAULTS, { modules: moduleConfig }, themeConfig, userConfig);
  ['bounds', 'container'].forEach(function(key) {
    if (typeof userConfig[key] === 'string') {
      userConfig[key] = document.querySelector(userConfig[key]);
    }
  });
  return userConfig;
}

function overload(index, length, name, value, source) {
  let formats = {};
  if (typeof index.index === 'number' && typeof index.length === 'number') {
    // Allow for throwaway end (used by insertText/insertEmbed)
    if (typeof length !== 'number') {
      source = value, value = name, name = length, length = index.length, index = index.index;
    } else {
      length = index.length, index = index.index;
    }
  } else if (typeof length !== 'number') {
    source = value, value = name, name = length, length = 0;
  }
  // Handle format being object, two format name/value strings or excluded
  if (typeof name === 'object') {
    formats = name;
    source = value;
  } else if (typeof name === 'string') {
    if (value != null) {
      formats[name] = value;
    } else {
      source = name;
    }
  }
  // Handle optional source
  source = source || Emitter.sources.API;
  return [index, length, formats, source];
}

function shiftRange(range, index, length, source) {
  if (range == null) return null;
  let start, end;
  if (index instanceof Delta) {
    [start, end] = [range.index, range.index + range.length].map(function(pos) {
      return index.transformPosition(pos, source === Emitter.sources.USER);
    });
  } else {
    [start, end] = [range.index, range.index + range.length].map(function(pos) {
      if (pos < index || (pos === index && source !== Emitter.sources.USER)) return pos;
      if (length >= 0) {
        return pos + length;
      } else {
        return Math.max(index, pos + length);
      }
    });
  }
  return new Range(start, end - start);
}

export { expandConfig, overload, Quill as default };
<commit_msg>Make sure `this.editor` is initialized before registering emitter listener<commit_after>import './polyfill';
import Delta from 'rich-text/lib/delta';
import Editor from './editor';
import Emitter from './emitter';
import Module from './module';
import Parchment from 'parchment';
import Selection, { Range } from './selection';
import extend from 'extend';
import logger from './logger';
import Theme from './theme';

let debug = logger('quill');

class Quill {
  static debug(limit) {
    logger.level(limit);
  }

  static import(name) {
    if (this.imports[name] == null) {
      debug.error(`Cannot import ${name}. Are you sure it was registered?`);
    }
    return this.imports[name];
  }

  static register(path, target, overwrite = false) {
    if (typeof path !== 'string') {
      let name = path.attrName || path.blotName;
      if (typeof name === 'string') {
        // register(Blot | Attributor, overwrite)
        this.register('formats/' + name, path, target);
      } else {
        Object.keys(path).forEach((key) => {
          this.register(key, path[key], target);
        });
      }
    } else {
      if (this.imports[path] != null && !overwrite) {
        debug.warn(`Overwriting ${path} with`, target);
      }
      this.imports[path] = target;
      if ((path.startsWith('blots/') || path.startsWith('formats/')) &&
          target.blotName !== 'abstract') {
        Parchment.register(target);
      }
    }
  }

  constructor(container, options = {}) {
    options = expandConfig(container, options);
    this.container = options.container;
    if (this.container == null) {
      return debug.error('Invalid Quill container', container);
    }
    if (options.debug) {
      Quill.debug(options.debug);
    }
    let html = this.container.innerHTML.trim();
    this.container.classList.add('ql-container');
    this.container.innerHTML = '';
    this.root = this.addContainer('ql-editor');
    this.emitter = new Emitter();
    this.scroll = Parchment.create(this.root, {
      emitter: this.emitter,
      whitelist: options.formats
    });
    this.editor = new Editor(this.scroll, this.emitter);
    this.selection = new Selection(this.scroll, this.emitter);
    this.emitter.on(Emitter.events.EDITOR_CHANGE, (type) => {
      if (type === Emitter.events.TEXT_CHANGE) {
        this.root.classList.toggle('ql-blank', this.editor.isBlank());
      }
    });
    this.theme = new options.theme(this, options);
    this.keyboard = this.theme.addModule('keyboard');
    this.clipboard = this.theme.addModule('clipboard');
    this.history = this.theme.addModule('history');
    this.theme.init();
    this.pasteHTML(`<div class='ql-editor' style="white-space: normal;">${html}<p><br></p></div>`);
    this.history.clear();
    if (options.readOnly) {
      this.disable();
    }
    if (options.placeholder) {
      this.root.dataset.placeholder = options.placeholder;
    }
  }

  addContainer(container, refNode = null) {
    if (typeof container === 'string') {
      let className = container;
      container = document.createElement('div');
      container.classList.add(className);
    }
    this.container.insertBefore(container, refNode);
    return container;
  }

  blur() {
    this.selection.setRange(null);
  }

  deleteText(index, length, source) {
    [index, length, , source] = overload(index, length, source);
    let range = this.getSelection();
    let change = this.editor.deleteText(index, length, source);
    range = shiftRange(range, index, -1*length, source);
    this.setSelection(range, Emitter.sources.SILENT);
    return change;
  }

  disable() {
    this.editor.enable(false);
  }

  enable(enabled = true) {
    this.editor.enable(enabled);
  }

  focus() {
    this.selection.focus();
    this.selection.scrollIntoView();
  }

  format(name, value, source = Emitter.sources.API) {
    let range = this.getSelection(true);
    let change = new Delta();
    if (range == null) return change;
    if (Parchment.query(name, Parchment.Scope.BLOCK)) {
      change = this.formatLine(range, name, value, source);
    } else if (range.length === 0) {
      this.selection.format(name, value);
      return change;
    } else {
      change = this.formatText(range, name, value, source);
    }
    this.setSelection(range, Emitter.sources.SILENT);
    return change;
  }

  formatLine(index, length, name, value, source) {
    let formats;
    [index, length, formats, source] = overload(index, length, name, value, source);
    let range = this.getSelection();
    let change = this.editor.formatLine(index, length, formats, source);
    this.selection.setRange(range, true, Emitter.sources.SILENT);
    this.selection.scrollIntoView();
    return change;
  }

  formatText(index, length, name, value, source) {
    let formats;
    [index, length, formats, source] = overload(index, length, name, value, source);
    let range = this.getSelection();
    let change = this.editor.formatText(index, length, formats, source);
    this.selection.setRange(range, true, Emitter.sources.SILENT);
    this.selection.scrollIntoView();
    return change;
  }

  getBounds(index, length = 0) {
    if (typeof index === 'number') {
      return this.selection.getBounds(index, length);
    } else {
      return this.selection.getBounds(index.index, index.length);
    }
  }

  getContents(index = 0, length = this.getLength() - index) {
    [index, length] = overload(index, length);
    return this.editor.getContents(index, length);
  }

  getFormat(index = this.getSelection(), length = 0) {
    if (typeof index === 'number') {
      return this.editor.getFormat(index, length);
    } else {
      return this.editor.getFormat(index.index, index.length);
    }
  }

  getLength() {
    return this.scroll.length();
  }

  getModule(name) {
    return this.theme.modules[name];
  }

  getSelection(focus = false) {
    if (focus) this.focus();
    this.update();  // Make sure we access getRange with editor in consistent state
    return this.selection.getRange()[0];
  }

  getText(index = 0, length = this.getLength() - index) {
    [index, length] = overload(index, length);
    return this.editor.getText(index, length);
  }

  hasFocus() {
    return this.selection.hasFocus();
  }

  insertEmbed(index, embed, value, source = Quill.sources.API) {
    let range = this.getSelection();
    let change = this.editor.insertEmbed(index, embed, value, source);
    range = shiftRange(range, change, source);
    this.setSelection(range, Emitter.sources.SILENT);
    return change;
  }

  insertText(index, text, name, value, source) {
    let formats, range = this.getSelection();
    [index, , formats, source] = overload(index, 0, name, value, source);
    let change = this.editor.insertText(index, text, formats, source);
    range = shiftRange(range, index, text.length, source);
    this.setSelection(range, Emitter.sources.SILENT);
    return change;
  }

  off() {
    return this.emitter.off.apply(this.emitter, arguments);
  }

  on() {
    return this.emitter.on.apply(this.emitter, arguments);
  }

  once() {
    return this.emitter.once.apply(this.emitter, arguments);
  }

  pasteHTML(index, html, source = Emitter.sources.API) {
    if (typeof index === 'string') {
      return this.setContents(this.clipboard.convert(index), html);
    } else {
      let paste = this.clipboard.convert(html);
      return this.updateContents(new Delta().retain(index).concat(paste), source);
    }
  }

  removeFormat(index, length, source) {
    let range = this.getSelection();
    [index, length, , source] = overload(index, length, source);
    let change = this.editor.removeFormat(index, length, source);
    range = shiftRange(range, change, source);
    this.setSelection(range, Emitter.sources.SILENT);
    return change;
  }

  setContents(delta, source = Emitter.sources.API) {
    delta = new Delta(delta).slice();
    let lastOp = delta.ops[delta.ops.length - 1];
    // Quill contents must always end with newline
    if (lastOp == null || lastOp.insert[lastOp.insert.length-1] !== '\n') {
      delta.insert('\n');
    }
    delta.delete(this.getLength());
    return this.editor.applyDelta(delta, source);
  }

  setSelection(index, length, source) {
    if (index == null) {
      this.selection.setRange(null, length || Quill.sources.API);
    } else {
      [index, length, , source] = overload(index, length, source);
      this.selection.setRange(new Range(index, length), source);
    }
    this.selection.scrollIntoView();
  }

  setText(text, source = Emitter.sources.API) {
    let delta = new Delta().insert(text);
    return this.setContents(delta, source);
  }

  update(source = Emitter.sources.USER) {
    let change = this.scroll.update(source);   // Will update selection before selection.update() does if text changes
    this.selection.update(source);
    return change;
  }

  updateContents(delta, source = Emitter.sources.API) {
    let range = this.getSelection();
    if (Array.isArray(delta)) {
      delta = new Delta(delta.slice());
    }
    let change = this.editor.applyDelta(delta, source);
    if (range != null) {
      range = shiftRange(range, change, source);
      this.setSelection(range, Emitter.sources.SILENT);
    }
    return change;
  }
}
Quill.DEFAULTS = {
  bounds: document.body,
  formats: null,
  modules: {},
  placeholder: '',
  readOnly: false,
  theme: 'default'
};
Quill.events = Emitter.events;
Quill.sources = Emitter.sources;
Quill.version = typeof(QUILL_VERSION) === 'undefined' ? 'dev' : QUILL_VERSION;

Quill.imports = {
  'delta'       : Delta,
  'parchment'   : Parchment,
  'core/module' : Module,
  'core/theme'  : Theme
};

function expandConfig(container, userConfig) {
  userConfig = extend(true, {
    container: container,
    modules: {
      clipboard: true,
      keyboard: true,
      history: true
    }
  }, userConfig);
  if (userConfig.theme == null || userConfig.theme === Quill.DEFAULTS.theme) {
    userConfig.theme = Theme;
  } else {
    userConfig.theme = Quill.import(`themes/${userConfig.theme}`);
    if (userConfig.theme == null) {
      throw new Error(`Invalid theme ${userConfig.theme}. Did you register it?`);
    }
  }
  let themeConfig = extend(true, {}, userConfig.theme.DEFAULTS);
  [themeConfig, userConfig].forEach(function(config) {
    config.modules = config.modules || {};
    Object.keys(config.modules).forEach(function(module) {
      if (config.modules[module] === true) {
        config.modules[module] = {};
      }
    });
  });
  let moduleNames = Object.keys(themeConfig.modules).concat(Object.keys(userConfig.modules));
  let moduleConfig = moduleNames.reduce(function(config, name) {
    let moduleClass = Quill.import(`modules/${name}`);
    if (moduleClass == null) {
      debug.error(`Cannot load ${name} module. Are you sure you registered it?`);
    } else {
      config[name] = moduleClass.DEFAULTS || {};
    }
    return config;
  }, {});
  // Special case toolbar shorthand
  if (userConfig.modules != null && userConfig.modules.toolbar != null &&
      userConfig.modules.toolbar.constructor !== Object) {
    userConfig.modules.toolbar = {
      container: userConfig.modules.toolbar
    };
  }
  userConfig = extend(true, {}, Quill.DEFAULTS, { modules: moduleConfig }, themeConfig, userConfig);
  ['bounds', 'container'].forEach(function(key) {
    if (typeof userConfig[key] === 'string') {
      userConfig[key] = document.querySelector(userConfig[key]);
    }
  });
  return userConfig;
}

function overload(index, length, name, value, source) {
  let formats = {};
  if (typeof index.index === 'number' && typeof index.length === 'number') {
    // Allow for throwaway end (used by insertText/insertEmbed)
    if (typeof length !== 'number') {
      source = value, value = name, name = length, length = index.length, index = index.index;
    } else {
      length = index.length, index = index.index;
    }
  } else if (typeof length !== 'number') {
    source = value, value = name, name = length, length = 0;
  }
  // Handle format being object, two format name/value strings or excluded
  if (typeof name === 'object') {
    formats = name;
    source = value;
  } else if (typeof name === 'string') {
    if (value != null) {
      formats[name] = value;
    } else {
      source = name;
    }
  }
  // Handle optional source
  source = source || Emitter.sources.API;
  return [index, length, formats, source];
}

function shiftRange(range, index, length, source) {
  if (range == null) return null;
  let start, end;
  if (index instanceof Delta) {
    [start, end] = [range.index, range.index + range.length].map(function(pos) {
      return index.transformPosition(pos, source === Emitter.sources.USER);
    });
  } else {
    [start, end] = [range.index, range.index + range.length].map(function(pos) {
      if (pos < index || (pos === index && source !== Emitter.sources.USER)) return pos;
      if (length >= 0) {
        return pos + length;
      } else {
        return Math.max(index, pos + length);
      }
    });
  }
  return new Range(start, end - start);
}

export { expandConfig, overload, Quill as default };
<|endoftext|>


<commit_before>/*
 @example

 // html

btn 1

btn 2

btn 3

btn 4

btn 5

btn 6

btn 7

btn 8

btn 9

btn 10

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10

 // css
 .slide-navi {
 position: relative;
 width: 100%;
 height: 50px;
 overflow: hidden;
 }

 .slide-navi .handle {
 position: absolute;
 top: 0;
 left: 0;
 }

 .slide-navi .btns {
 display: block;
 position: relative;
 margin: 0;
 padding: 0;
 white-space: nowrap;
 }

 .slide-navi .btns:after {
 content: "";
 display: block;
 clear: both;
 }

 .slide-navi .btns li {
 display: inline-block;
 height: 50px;
 line-height: 50px;
 outline: 1px solid #006666;
 }

 .slide-navi .btns li a {
 display: block;
 margin-left: 0;
 margin-right: 0;
 padding-left: 5px;
 padding-right: 5px;
 background-color: #555555;
 color: #222;
 text-align: center;
 }

 .slide-navi .btns li a.on {
 color: #f00;
 }

 // js
 import HorizontalSlideNavi from './component/HorizontalSlideNavi';

 let slideNaviWrap = $('.slide-navi'),
 btnsWrap = $('.btns', slideNaviWrap);

 let slideNavi = new HorizontalSlideNavi({
 // Navi.js options
 btns: $('li a', btnsWrap),
 mouseoverCallback: function (obj) {
 console.log('mouseover :', obj);
 },
 mouseoutCallback: function (obj) {
 console.log('mouseout :', obj);
 },
 mousedownCallback: function (obj) {
 console.log('mousedown :', obj);
 },
 mouseupCallback: function (obj) {
 console.log('mouseup :', obj);
 },
 clickCallback: function (obj) {
 console.log('click :', obj);
 },
 activateCallback: function (obj) {
 let btns = $(slideNavi.getBtns()),
 btn = $(slideNavi.getBtn(obj.index));

 btns.removeClass('on');
 btn.addClass('on');
 },

 // HorizontalSlideNavi.js options
 wrap: slideNaviWrap,
 handleClass: 'handle',
 btnsWrap: btnsWrap,

 disabled: false,
 slide: true,
 loose: true,
 speed: 0.25,
 css3: true,

 dragStartCallback: function (x, y) {
 console.log('dragStartCallback :', x, y);
 },
 dragStopCallback: function (x, y) {
 console.log('dragStopCallback :', x, y);
 },
 slideEndCallback: function (x, y) {
 console.log('scrollEnd x, y :', x, y);
 }
 });
 slideNavi.init();

 // TEST
 $('.test-btns a').on('click', function (evt) {
 let index = $(this).index() + 1;
 activateSlideNavi(index);
 });

 function activateSlideNavi(index) {
 if (slideNavi) slideNavi.activate(index);

 if (index < 1 || index > slideNavi.getBtns().length) return;

 let prev = (index <= 1) ? 0 : index - 1,
 next = (index > slideNavi.getBtns().length) ? 0 : index + 1;

 if (!prev) {
 // go to left end.
 slideNavi.setRatioX(0);
 return;
 }

 if (!next) {
 // go go right end.
 slideNavi.setRatioX(1);
 return;
 }

 let btn = $(slideNavi.getBtn(prev));
 if (btn.length) slideNavi.setX(-btn.position().left);
 }
 */

import Navi from './Navi';

class HorizontalSlideNavi extends Navi {
  constructor(options) {
    if (!options) return;

    let opt = {
      /*
       // Navi.js options
       btns,
       mouseoverCallback,
       mouseoutCallback,
       mousedownCallback,
       mouseupCallback,
       clickCallback,
       activateCallback,
       */
      Dragdealer: null,

      wrap: null,
      handleClass: '',
      btnsWrap: null,

      disabled: false,
      slide: true,
      loose: true,
      speed: 0.25,
      css3: true,

      dragStartCallback: null,
      dragStopCallback: null,
      slideEndCallback: null
    };
    $.extend(opt, options);

    opt.Dragdealer = (opt.Dragdealer) ? opt.Dragdealer : window.Dragdealer;
    if(!opt.Dragdealer) {
      // https://github.com/skidding/dragdealer
      throw new Error('HorizontalSlideNavi.js require Dragdealer.js Library.');
    }

    super(opt);

    let _ = this;

    _.option = opt;

    _.$proxyResize = $.proxy(_.resize, _);

    _.isDraggable = false;

    _.dragDealer = null;
  }

  init(obj) {
    super.init(obj);

    this.setInstance();
  }

  setInstance() {
    const _ = this;

    let opt = _.option;

    _.dragDealer = new opt.Dragdealer($(opt.wrap).get(0), {
      handleClass: opt.handleClass,
      disabled: opt.disabled,
      horizontal: true,
      vertical: false,
      slide: opt.slide,
      loose: opt.loose,
      speed: opt.speed,
      css3: opt.css3,

      dragStartCallback: opt.dragStartCallback,
      dragStopCallback: opt.dragStopCallback,
      callback: opt.slideEndCallback
    });

    $(window).on('resize.ui.horizontalslidenavi', _.$proxyResize);
    _.resize();
  }

  resize(evt) {
    const _ = this;

    if (!_.dragDealer) return;

    if (_.option.btnsWrap.width() > window.innerWidth) {
      // console.log('can scroll');
      _.dragDealer.enable();

      _.isDraggable = true;

    } else {
      // console.log('can not scroll');
      if(!_.dragDealer.disabled) _.dragDealer.disable();

      _.setRatioX(0);

      _.isDraggable = false;
    }

    return _;
  }

  /*
   * public methods
   */
  // getBtns()
  // getBtn(index)
  // getActivatedIndex()
  // activate(index)

  getRatioX() {
    let offset = this.dragDealer.getValue();
    return offset[0];
  }

  getOffsetRatioByPosition(x) {
    return this.dragDealer.getRatiosByOffsets([x, 0]); // return [0, 0];
  }

  setX(x) {
    let offset = this.getOffsetRatioByPosition(x);
    this.dragDealer.setValue(offset[0], offset[1]);

    return this;
  }

  setRatioX(ratioX) {
    this.dragDealer.setValue(ratioX, 0);
    return this;
  }

  isSlidable() {
    return this.isDraggable;
  }

  enable() {
    this.dragDealer.enable();
    return this;
  }

  disable() {
    this.dragDealer.disable();
    return this;
  }

  destroy(obj) {
    let _ = this;

    $(window).off('resize.ui.horizontalslidenavi', _.$proxyResize);
    _.$proxyResize = null;

    _.isDraggable = false;

    if (_.dragDealer) _.dragDealer.unbindEventListeners();
    _.dragDealer = null;

    super.destroy(obj);

    return _;
  }
}

export default HorizontalSlideNavi;<commit_msg>add getHandler function in HorizontalSlideNavi.js<commit_after>/*
 @example

 // html

btn 1

btn 2

btn 3

btn 4

btn 5

btn 6

btn 7

btn 8

btn 9

btn 10

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10

 // css
 .slide-navi {
 position: relative;
 width: 100%;
 height: 50px;
 overflow: hidden;
 }

 .slide-navi .handle {
 position: absolute;
 top: 0;
 left: 0;
 }

 .slide-navi .btns {
 display: block;
 position: relative;
 margin: 0;
 padding: 0;
 white-space: nowrap;
 }

 .slide-navi .btns:after {
 content: "";
 display: block;
 clear: both;
 }

 .slide-navi .btns li {
 display: inline-block;
 height: 50px;
 line-height: 50px;
 outline: 1px solid #006666;
 }

 .slide-navi .btns li a {
 display: block;
 margin-left: 0;
 margin-right: 0;
 padding-left: 5px;
 padding-right: 5px;
 background-color: #555555;
 color: #222;
 text-align: center;
 }

 .slide-navi .btns li a.on {
 color: #f00;
 }

 // js
 import HorizontalSlideNavi from './component/HorizontalSlideNavi';

 let slideNaviWrap = $('.slide-navi'),
 btnsWrap = $('.btns', slideNaviWrap);

 let slideNavi = new HorizontalSlideNavi({
 // Navi.js options
 btns: $('li a', btnsWrap),
 mouseoverCallback: function (obj) {
 console.log('mouseover :', obj);
 },
 mouseoutCallback: function (obj) {
 console.log('mouseout :', obj);
 },
 mousedownCallback: function (obj) {
 console.log('mousedown :', obj);
 },
 mouseupCallback: function (obj) {
 console.log('mouseup :', obj);
 },
 clickCallback: function (obj) {
 console.log('click :', obj);
 },
 activateCallback: function (obj) {
 let btns = $(slideNavi.getBtns()),
 btn = $(slideNavi.getBtn(obj.index));

 btns.removeClass('on');
 btn.addClass('on');
 },

 // HorizontalSlideNavi.js options
 wrap: slideNaviWrap,
 handleClass: 'handle',
 btnsWrap: btnsWrap,

 disabled: false,
 slide: true,
 loose: true,
 speed: 0.25,
 css3: true,

 dragStartCallback: function (x, y) {
 console.log('dragStartCallback :', x, y);
 },
 dragStopCallback: function (x, y) {
 console.log('dragStopCallback :', x, y);
 },
 slideEndCallback: function (x, y) {
 console.log('scrollEnd x, y :', x, y);
 }
 });
 slideNavi.init();

 // TEST
 $('.test-btns a').on('click', function (evt) {
 let index = $(this).index() + 1;
 activateSlideNavi(index);
 });

 function activateSlideNavi(index) {
 if (slideNavi) slideNavi.activate(index);

 if (index < 1 || index > slideNavi.getBtns().length) return;

 let prev = (index <= 1) ? 0 : index - 1,
 next = (index > slideNavi.getBtns().length) ? 0 : index + 1;

 if (!prev) {
 // go to left end.
 slideNavi.setRatioX(0);
 return;
 }

 if (!next) {
 // go go right end.
 slideNavi.setRatioX(1);
 return;
 }

 let btn = $(slideNavi.getBtn(prev));
 if (btn.length) slideNavi.setX(-btn.position().left);
 }
 */

import Navi from './Navi';

class HorizontalSlideNavi extends Navi {
  constructor(options) {
    if (!options) return;

    let opt = {
      /*
       // Navi.js options
       btns,
       mouseoverCallback,
       mouseoutCallback,
       mousedownCallback,
       mouseupCallback,
       clickCallback,
       activateCallback,
       */
      Dragdealer: null,

      wrap: null,
      handleClass: '',
      btnsWrap: null,

      disabled: false,
      slide: true,
      loose: true,
      speed: 0.25,
      css3: true,

      dragStartCallback: null,
      dragStopCallback: null,
      slideEndCallback: null
    };
    $.extend(opt, options);

    opt.Dragdealer = (opt.Dragdealer) ? opt.Dragdealer : window.Dragdealer;
    if(!opt.Dragdealer) {
      // https://github.com/skidding/dragdealer
      throw new Error('HorizontalSlideNavi.js require Dragdealer.js Library.');
    }

    super(opt);

    let _ = this;

    _.option = opt;

    _.$proxyResize = $.proxy(_.resize, _);

    _.isDraggable = false;

    _.dragDealer = null;
  }

  init(obj) {
    super.init(obj);

    this.setInstance();
  }

  setInstance() {
    const _ = this;

    let opt = _.option;

    _.dragDealer = new opt.Dragdealer($(opt.wrap).get(0), {
      handleClass: opt.handleClass,
      disabled: opt.disabled,
      horizontal: true,
      vertical: false,
      slide: opt.slide,
      loose: opt.loose,
      speed: opt.speed,
      css3: opt.css3,

      dragStartCallback: opt.dragStartCallback,
      dragStopCallback: opt.dragStopCallback,
      callback: opt.slideEndCallback
    });

    $(window).on('resize.ui.horizontalslidenavi', _.$proxyResize);
    _.resize();
  }

  resize(evt) {
    const _ = this;

    if (!_.dragDealer) return;

    if (_.option.btnsWrap.width() > window.innerWidth) {
      // console.log('can scroll');
      _.dragDealer.enable();

      _.isDraggable = true;

    } else {
      // console.log('can not scroll');
      if(!_.dragDealer.disabled) _.dragDealer.disable();

      _.setRatioX(0);

      _.isDraggable = false;
    }

    return _;
  }

  /*
   * public methods
   */
  // getBtns()
  // getBtn(index)
  // getActivatedIndex()
  // activate(index)

  getRatioX() {
    let offset = this.dragDealer.getValue();
    return offset[0];
  }

  getOffsetRatioByPosition(x) {
    return this.dragDealer.getRatiosByOffsets([x, 0]); // return [0, 0];
  }

  getHandle() {
    return this.dragDealer.handle;
  }

  setX(x) {
    let offset = this.getOffsetRatioByPosition(x);
    this.dragDealer.setValue(offset[0], offset[1]);

    return this;
  }

  setRatioX(ratioX) {
    this.dragDealer.setValue(ratioX, 0);
    return this;
  }

  isSlidable() {
    return this.isDraggable;
  }

  enable() {
    this.dragDealer.enable();
    return this;
  }

  disable() {
    this.dragDealer.disable();
    return this;
  }

  destroy(obj) {
    let _ = this;

    $(window).off('resize.ui.horizontalslidenavi', _.$proxyResize);
    _.$proxyResize = null;

    _.isDraggable = false;

    if (_.dragDealer) _.dragDealer.unbindEventListeners();
    _.dragDealer = null;

    super.destroy(obj);

    return _;
  }
}

export default HorizontalSlideNavi;<|endoftext|>