<commit_before>/*    _____                    _____
     /\    \                  /\    \
    /::\    \                /::\    \
    \:::\    \              /::::\    \
     \:::\    \            /::::::\    \
      \:::\    \          /:::/\:::\    \
       \:::\    \        /:::/  \:::\    \
       /::::\    \      /:::/    \:::\    \
      /::::::\    \    /:::/    / \:::\    \
     /:::/\:::\    \  /:::/    /   \:::\    \
    /:::/  \:::\____\/:::/____/     \:::\____\
   /:::/    \::/    /\:::\    \      \::/    /
  /:::/    / \/____/  \:::\    \      \/____/
 /:::/    /            \:::\    \
/:::/    /              \:::\    \
\::/    /                \:::\    \
 \/____/                  \:::\    \
                           \:::\    \
                            \:::\____\
                             \::/    /
                              \/____/
                             TYPE/CODE
                         From 2010 till ∞     */

(function(window, $) {

	var NI = window.NI;

	function Tooltip(options) {

		var o = $.extend({
			triggers: $('.tooltip_trigger'),
			trigger_class:null,
			tooltip:null,
			markup_generator:null,
			animate_slide:true,
			animate_opacity:true,
			offset_left:0,
			offset_top:0,
			use_mousepos:true,
			positions:['top','right','bottom','left'],
			container:$('body'),
			hide_delay:200
		}, options);

		var internal = {
			window:$(window),
			tooltip:(o.tooltip ? o.tooltip : $('

').appendTo($('body'))),
			tooltip_content:null,
			tails:null,
			triggers:o.triggers,
			has_been_shown:false,
			current_trigger:null,
			current_trigger_id:null,
			cache:{},
			animating:false,
			visible:false,
			mousepos:null,
			visibility_timer:null
		};

		function init(me){
			internal.triggers.bind('mouseover', {me:me}, handlers.trigger_mouseover);
			internal.triggers.bind('mouseout', {me:me}, handlers.trigger_mouseout);
			internal.tooltip.bind('mouseover', {me:me}, handlers.tooltip_mouseover);
			internal.tooltip.bind('mouseout', {me:me}, handlers.tooltip_mouseout);
			internal.tooltip.css({
				'overflow':'visible'
			});
			generate_tails();
			if(o.use_mousepos){
				$(document).bind('mousemove',function(e,d){
					if(d && d.mousepos){
						internal.mousepos = d.mousepos;
					} else {
						internal.mousepos = {
							x:e.pageX,
							y:e.pageY
						};
					}
				});
			}
		};

		function generate_tails(){
			var i, my_tail;

			var css_fn = {
				top:function(container){
					return {
						//'border':'1px solid red',
						'width':'100%',
						//'bottom': '-' + (container.children('.tooltip-tail').css('height')),
						'bottom' : (0) + 'px',
						'left': (0) + 'px'
					};
				},
				right:function(container){
					return {
						//'border':'1px solid green',
						'height':'100%',
						'top': (0) + 'px',
						'left': '-' + (container.children('.tooltip-tail').css('width'))
						//'left' : (0) + 'px'
					};
				},
				bottom:function(container){
					return {
						//'border':'1px solid yellow',
						'width':'100%',
						'top': '-' + (container.children('.tooltip-tail').css('height')),
						//'top' : (0) + 'px',
						'left': (0) + 'px'
					};
				},
				left:function(container){
					return {
						//'border':'1px solid blue',
						'height':'100%',
						'top': (0) + 'px',
						//'right': '-' + (container.children('.tooltip-tail').css('width'))
						'right' : (0) + 'px'
					};
				}
			}

			for(i in o.positions){
				my_tail = $('

');
				internal.tooltip.append(my_tail);
				my_tail.css($.extend(css_fn[o.positions[i]](my_tail),{
					'position':'absolute',
					'zIndex':100
				}));
			}
			internal.tails = internal.tooltip.find('.tooltip-tail-container');

			internal.tooltip_content = $('

');
			internal.tooltip.append(internal.tooltip_content);
		}

		function markup_generator(data){
			var output;
			output = $((data ? data : '
No Data.
'));
			return $('
').append(output).html();
		};

		function show(data){
			//internal.tooltip.html(($.isFunction(o.markup_generator) ? o.markup_generator(data) : markup_generator(data)));
			internal.tooltip_content.html(($.isFunction(o.markup_generator) ? o.markup_generator(data) : markup_generator(data)));
			move_to_target(calculate_target_position());
		};

		function get_source_position(){
			if(o.use_mousepos){
				return {
					top: internal.mousepos.y,
					left: internal.mousepos.x
				};
			} else {
				return {
					left: internal.current_trigger.offset().left,
					top: internal.current_trigger.offset().top
				};
			}
		}

		function get_trigger_size(){
			if(o.use_mousepos){
				return {
					width:0,
					height:0
				};
			} else {
				return {
					left: internal.current_trigger.width(),
					top: internal.current_trigger.heigh()
				};
			}
		}

		function get_tooltip_size(){
			return {
				height:internal.tooltip.height(),
				width:internal.tooltip.width()
			}
		}

		var calculate_position = {
			top:function(sp,trs,tts){
				return {
					className:'top',
					top:(sp.top - (tts.height) - o.offset_top - (get_tail('top') ? get_tail('top').height() : 0)),
					left:((sp.left + (trs.width/2)) - (tts.width/2) + o.offset_left)
				};
			},
			bottom:function(sp,trs,tts){
				return {
					className:'bottom',
					top:(sp.top + trs.height + o.offset_top + (get_tail('bottom') ? get_tail('bottom').height() : 0) ),
					left:((sp.left + (trs.width/2)) - (tts.width/2) + o.offset_left)
				};
			},
			right:function(sp,trs,tts){
				return {
					className:'right',
					top: (sp.top + (trs.height/2) - (tts.height/2)),
					left: (sp.left + (trs.width) + o.offset_top + (get_tail('right') ? get_tail('right').width() : 0))
				};
			},
			left:function(sp,trs,tts){
				return {
					className:'left',
					top: (sp.top + (trs.height/2) - (tts.height/2)),
					left: (sp.left - (tts.width) - o.offset_top - (get_tail('left') ? get_tail('left').width() : 0))
				};
			}
		}

		function get_tail(position){
			var tail;
			tail = internal.tails.filter('.'+position).children('.tooltip-tail');
			if(tail.length){
				return tail;
			}
			return null;
		}

		function get_edge_collisions(tp, tts){
			var collisions;
			collisions = [];

			//check top
			if((tp.top - internal.window.scrollTop()) < 0){
				collisions.push('top');
			}

			//check bottom
			if((tp.top + tts.height) > internal.window.height()){
				collisions.push('bottom');
			}

			//check left
			if((tp.left - internal.window.scrollLeft()) < 0){
				collisions.push('left');
			}

			//check right
			if((tp.left + tts.width) > internal.window.width()){
				collisions.push('right');
			}

			return collisions;
		}

		function calculate_target_position(){
			var source_position, trigger_size, tooltip_size, i, target_position;
			source_position = get_source_position();
			trigger_size = get_trigger_size();
			tooltip_size = get_tooltip_size();
			tail = get_tail();
			for(i in o.positions){
				if($.isFunction(calculate_position[o.positions[i]])){
					target_position = calculate_position[o.positions[i]](source_position, trigger_size, tooltip_size);
				}
				if(!get_edge_collisions(target_position, tooltip_size).length){
					return target_position;
				}
			}
			return target_position;
		}

		function move_to_target(target_pos){
			var me, css_change, animate_change;
			me = this;

			internal.tooltip.removeClass('position-top position-right position-bottom position-left').addClass('position-' + target_pos.className);
			internal.tails.css('visibility','hidden').filter('.' + target_pos.className).css('visibility','visible');

			css_change = {};
			animate_change = {};

			tail_css_change = {};
			tail_animate_change = {};

			if(o.animate_slide){
				animate_change.top = target_pos.top;
				animate_change.left = target_pos.left;
				switch(target_pos.className){
					case 'top':
					case 'bottom':
						tail_animate_change.left = (internal.tooltip.width()/2) - o.offset_left - (get_tail(target_pos.className).width()/2);
						break;
					case 'left':
					case 'right':
						tail_animate_change.top = (internal.tooltip.height()/2) + o.offset_top - (get_tail(target_pos.className).height()/2);
						break;
				}
			} else {
				css_change.top = target_pos.top;
				css_change.left = target_pos.left;
				switch(target_pos.className){
					case 'top':
					case 'bottom':
						tail_css_change.left = (internal.tooltip.width()/2) - o.offset_left - (get_tail(target_pos.className).width()/2);
						break;
					case 'left':
					case 'right':
						tail_css_change.top = (internal.tooltip.height()/2) + o.offset_top - (get_tail(target_pos.className).height()/2);
						break;
				}
			}

			if(o.animate_opacity){
				if(!internal.has_been_shown){
					css_change.opacity = '0.0';
				}
				animate_change.opacity = '1.0';
			} else {
				css_change.opacity = '1.0';
			}

			internal.animating = true;
			get_tail(target_pos.className).css(tail_css_change).stop(true).show().animate(tail_animate_change,500,'easeOutCubic',function(){});
			internal.tooltip.stop().show().css(css_change).animate(animate_change,500,'easeOutCubic',function(){
				internal.animating = false;
				internal.visible = true;
			});

			internal.has_been_shown = true;
		};

		function hide(){
			internal.animating = true;
			internal.visible = false;
			internal.tooltip.stop().animate({
				'opacity':0.0
			},200,'easeOutCirc',function(){
				$(this).hide();
				internal.animating = false;
				internal.current_trigger = null;
			});
		};

		var handlers = {
				trigger_mouseover:function(e){
					if(internal.visibility_timer){
						clearTimeout(internal.visibility_timer);
					};
					internal.current_trigger = $(this);
					show();
				},
				trigger_mouseout:function(e){
					if(internal.visibility_timer){
						clearTimeout(internal.visibility_timer);
					};
					if(!$.contains(this,e.target)){
						internal.visibility_timer = setTimeout(hide,o.hide_delay);
						//hide();
					}
				},
				tooltip_mouseover:function(e){
					if(internal.visibility_timer){
						clearTimeout(internal.visibility_timer);
					};
					if(!o.use_mousepos && internal.current_trigger && !internal.visible){
						show();
					}
				},
				tooltip_mouseout:function(e,d){
					if(internal.animating){
						return;
					}
					if(internal.visibility_timer){
						clearTimeout(internal.visibility_timer);
					};
					if(!((this == e.target) && (this == e.relatedTarget))){
						if((!$.contains(this,e.target) && $.contains(this,e.relatedTarget)) ||
								($.contains(this,e.target) && !$.contains(this,e.relatedTarget))){
							internal.visibility_timer = setTimeout(hide,o.hide_delay);
							//hide();
						}
					}

				}
		};

		this.add_trigger = function(trigger){
			trigger.bind('mouseover', {me:this}, this.handlers.trigger_mouseover);
			trigger.bind('mouseout', {me:this}, this.handlers.trigger_mouseout);
			if(!internal.triggers.length){
				internal.triggers = trigger;
			} else {
				internal.triggers.add(trigger);
			}
		};

		this.clear_triggers = function(trigger){
			internal.triggers.each(function(i,j){
				$(j).unbind('mouseover').unbind('mouseout');
			});
			internal.triggers = $({});
		};

		this.show_tooltip = function(_options){
			var _o = $.extend({
				trigger:null,
				data:null
			},_options);

			if(!_o.trigger){
				return false;
			}

			if(internal.visibility_timer){
				clearTimeout(internal.visibility_timer);
			};

			internal.current_trigger = _o.trigger;
			internal.tooltip.stop();
			show(_o.data);
		}

		this.hide_tooltip = function(delay){
			if(internal.visibility_timer){
				clearTimeout(internal.visibility_timer);
			};
			internal.visibility_timer = setTimeout(hide,(delay ? delay : o.hide_delay));
		}

		this.get_tooltip = function(){
			return internal.tooltip;
		}

		init(this);
	}

//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

	NI.Tooltip = Tooltip;

}(this, this.jQuery));<commit_msg>hopfully the tootips will work<commit_after>/*    _____                    _____
     /\    \                  /\    \
    /::\    \                /::\    \
    \:::\    \              /::::\    \
     \:::\    \            /::::::\    \
      \:::\    \          /:::/\:::\    \
       \:::\    \        /:::/  \:::\    \
       /::::\    \      /:::/    \:::\    \
      /::::::\    \    /:::/    / \:::\    \
     /:::/\:::\    \  /:::/    /   \:::\    \
    /:::/  \:::\____\/:::/____/     \:::\____\
   /:::/    \::/    /\:::\    \      \::/    /
  /:::/    / \/____/  \:::\    \      \/____/
 /:::/    /            \:::\    \
/:::/    /              \:::\    \
\::/    /                \:::\    \
 \/____/                  \:::\    \
                           \:::\    \
                            \:::\____\
                             \::/    /
                              \/____/
                             TYPE/CODE
                         From 2010 till ∞     */

(function(window, $) {

	var NI = window.NI;

	function Tooltip(options) {

		var o = $.extend({
			triggers: $('.tooltip_trigger'),
			trigger_class:null,
			tooltip:null,
			markup_generator:null,
			animate_slide:true,
			animate_opacity:true,
			offset_left:0,
			offset_top:0,
			use_mousepos:true,
			positions:['top','right','bottom','left'],
			container:$('body'),
			hide_delay:200
		}, options);

		var internal = {
			window:$(window),
			tooltip:(o.tooltip ? o.tooltip : $('

').appendTo($('body'))),
			tooltip_content:null,
			tails:null,
			triggers:o.triggers,
			has_been_shown:false,
			current_trigger:null,
			current_trigger_id:null,
			cache:{},
			animating:false,
			visible:false,
			mousepos:null,
			visibility_timer:null
		};

		function init(me){
			internal.triggers.bind('mouseover', {me:me}, handlers.trigger_mouseover);
			internal.triggers.bind('mouseout', {me:me}, handlers.trigger_mouseout);
			internal.tooltip.bind('mouseover', {me:me}, handlers.tooltip_mouseover);
			internal.tooltip.bind('mouseout', {me:me}, handlers.tooltip_mouseout);
			internal.tooltip.css({
				'overflow':'visible'
			});
			generate_tails();
			if(o.use_mousepos){
				$(document).bind('mousemove',function(e,d){
					if(d && d.mousepos){
						internal.mousepos = d.mousepos;
					} else {
						internal.mousepos = {
							x:e.pageX,
							y:e.pageY
						};
					}
				});
			}
		};

		function generate_tails(){
			var i, my_tail;

			var css_fn = {
				top:function(container){
					return {
						//'border':'1px solid red',
						'width':'100%',
						//'bottom': '-' + (container.children('.tooltip-tail').css('height')),
						'bottom' : (0) + 'px',
						'left': (0) + 'px'
					};
				},
				right:function(container){
					return {
						//'border':'1px solid green',
						'height':'100%',
						'top': (0) + 'px',
						'left': '-' + (container.children('.tooltip-tail').css('width'))
						//'left' : (0) + 'px'
					};
				},
				bottom:function(container){
					return {
						//'border':'1px solid yellow',
						'width':'100%',
						'top': '-' + (container.children('.tooltip-tail').css('height')),
						//'top' : (0) + 'px',
						'left': (0) + 'px'
					};
				},
				left:function(container){
					return {
						//'border':'1px solid blue',
						'height':'100%',
						'top': (0) + 'px',
						//'right': '-' + (container.children('.tooltip-tail').css('width'))
						'right' : (0) + 'px'
					};
				}
			}

			for(i in o.positions){
				my_tail = $('

');
				internal.tooltip.append(my_tail);
				my_tail.css($.extend(css_fn[o.positions[i]](my_tail),{
					'position':'absolute',
					'zIndex':100
				}));
			}
			internal.tails = internal.tooltip.find('.tooltip-tail-container');

			internal.tooltip_content = $('

');
			internal.tooltip.append(internal.tooltip_content);
		}

		function markup_generator(data){
			var output;
			output = $((data ? data : '
No Data.
'));
			return $('
').append(output).html();
		};

		function show(data){
			//internal.tooltip.html(($.isFunction(o.markup_generator) ? o.markup_generator(data) : markup_generator(data)));
			internal.tooltip_content.html(($.isFunction(o.markup_generator) ? o.markup_generator(data) : markup_generator(data)));
			move_to_target(calculate_target_position());
		};

		function get_source_position(){
			if(o.use_mousepos){
				return {
					top: internal.mousepos.y,
					left: internal.mousepos.x
				};
			} else {
				return {
					left: internal.current_trigger.offset().left,
					top: internal.current_trigger.offset().top
				};
			}
		}

		function get_trigger_size(){
			if(o.use_mousepos){
				return {
					width:0,
					height:0
				};
			} else {
				return {
					left: internal.current_trigger.width(),
					top: internal.current_trigger.height()
				};
			}
		}

		function get_tooltip_size(){
			return {
				height:internal.tooltip.height(),
				width:internal.tooltip.width()
			}
		}

		var calculate_position = {
			top:function(sp,trs,tts){
				return {
					className:'top',
					top:(sp.top - (tts.height) - o.offset_top - (get_tail('top') ? get_tail('top').height() : 0)),
					left:((sp.left + (trs.width/2)) - (tts.width/2) + o.offset_left)
				};
			},
			bottom:function(sp,trs,tts){
				return {
					className:'bottom',
					top:(sp.top + trs.height + o.offset_top + (get_tail('bottom') ? get_tail('bottom').height() : 0) ),
					left:((sp.left + (trs.width/2)) - (tts.width/2) + o.offset_left)
				};
			},
			right:function(sp,trs,tts){
				return {
					className:'right',
					top: (sp.top + (trs.height/2) - (tts.height/2)),
					left: (sp.left + (trs.width) + o.offset_top + (get_tail('right') ? get_tail('right').width() : 0))
				};
			},
			left:function(sp,trs,tts){
				return {
					className:'left',
					top: (sp.top + (trs.height/2) - (tts.height/2)),
					left: (sp.left - (tts.width) - o.offset_top - (get_tail('left') ? get_tail('left').width() : 0))
				};
			}
		}

		function get_tail(position){
			var tail;
			tail = internal.tails.filter('.'+position).children('.tooltip-tail');
			if(tail.length){
				return tail;
			}
			return null;
		}

		function get_edge_collisions(tp, tts){
			var collisions;
			collisions = [];

			//check top
			if((tp.top - internal.window.scrollTop()) < 0){
				collisions.push('top');
			}

			//check bottom
			if((tp.top + tts.height) > internal.window.height()){
				collisions.push('bottom');
			}

			//check left
			if((tp.left - internal.window.scrollLeft()) < 0){
				collisions.push('left');
			}

			//check right
			if((tp.left + tts.width) > internal.window.width()){
				collisions.push('right');
			}

			return collisions;
		}

		function calculate_target_position(){
			var source_position, trigger_size, tooltip_size, i, target_position;
			source_position = get_source_position();
			trigger_size = get_trigger_size();
			tooltip_size = get_tooltip_size();
			tail = get_tail();
			for(i in o.positions){
				if($.isFunction(calculate_position[o.positions[i]])){
					target_position = calculate_position[o.positions[i]](source_position, trigger_size, tooltip_size);
				}
				if(!get_edge_collisions(target_position, tooltip_size).length){
					return target_position;
				}
			}
			return target_position;
		}

		function move_to_target(target_pos){
			var me, css_change, animate_change;
			me = this;

			internal.tooltip.removeClass('position-top position-right position-bottom position-left').addClass('position-' + target_pos.className);
			internal.tails.css('visibility','hidden').filter('.' + target_pos.className).css('visibility','visible');

			css_change = {};
			animate_change = {};

			tail_css_change = {};
			tail_animate_change = {};

			if(o.animate_slide){
				animate_change.top = target_pos.top;
				animate_change.left = target_pos.left;
				switch(target_pos.className){
					case 'top':
					case 'bottom':
						tail_animate_change.left = (internal.tooltip.width()/2) - o.offset_left - (get_tail(target_pos.className).width()/2);
						break;
					case 'left':
					case 'right':
						tail_animate_change.top = (internal.tooltip.height()/2) + o.offset_top - (get_tail(target_pos.className).height()/2);
						break;
				}
			} else {
				css_change.top = target_pos.top;
				css_change.left = target_pos.left;
				switch(target_pos.className){
					case 'top':
					case 'bottom':
						tail_css_change.left = (internal.tooltip.width()/2) - o.offset_left - (get_tail(target_pos.className).width()/2);
						break;
					case 'left':
					case 'right':
						tail_css_change.top = (internal.tooltip.height()/2) + o.offset_top - (get_tail(target_pos.className).height()/2);
						break;
				}
			}

			if(o.animate_opacity){
				if(!internal.has_been_shown){
					css_change.opacity = '0.0';
				}
				animate_change.opacity = '1.0';
			} else {
				css_change.opacity = '1.0';
			}

			internal.animating = true;
			get_tail(target_pos.className).css(tail_css_change).stop(true).show().animate(tail_animate_change,500,'easeOutCubic',function(){});
			internal.tooltip.stop().show().css(css_change).animate(animate_change,500,'easeOutCubic',function(){
				internal.animating = false;
				internal.visible = true;
			});

			internal.has_been_shown = true;
		};

		function hide(){
			internal.animating = true;
			internal.visible = false;
			internal.tooltip.stop().animate({
				'opacity':0.0
			},200,'easeOutCirc',function(){
				$(this).hide();
				internal.animating = false;
				internal.current_trigger = null;
			});
		};

		var handlers = {
				trigger_mouseover:function(e){
					if(internal.visibility_timer){
						clearTimeout(internal.visibility_timer);
					};
					internal.current_trigger = $(this);
					show();
				},
				trigger_mouseout:function(e){
					if(internal.visibility_timer){
						clearTimeout(internal.visibility_timer);
					};
					if(!$.contains(this,e.target)){
						internal.visibility_timer = setTimeout(hide,o.hide_delay);
						//hide();
					}
				},
				tooltip_mouseover:function(e){
					if(internal.visibility_timer){
						clearTimeout(internal.visibility_timer);
					};
					if(!o.use_mousepos && internal.current_trigger && !internal.visible){
						show();
					}
				},
				tooltip_mouseout:function(e,d){
					if(internal.animating){
						return;
					}
					if(internal.visibility_timer){
						clearTimeout(internal.visibility_timer);
					};
					if(!((this == e.target) && (this == e.relatedTarget))){
						if((!$.contains(this,e.target) && $.contains(this,e.relatedTarget)) ||
								($.contains(this,e.target) && !$.contains(this,e.relatedTarget))){
							internal.visibility_timer = setTimeout(hide,o.hide_delay);
							//hide();
						}
					}

				}
		};

		this.add_trigger = function(trigger){
			trigger.bind('mouseover', {me:this}, this.handlers.trigger_mouseover);
			trigger.bind('mouseout', {me:this}, this.handlers.trigger_mouseout);
			if(!internal.triggers.length){
				internal.triggers = trigger;
			} else {
				internal.triggers.add(trigger);
			}
		};

		this.clear_triggers = function(trigger){
			internal.triggers.each(function(i,j){
				$(j).unbind('mouseover').unbind('mouseout');
			});
			internal.triggers = $({});
		};

		this.show_tooltip = function(_options){
			var _o = $.extend({
				trigger:null,
				data:null
			},_options);

			if(!_o.trigger){
				return false;
			}

			if(internal.visibility_timer){
				clearTimeout(internal.visibility_timer);
			};

			internal.current_trigger = _o.trigger;
			internal.tooltip.stop();
			show(_o.data);
		}

		this.hide_tooltip = function(delay){
			if(internal.visibility_timer){
				clearTimeout(internal.visibility_timer);
			};
			internal.visibility_timer = setTimeout(hide,(delay ? delay : o.hide_delay));
		}

		this.get_tooltip = function(){
			return internal.tooltip;
		}

		init(this);
	}

//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

	NI.Tooltip = Tooltip;

}(this, this.jQuery));<|endoftext|>


<commit_before>import React from 'react'
import PropTypes from 'prop-types'
import Button from 'fyndiq-component-button'

import Modal from './modal'

const isSameType = (element, component) =>
  React.isValidElement(element) &&
  (element.type === component || element.type.displayName === component.name)

// Proptype checker: checks that the element is of a specific Component type
// FIXME: this declaration should be in its own package, like fyndiq-utils
// or fyndiq-prop-types or something
export const ElementOfType = type => (props, propName, componentName) => {
  const prop = props[propName]
  if (isSameType(prop, type)) return null

  // Otherwise, return Error
  return new Error(
    `Invalid prop \`${propName}\` supplied to` +
      ` \`${componentName}\`. Must be of type ${type.displayName || type.name}`,
  )
}

class ModalButton extends React.Component {
  static propTypes = {
    button: PropTypes.oneOfType([PropTypes.string, ElementOfType(Button)]),
    children: PropTypes.oneOfType([PropTypes.node, ElementOfType(Modal)]),
  }

  static defaultProps = {
    button: 'Open Modal',
    children: null,
  }

  constructor(props) {
    super(props)
    this.state = { open: false }

    this.openModal = this.openModal.bind(this)
    this.closeModal = this.closeModal.bind(this)
  }

  getButton() {
    const { button } = this.props
    console.log(button.type.displayName, Button.name)
    if (isSameType(button, Button)) {
      return React.cloneElement(button, {
        onClick: this.openModal,
      })
    }

    return <Button onClick={this.openModal}>{button}</Button>
  }

  getModal() {
    const { children } = this.props

    const modalProps = {
      open: this.state.open,
      onClose: this.closeModal,
    }
    if (isSameType(children, Modal)) {
      return React.cloneElement(this.props.children, modalProps)
    }

    return <Modal {...modalProps}>{children}</Modal>
  }

  closeModal() {
    this.setState({ open: false })
  }

  openModal() {
    this.setState({ open: true })
  }

  render() {
    return (

        {this.getButton()}
        {this.getModal()}

    )
  }
}

export default ModalButton
<commit_msg>:fire: Remove console.log<commit_after>import React from 'react'
import PropTypes from 'prop-types'
import Button from 'fyndiq-component-button'

import Modal from './modal'

const isSameType = (element, component) =>
  React.isValidElement(element) &&
  (element.type === component || element.type.displayName === component.name)

// Proptype checker: checks that the element is of a specific Component type
// FIXME: this declaration should be in its own package, like fyndiq-utils
// or fyndiq-prop-types or something
export const ElementOfType = type => (props, propName, componentName) => {
  const prop = props[propName]
  if (isSameType(prop, type)) return null

  // Otherwise, return Error
  return new Error(
    `Invalid prop \`${propName}\` supplied to` +
      ` \`${componentName}\`. Must be of type ${type.displayName || type.name}`,
  )
}

class ModalButton extends React.Component {
  static propTypes = {
    button: PropTypes.oneOfType([PropTypes.string, ElementOfType(Button)]),
    children: PropTypes.oneOfType([PropTypes.node, ElementOfType(Modal)]),
  }

  static defaultProps = {
    button: 'Open Modal',
    children: null,
  }

  constructor(props) {
    super(props)
    this.state = { open: false }

    this.openModal = this.openModal.bind(this)
    this.closeModal = this.closeModal.bind(this)
  }

  getButton() {
    const { button } = this.props
    if (isSameType(button, Button)) {
      return React.cloneElement(button, {
        onClick: this.openModal,
      })
    }

    return <Button onClick={this.openModal}>{button}</Button>
  }

  getModal() {
    const { children } = this.props

    const modalProps = {
      open: this.state.open,
      onClose: this.closeModal,
    }
    if (isSameType(children, Modal)) {
      return React.cloneElement(this.props.children, modalProps)
    }

    return <Modal {...modalProps}>{children}</Modal>
  }

  closeModal() {
    this.setState({ open: false })
  }

  openModal() {
    this.setState({ open: true })
  }

  render() {
    return (

        {this.getButton()}
        {this.getModal()}

    )
  }
}

export default ModalButton
<|endoftext|>


<commit_before>"use strict";

var RtUpdate = function (token){
	var rt = this;
	rt.on = true;
	rt.token = token;
	rt.handlers = new RtHandler();
	rt.ready = new Promise(function(resolve,reject){
		var oReq = new XMLHttpRequest();
		oReq.onload = function (){
			if(oReq.status < 400){
				var res = JSON.parse(oReq.response.slice(oReq.response.indexOf("{")));
				rt.wSocket = new WebSocket(gConfig.rt.replace("https","wss")+"?token="+token+"&transport=websocket&sid=" + res.sid);
				rt.wSocket.onopen = function(){
					rt.wSocket.send("2probe");
					rt.wSocket.onmessage = function(e){
						if(e.data == "3probe")rt.wSocket.send("5");
						setInterval(function (){rt.ping();}, res.pingInterval);
						rt.wSocket.onmessage = null;
						rt.wSocket.addEventListener("message", function (e){rt.message(e)});
						resolve();
					};
				};
			} else console.log(oReq);
		}
		oReq.open("get",gConfig.rt+"?token="+token+"&transport=polling&t="+Date.now(), true);
		oReq.send();
	});
}
RtUpdate.prototype = {
	  constructor: RtUpdate
	, on: false
	, wSocket: undefined
	, token: undefined
	, ready: undefined
	, handlers: Object
	, close: function(){
		var rt = this;
		try{
			rt.wSocket.close();
		}catch(e){};
	}
	, ping: function (){
		var rt = this;
		rt.wSocket.send("2");
	}
	, message: function(msg){
		var rt = this;
		var idxPayload = msg.data.indexOf("[");
		if (idxPayload == -1) return;
		var type = msg.data.slice(0,idxPayload);
		var data = JSON.parse(msg.data.slice(idxPayload));
		console.log(msg);
		if (Array.isArray(data) &&  (typeof rt.handlers[data[0]] !== "undefined")) rt.handlers[data[0]](data[1]);
	}
	, handle: function (msg,f){
		var rt = this;
		rt.handlers[msg] = f;
	}
	, subscribe: function (timeline){
		var rt = this;
		if(rt.ready == undefined)return;
		rt.ready.then(function(){
			rt.wSocket.send("42"+JSON.stringify(["subscribe", {"timeline":[timeline]}]));
		});
	}
}
<commit_msg>implement:real-time socket reconnecting<commit_after>"use strict";

var RtUpdate = function (token){
	var rt = this;
	rt.on = true;
	rt.token = token;
	rt.connect();
	rt.handlers = new RtHandler();
	rt.subscriptions = new Array();
}
RtUpdate.prototype = {
	  constructor: RtUpdate
	, on: false
	, gotping: true
	, wSocket: undefined
	, token: undefined
	, ready: undefined
	, subscriptions: Array
	, handlers: Object
	, callback: undefined
	, connect: function(){
		var rt= this;
		rt.ready = new Promise(function(resolve,reject){
			var oReq = new XMLHttpRequest();
			oReq.onload = function (){
				if(oReq.status < 400){
					var res = JSON.parse(oReq.response.slice(oReq.response.indexOf("{")));
					rt.wSocket = new WebSocket(gConfig.rt.replace("https","wss")+"?token="+rt.token+"&transport=websocket&sid=" + res.sid);
					rt.wSocket.onopen = function(){
						rt.wSocket.send("2probe");
						rt.wSocket.onmessage = function(e){
							if(e.data == "3probe")rt.wSocket.send("5");
							setInterval(function (){rt.ping();}, res.pingInterval);
							rt.wSocket.onmessage = null;
							rt.callback =  function (e){rt.message(e)};
							rt.wSocket.addEventListener("message",rt.callback);
							resolve();
						};
					};
				} else console.log(oReq);
			}
			oReq.open("get",gConfig.rt+"?token="+rt.token+"&transport=polling&t="+Date.now(), true);
			oReq.send();
		});
	}
	, close: function(){
		var rt = this;
		try{
			rt.wSocket.close();
		}catch(e){};
	}
	, ping: function (){
		var rt = this;
		if (rt.gotPing){
			rt.wSocket.send("2");
			return;
		}
		if(typeof rt.callback !== "undefined")
			rt.wSocket.removeEventListener("message", rt.callback);
		rt.close();
		rt.connect().then(function(){rt.subscriptions.forEach(function(t){rt.subscribe(t);})});
	}
	, message: function(msg){
		var rt = this;
		if (msg.data == "3"){
			rt.gotPing = true;
		}
		var idxPayload = msg.data.indexOf("[");
		if (idxPayload == -1) return;
		var type = msg.data.slice(0,idxPayload);
		var data = JSON.parse(msg.data.slice(idxPayload));
		console.log(msg);
		if (Array.isArray(data) &&  (typeof rt.handlers[data[0]] !== "undefined")) rt.handlers[data[0]](data[1]);
	}
	, handle: function (msg,f){
		var rt = this;
		rt.handlers[msg] = f;
	}
	, subscribe: function (timeline){
		var rt = this;
		rt.subscriptions.push(timeline);
		if(rt.ready == undefined)return;
		rt.ready.then(function(){
			rt.wSocket.send("42"+JSON.stringify(["subscribe", {"timeline":[timeline]}]));
		});
	}
}
<|endoftext|>


<commit_before>/**
 * Function that returns default values.
 * Used because Object.assign does a shallow instead of a deep copy.
 * Using [].push will add to the base array, so a require will alter
 * the base array output.
 */
'use strict';

const path = require('path');
const srcPath = path.join(__dirname, '/../src');
const dfltPort = 8000;

/**
 * Get the default modules object for webpack
 * @return {Object}
 */
function getDefaultModules() {
  return {
    preLoaders: [
      {
        test: /\.(js|jsx)$/,
        include: srcPath,
        loader: 'eslint-loader'
      }
    ],
    loaders: [
      {
        test: /\.css$/,
        loader: 'style-loader!css-loader!autoprefixer-loader?{browsers:["last 2 version"]}'
      },
      {
        test: /\.sass/,
        loader: 'style-loader!css-loader!sass-loader?outputStyle=expanded&indentedSyntax'
      },
      {
        test: /\.scss/,
        loader: 'style-loader!css-loader!autoprefixer-loader?{browsers:["last 2 version"]}!sass-loader?outputStyle=expanded'
      },
      {
        test: /\.less/,
        loader: 'style-loader!css-loader!less-loader'
      },
      {
        test: /\.styl/,
        loader: 'style-loader!css-loader!stylus-loader'
      },
      {
        test: /\.json$/,
        loader: 'json-loader'
      },
      {
        test: /\.(png|jpg|gif|woff|woff2|eot|ttf|svg)$/,
        loader: 'url-loader?limit=8192'
      },
      {
        test: /\.(mp4|ogg|svg)$/,
        loader: 'file-loader'
      }
    ]
  };
}

module.exports = {
  srcPath: srcPath,
  publicPath: '/assets/',
  port: dfltPort,
  getDefaultModules: getDefaultModules
};
<commit_msg>change path from absolute to relative<commit_after>/**
 * Function that returns default values.
 * Used because Object.assign does a shallow instead of a deep copy.
 * Using [].push will add to the base array, so a require will alter
 * the base array output.
 */
'use strict';

const path = require('path');
const srcPath = path.join(__dirname, '/../src');
const dfltPort = 8000;

/**
 * Get the default modules object for webpack
 * @return {Object}
 */
function getDefaultModules() {
  return {
    preLoaders: [
      {
        test: /\.(js|jsx)$/,
        include: srcPath,
        loader: 'eslint-loader'
      }
    ],
    loaders: [
      {
        test: /\.css$/,
        loader: 'style-loader!css-loader!autoprefixer-loader?{browsers:["last 2 version"]}'
      },
      {
        test: /\.sass/,
        loader: 'style-loader!css-loader!sass-loader?outputStyle=expanded&indentedSyntax'
      },
      {
        test: /\.scss/,
        loader: 'style-loader!css-loader!autoprefixer-loader?{browsers:["last 2 version"]}!sass-loader?outputStyle=expanded'
      },
      {
        test: /\.less/,
        loader: 'style-loader!css-loader!less-loader'
      },
      {
        test: /\.styl/,
        loader: 'style-loader!css-loader!stylus-loader'
      },
      {
        test: /\.json$/,
        loader: 'json-loader'
      },
      {
        test: /\.(png|jpg|gif|woff|woff2|eot|ttf|svg)$/,
        loader: 'url-loader?limit=8192'
      },
      {
        test: /\.(mp4|ogg|svg)$/,
        loader: 'file-loader'
      }
    ]
  };
}

module.exports = {
  srcPath: srcPath,
  publicPath: 'assets/',
  port: dfltPort,
  getDefaultModules: getDefaultModules
};
<|endoftext|>


<commit_before>define([
	'jquery', 'cascade', 'bootstrap'
], function ($, $cascade) {
	// Global handler for better bootstrap implicit experience
	$('body').popover({selector: '[data-toggle="popover"]:not([data-trigger="manual"])', html: 'true', trigger: 'hover focus', container: 'body'});
	$('body').tooltip({selector: '[data-toggle="tooltip"]:not([data-trigger="manual"])', html: 'true', trigger: 'hover focus', container: 'body'});
	$(document).on('click', '.toggle-visibility', function () {
		$(this).toggleClass('active');
	}).on('click', '.disabled,[disabled]', function (event) {
		event.preventDefault();
	}).on('click', '[data-toggle="popover"][data-trigger="manual"]', function () {
		$(this).popover('toggle');
	}).on('mousedown', function (e) {
		// Auto hide popover on click
		if ($('.popover.in').length && $(e.target).closest('[data-toggle="popover"],.popover').length === 0) {
			traceLog('click .popover.in');
			$('.popover.in').each(function () {
				traceLog('click .popover.in found');
				$('[aria-describedby="' + $(this).attr('id') + '"]').popover('hide');
			});
		}
	}).on('change', '.btn-file :file', function () {
		var $input = $(this);
		var label = $input.val().replace(/\\/g, '/').replace(/.*\//, '');
		$input.parents('.input-group').find(':text').val(label);
		// FIX : #19192 ->
	}).off('click.bs.button.data-api', '[data-toggle^="button"]').on('click.bs.button.data-api', '[data-toggle^="button"]', function (e) {
		var $btn = $(e.target).closest('.btn').button('toggle');
		if (!($(e.target).is('input[type="radio"]') || $(e.target).is('input[type="checkbox"]'))) {
			// Prevent double click on radios, and the double selections (so cancellation) on checkboxes
			e.preventDefault();
			// The target component still receive the focus
			if ($btn.is('input,button')) {
				$btn.trigger('focus');
			} else {
				$btn.find('input:visible,button:visible').first().trigger('focus');
			}
		}
	}).on('click', '.retract', function () {
		$(this).closest('.retractable').toggleClass('retracted');
	}).on('keypress', 'form:not([method]),[method="get"],form[method="GET"]', function (e) {
		// Some browser (like Chrome) the first submit is used (hidden or not) and receive a click
		if ((e.which === 13 || e.keyCode === 13) && !$(e.target).is('textarea')) {
			// Determines the right input
			var $button = $(this).find('input:visible[type=submit]:not(.disabled):not(.hide):not([disabled]),button:visible[type=submit]:not(.disabled):not(.hide):not([disabled])').first();
			if ($button.length) {
				$button.trigger('click');
				e.preventDefault();
				return false;
			}
		}
	}).on('submit', 'form:not([method]),[method="get"],form[method="GET"]', function (e) {
		e.preventDefault();
	}).on('show.bs.tab', 'a[data-toggle="tab"]', function () {
		// Load active partials for tab
		var $target = $($(this).attr('href'));
		if ($target.is('[data-ajax]')) {
			$.proxy($cascade.loadPartial, $target)();
		}
	}).on('show.bs.collapse', '.collapse[data-ajax]',
	// Load active partials for collapse
	$cascade.loadPartial).on('show.bs.popover', '[data-ajax]',
	// Load active partials for popover
	$cascade.loadPartial).on('show.bs.modal', '.modal[data-ajax]',
	// Load active partials for modal
	$cascade.loadPartial);

	$.fn.hideGroup = function () {
		$(this).closest('.form-group').addClass('hide');
		return this;
	};
	$.fn.showGroup = function () {
		$(this).closest('.form-group').removeClass('hide');
		return this;
	};
	$.fn.rawText = function (rawText) {
		// Get text mode
		if (typeof rawText === 'undefined') {
			var text = this.first().contents().filter(function () {
				return this.nodeType === 3;
			});
			return text.length ? text[0].textContent || '' : '';
		}
		// Set text
		this.each(function () {
			var text = $(this).contents().filter(function () {
				return this.nodeType === 3;
			});
			if (rawText && text.length === 0) {
				// Create a new text node at the end
				$(this).append(document.createTextNode(rawText));
			} else {
				// Replace the content of existing node
				text.each(function () {
					this.textContent = rawText;
				});
			}
		});
		return this;
	};

	function selectMenu() {
		var selector = $(this).closest('li');
		// Check there is not yet selected child
		if (selector.parents('.navbar,.nav-pills.nav-stacked').find('li.active').length === 0) {
			selector.addClass('active');
			$.fn.collapse && selector.parents('.navbar').length === 0 && selector.parents('.collapse').collapse('show');
			selector.parents('.dropdown').addClass('active');
		}
	}

	/**
	 * Synchronize the menu with the URL of the context url
	 * @param  {string} url Current url to synchronize with menus.
	 */
	function synchronizeMenu(url) {
		var patterns = [];
		var fragments = url.split('/');
		do {
			patterns.push('a[href^="' + fragments.join('/').replace(/"/g, '\\"') + '"]');
			fragments.pop();
		} while (fragments.length);
		var base = _('_main').find('.navbar,.nav-pills.nav-stacked');

		// Remove all highlights
		base.find('li.active').removeClass('active');

		// Highlight tool bar menu
		for (var index = 0; index < patterns.length; index++) {
			base.find(patterns[index]).each(selectMenu);
		}
	}

	// Transformation
	$cascade.register('html', function (selector) {
		// Add popover feature
		selector.find('.tab-pane.active[data-ajax]').each($cascade.loadPartial);
	});
	$cascade.register('hash', function (url) {
		$('.modal-backdrop').remove();
		$('.tooltip').remove();
		$('.popover').remove();
		synchronizeMenu(url);
	});

	/**
	 * Full screen management : enter full screen
	 * @param {Object} $selector Optional selector.
	 */
	$.fn.fullscreen = function() {
		var el = $(this)[0] || document.documentElement;

		// use necessary prefixed versions
		if (el.webkitRequestFullscreen) {
			el.webkitRequestFullscreen();
			return;
		}
		if (el.mozRequestFullScreen) {
			el.mozRequestFullScreen();
			return;
		}
		if (el.msRequestFullscreen) {
			el.msRequestFullscreen();
			return;
		}
		// finally the standard version
		el.requestFullscreen && el.requestFullscreen();
	};

	/**
	 * Exit full screen management
	 */
	$.fn.exitFullscreen = function() {
		// use necessary prefixed versions
		if (document.webkitExitFullscreen) {
			document.webkitCancelFullScreen();
			return;
		}
		if (document.mozCancelFullScreen) {
			document.mozCancelFullScreen();
			return;
		}
		if (document.msExitFullscreen) {
			document.msExitFullscreen();
			return;
		}
		// finally the standard version
		document.exitFullscreen && document.exitFullscreen();
	};

});
<commit_msg>Cleanup log messages<commit_after>define([
	'jquery', 'cascade', 'bootstrap'
], function ($, $cascade) {
	// Global handler for better bootstrap implicit experience
	$('body').popover({selector: '[data-toggle="popover"]:not([data-trigger="manual"])', html: 'true', trigger: 'hover focus', container: 'body'});
	$('body').tooltip({selector: '[data-toggle="tooltip"]:not([data-trigger="manual"])', html: 'true', trigger: 'hover focus', container: 'body'});
	$(document).on('click', '.toggle-visibility', function () {
		$(this).toggleClass('active');
	}).on('click', '.disabled,[disabled]', function (event) {
		event.preventDefault();
	}).on('click', '[data-toggle="popover"][data-trigger="manual"]', function () {
		$(this).popover('toggle');
	}).on('mousedown', function (e) {
		// Auto hide popover on click
		if ($('.popover.in').length && $(e.target).closest('[data-toggle="popover"],.popover').length === 0) {
			$('.popover.in').each(function () {
				$('[aria-describedby="' + $(this).attr('id') + '"]').popover('hide');
			});
		}
	}).on('change', '.btn-file :file', function () {
		var $input = $(this);
		var label = $input.val().replace(/\\/g, '/').replace(/.*\//, '');
		$input.parents('.input-group').find(':text').val(label);
		// FIX : #19192 ->
	}).off('click.bs.button.data-api', '[data-toggle^="button"]').on('click.bs.button.data-api', '[data-toggle^="button"]', function (e) {
		var $btn = $(e.target).closest('.btn').button('toggle');
		if (!($(e.target).is('input[type="radio"]') || $(e.target).is('input[type="checkbox"]'))) {
			// Prevent double click on radios, and the double selections (so cancellation) on checkboxes
			e.preventDefault();
			// The target component still receive the focus
			if ($btn.is('input,button')) {
				$btn.trigger('focus');
			} else {
				$btn.find('input:visible,button:visible').first().trigger('focus');
			}
		}
	}).on('click', '.retract', function () {
		$(this).closest('.retractable').toggleClass('retracted');
	}).on('keypress', 'form:not([method]),[method="get"],form[method="GET"]', function (e) {
		// Some browser (like Chrome) the first submit is used (hidden or not) and receive a click
		if ((e.which === 13 || e.keyCode === 13) && !$(e.target).is('textarea')) {
			// Determines the right input
			var $button = $(this).find('input:visible[type=submit]:not(.disabled):not(.hide):not([disabled]),button:visible[type=submit]:not(.disabled):not(.hide):not([disabled])').first();
			if ($button.length) {
				$button.trigger('click');
				e.preventDefault();
				return false;
			}
		}
	}).on('submit', 'form:not([method]),[method="get"],form[method="GET"]', function (e) {
		e.preventDefault();
	}).on('show.bs.tab', 'a[data-toggle="tab"]', function () {
		// Load active partials for tab
		var $target = $($(this).attr('href'));
		if ($target.is('[data-ajax]')) {
			$.proxy($cascade.loadPartial, $target)();
		}
	}).on('show.bs.collapse', '.collapse[data-ajax]',
	// Load active partials for collapse
	$cascade.loadPartial).on('show.bs.popover', '[data-ajax]',
	// Load active partials for popover
	$cascade.loadPartial).on('show.bs.modal', '.modal[data-ajax]',
	// Load active partials for modal
	$cascade.loadPartial);

	$.fn.hideGroup = function () {
		$(this).closest('.form-group').addClass('hide');
		return this;
	};
	$.fn.showGroup = function () {
		$(this).closest('.form-group').removeClass('hide');
		return this;
	};
	$.fn.rawText = function (rawText) {
		// Get text mode
		if (typeof rawText === 'undefined') {
			var text = this.first().contents().filter(function () {
				return this.nodeType === 3;
			});
			return text.length ? text[0].textContent || '' : '';
		}
		// Set text
		this.each(function () {
			var text = $(this).contents().filter(function () {
				return this.nodeType === 3;
			});
			if (rawText && text.length === 0) {
				// Create a new text node at the end
				$(this).append(document.createTextNode(rawText));
			} else {
				// Replace the content of existing node
				text.each(function () {
					this.textContent = rawText;
				});
			}
		});
		return this;
	};

	function selectMenu() {
		var selector = $(this).closest('li');
		// Check there is not yet selected child
		if (selector.parents('.navbar,.nav-pills.nav-stacked').find('li.active').length === 0) {
			selector.addClass('active');
			$.fn.collapse && selector.parents('.navbar').length === 0 && selector.parents('.collapse').collapse('show');
			selector.parents('.dropdown').addClass('active');
		}
	}

	/**
	 * Synchronize the menu with the URL of the context url
	 * @param  {string} url Current url to synchronize with menus.
	 */
	function synchronizeMenu(url) {
		var patterns = [];
		var fragments = url.split('/');
		do {
			patterns.push('a[href^="' + fragments.join('/').replace(/"/g, '\\"') + '"]');
			fragments.pop();
		} while (fragments.length);
		var base = _('_main').find('.navbar,.nav-pills.nav-stacked');

		// Remove all highlights
		base.find('li.active').removeClass('active');

		// Highlight tool bar menu
		for (var index = 0; index < patterns.length; index++) {
			base.find(patterns[index]).each(selectMenu);
		}
	}

	// Transformation
	$cascade.register('html', function (selector) {
		// Add popover feature
		selector.find('.tab-pane.active[data-ajax]').each($cascade.loadPartial);
	});
	$cascade.register('hash', function (url) {
		$('.modal-backdrop').remove();
		$('.tooltip').remove();
		$('.popover').remove();
		synchronizeMenu(url);
	});

	/**
	 * Full screen management : enter full screen
	 * @param {Object} $selector Optional selector.
	 */
	$.fn.fullscreen = function() {
		var el = $(this)[0] || document.documentElement;

		// use necessary prefixed versions
		if (el.webkitRequestFullscreen) {
			el.webkitRequestFullscreen();
			return;
		}
		if (el.mozRequestFullScreen) {
			el.mozRequestFullScreen();
			return;
		}
		if (el.msRequestFullscreen) {
			el.msRequestFullscreen();
			return;
		}
		// finally the standard version
		el.requestFullscreen && el.requestFullscreen();
	};

	/**
	 * Exit full screen management
	 */
	$.fn.exitFullscreen = function() {
		// use necessary prefixed versions
		if (document.webkitExitFullscreen) {
			document.webkitCancelFullScreen();
			return;
		}
		if (document.mozCancelFullScreen) {
			document.mozCancelFullScreen();
			return;
		}
		if (document.msExitFullscreen) {
			document.msExitFullscreen();
			return;
		}
		// finally the standard version
		document.exitFullscreen && document.exitFullscreen();
	};

});
<|endoftext|>


<commit_before>var locationHelper = (function () {
	/**
	 * CustomEvent polyfill
	 * @see https://developer.mozilla.org/ru/docs/Web/API/CustomEvent/CustomEvent
	 */
	var CustomEvent = window.CustomEvent;
	if (typeof CustomEvent !== 'function') {
		CustomEvent = function (event, params) {
			params = params || { bubbles: false, cancelable: false, detail: undefined };
			var evt = document.createEvent('CustomEvent');
			evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
			return evt;
		}
		CustomEvent.prototype = window.Event.prototype;
	}

	function LocationHelper() {
		var prevChange = null;

		this.trigger = function (type, detail) {
			document.dispatchEvent(new CustomEvent(type, {
				detail: detail,
				bubbles: true,
				cancelable: false,
			}));

			if (type == 'location-change') {
				// trigger relative sub-events:
				if (!prevChange || prevChange.parts.path != detail.parts.path) {
					this.trigger('location-change-path', {
						href: detail.href,
						parts: detail.parts,
						prevPath: prevChange ? prevChange.parts.path : null,
						path: detail.parts.path,
					});
				}
				if (!prevChange || prevChange.parts.search != detail.parts.search) {
					this.trigger('location-change-search', {
						href: detail.href,
						parts: detail.parts,
						prevSearch: prevChange ? prevChange.parts.search : null,
						search: detail.parts.search,
					});
				}
				if (!prevChange || prevChange.parts.hash != detail.parts.hash) {
					this.trigger('location-change-hash', {
						href: detail.href,
						parts: detail.parts,
						prevHash: prevChange ? prevChange.parts.hash : null,
						hash: detail.parts.hash,
					});
				}

				prevChange = JSON.parse(JSON.stringify({
					href: detail.href,
					parts: detail.parts,
				}));
			}
		};
	}

	LocationHelper.prototype.parseParams = function (s) {
		var res = {};
		s = s.split('&');
		var param;
		for (var i = 0; i < s.length; i++) {
			if (!s[i])
				continue;
			param = s[i].split('=', 2);
			LocationHelper.setValueByPath(res, param[0], param.length > 1 ? param[1] : true);
		}
		return res;
	};

	LocationHelper.setValueByPath = function (o, path, value) {
		if (!(path instanceof Array)) {
			path = path.replace(/^([^\[]+)/, '[$1]');
			path = path.slice(1, -1).split('][');
		}
		if (typeof value == 'string')
			value = decodeURIComponent(value);

		var name = path.pop();
		var res = o;
		var dir = false;
		while (path.length > 0) {
			dir = decodeURIComponent(path.shift());

			if (dir === '') {
				if (o[dir] && !(o[dir] instanceof Array))
					o[dir] = [];
			}
			else if (typeof o[dir] != 'object' || !o[dir]) {
				o[dir] = {};
			}

			if (path.length) {
				o = o[dir];
			}
		}

		if (name === '') {
			if (dir !== false && !(o[dir] instanceof Array))
				o[dir] = [];
			if (dir !== false)
				o = o[dir];
			o.push(value);
		}
		else {
			if (dir !== false)
				o = o[dir];
			o[name] = value;
		}

		return o;
	};

	var parseURLRegExp = /^(?:(https?|file|[a-z]+):\/\/(?:([^\/:]+)(?::(\d+))?|))?(\/[^?#]*)?(\/?[^#]*)?(#\S*)?/;

	LocationHelper.prototype.parseURL = function (url) {
		var res = parseURLRegExp.exec(url);
		if (!res)
			return false;
		res = {
			schema: res[1],
			protocol: res[1] && res[1] + ':' || res[1],
			host: res[2],
			port: res[3],
			path: res[4],
			search: res[5],
			hash: res[6],
		};

		return res;
	};

	LocationHelper.prototype.buildURL = function (parts, baseParts) {
		if (!parts.protocol || parts.schema)
			parts.protocol = parts.schema + ':';
		else if (parts.protocol || !parts.schema)
			parts.schema = parts.protocol.slice(0, -1);

		if (baseParts) {
			if (!parts.protocol || !parts.host || !parts.port) {
				parts.protocol = baseParts.protocol;
				parts.schema = baseParts.schema;
				parts.host = baseParts.host;
				parts.port = baseParts.port;
			}
			if (!parts.path) {
				parts.path = baseParts.path;
			}
			if (parts.hash) {
				var newHash = parts.hash.split('!', 2);
				if (newHash.length < 2)
					newHash[1] = '';
				newHash[0] = newHash[0].length > 1 ? newHash[0] : (baseParts.hash && baseParts.hash.split('!')[0] || '');
				if (typeof newHash[1] == 'undefined') {
					newHash[1] = baseParts.hash && baseParts.hash.split('!')[1] || '';
				}
				else if (newHash[1][0] == '&') {
					newHash[1] = newHash[1].substr(1).split('&');
					var currentHashParams = this.getHashParams();
					for (var i = 0; i < newHash[1].length; i++) {
						var s = newHash[1][i].split('=', 2);
						LocationHelper.setValueByPath(currentHashParams, s[0], s[1]);
					}
					newHash[1] = this.buildParams(currentHashParams);
				}
				if (!newHash[1])
					newHash = [ newHash[0] ];
				if (newHash[1] && !newHash[0])
					newHash[0] = '#';
				parts.hash = newHash[0] == '#' && !newHash[1] ? '' : newHash.join('!');
			}
		}

		var s = [
			parts.path || '',
			parts.search || '',
			parts.hash || '',
		];

		if (parts.protocol == 'file:') {
			s.unshift(parts.protocol + '//');
		}
		else if (parts.host && parts.protocol) {
			if (parts.port)
				s.unshift(':' + parts.port);
			s.unshift(parts.host);
			s.unshift(parts.protocol + '//');
		}

		return s.join('');
	};

	LocationHelper.prototype.buildParams = function (o, parent) {
		if (typeof o != 'object')
			return parent + '=' + encodeURIComponent(o);

		var s = [];
		if (o instanceof Array) {
			for (var i = 0; i < o.length; i++) {
				var v = o[i];
				var path = parent ? parent + '[]' : '[]';
				s.push(this.buildParams(v, path));
			}
		}
		else {
			for (var k in o) {
				var v = o[k];
				var path = parent ? parent + '[' + encodeURIComponent(k) + ']' : encodeURIComponent(k);
				s.push(this.buildParams(v, path));
			}
		}
		return s.join('&');
	};

	LocationHelper.prototype.getHref = function () {
		return document.location.href;
	};

	LocationHelper.prototype.getHash = function () {
		return document.location.hash;
	};

	LocationHelper.prototype.getSearch = function () {
		return document.location.search;
	};

	LocationHelper.prototype.getPath = function () {
		return document.location.pathname;
	};

	LocationHelper.prototype.getHashParams = function () {
		var s = this.getHash();
		return this.parseParams(s.split('!', 2)[1] || '');
	};

	LocationHelper.prototype.getSearchParams = function () {
		var s = this.getSearch();
		return this.parseParams(s.slice(1));
	};

	LocationHelper.prototype.setLocation = function (hrefOrParts, replace, originalEvent) {
		var parts = typeof hrefOrParts == 'object' ? hrefOrParts : this.parseURL(hrefOrParts);
		var curParts = this.parseURL(this.getHref());
		var href = this.buildURL(parts, curParts);

		history[replace ? 'replaceState' : 'pushState']({
			href: href,
			parts: parts,
		}, '', href);

		this.trigger('location-change', {
			href: href,
			parts: parts,
			originalEvent: originalEvent,
		});

		return this;
	};

	var bindParams = false;

	LocationHelper.prototype.bind = function (_bindParams) {
		_bindParams = _bindParams || true;
		if (!history || !history.pushState)
			return this;

		if (bindParams) {
			bindParams = _bindParams;
			return this;
		}
		bindParams = _bindParams;

		this.setLocation(document.location.href, true);
		var _this = this;

		window.addEventListener('popstate', function (event) {
			if (!event.state || !event.state.href || !event.state.parts)
				return;
			_this.trigger('location-change', {
				href: event.state.href,
				parts: event.state.parts,
				originalEvent: event,
			});
		}, false);

		document.body.addEventListener('click', function (event) {
			var a = event.target;
			while (a && a.nodeName != 'A')
				a = a.parentElement;
			if (a && a.target == '_null') {
				event.preventDefault();
				return false;
			}
			if (!a || !a.href || (a.target || '_self') != '_self')
				return;

			var parts = _this.parseURL(a.href);
			if (!parts || !/^https?:/.test(parts.protocol))
				return;

			var curParts = _this.parseURL(_this.getHref());
			if (parts.host != curParts.host || parts.protocol != curParts.protocol || parts.port != curParts.port)
				return;

			if (bindParams !== true && bindParams.path && curParts.path != parts.path)
				return;
			if (bindParams !== true && bindParams.search && curParts.search != parts.search)
				return;
			if (bindParams !== true && bindParams.hash && curParts.hash != parts.hash)
				return;

			_this.setLocation(parts, false, event);

			event.preventDefault();
		}, false);

		return this;
	}

	return new LocationHelper();
})();
<commit_msg>Add locationHelper.reload function; move changed parameters to the end<commit_after>var locationHelper = (function () {
	/**
	 * CustomEvent polyfill
	 * @see https://developer.mozilla.org/ru/docs/Web/API/CustomEvent/CustomEvent
	 */
	var CustomEvent = window.CustomEvent;
	if (typeof CustomEvent !== 'function') {
		CustomEvent = function (event, params) {
			params = params || { bubbles: false, cancelable: false, detail: undefined };
			var evt = document.createEvent('CustomEvent');
			evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
			return evt;
		}
		CustomEvent.prototype = window.Event.prototype;
	}

	function LocationHelper() {
		var prevChange = null;

		this.trigger = function (type, detail) {
			document.dispatchEvent(new CustomEvent(type, {
				detail: detail,
				bubbles: true,
				cancelable: false,
			}));

			if (type == 'location-change') {
				// trigger relative sub-events:
				if (!prevChange || prevChange.parts.path != detail.parts.path) {
					this.trigger('location-change-path', {
						href: detail.href,
						parts: detail.parts,
						prevPath: prevChange ? prevChange.parts.path : null,
						path: detail.parts.path,
					});
				}
				if (!prevChange || prevChange.parts.search != detail.parts.search) {
					this.trigger('location-change-search', {
						href: detail.href,
						parts: detail.parts,
						prevSearch: prevChange ? prevChange.parts.search : null,
						search: detail.parts.search,
					});
				}
				if (!prevChange || prevChange.parts.hash != detail.parts.hash) {
					this.trigger('location-change-hash', {
						href: detail.href,
						parts: detail.parts,
						prevHash: prevChange ? prevChange.parts.hash : null,
						hash: detail.parts.hash,
					});
				}

				prevChange = JSON.parse(JSON.stringify({
					href: detail.href,
					parts: detail.parts,
				}));
			}
		};
	}

	LocationHelper.prototype.parseParams = function (s) {
		var res = {};
		s = s.split('&');
		var param;
		for (var i = 0; i < s.length; i++) {
			if (!s[i])
				continue;
			param = s[i].split('=', 2);
			LocationHelper.setValueByPath(res, param[0], param.length > 1 ? param[1] : true);
		}
		return res;
	};

	LocationHelper.setValueByPath = function (o, path, value) {
		if (!(path instanceof Array)) {
			path = path.replace(/^([^\[]+)/, '[$1]');
			path = path.slice(1, -1).split('][');
		}
		if (typeof value == 'string')
			value = decodeURIComponent(value);

		var name = path.pop();
		var res = o;
		var dir = false;
		while (path.length > 0) {
			dir = decodeURIComponent(path.shift());

			if (dir === '') {
				if (o[dir] && !(o[dir] instanceof Array))
					o[dir] = [];
			}
			else if (typeof o[dir] != 'object' || !o[dir]) {
				o[dir] = {};
			}

			if (path.length) {
				o = o[dir];
			}
		}

		if (name === '') {
			if (dir !== false && !(o[dir] instanceof Array))
				o[dir] = [];
			if (dir !== false) {
				var v = o[dir];
				delete o[dir];
				o[dir] = v;
				o = o[dir];
			}
			o.push(value);
		}
		else {
			if (dir !== false)
				o = o[dir];
			delete o[name];
			o[name] = value;
		}

		return o;
	};

	var parseURLRegExp = /^(?:(https?|file|[a-z]+):\/\/(?:([^\/:]+)(?::(\d+))?|))?(\/[^?#]*)?(\/?[^#]*)?(#\S*)?/;

	LocationHelper.prototype.parseURL = function (url) {
		var res = parseURLRegExp.exec(url);
		if (!res)
			return false;
		res = {
			schema: res[1],
			protocol: res[1] && res[1] + ':' || res[1],
			host: res[2],
			port: res[3],
			path: res[4],
			search: res[5],
			hash: res[6],
		};

		return res;
	};

	LocationHelper.prototype.buildURL = function (parts, baseParts) {
		if (!parts.protocol || parts.schema)
			parts.protocol = parts.schema + ':';
		else if (parts.protocol || !parts.schema)
			parts.schema = parts.protocol.slice(0, -1);

		if (baseParts) {
			if (!parts.protocol || !parts.host || !parts.port) {
				parts.protocol = baseParts.protocol;
				parts.schema = baseParts.schema;
				parts.host = baseParts.host;
				parts.port = baseParts.port;
			}
			if (!parts.path) {
				parts.path = baseParts.path;
			}
			if (parts.hash) {
				var newHash = parts.hash.split('!', 2);
				if (newHash.length < 2)
					newHash[1] = '';
				newHash[0] = newHash[0].length > 1 ? newHash[0] : (baseParts.hash && baseParts.hash.split('!')[0] || '');
				if (typeof newHash[1] == 'undefined') {
					newHash[1] = baseParts.hash && baseParts.hash.split('!')[1] || '';
				}
				else if (newHash[1][0] == '&') {
					newHash[1] = newHash[1].substr(1).split('&');
					var currentHashParams = this.getHashParams();
					for (var i = 0; i < newHash[1].length; i++) {
						var s = newHash[1][i].split('=', 2);
						LocationHelper.setValueByPath(currentHashParams, s[0], s[1]);
					}
					newHash[1] = this.buildParams(currentHashParams);
				}
				if (!newHash[1])
					newHash = [ newHash[0] ];
				if (newHash[1] && !newHash[0])
					newHash[0] = '#';
				parts.hash = newHash[0] == '#' && !newHash[1] ? '' : newHash.join('!');
			}
		}

		var s = [
			parts.path || '',
			parts.search || '',
			parts.hash || '',
		];

		if (parts.protocol == 'file:') {
			s.unshift(parts.protocol + '//');
		}
		else if (parts.host && parts.protocol) {
			if (parts.port)
				s.unshift(':' + parts.port);
			s.unshift(parts.host);
			s.unshift(parts.protocol + '//');
		}

		return s.join('');
	};

	LocationHelper.prototype.buildParams = function (o, parent) {
		if (typeof o != 'object')
			return parent + '=' + encodeURIComponent(o);

		var s = [];
		if (o instanceof Array) {
			for (var i = 0; i < o.length; i++) {
				var v = o[i];
				var path = parent ? parent + '[]' : '[]';
				s.push(this.buildParams(v, path));
			}
		}
		else {
			for (var k in o) {
				var v = o[k];
				var path = parent ? parent + '[' + encodeURIComponent(k) + ']' : encodeURIComponent(k);
				s.push(this.buildParams(v, path));
			}
		}
		return s.join('&');
	};

	LocationHelper.prototype.getHref = function () {
		return document.location.href;
	};

	LocationHelper.prototype.getHash = function () {
		return document.location.hash;
	};

	LocationHelper.prototype.getSearch = function () {
		return document.location.search;
	};

	LocationHelper.prototype.getPath = function () {
		return document.location.pathname;
	};

	LocationHelper.prototype.getHashParams = function () {
		var s = this.getHash();
		return this.parseParams(s.split('!', 2)[1] || '');
	};

	LocationHelper.prototype.getSearchParams = function () {
		var s = this.getSearch();
		return this.parseParams(s.slice(1));
	};

	LocationHelper.prototype.setLocation = function (hrefOrParts, replace, originalEvent) {
		var parts = typeof hrefOrParts == 'object' ? hrefOrParts : this.parseURL(hrefOrParts);
		var curParts = this.parseURL(this.getHref());
		var href = this.buildURL(parts, curParts);

		history[replace ? 'replaceState' : 'pushState']({
			href: href,
			parts: parts,
		}, '', href);

		this.trigger('location-change', {
			href: href,
			parts: parts,
			originalEvent: originalEvent,
		});

		return this;
	};

	LocationHelper.prototype.reload = function (originalEvent) {
		var href = this.getHref();
		var parts = this.parseURL(href);

		history['replaceState']({
			href: href,
			parts: parts,
		}, '', href);

		this.trigger('location-change', {
			href: href,
			parts: parts,
			originalEvent: originalEvent,
		});

		return this;
	};

	var bindParams = false;

	LocationHelper.prototype.bind = function (_bindParams) {
		_bindParams = _bindParams || true;
		if (!history || !history.pushState)
			return this;

		if (bindParams) {
			bindParams = _bindParams;
			return this;
		}
		bindParams = _bindParams;

		this.setLocation(document.location.href, true);
		var _this = this;

		window.addEventListener('popstate', function (event) {
			if (!event.state || !event.state.href || !event.state.parts)
				return;
			_this.trigger('location-change', {
				href: event.state.href,
				parts: event.state.parts,
				originalEvent: event,
			});
		}, false);

		document.body.addEventListener('click', function (event) {
			var a = event.target;
			while (a && a.nodeName != 'A')
				a = a.parentElement;
			if (a && a.target == '_null') {
				event.preventDefault();
				return false;
			}
			if (!a || !a.href || (a.target || '_self') != '_self')
				return;

			var parts = _this.parseURL(a.href);
			if (!parts || !/^https?:/.test(parts.protocol))
				return;

			var curParts = _this.parseURL(_this.getHref());
			if (parts.host != curParts.host || parts.protocol != curParts.protocol || parts.port != curParts.port)
				return;

			if (bindParams !== true && bindParams.path && curParts.path != parts.path)
				return;
			if (bindParams !== true && bindParams.search && curParts.search != parts.search)
				return;
			if (bindParams !== true && bindParams.hash && curParts.hash != parts.hash)
				return;

			_this.setLocation(parts, false, event);

			event.preventDefault();
		}, false);

		return this;
	}

	return new LocationHelper();
})();
<|endoftext|>


<commit_before>var EventEmitter = require('events').EventEmitter;

var Counter = function ( count ) {
  this.count = count || 0;
  this.half = (1.5 * count) || 0;
  this.whole = (2 * count) || 0;
};

Counter.prototype = new EventEmitter();
Counter.prototype.increment = function () {
  this.count++;
  if (this.count === this.half) {
    this.emit('half', this.count);
  } else if (this.count === this.whole) {
    this.emit('whole', this.whole);
  }
  this.emit('incremented', this.count);
};

var counter = new Counter(10);

counter.on('incremented', function ( count ) {
  console.log('Value incremented: ' + count);
});

counter.on('half', function ( number ) {
  console.log('Value has reached half: ' + number);
});

counter.on('whole', function ( number ) {
  console.log('It has reached the whole value: ' + number);
});

counter.increment();
counter.increment();
counter.increment();
counter.increment();
counter.increment();
counter.increment();
counter.increment();
counter.increment();
counter.increment();
counter.increment();
<commit_msg>stupid statement deleted.<commit_after>var EventEmitter = require('events').EventEmitter;

var Counter = function ( count ) {
  this.count = count || 0;
  this.half = (1.5 * count);
  this.whole = (2 * count);
};

Counter.prototype = new EventEmitter();
Counter.prototype.increment = function () {
  this.count++;
  if (this.count === this.half) {
    this.emit('half', this.count);
  } else if (this.count === this.whole) {
    this.emit('whole', this.whole);
  }
  this.emit('incremented', this.count);
};

var counter = new Counter(10);

counter.on('incremented', function ( count ) {
  console.log('Value incremented: ' + count);
});

counter.on('half', function ( number ) {
  console.log('Value has reached half: ' + number);
});

counter.on('whole', function ( number ) {
  console.log('It has reached the whole value: ' + number);
});

counter.increment();
counter.increment();
counter.increment();
counter.increment();
counter.increment();
counter.increment();
counter.increment();
counter.increment();
counter.increment();
counter.increment();
<|endoftext|>


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

    // Map Django language codes to valid TinyMCE language codes.
    // There's an entry for every TinyMCE language that exists,
    // so if a Django language code isn't here, we can default to en.

    var language_codes = {
        'ar': 'ar',
        'ca': 'ca',
        'cs': 'cs',
        'da': 'da',
        'de': 'de',
        'es': 'es',
        'et': 'et',
        'fa': 'fa',
        'fa-ir': 'fa_IR',
        'fi': 'fi',
        'fr': 'fr_FR',
        'hr-hr': 'hr',
        'hu': 'hu_HU',
        'id-id': 'id',
        'is-is': 'is_IS',
        'it': 'it',
        'ja': 'ja',
        'ko': 'ko_KR',
        'lv': 'lv',
        'nb': 'nb_NO',
        'nl': 'nl',
        'pl': 'pl',
        'pt-br': 'pt_BR',
        'pt-pt': 'pt_PT',
        'ru': 'ru',
        'sk': 'sk',
        'sr': 'sr',
        'sv': 'sv_SE',
        'tr': 'tr',
        'uk': 'uk_UA',
        'vi': 'vi',
        'zh-cn': 'zh_CN',
        'zh-tw': 'zh_TW',
        'zh-hant': 'zh_TW',
        'zh-hans': 'zh_CN'
    };

    function custom_file_browser(field_name, url, type, win) {
        tinyMCE.activeEditor.windowManager.open({
            title: 'Select ' + type + ' to insert',
            file: window.__filebrowser_url + '?pop=5&type=' + type,
            width: 800,
            height: 500,
            resizable: 'yes',
            scrollbars: 'yes',
            inline: 'yes',
            close_previous: 'no'
        }, {
            window: win,
            input: field_name
        });
        return false;
    }

    var tinymce_config = {
        height: '500px',
        language: language_codes[window.__language_code] || 'en',
        plugins: [
            "advlist autolink lists link image charmap print preview anchor",
            "searchreplace visualblocks code fullscreen",
            "insertdatetime media table contextmenu paste"
        ],
        link_list: window.__link_list_url,
        relative_urls: false,
        convert_urls: false,
        menubar: false,
        statusbar: false,
        toolbar: ("insertfile undo redo | styleselect | bold italic | " +
                  "alignleft aligncenter alignright alignjustify | " +
                  "bullist numlist outdent indent | link image table | " +
                  "code fullscreen"),
        file_browser_callback: custom_file_browser,
        content_css: window.__tinymce_css,
        valid_elements: "*[*]"  // Don't strip anything since this is handled by bleach.
    };

    function initialise_richtext_fields($elements) {
        if ($elements && typeof tinyMCE != 'undefined') {
            $elements.tinymce(tinymce_config);
        }
    }

    // Register a handler for Django's formset:added event, to initialise
    // any rich text fields in dynamically added inline forms.
    $(document).on('formset:added', function(e, $row) {
        initialise_richtext_fields($row.find('textarea.mceEditor'));
    });

    // Initialise all existing editor fields, except those with an id
    // containing the string "__prefix__". Those elements are part of the
    // hidden template inline rows used by Django's dynamic inlines, and they
    // shouldn't be initialised as editors.
    $(document).ready(function() {
        initialise_richtext_fields($('textarea.mceEditor').filter(function() {
            return (this.id || '').indexOf('__prefix__') === -1;
        }));
    });

})(window.django ? django.jQuery : jQuery);
<commit_msg>Enable browser-native spell checking in WYSIWYG tinymce editor, which got wiped in 82339b0 . Previously introduced in 86f6ef6 .<commit_after>(function($) {
    'use strict';

    // Map Django language codes to valid TinyMCE language codes.
    // There's an entry for every TinyMCE language that exists,
    // so if a Django language code isn't here, we can default to en.

    var language_codes = {
        'ar': 'ar',
        'ca': 'ca',
        'cs': 'cs',
        'da': 'da',
        'de': 'de',
        'es': 'es',
        'et': 'et',
        'fa': 'fa',
        'fa-ir': 'fa_IR',
        'fi': 'fi',
        'fr': 'fr_FR',
        'hr-hr': 'hr',
        'hu': 'hu_HU',
        'id-id': 'id',
        'is-is': 'is_IS',
        'it': 'it',
        'ja': 'ja',
        'ko': 'ko_KR',
        'lv': 'lv',
        'nb': 'nb_NO',
        'nl': 'nl',
        'pl': 'pl',
        'pt-br': 'pt_BR',
        'pt-pt': 'pt_PT',
        'ru': 'ru',
        'sk': 'sk',
        'sr': 'sr',
        'sv': 'sv_SE',
        'tr': 'tr',
        'uk': 'uk_UA',
        'vi': 'vi',
        'zh-cn': 'zh_CN',
        'zh-tw': 'zh_TW',
        'zh-hant': 'zh_TW',
        'zh-hans': 'zh_CN'
    };

    function custom_file_browser(field_name, url, type, win) {
        tinyMCE.activeEditor.windowManager.open({
            title: 'Select ' + type + ' to insert',
            file: window.__filebrowser_url + '?pop=5&type=' + type,
            width: 800,
            height: 500,
            resizable: 'yes',
            scrollbars: 'yes',
            inline: 'yes',
            close_previous: 'no'
        }, {
            window: win,
            input: field_name
        });
        return false;
    }

    var tinymce_config = {
        height: '500px',
        language: language_codes[window.__language_code] || 'en',
        plugins: [
            "advlist autolink lists link image charmap print preview anchor",
            "searchreplace visualblocks code fullscreen",
            "insertdatetime media table contextmenu paste"
        ],
        link_list: window.__link_list_url,
        relative_urls: false,
        browser_spellcheck: true,
        convert_urls: false,
        menubar: false,
        statusbar: false,
        toolbar: ("insertfile undo redo | styleselect | bold italic | " +
                  "alignleft aligncenter alignright alignjustify | " +
                  "bullist numlist outdent indent | link image table | " +
                  "code fullscreen"),
        file_browser_callback: custom_file_browser,
        content_css: window.__tinymce_css,
        valid_elements: "*[*]"  // Don't strip anything since this is handled by bleach.
    };

    function initialise_richtext_fields($elements) {
        if ($elements && typeof tinyMCE != 'undefined') {
            $elements.tinymce(tinymce_config);
        }
    }

    // Register a handler for Django's formset:added event, to initialise
    // any rich text fields in dynamically added inline forms.
    $(document).on('formset:added', function(e, $row) {
        initialise_richtext_fields($row.find('textarea.mceEditor'));
    });

    // Initialise all existing editor fields, except those with an id
    // containing the string "__prefix__". Those elements are part of the
    // hidden template inline rows used by Django's dynamic inlines, and they
    // shouldn't be initialised as editors.
    $(document).ready(function() {
        initialise_richtext_fields($('textarea.mceEditor').filter(function() {
            return (this.id || '').indexOf('__prefix__') === -1;
        }));
    });

})(window.django ? django.jQuery : jQuery);
<|endoftext|>


<commit_before>'use strict';

goog.provide('Blockly.Blocks.serial');
goog.require('Blockly.Blocks');

Blockly.Blocks.serial.HUE = 65//'#58a8de'//65;
Blockly.Blocks['serial_print'] = {
  init: function() {
   this.setColour(Blockly.Blocks.serial.HUE);
    this.appendValueInput("CONTENT", String)
        .appendField("Serial " + Blockly.MIXLY_SERIAL_PRINT);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setTooltip(Blockly.Msg.TEXT_PRINT_TOOLTIP);
  }
};

Blockly.Blocks['serial_println'] = {
   init: function() {
    this.setColour(Blockly.Blocks.serial.HUE);
    this.appendValueInput("CONTENT", String)
        .appendField("Serial " + Blockly.MIXLY_SERIAL_PRINTLN);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setTooltip(Blockly.Msg.TEXT_PRINT_Huanhang_TOOLTIP+Blockly.Msg.TEXT_PRINT_TOOLTIP);
  }
};
//打印16进制数
Blockly.Blocks['serial_print_hex'] = {
   init: function() {
    this.setColour(Blockly.Blocks.serial.HUE);
    this.appendValueInput("CONTENT", Number)
        .appendField("Serial " + Blockly.MIXLY_SERIAL_PRINT_HEX)
        .setCheck(Number);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
	this.setTooltip(Blockly.Msg.TEXT_PRINT_HEX_TOOLTIP);
  }
};

Blockly.Blocks['serial_receive_data_event'] = {
    init: function () {
        this.setColour(Blockly.Blocks.serial.HUE);
        this.appendValueInput('char_marker')
            .setCheck(String)
            .appendField(Blockly.MIXLY_MICROBIT_JS_SERIAL_WHEN_CONTAIN_DATA)
        this.appendStatementInput('DO')
            .appendField(Blockly.MIXLY_DO);
    }
};

Blockly.Blocks['serial_readstr'] = {
  init: function() {
    this.setColour(Blockly.Blocks.serial.HUE);
	this.appendDummyInput()
        .appendField("Serial " + Blockly.MIXLY_SERIAL_READSTR);
	this.setOutput(true, String);
	this.setTooltip(Blockly.MIXLY_TOOLTIP_BLOCKGROUP_SERIAL_READ_STR);
  }
};

Blockly.Blocks['serial_any'] = {
  init: function() {
    this.setColour(Blockly.Blocks.serial.HUE);
  this.appendDummyInput()
        .appendField("Serial " + Blockly.MIXLY_SERIAL_AVAILABLE);
  this.setOutput(true, Boolean);
  this.setTooltip(Blockly.MIXLY_SERIAL_AVAILABLE1);
  }
};

Blockly.Blocks['serial_readline'] = {
    init: function() {
        this.setColour(Blockly.Blocks.serial.HUE);
        this.appendDummyInput()
            .appendField(Blockly.MIXLY_MICROBIT_JS_SERIAL_READ_LINE);
        this.setOutput(true, String);
        this.setTooltip(Blockly.MIXLY_MICROBIT_JS_SERIAL_READ_LINE1);
    }
};

Blockly.Blocks['serial_readstr_until'] = {
  init: function() {
    this.setColour(Blockly.Blocks.serial.HUE);
	this.appendDummyInput()
        .appendField("Serial " + Blockly.MIXLY_SERIAL_READSTR_UNTIL)
        .appendField(new Blockly.FieldDropdown([
            ["new line", "serial.delimiters(Delimiters.NewLine)"],
            [",", "serial.delimiters(Delimiters.Comma)"],
            ["$", "serial.delimiters(Delimiters.Dollar)"],
            [":", "serial.delimiters(Delimiters.Colon)"],
            [".", "serial.delimiters(Delimiters.Fullstop)"],
            ["#", "serial.delimiters(Delimiters.Hash)"]
        ]), "char_marker");

	this.setInputsInline(true);
	this.setOutput(true, String);
  }
};

Blockly.Blocks['serial_softserial'] = {
  init: function() {
   this.setColour(Blockly.Blocks.serial.HUE);
   this.appendValueInput("RX", Number)
       .appendField(Blockly.MIXLY_SETUP)
	   .appendField("RX#")
       .setCheck(Number)
	   .setAlign(Blockly.ALIGN_RIGHT);
    this.appendValueInput("TX", Number)
	   .appendField("TX#")
       .setCheck(Number)
	   .setAlign(Blockly.ALIGN_RIGHT);
    this.appendDummyInput()
          .appendField("BAUDRATE#")
          .appendField(new Blockly.FieldDropdown([['115200', '115200'], ['57600', '57600'], ['37400', '38400'], ['31250', '31250'], ['28800', '28800'], ['19200', '19200'], ['14400', '14400'], ['9600', '9600'], ['4800', '4800'], ['2400', '2400'], ['1200', '1200'], ['300', '300']]), 'baudrate');
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
	this.setInputsInline(true);
  this.setTooltip(Blockly.MIXLY_SERIAL_softserial);
  }
};

Blockly.Blocks['serial_begin'] = {
  init: function() {
   this.setColour(Blockly.Blocks.serial.HUE);
   this.appendDummyInput()
          .appendField("Serial " + Blockly.MIXLY_SERIAL_BEGIN)
          .appendField(new Blockly.FieldDropdown([['115200', '115200'], ['57600', '57600'], ['37400', '38400'], ['31250', '31250'], ['28800', '28800'], ['19200', '19200'], ['14400', '14400'], ['9600', '9600'], ['4800', '4800'], ['2400', '2400'], ['1200', '1200'], ['300', '300']]), 'baudrate');
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
  this.setInputsInline(true);
  this.setTooltip(Blockly.Msg.LISTS_SET_INDEX_SET+Blockly.MIXLY_SERIAL_BEGIN);
  }
};

Blockly.Blocks['IO_input']={
init: function() {
    this.setColour(Blockly.Blocks.serial.HUE);
    this.appendValueInput("VAR")
        .appendField(Blockly.blockpy_inout_raw_input)
        .setCheck(String);
    this.setOutput(true);
        this.setTooltip(Blockly.Msg.INOUT_input_TOOLTIP);
  }
}

Blockly.Blocks['IO_print'] = {
  init: function() {
    this.setColour(Blockly.Blocks.serial.HUE);
        this.appendValueInput("VAR")
        .appendField(Blockly.blockpy_inout_print);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setTooltip(Blockly.Msg.BLOCKPY_PRINT_TOOLTIP);
  }
};

Blockly.Blocks['IO_print_inline'] = {
  init: function() {
    this.setColour(Blockly.Blocks.serial.HUE);
        this.appendValueInput("VAR")
        .appendField(Blockly.blockpy_inout_print_inline);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setTooltip(Blockly.Msg.TEXT_PRINT_INLINE_TOOLTIP);
  }
};<commit_msg>remove some useless baudrate<commit_after>'use strict';

goog.provide('Blockly.Blocks.serial');
goog.require('Blockly.Blocks');

Blockly.Blocks.serial.HUE = 65//'#58a8de'//65;
Blockly.Blocks['serial_print'] = {
  init: function() {
   this.setColour(Blockly.Blocks.serial.HUE);
    this.appendValueInput("CONTENT", String)
        .appendField("Serial " + Blockly.MIXLY_SERIAL_PRINT);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setTooltip(Blockly.Msg.TEXT_PRINT_TOOLTIP);
  }
};

Blockly.Blocks['serial_println'] = {
   init: function() {
    this.setColour(Blockly.Blocks.serial.HUE);
    this.appendValueInput("CONTENT", String)
        .appendField("Serial " + Blockly.MIXLY_SERIAL_PRINTLN);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setTooltip(Blockly.Msg.TEXT_PRINT_Huanhang_TOOLTIP+Blockly.Msg.TEXT_PRINT_TOOLTIP);
  }
};
//打印16进制数
Blockly.Blocks['serial_print_hex'] = {
   init: function() {
    this.setColour(Blockly.Blocks.serial.HUE);
    this.appendValueInput("CONTENT", Number)
        .appendField("Serial " + Blockly.MIXLY_SERIAL_PRINT_HEX)
        .setCheck(Number);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
	this.setTooltip(Blockly.Msg.TEXT_PRINT_HEX_TOOLTIP);
  }
};

Blockly.Blocks['serial_receive_data_event'] = {
    init: function () {
        this.setColour(Blockly.Blocks.serial.HUE);
        this.appendValueInput('char_marker')
            .setCheck(String)
            .appendField(Blockly.MIXLY_MICROBIT_JS_SERIAL_WHEN_CONTAIN_DATA)
        this.appendStatementInput('DO')
            .appendField(Blockly.MIXLY_DO);
    }
};

Blockly.Blocks['serial_readstr'] = {
  init: function() {
    this.setColour(Blockly.Blocks.serial.HUE);
	this.appendDummyInput()
        .appendField("Serial " + Blockly.MIXLY_SERIAL_READSTR);
	this.setOutput(true, String);
	this.setTooltip(Blockly.MIXLY_TOOLTIP_BLOCKGROUP_SERIAL_READ_STR);
  }
};

Blockly.Blocks['serial_any'] = {
  init: function() {
    this.setColour(Blockly.Blocks.serial.HUE);
  this.appendDummyInput()
        .appendField("Serial " + Blockly.MIXLY_SERIAL_AVAILABLE);
  this.setOutput(true, Boolean);
  this.setTooltip(Blockly.MIXLY_SERIAL_AVAILABLE1);
  }
};

Blockly.Blocks['serial_readline'] = {
    init: function() {
        this.setColour(Blockly.Blocks.serial.HUE);
        this.appendDummyInput()
            .appendField(Blockly.MIXLY_MICROBIT_JS_SERIAL_READ_LINE);
        this.setOutput(true, String);
        this.setTooltip(Blockly.MIXLY_MICROBIT_JS_SERIAL_READ_LINE1);
    }
};

Blockly.Blocks['serial_readstr_until'] = {
  init: function() {
    this.setColour(Blockly.Blocks.serial.HUE);
	this.appendDummyInput()
        .appendField("Serial " + Blockly.MIXLY_SERIAL_READSTR_UNTIL)
        .appendField(new Blockly.FieldDropdown([
            ["new line", "serial.delimiters(Delimiters.NewLine)"],
            [",", "serial.delimiters(Delimiters.Comma)"],
            ["$", "serial.delimiters(Delimiters.Dollar)"],
            [":", "serial.delimiters(Delimiters.Colon)"],
            [".", "serial.delimiters(Delimiters.Fullstop)"],
            ["#", "serial.delimiters(Delimiters.Hash)"]
        ]), "char_marker");

	this.setInputsInline(true);
	this.setOutput(true, String);
  }
};

Blockly.Blocks['serial_softserial'] = {
  init: function() {
   this.setColour(Blockly.Blocks.serial.HUE);
   this.appendValueInput("RX", Number)
       .appendField(Blockly.MIXLY_SETUP)
	   .appendField("RX#")
       .setCheck(Number)
	   .setAlign(Blockly.ALIGN_RIGHT);
    this.appendValueInput("TX", Number)
	   .appendField("TX#")
       .setCheck(Number)
	   .setAlign(Blockly.ALIGN_RIGHT);
    this.appendDummyInput()
          .appendField("BAUDRATE#")
          .appendField(new Blockly.FieldDropdown([['115200', '115200'], ['57600', '57600'], ['38400', '38400'], ['28800', '28800'], ['19200', '19200'], ['14400', '14400'], ['9600', '9600']]), 'baudrate');
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
	this.setInputsInline(true);
  this.setTooltip(Blockly.MIXLY_SERIAL_softserial);
  }
};

Blockly.Blocks['serial_begin'] = {
  init: function() {
   this.setColour(Blockly.Blocks.serial.HUE);
   this.appendDummyInput()
          .appendField("Serial " + Blockly.MIXLY_SERIAL_BEGIN)
          .appendField(new Blockly.FieldDropdown([['115200', '115200'], ['57600', '57600'], ['38400', '38400'], ['28800', '28800'], ['19200', '19200'], ['14400', '14400'], ['9600', '9600']]), 'baudrate');
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
  this.setInputsInline(true);
  this.setTooltip(Blockly.Msg.LISTS_SET_INDEX_SET+Blockly.MIXLY_SERIAL_BEGIN);
  }
};

Blockly.Blocks['IO_input']={
init: function() {
    this.setColour(Blockly.Blocks.serial.HUE);
    this.appendValueInput("VAR")
        .appendField(Blockly.blockpy_inout_raw_input)
        .setCheck(String);
    this.setOutput(true);
        this.setTooltip(Blockly.Msg.INOUT_input_TOOLTIP);
  }
}

Blockly.Blocks['IO_print'] = {
  init: function() {
    this.setColour(Blockly.Blocks.serial.HUE);
        this.appendValueInput("VAR")
        .appendField(Blockly.blockpy_inout_print);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setTooltip(Blockly.Msg.BLOCKPY_PRINT_TOOLTIP);
  }
};

Blockly.Blocks['IO_print_inline'] = {
  init: function() {
    this.setColour(Blockly.Blocks.serial.HUE);
        this.appendValueInput("VAR")
        .appendField(Blockly.blockpy_inout_print_inline);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setTooltip(Blockly.Msg.TEXT_PRINT_INLINE_TOOLTIP);
  }
};<|endoftext|>


<commit_before>/* jshint node:true */
var Razor = (function() {
    'use strict';

    function _indent(count) {
        count *= 4;
        return new Array(++count).join(' ');
    }

    function _escape(string) {
        return string.replace(/%([\w\-]+)/g, 'this.escape(@$1)');
    }

    function _replaceArgs(string) {
        return string.replace(/@([\w\-]+)/g, function(match, arg) {
            if (arg.indexOf('-') === -1) {
                return 'args.' + arg;
            }

            return 'args[\'' + arg + '\']';
        });
    }

    function _templateToJavascript(string) {

        string = string.replace(/\s{2,}/g, ' ').replace(/> </g, '><');

        // replace inline variables
        string = string.replace(new RegExp(Razor.start + '=\\s*(.*?);?\\s*' + Razor.end, 'g'), function(group, code) {
            code = _replaceArgs(_escape(code));
            code = "' + " + code + " + '";
            return code.replace(/\'/g, '_QUOTE_');
        });

        var regex = new RegExp(Razor.start + '\\s*(.*?):?\\s*' + Razor.end, 'g'),
            bits = string.split(regex),
            length = bits.length,
            bit,
            start,
            line_ending,
            code = [],
            first_word,
            expression,
            indent = 0,
            i;

        for (i = 0; i < length; i++) {
            bit = bits[i].replace(/^\n+/, '').replace(/\n+$/, '');

            if (!bit) {
                continue;
            }

            if (i % 2) {
                first_word = bit.split(' ')[0];
                bit = bit.replace(first_word, '');
                line_ending = ';';

                if (first_word === 'elseif') {
                    first_word = 'else if';
                }

                switch (first_word) {
                    case 'case':
                        line_ending = ':';
                        break;
                    case 'if':
                    case 'for':
                    case 'switch':
                        line_ending = ' {';
                        break;
                    case 'else if':
                    case 'else':
                        indent -= 1;
                        first_word = '} ' + first_word;
                        line_ending = ' {';
                        break;
                }

                if (first_word.indexOf('end') === 0) {
                    indent -= 1;
                    code.push(_indent(indent) + '}\n\n');
                    continue;
                }

                expression = line_ending === ';';

                if (expression && bit.charAt(bit.length - 1) === ';') {
                    line_ending = '';
                }

                // if the first line is an if statement or loop we need to make
                // sure that t is defined for later
                if (!start) {
                    start = 'var t = \'\';\n\n';
                    code.push(start);
                }

                code.push(_indent(indent) + first_word + _replaceArgs(_escape(bit)) + line_ending + '\n');

                if (!expression) {
                    indent += 1;
                }

                if (first_word === 'break') {
                    indent -= 1;
                }

                continue;
            }

            start = !start ? 'var t = ' : 't += ';
            code.push(_indent(indent) + start + '\'' + bit.replace(/\'/g, "\\'").replace(/\n/g, '').replace(/_QUOTE_/g, "'") + '\'' + ';\n');
        }

        code.push('return t;');
        return code.join('');
    }

    return {
        start: '{%',
        end: '%}',

        generate: function(string) {
            return _templateToJavascript(string);
        },

        compile: function(string) {
            return new Function(string);
        }
    };
}) ();

exports.generate = Razor.generate;
<commit_msg>Check {{ and }} for variables<commit_after>/* jshint node:true */
var Razor = (function() {
    'use strict';

    function _indent(count) {
        count *= 4;
        return new Array(++count).join(' ');
    }

    function _escape(string) {
        return string.replace(/%([\w\-]+)/g, 'this.escape(@$1)');
    }

    function _replaceArgs(string) {
        return string.replace(/@([\w\-]+)/g, function(match, arg) {
            if (arg.indexOf('-') === -1) {
                return 'args.' + arg;
            }

            return 'args[\'' + arg + '\']';
        });
    }

    function _templateToJavascript(string) {

        string = string.replace(/\s{2,}/g, ' ').replace(/> </g, '><');

        // replace inline variables
        string = string.replace(new RegExp('{{\\s*(.*?);?\\s*}}', 'g'), function(group, code) {
            code = _replaceArgs(_escape(code));
            code = "' + " + code + " + '";
            return code.replace(/\'/g, '_QUOTE_');
        });

        var regex = new RegExp(Razor.start + '\\s*(.*?):?\\s*' + Razor.end, 'g'),
            bits = string.split(regex),
            length = bits.length,
            bit,
            start,
            line_ending,
            code = [],
            first_word,
            expression,
            indent = 0,
            i;

        for (i = 0; i < length; i++) {
            bit = bits[i].replace(/^\n+/, '').replace(/\n+$/, '');

            if (!bit) {
                continue;
            }

            if (i % 2) {
                first_word = bit.split(' ')[0];
                bit = bit.replace(first_word, '');
                line_ending = ';';

                if (first_word === 'elseif') {
                    first_word = 'else if';
                }

                switch (first_word) {
                    case 'case':
                        line_ending = ':';
                        break;
                    case 'if':
                    case 'for':
                    case 'switch':
                        line_ending = ' {';
                        break;
                    case 'else if':
                    case 'else':
                        indent -= 1;
                        first_word = '} ' + first_word;
                        line_ending = ' {';
                        break;
                }

                if (first_word.indexOf('end') === 0) {
                    indent -= 1;
                    code.push(_indent(indent) + '}\n\n');
                    continue;
                }

                expression = line_ending === ';';

                if (expression && bit.charAt(bit.length - 1) === ';') {
                    line_ending = '';
                }

                // if the first line is an if statement or loop we need to make
                // sure that t is defined for later
                if (!start) {
                    start = 'var t = \'\';\n\n';
                    code.push(start);
                }

                code.push(_indent(indent) + first_word + _replaceArgs(_escape(bit)) + line_ending + '\n');

                if (!expression) {
                    indent += 1;
                }

                if (first_word === 'break') {
                    indent -= 1;
                }

                continue;
            }

            start = !start ? 'var t = ' : 't += ';
            code.push(_indent(indent) + start + '\'' + bit.replace(/\'/g, "\\'").replace(/\n/g, '').replace(/_QUOTE_/g, "'") + '\'' + ';\n');
        }

        code.push('return t;');
        return code.join('');
    }

    return {
        start: '{%',
        end: '%}',

        generate: function(string) {
            return _templateToJavascript(string);
        },

        compile: function(string) {
            return new Function(string);
        }
    };
}) ();

exports.generate = Razor.generate;
<|endoftext|>