<commit_before>function validaContenido(input, min_length, max_length, errors, form) {
    var error = '';
    if (input.val().length < min_length)
        error = 'El contenido de tu mensaje debe ser mayor a ' + min_length;
    else if (input.val().length > max_length)
        error = 'El contenido de tu mensaje debe ser menor a ' + max_length;

    if(error == '') {
        form.submit();
    	return false;
    } else {
        errors.text(error);
    }
}

function textChange(areaTexto, areaCount) {
    $(areaCount).text(
    	555 - $(areaTexto).val().length
    );
}

function getDataVideo(idVideo, callback) {
	var respuesta = new Object();
	urlApiYoutube = "http://gdata.youtube.com/feeds/api/videos?v=2&alt=jsonc&q=" + idVideo;

	$.ajax({
		  url: urlApiYoutube,
		  async: true,
		  dataType: 'jsonp',
		  success: function(response) {
			  if ($.type(response) == 'string') {
				  response = $.parseJSON(response);
			  }
			  if (response.data != null) {
				  if (response.data.items != null && response.data.items.length > 0) {
					  datosVideo = response.data.items[0];
					  respuesta.titulo = datosVideo.title;
					  respuesta.descripcion = datosVideo.description;
					  respuesta.thumbnail = datosVideo.thumbnail.sqDefault;
					  respuesta.urlVideo = 'http://www.youtube.com/watch?v=' + idVideo;

					  callback(respuesta);

				  }
			  }
		  }
	});
	return respuesta;
}

function getHtmlDataVideoPost(data){
	var id = 0;
	var regexYoutube = /www\.youtube\.com\/watch\?[^v]*v=([^&]{11})/ig;
	var urlYoutube = regexYoutube.exec(data.urlVideo);
	if (urlYoutube != null)
		id = urlYoutube[1];

	return "
" + data.titulo + "
" +
	"
" +
	"

" + data.descripcion + "
<input type='hidden' id='youtubeI' value='" + id + "' />";
}

function getHtmlDataVideo(data){
	return "
" + data.titulo + "

X
" +
	"
" +
	"

" + data.descripcion + "
" + data.urlVideo + "

";
}

function findVideo() {
	if ($('#video').html() == '') {
		var areaText = $('#contenido_texto').val();
		var regexYoutube = /www\.youtube\.com\/watch\?[^v]*v=([^&]{11})/ig;

		var urlYoutube = regexYoutube.exec(areaText);
		if (urlYoutube != null) {
			getDataVideo(urlYoutube[1], function(data){
				var html = getHtmlDataVideo(data);
				$('#video').html(html);
				$('#video').show();
				$('#contenido_url_video').val(data.urlVideo);
				$('#contenido_categoria option').each(function() {
					if ($(this).text() == 'Video'){
						$('#contenido_categoria').val($(this).val());
					} else {
						$(this).attr("disabled", "disabled");
					}
				});
				$('#eliminarVideo').click(function(){ eliminarVideo(); });
			});
		}
	}
}

function eliminarVideo() {
	$('#video').html("");
	$('#video').hide();
	$('#contenido_url_video').removeAttr('value');
	$('#contenido_categoria option').each(function() {
		if ($(this).attr("disabled")) {
			$(this).removeAttr("disabled");
		}
	});
	$('#contenido_categoria').val("");
}

function getHtmlEmbedVideo(idVideo) {
	var urlVideoYoutube = "http://www.youtube.com/embed/" + idVideo + '?fs=1&autoplay=1';
	var htmlYoutube = '

';
	return htmlYoutube;
}

function renderizarVideosPost($html) {
	var posts = $html;
	if ($html == null) {
		$html = $(document);
		posts = $html.find('.Post');
	}
	posts.each(function() {
		var contenido = $(this).find('.Contenido');
		var urlVideo = $(this).find('.UrlVideo').val();
		if (urlVideo != null && urlVideo != '') {
			var regex = /[\?&]+v=([^&]{11})/i;
			var idVideoR = regex.exec(urlVideo);
			if (idVideoR.length == 2) {
				var idVideo = idVideoR[1];
				getDataVideo(idVideo, function(data) {
					contenido.html(
							contenido.html() +
							'
' +
							getHtmlDataVideoPost(data) +
							'
'
					);
					contenido.find('.ThumbnailVideo a').click(function(){
						contenido.find('.VideoData').fadeOut(
							300,
							function() {
								$(this).remove();
								contenido.html(contenido.html() + getHtmlEmbedVideo(idVideo));
							}
						);
					});
				});
			}
		}
	});
}

function renderizarVideos() {
	$('.Post').each(function(){
		if ($(this).find('.TituloTexto').text().indexOf("Video") != '-1') {
			var contenido = $(this).children('.Contenido');
			var regexYoutube = /h?t?t?p?:?\/?\/?www\.youtube\.com\/watch\?[^v]*v=([^&]{11}).*/i;
			var contenidoTexto = contenido.text().trim();
			var idVideoYoutube = regexYoutube.exec(contenidoTexto);
			if (idVideoYoutube != null) {
				var urlVideoYoutube = "http://www.youtube.com/embed/" + idVideoYoutube[1];
				var htmlYoutube = '

';
				contenido.html(
					contenidoTexto.replace(regexYoutube, htmlYoutube)
				);
			}
		}
	});
}

function obtenerContenidos() {
    $('#masContenidos').css("visibility", "hidden");
    $('.PostLoading').show();

    var cid = $("#cid").val();
    var lastId = $(".Post:last").attr("id");
    var urlContenidos = "contenido/" + cid + "/" + lastId + "/5";
    var response = '';

    $.ajax({
    	url: urlContenidos,
    	async: true,
    	success: function(response) {
    		if (response != "") {
    			var lastPost = $(".Post:last");
    			lastPost.after(response);
    			$('html,body').animate({scrollTop : lastPost.position().top}, 'slow');
    			var newPosts = lastPost.nextAll();
			  	asignarOnClickVerComentarios(newPosts);
			  	//actualizarBotones(newPosts);
			  	asignarOnSubmitComentarAjax();
			  	renderizarVideosPost(newPosts);
		  	} else {
		  		$('#masContenidos').hide();
		  	}
		  	$('.PostLoading').hide();
	        $('#masContenidos').css("visibility", 'visible');
    	}
	});
};

function actualizarBotones($response) {

	if( $response.length < 1 ) return;

	$response.each(function(){
		gapi.plusone.go(
				$(this).attr('id')
		);
		FB.XFBML.parse(
				$(this).get(0)
		);
		twttr.widgets.load(
				$(this).find('a.twitter-share-button').eq(0).get(0)
		);
	});
}

function comentarioEliminar() {
	return confirm('Esta seguro que desea eliminar este comentario ?');
}

function asignarOnHoverComentarioEliminar(selComentario, selItem) {
	$(selItem).unbind('click');
	$(selItem).click(function(evt){
		evt.preventDefault();
		if (comentarioEliminar()) {
			var post = $(this).parents('.Post');
			var comentario = $(this).parents('.Comentario');
			var id = comentario.attr('id');
			var urlAjax = '/usuario/comentario/' + id + '/eliminar';
			$.ajax({
	            url: urlAjax,
	            success: function(data) {
	            	if (post.find('.Comentario').length == 1) {
	            		comentario.before($('
No hay comentarios aún.
'));
	            	}
	            	comentario.remove();
	            }
	        });
	    }
	});
	$(selComentario).hover(
    		function() {
				$(this).find(selItem).css("display", "block");
    		},
			function() {
    			$(this).find(selItem).css("display", "none");
    		}
	);
}

function asignarOnClickVerComentarios($html) {
	if ($html == null) {
		$html = $(document);
	}
	$html.find('.VerComentarios').click(
		function (){
			$(this).parents('.Comentarios').children('.Comentario').removeClass('Hidden');
			$(this).remove();
		}
	);
}

function asignarOnSubmitComentarAjax(urlCustomAjax) {
	$('input[name="comentario[texto]"]').each(function(){
		var inputTexto = $(this);
		$(this).parents('form').submit(function(evt){
	        evt.preventDefault();
	        inputTexto.attr("disabled", "disabled");
	        var post = $(this).parents('div.Post');
	        var texto = $(this).find('#comentario_texto').val();
	        var token = $(this).find('#comentario__token').val();
	        data = 'comentario[texto]=' + texto + '&comentario[_token]=' + token;
	        var comentario = post.find('.Comentario:last');
	        var urlAjax = 'contenido/' + post.attr('id') + '/comentar/ajax/0';
	        if (urlCustomAjax != null) {
	        	urlAjax = post.attr('id') + urlCustomAjax;
	        }
	        if (comentario.length > 0) {
	        	urlAjax = urlAjax.replace('/0', '/' + comentario.attr('id'));
	        }
	        $.ajax({
	            type: 'POST',
	            url: urlAjax,
	            data: data,
	            success: function(data){
	            	if (comentario.length > 0) {
	            		comentario.after($(data));
	            	} else {
	            		var pcomentario = post.find('.Comentarios').find('p');
	            		pcomentario.after($(data));
	            		pcomentario.remove();
	            	}
	            	inputTexto.val('');
	            	inputTexto.removeAttr("disabled");
	            	inputTexto.focus();
	            	var p_comentario = post.find('.Comentarios').find('p.PComentarios').find('a');
	            	if (p_comentario.length > 0) {
	            		p_comentario.text(
	            			p_comentario.text().replace(/\d+/gi, post.find('.Comentario').length)
	            		);
	            	}
	                asignarOnHoverComentarioEliminar('.Comentario', '.EliminarItem');
	            }
	        });

	    });
	});
}

<commit_msg>agregado onerror al metodo obtenercontenidos<commit_after>function validaContenido(input, min_length, max_length, errors, form) {
    var error = '';
    if (input.val().length < min_length)
        error = 'El contenido de tu mensaje debe ser mayor a ' + min_length;
    else if (input.val().length > max_length)
        error = 'El contenido de tu mensaje debe ser menor a ' + max_length;

    if(error == '') {
        form.submit();
    	return false;
    } else {
        errors.text(error);
    }
}

function textChange(areaTexto, areaCount) {
    $(areaCount).text(
    	555 - $(areaTexto).val().length
    );
}

function getDataVideo(idVideo, callback) {
	var respuesta = new Object();
	urlApiYoutube = "http://gdata.youtube.com/feeds/api/videos?v=2&alt=jsonc&q=" + idVideo;

	$.ajax({
		  url: urlApiYoutube,
		  async: true,
		  dataType: 'jsonp',
		  success: function(response) {
			  if ($.type(response) == 'string') {
				  response = $.parseJSON(response);
			  }
			  if (response.data != null) {
				  if (response.data.items != null && response.data.items.length > 0) {
					  datosVideo = response.data.items[0];
					  respuesta.titulo = datosVideo.title;
					  respuesta.descripcion = datosVideo.description;
					  respuesta.thumbnail = datosVideo.thumbnail.sqDefault;
					  respuesta.urlVideo = 'http://www.youtube.com/watch?v=' + idVideo;

					  callback(respuesta);

				  }
			  }
		  }
	});
	return respuesta;
}

function getHtmlDataVideoPost(data){
	var id = 0;
	var regexYoutube = /www\.youtube\.com\/watch\?[^v]*v=([^&]{11})/ig;
	var urlYoutube = regexYoutube.exec(data.urlVideo);
	if (urlYoutube != null)
		id = urlYoutube[1];

	return "
" + data.titulo + "
" +
	"
" +
	"

" + data.descripcion + "
<input type='hidden' id='youtubeI' value='" + id + "' />";
}

function getHtmlDataVideo(data){
	return "
" + data.titulo + "

X
" +
	"
" +
	"

" + data.descripcion + "
" + data.urlVideo + "

";
}

function findVideo() {
	if ($('#video').html() == '') {
		var areaText = $('#contenido_texto').val();
		var regexYoutube = /www\.youtube\.com\/watch\?[^v]*v=([^&]{11})/ig;

		var urlYoutube = regexYoutube.exec(areaText);
		if (urlYoutube != null) {
			getDataVideo(urlYoutube[1], function(data){
				var html = getHtmlDataVideo(data);
				$('#video').html(html);
				$('#video').show();
				$('#contenido_url_video').val(data.urlVideo);
				$('#contenido_categoria option').each(function() {
					if ($(this).text() == 'Video'){
						$('#contenido_categoria').val($(this).val());
					} else {
						$(this).attr("disabled", "disabled");
					}
				});
				$('#eliminarVideo').click(function(){ eliminarVideo(); });
			});
		}
	}
}

function eliminarVideo() {
	$('#video').html("");
	$('#video').hide();
	$('#contenido_url_video').removeAttr('value');
	$('#contenido_categoria option').each(function() {
		if ($(this).attr("disabled")) {
			$(this).removeAttr("disabled");
		}
	});
	$('#contenido_categoria').val("");
}

function getHtmlEmbedVideo(idVideo) {
	var urlVideoYoutube = "http://www.youtube.com/embed/" + idVideo + '?fs=1&autoplay=1';
	var htmlYoutube = '

';
	return htmlYoutube;
}

function renderizarVideosPost($html) {
	var posts = $html;
	if ($html == null) {
		$html = $(document);
		posts = $html.find('.Post');
	}
	posts.each(function() {
		var contenido = $(this).find('.Contenido');
		var urlVideo = $(this).find('.UrlVideo').val();
		if (urlVideo != null && urlVideo != '') {
			var regex = /[\?&]+v=([^&]{11})/i;
			var idVideoR = regex.exec(urlVideo);
			if (idVideoR.length == 2) {
				var idVideo = idVideoR[1];
				getDataVideo(idVideo, function(data) {
					contenido.html(
							contenido.html() +
							'
' +
							getHtmlDataVideoPost(data) +
							'
'
					);
					contenido.find('.ThumbnailVideo a').click(function(){
						contenido.find('.VideoData').fadeOut(
							300,
							function() {
								$(this).remove();
								contenido.html(contenido.html() + getHtmlEmbedVideo(idVideo));
							}
						);
					});
				});
			}
		}
	});
}

function renderizarVideos() {
	$('.Post').each(function(){
		if ($(this).find('.TituloTexto').text().indexOf("Video") != '-1') {
			var contenido = $(this).children('.Contenido');
			var regexYoutube = /h?t?t?p?:?\/?\/?www\.youtube\.com\/watch\?[^v]*v=([^&]{11}).*/i;
			var contenidoTexto = contenido.text().trim();
			var idVideoYoutube = regexYoutube.exec(contenidoTexto);
			if (idVideoYoutube != null) {
				var urlVideoYoutube = "http://www.youtube.com/embed/" + idVideoYoutube[1];
				var htmlYoutube = '

';
				contenido.html(
					contenidoTexto.replace(regexYoutube, htmlYoutube)
				);
			}
		}
	});
}

function obtenerContenidos() {
    $('#masContenidos').css("visibility", "hidden");
    $('.PostLoading').show();

    var cid = $("#cid").val();
    var lastId = $(".Post:last").attr("id");
    var urlContenidos = "contenido/" + cid + "/" + lastId + "/5";
    var response = '';

    $.ajax({
    	url: urlContenidos,
    	async: true,
    	success: function(response) {
    		if (response != "") {
    			var lastPost = $(".Post:last");
    			lastPost.after(response);
    			$('html,body').animate({scrollTop : lastPost.position().top}, 'slow');
    			var newPosts = lastPost.nextAll();
			  	asignarOnClickVerComentarios(newPosts);
			  	//actualizarBotones(newPosts);
			  	asignarOnSubmitComentarAjax();
			  	renderizarVideosPost(newPosts);
		  	} else {
		  		$('#masContenidos').hide();
		  	}
		  	$('.PostLoading').hide();
	        $('#masContenidos').css("visibility", 'visible');
    	},
    	error: function() {
    		$('.PostLoading').hide();
	        $('#masContenidos').css("visibility", 'visible');
    	}

	});
};

function actualizarBotones($response) {

	if( $response.length < 1 ) return;

	$response.each(function(){
		gapi.plusone.go(
				$(this).attr('id')
		);
		FB.XFBML.parse(
				$(this).get(0)
		);
		twttr.widgets.load(
				$(this).find('a.twitter-share-button').eq(0).get(0)
		);
	});
}

function comentarioEliminar() {
	return confirm('Esta seguro que desea eliminar este comentario ?');
}

function asignarOnHoverComentarioEliminar(selComentario, selItem) {
	$(selItem).unbind('click');
	$(selItem).click(function(evt){
		evt.preventDefault();
		if (comentarioEliminar()) {
			var post = $(this).parents('.Post');
			var comentario = $(this).parents('.Comentario');
			var id = comentario.attr('id');
			var urlAjax = '/usuario/comentario/' + id + '/eliminar';
			$.ajax({
	            url: urlAjax,
	            success: function(data) {
	            	if (post.find('.Comentario').length == 1) {
	            		comentario.before($('
No hay comentarios aún.
'));
	            	}
	            	comentario.remove();
	            }
	        });
	    }
	});
	$(selComentario).hover(
    		function() {
				$(this).find(selItem).css("display", "block");
    		},
			function() {
    			$(this).find(selItem).css("display", "none");
    		}
	);
}

function asignarOnClickVerComentarios($html) {
	if ($html == null) {
		$html = $(document);
	}
	$html.find('.VerComentarios').click(
		function (){
			$(this).parents('.Comentarios').children('.Comentario').removeClass('Hidden');
			$(this).remove();
		}
	);
}

function asignarOnSubmitComentarAjax(urlCustomAjax) {
	$('input[name="comentario[texto]"]').each(function(){
		var inputTexto = $(this);
		$(this).parents('form').submit(function(evt){
	        evt.preventDefault();
	        inputTexto.attr("disabled", "disabled");
	        var post = $(this).parents('div.Post');
	        var texto = $(this).find('#comentario_texto').val();
	        var token = $(this).find('#comentario__token').val();
	        data = 'comentario[texto]=' + texto + '&comentario[_token]=' + token;
	        var comentario = post.find('.Comentario:last');
	        var urlAjax = 'contenido/' + post.attr('id') + '/comentar/ajax/0';
	        if (urlCustomAjax != null) {
	        	urlAjax = post.attr('id') + urlCustomAjax;
	        }
	        if (comentario.length > 0) {
	        	urlAjax = urlAjax.replace('/0', '/' + comentario.attr('id'));
	        }
	        $.ajax({
	            type: 'POST',
	            url: urlAjax,
	            data: data,
	            success: function(data){
	            	if (comentario.length > 0) {
	            		comentario.after($(data));
	            	} else {
	            		var pcomentario = post.find('.Comentarios').find('p');
	            		pcomentario.after($(data));
	            		pcomentario.remove();
	            	}
	            	inputTexto.val('');
	            	inputTexto.removeAttr("disabled");
	            	inputTexto.focus();
	            	var p_comentario = post.find('.Comentarios').find('p.PComentarios').find('a');
	            	if (p_comentario.length > 0) {
	            		p_comentario.text(
	            			p_comentario.text().replace(/\d+/gi, post.find('.Comentario').length)
	            		);
	            	}
	                asignarOnHoverComentarioEliminar('.Comentario', '.EliminarItem');
	            }
	        });

	    });
	});
}

<|endoftext|>


<commit_before>const path = require('path')
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const baseWebpackConfig = require('./webpack.base.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')

let env = process.env.NODE_ENV === 'testing'
  ? require('../config/test.env')
  : config.dist.env

let webpackConfig = merge(baseWebpackConfig, {
  entry: {
    app: './src/components/index.js'
  },
  output: {
    path: config.dist.assetsRoot,
    filename: 'uiv.min.js'
  },
  module: {
    rules: utils.styleLoaders({
      sourceMap: config.dist.productionSourceMap,
      extract: true
    })
  },
  devtool: config.dist.productionSourceMap ? '#source-map' : false,
  plugins: [
    // http://vuejs.github.io/vue-loader/en/workflow/production.html
    new webpack.DefinePlugin({
      'process.env': env
    }),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      },
      sourceMap: true
    }),
    // extract css into its own file
    new ExtractTextPlugin({
      filename: 'uiv.min.css'
    }),
    // Compress extracted CSS. We are using this plugin so that possible
    // duplicated CSS from different components can be deduped.
    new OptimizeCSSPlugin()
  ]
})

if (config.dist.productionGzip) {
  let CompressionWebpackPlugin = require('compression-webpack-plugin')

  webpackConfig.plugins.push(
    new CompressionWebpackPlugin({
      asset: '[path].gz[query]',
      algorithm: 'gzip',
      test: new RegExp(
        '\\.(' +
        config.build.productionGzipExtensions.join('|') +
        ')$'
      ),
      threshold: 10240,
      minRatio: 0.8
    })
  )
}

module.exports = webpackConfig
<commit_msg>update webpack setting<commit_after>const path = require('path')
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const baseWebpackConfig = require('./webpack.base.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')

let env = process.env.NODE_ENV === 'testing'
  ? require('../config/test.env')
  : config.dist.env

let webpackConfig = merge(baseWebpackConfig, {
  entry: {
    app: './src/components/index.js'
  },
  output: {
    path: config.dist.assetsRoot,
    filename: 'uiv.min.js',
    library: 'uiv',
    libraryTarget: 'umd'
  },
  module: {
    rules: utils.styleLoaders({
      sourceMap: config.dist.productionSourceMap,
      extract: true
    })
  },
  devtool: config.dist.productionSourceMap ? '#source-map' : false,
  plugins: [
    // http://vuejs.github.io/vue-loader/en/workflow/production.html
    new webpack.DefinePlugin({
      'process.env': env
    }),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      },
      sourceMap: true
    }),
    // extract css into its own file
    new ExtractTextPlugin({
      filename: 'uiv.min.css'
    }),
    // Compress extracted CSS. We are using this plugin so that possible
    // duplicated CSS from different components can be deduped.
    new OptimizeCSSPlugin()
  ]
})

if (config.dist.productionGzip) {
  let CompressionWebpackPlugin = require('compression-webpack-plugin')

  webpackConfig.plugins.push(
    new CompressionWebpackPlugin({
      asset: '[path].gz[query]',
      algorithm: 'gzip',
      test: new RegExp(
        '\\.(' +
        config.build.productionGzipExtensions.join('|') +
        ')$'
      ),
      threshold: 10240,
      minRatio: 0.8
    })
  )
}

module.exports = webpackConfig
<|endoftext|>


<commit_before>angular.module('feedbackcontrol', [])
.directive('transform', function(FeedbackSignal) {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind('click', function(e) {
                var currentUrl = window.location.pathname;
                var me = $(element);
                var data = FeedbackSignal.data;

                if(currentUrl.match(/published|contacts/g)) {

                    if(me.attr('return-policy') == 1) {
                        hide_the_children(me);
                    }

                    if(data.status != "fileas") {
                        if(data.status == "feature") {
                            var state = {
                                activate: {'background-position': '-64px -31px'}
                              , deactivate_sibling: {'background-position': '-32px 0px'}
                              , activation_color: {'background-color': '#FFFFE0'}
                              , state_change_inbox: '{"status": "inbox", "id": ' + data.id + ', "catid": ' + data.catid + ', "origin": "publish"}'
                              , state_change: '{"status": "publish", "id": ' + data.id + ', "catid": ' + data.catid + ', "origin": "publish"}'
                            }
                            published_state(me, '.publish', 'Publish Feedback', state);
                        }

                        if(data.status == "publish") {
                            var state = {
                                activate: {'background-position': '-32px -31px'}
                              , deactivate_sibling: {'background-position': '-64px 0px'}
                              , activation_color: {'background-color': '#FFF'}
                              , state_change_inbox: '{"status": "inbox", "id": ' + data.id + ', "catid": ' + data.catid + ', "origin": "publish"}'
                              , state_change: '{"status": "feature", "id": ' + data.id + ', "catid": ' + data.catid + ', "origin": "publish"}'
                            }
                            published_state(me, '.feature', 'Feature Feedback', state);
                        }
                    } else {
                        hide_the_children(me);
                    }

                } else if(currentUrl.match(/filed/g)) {

                    var data_status = data.status;

                    if(data_status == "publish" || data_status == "feature" || data_status == "delete") {
                        hide_the_children(me);
                    }

                } else {
                    hide_the_children(me);
                }

                e.preventDefault();
            });
        }
    }
})
.directive('undo', function(FeedbackSignal, FeedbackControlService) {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind("click", function(e) {
                $(".checky-box-container").hide();
                if (FeedbackSignal.data.id instanceof Array) {
                    for(var i=0; i < FeedbackSignal.data.id.length ; i++) {
                        var feedback = $(".dashboard-feedback[feedback=" + FeedbackSignal.data.id[i] + "]");
                        feedback.show();
                        $(feedback).parents('.feedback-group').show();
                    }
                } else {
                    var feedback = $(".dashboard-feedback[feedback=" + FeedbackSignal.data.id + "]");
                    feedback.show();
                    $(feedback).parents('.feedback-group').show();
                }

                if($(".sorter-checkbox").is(":checked")) {
                    $(".sorter-checkbox").click();
                }

                console.log($(".feed-checkbox").click());

                FeedbackControlService.expunge();
                e.preventDefault();
            });
        }
    }
})
.directive('close', function(FeedbackControlService) {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind("click", function(e) {
                $(".checky-box-container").hide();
                FeedbackControlService.expunge();
                e.preventDefault();
            });
        }
    }
})
.directive('feedcheckbox', function() {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            var checkbox = $(element);

            checkbox.bind('change', function() {
                if(checkbox.is(":checked")) {
                    checkbox.parents('.dashboard-feedback').css({'background-color': '#F7F7F7'});
                } else {
                    checkbox.parents('.dashboard-feedback').css({'background-color': '#FFF'});
                }
            });

        }
    }
})
.directive('statuschange', function(FeedbackService) {
    return {
        restrict: 'A'
      , scope: {
            feedid: "=feedid"
        }
      , link: function(scope, element, attrs) {
            $(element).bind('change', function() {
                FeedbackService.inline_change($(this).val(), scope.feedid, 'status');
            })
        }
    }
})
.directive('prioritychange', function(FeedbackService) {
    return {
        restrict: 'A'
      , scope: {
            feedid: "=feedid"
        }
      , link: function(scope, element, attrs) {
            $(element).bind('change', function() {
                FeedbackService.inline_change($(this).val(), scope.feedid, 'priority');
            })
        }
    }
})
.directive('deleteBlock', function() {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind('click', function(e) {
                $(this).parents('.custom-att').fadeOut(400, function() {
                     var new_uploaded_images = new Array;
                     var new_attached_link;

                     var div = $(this).parents('.uploaded-images-and-links');
                     var images = div.find('.uploaded_image');
                     var media_attachment = div.find('.attached_link');

                     var remove_image = {
                        'small_url'    :$(this).find('.small-image-url').val(),
                        'medium_url'   :$(this).find('.medium-image-url').val(),
                        'large_url'    :$(this).find('.large-image-url').val()
                     }

                    if(images.length > 0){
                        var us = images.not(":hidden");
                        for(var i=0; i < us.length; i++) {
                            new_uploaded_images.push({
                                'name': $(us[i]).find('.image-name').val()
                            });
                        }
                    }

                    if(!media_attachment.is(":hidden")) {
                        new_attached_link = {
                            title           : media_attachment.find('.link-title').val(),
                            description     : media_attachment.find('.link-description').val(),
                            image           : media_attachment.find('.link-image').val(),
                            url             : media_attachment.find('.link-url').val(),
                            video           : media_attachment.find('.link-video').val(),
                        }
                    }

                    var remaining = {
                        uploaded_images : new_uploaded_images
                      , attached_link   : new_attached_link
                    }

                    var attachment_data = {
                        feedbackId      : div.find('.attachment_feedback_id').val()
                      , attachments     : remaining
                      , remove_image    : remove_image
                    }

                    $.ajax({
                        type: "POST"
                      , url: "/inbox/update_feedback_attachment"
                      , dataType: "json"
                      , data: attachment_data
                    });
                });
                e.preventDefault();
            })
        }
    }
})

function published_state(obj, sibling_id, msg, state) {
    obj.parents('.dashboard-feedback').css(state.activation_color);
    obj.css(state.activate);
    obj.children('.action-tooltip').children('span').html("Return to Inbox");
    obj.siblings(sibling_id).css(state.deactivate_sibling);
    obj.siblings(sibling_id).children('.action-tooltip').children('span').html(msg);
    obj.siblings(sibling_id).attr('return-policy', 0);
    obj.siblings(sibling_id).attr('data-feed', state.state_change);
    obj.attr('return-policy', 1);
    obj.attr('data-feed', state.state_change_inbox);
}

function hide_the_children(obj) {
    obj.parents('.dashboard-feedback').hide();
    var child_count = obj.parents('.feedback-group').children('.dashboard-feedback:visible');
    if(child_count.length == 0) {
        obj.parents('.feedback-group').hide();
    }

    $(".checky-box-container").show();
}
<commit_msg>dont walk away from meeeee<commit_after>angular.module('feedbackcontrol', [])
.directive('transform', function(FeedbackSignal) {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind('click', function(e) {
                var currentUrl = window.location.pathname;
                var me = $(element);
                var data = FeedbackSignal.data;

                if(currentUrl.match(/published|contacts/g)) {

                    if(me.attr('return-policy') == 1) {
                        hide_the_children(me);
                    }

                    if(data.status != "fileas") {
                        if(data.status == "feature") {
                            var state = {
                                activate: {'background-position': '-64px -31px'}
                              , deactivate_sibling: {'background-position': '-32px 0px'}
                              , activation_color: {'background-color': '#FFFFE0'}
                              , state_change_inbox: '{"status": "inbox", "id": ' + data.id + ', "catid": ' + data.catid + ', "origin": "publish"}'
                              , state_change: '{"status": "publish", "id": ' + data.id + ', "catid": ' + data.catid + ', "origin": "publish"}'
                            }
                            published_state(me, '.publish', 'Publish Feedback', state);
                        }

                        if(data.status == "publish") {
                            var state = {
                                activate: {'background-position': '-32px -31px'}
                              , deactivate_sibling: {'background-position': '-64px 0px'}
                              , activation_color: {'background-color': '#FFF'}
                              , state_change_inbox: '{"status": "inbox", "id": ' + data.id + ', "catid": ' + data.catid + ', "origin": "publish"}'
                              , state_change: '{"status": "feature", "id": ' + data.id + ', "catid": ' + data.catid + ', "origin": "publish"}'
                            }
                            published_state(me, '.feature', 'Feature Feedback', state);
                        }
                    } else {
                        hide_the_children(me);
                    }

                } else if(currentUrl.match(/filed/g)) {

                    var data_status = data.status;

                    if(data_status == "publish" || data_status == "feature" || data_status == "delete") {
                        hide_the_children(me);
                    }

                } else {
                    hide_the_children(me);
                }

                e.preventDefault();
            });
        }
    }
})
.directive('undo', function(FeedbackSignal, FeedbackControlService) {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind("click", function(e) {
                $(".checky-box-container").hide();
                if (FeedbackSignal.data.id instanceof Array) {
                    for(var i=0; i < FeedbackSignal.data.id.length ; i++) {
                        var feedback = $(".dashboard-feedback[feedback=" + FeedbackSignal.data.id[i] + "]");
                        feedback.show();
                        $(feedback).parents('.feedback-group').show();
                    }
                } else {
                    var feedback = $(".dashboard-feedback[feedback=" + FeedbackSignal.data.id + "]");
                    feedback.show();
                    $(feedback).parents('.feedback-group').show();
                }

                if($(".sorter-checkbox").is(":checked")) {
                    $(".sorter-checkbox").click();
                    $(".feed-checkbox").click();
                }

                FeedbackControlService.expunge();
                e.preventDefault();
            });
        }
    }
})
.directive('close', function(FeedbackControlService) {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind("click", function(e) {
                $(".checky-box-container").hide();
                FeedbackControlService.expunge();
                e.preventDefault();
            });
        }
    }
})
.directive('feedcheckbox', function() {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            var checkbox = $(element);

            checkbox.bind('change', function() {
                if(checkbox.is(":checked")) {
                    checkbox.parents('.dashboard-feedback').css({'background-color': '#F7F7F7'});
                } else {
                    checkbox.parents('.dashboard-feedback').css({'background-color': '#FFF'});
                }
            });

        }
    }
})
.directive('statuschange', function(FeedbackService) {
    return {
        restrict: 'A'
      , scope: {
            feedid: "=feedid"
        }
      , link: function(scope, element, attrs) {
            $(element).bind('change', function() {
                FeedbackService.inline_change($(this).val(), scope.feedid, 'status');
            })
        }
    }
})
.directive('prioritychange', function(FeedbackService) {
    return {
        restrict: 'A'
      , scope: {
            feedid: "=feedid"
        }
      , link: function(scope, element, attrs) {
            $(element).bind('change', function() {
                FeedbackService.inline_change($(this).val(), scope.feedid, 'priority');
            })
        }
    }
})
.directive('deleteBlock', function() {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind('click', function(e) {
                $(this).parents('.custom-att').fadeOut(400, function() {
                     var new_uploaded_images = new Array;
                     var new_attached_link;

                     var div = $(this).parents('.uploaded-images-and-links');
                     var images = div.find('.uploaded_image');
                     var media_attachment = div.find('.attached_link');

                     var remove_image = {
                        'small_url'    :$(this).find('.small-image-url').val(),
                        'medium_url'   :$(this).find('.medium-image-url').val(),
                        'large_url'    :$(this).find('.large-image-url').val()
                     }

                    if(images.length > 0){
                        var us = images.not(":hidden");
                        for(var i=0; i < us.length; i++) {
                            new_uploaded_images.push({
                                'name': $(us[i]).find('.image-name').val()
                            });
                        }
                    }

                    if(!media_attachment.is(":hidden")) {
                        new_attached_link = {
                            title           : media_attachment.find('.link-title').val(),
                            description     : media_attachment.find('.link-description').val(),
                            image           : media_attachment.find('.link-image').val(),
                            url             : media_attachment.find('.link-url').val(),
                            video           : media_attachment.find('.link-video').val(),
                        }
                    }

                    var remaining = {
                        uploaded_images : new_uploaded_images
                      , attached_link   : new_attached_link
                    }

                    var attachment_data = {
                        feedbackId      : div.find('.attachment_feedback_id').val()
                      , attachments     : remaining
                      , remove_image    : remove_image
                    }

                    $.ajax({
                        type: "POST"
                      , url: "/inbox/update_feedback_attachment"
                      , dataType: "json"
                      , data: attachment_data
                    });
                });
                e.preventDefault();
            })
        }
    }
})

function published_state(obj, sibling_id, msg, state) {
    obj.parents('.dashboard-feedback').css(state.activation_color);
    obj.css(state.activate);
    obj.children('.action-tooltip').children('span').html("Return to Inbox");
    obj.siblings(sibling_id).css(state.deactivate_sibling);
    obj.siblings(sibling_id).children('.action-tooltip').children('span').html(msg);
    obj.siblings(sibling_id).attr('return-policy', 0);
    obj.siblings(sibling_id).attr('data-feed', state.state_change);
    obj.attr('return-policy', 1);
    obj.attr('data-feed', state.state_change_inbox);
}

function hide_the_children(obj) {
    obj.parents('.dashboard-feedback').hide();
    var child_count = obj.parents('.feedback-group').children('.dashboard-feedback:visible');
    if(child_count.length == 0) {
        obj.parents('.feedback-group').hide();
    }

    $(".checky-box-container").show();
}
<|endoftext|>


<commit_before>/**
 * Created by Matuszewski on 03/02/16.
 */
angular.module('whoWillWinOscars.controllers')
    .controller('IndexController', function(
        $scope,
        $interval,
        $timeout,
        $filter
    ){
      $scope.socket = io.connect('http://localhost:3001', {
        multiplex: false
      });
      $scope.tweets = [];
      $scope.newVal = null;
      $scope.newValNonAgg = null;
      $scope.tweet = null;
      $scope.tweethide = false;
      $scope.initialized = false;
      $scope.tweetCount = {}
      $scope.counters = [];
      $scope.preparedAggregatedData = {};
      $scope.preparedNotAggregatedData = {};

      $scope.movieLabels = {}

      $scope.socket.on("connect", function(socket){
        console.log("client connected to server");
      });

      $scope.socket.on("structure", function(data){
        $scope.$apply(function(){
          $scope.chartConfig = {
            bindto: '#aggregated_chart',
            data: {
              x: 'time',
              xFormat: '%H:%M',
              json: $scope.preparedAggregatedData,
              type: 'spline',
              colors: {}
            },
            tooltip: {
              show: false,
              //contents: function (d, defaultTitleFormat, defaultValueFormat, color) {
              //  return "
Tooltip
"
              //}
            },
            point: {
              show: false
            },
            legend: {
              show: false
            },
            axis:{
              x: {
                type: 'timeseries',
                tick: {
                  format: '%H:%M'
                }
              },
              y: {
                show: false,
                padding: {bottom:10}
              },
              y2: {
                show: true
              }
            }
          }
          var index = 0;
          angular.forEach(data.labels, function(value, key){
            $scope.movieLabels[key] = value;
            $scope.chartConfig['data']['colors'][key] = data.colors[key];
            $scope.preparedAggregatedData[key] = [];
            index = index + 1;
          })
          $scope.preparedAggregatedData['time'] = []
          $scope.preparedNotAggregatedData = angular.copy($scope.preparedAggregatedData);

          /* Generating charts */

          $scope.aggregatedChart = c3.generate($scope.chartConfig);
          $scope.chartConfig['bindto'] = '#not_aggregated_chart';
          $scope.chartConfig['data']['json'] = $scope.preparedNotAggregatedData;
          $scope.chartConfig['data']['xFormat'] = '%H:%M:%S';
          $scope.chartConfig['axis']['x']['tick']['format'] = '%H:%M:%S';
          $scope.nonAggregatedChart = c3.generate($scope.chartConfig);
        })
      })

      $scope.socket.on("disconnect", function(socket){
        console.log("client disconnected from server");
      });

      $scope.socket.on('tweet', function(data){
        $scope.$apply(function(){
          if(!$scope.tweet){
            $scope.tweethide = false;
            $scope.tweet = data;
            $scope.tweet.text = $scope.tweet.text.replace(new RegExp($scope.tweet.movies[0].replace(' ', ''), "ig"),
                ''+$scope.tweet.movies[0]+'')
            $scope.initialized = true;
            $timeout(function(){
              $scope.tweethide = true;
              $timeout(function(){
                $scope.tweet = null;
              }, 1500)
            }, 6000)
          }
        });
      });

      $scope.socket.on('initialize_tweet_aggregated', function(data){
        $scope.prepareChart($scope.aggregatedChart, data, $scope.preparedAggregatedData);
        $scope.counters.length = 0;
        var counter_key = Object.keys(data[0])
        $scope.updateCounters(data[0][counter_key]);
        $scope.updateChart($scope.aggregatedChart, $scope.preparedAggregatedData, 'newVal', true);
      })

      $scope.socket.on('initialize_tweet_not_aggregated', function(data){
        $scope.prepareNonAggChart(data);
        $scope.updateNonAggChart($scope.nonAggregatedChart, $scope.preparedNotAggregatedData, 'newValNonAgg');
      })

      $scope.socket.on('new_tweets_aggregates', function(data){
        $scope.newVal = data;
      })

      $scope.socket.on('new_tweets', function(data){
        $scope.newValNonAgg = data;
      })

      $scope.applyClass = applyClass;
      $scope.applyHighlight = applyHighlight;
      $scope.prepareChart = prepareChart;
      $scope.prepareNonAggChart = prepareNonAggChart
      $scope.updateChart = updateChart;
      $scope.updateNonAggChart = updateNonAggChart;
      $scope.updateCounters = updateCounters;

      function applyHighlight(index){
        return index == 0
      }

      function applyClass(params){
        if(!params){
          return;
        }
        return params.split(' ').join('-').toLowerCase();
      }

      function prepareChart(chart, data, chartData){
        angular.forEach(data, function(value, index){
          var key = Object.keys(value)[0]
          chartData['time'].push(key)
          angular.forEach(value[key], function(val,key){
            chartData[key].push(val);
          })
        })
      }

      function prepareNonAggChart(data){
        var key = Object.keys(data[0])[0]
        angular.forEach(data[0][key], function(value, valkey){
          $scope.preparedNotAggregatedData[valkey].push(value);
        })
        var date = new Date();
        $scope.preparedNotAggregatedData['time'].unshift(d3.time.format("%H:%M:%S")(new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds())));
      }

      function updateChart(chart, chartData, newValListener, updateCounters){
        $interval(function(){
          var date = new Date();
          var current_time =  d3.time.format("%H:%M")(new Date(date.getUTCFullYear(), date.getUTCMonth(),
              date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds()));
          var time = false;
          angular.forEach(chartData['time'], function(value, index){
            if(value == current_time){
              time = true;
            }
          })
          if(!time){
            chartData['time'].unshift(current_time);
            chartData['time'].pop();
            angular.forEach(chartData, function(value, key){
              if(key != 'time'){
                value.pop();
                value.unshift(value[0]);
              }
            });
            chart.load({
              json: chartData
            });
          }
          if($scope[newValListener]){
            var counter_key = Object.keys($scope[newValListener])[0]
            if(updateCounters){
              $scope.counters.length = 0;
              $scope.updateCounters($scope[newValListener][counter_key])
            }
            angular.forEach($scope[newValListener][counter_key], function(newValue, key){
              if(!time){
                chartData[key].unshift(newValue);
                if(chartData[key].length > 60){
                  chartData[key].pop();
                }
              }else{
                chartData[key][0] = newValue;
              }
            })
            chart.load({
              json: chartData
            });
            $scope[newValListener] = null;
          }
        }, 1000)
      }

      function updateNonAggChart(chart, chartData, newValListener){
        $interval(function(){
          var date = new Date();
          chartData['time'].unshift(d3.time.format("%H:%M:%S")(new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds())));
          if(chartData['time'].length > 59){
            chartData['time'].pop();
          }
          angular.forEach(chartData, function(value, key){
            if(key != 'time'){
              value.unshift(0);
              if(value.length > 59){
                value.pop();
              }
            }
          });
          if($scope[newValListener]){
            var counter_key = Object.keys($scope[newValListener])[0]
            angular.forEach($scope[newValListener][counter_key], function(newValue, key){
              chartData[key][0] = newValue;
            })
            $scope[newValListener] = null;
          }
          chart.load({
            json: chartData
          });
        }, 1000);
      }

      function updateCounters(data){
        angular.forEach(data, function(value, key){
          $scope.counters.push({value: value, name: key})
        });
        $scope.counters = $filter('orderBy')($scope.counters, 'value', true);
      }

    })<commit_msg>refs #19386 - Set up of servers - reverted graph  scrolling every second again<commit_after>/**
 * Created by Matuszewski on 03/02/16.
 */
angular.module('whoWillWinOscars.controllers')
    .controller('IndexController', function(
        $scope,
        $interval,
        $timeout,
        $filter
    ){
      $scope.socket = io.connect('http://localhost:3001', {
        multiplex: false
      });
      $scope.tweets = [];
      $scope.newVal = null;
      $scope.newValNonAgg = null;
      $scope.tweet = null;
      $scope.tweethide = false;
      $scope.initialized = false;
      $scope.tweetCount = {}
      $scope.counters = [];
      $scope.preparedAggregatedData = {};
      $scope.preparedNotAggregatedData = {};

      $scope.movieLabels = {}

      $scope.socket.on("connect", function(socket){
        console.log("client connected to server");
      });

      $scope.socket.on("structure", function(data){
        $scope.$apply(function(){
          $scope.chartConfig = {
            bindto: '#aggregated_chart',
            data: {
              x: 'time',
              xFormat: '%H:%M',
              json: $scope.preparedAggregatedData,
              type: 'spline',
              colors: {}
            },
            tooltip: {
              show: false,
              //contents: function (d, defaultTitleFormat, defaultValueFormat, color) {
              //  return "
Tooltip
"
              //}
            },
            point: {
              show: false
            },
            legend: {
              show: false
            },
            axis:{
              x: {
                type: 'timeseries',
                tick: {
                  format: '%H:%M'
                }
              },
              y: {
                show: false,
                padding: {bottom:10}
              },
              y2: {
                show: true
              }
            }
          }
          var index = 0;
          angular.forEach(data.labels, function(value, key){
            $scope.movieLabels[key] = value;
            $scope.chartConfig['data']['colors'][key] = data.colors[key];
            $scope.preparedAggregatedData[key] = [];
            index = index + 1;
          })
          $scope.preparedAggregatedData['time'] = []
          $scope.preparedNotAggregatedData = angular.copy($scope.preparedAggregatedData);

          /* Generating charts */

          $scope.aggregatedChart = c3.generate($scope.chartConfig);
          $scope.chartConfig['bindto'] = '#not_aggregated_chart';
          $scope.chartConfig['data']['json'] = $scope.preparedNotAggregatedData;
          $scope.nonAggregatedChart = c3.generate($scope.chartConfig);
        })
      })

      $scope.socket.on("disconnect", function(socket){
        console.log("client disconnected from server");
      });

      $scope.socket.on('tweet', function(data){
        $scope.$apply(function(){
          if(!$scope.tweet){
            $scope.tweethide = false;
            $scope.tweet = data;
            $scope.tweet.text = $scope.tweet.text.replace(new RegExp($scope.tweet.movies[0].replace(' ', ''), "ig"),
                ''+$scope.tweet.movies[0]+'')
            $scope.initialized = true;
            $timeout(function(){
              $scope.tweethide = true;
              $timeout(function(){
                $scope.tweet = null;
              }, 1500)
            }, 6000)
          }
        });
      });

      $scope.socket.on('initialize_tweet_aggregated', function(data){
        $scope.prepareChart($scope.aggregatedChart, data, $scope.preparedAggregatedData);
        $scope.counters.length = 0;
        var counter_key = Object.keys(data[0])
        $scope.updateCounters(data[0][counter_key]);
        $scope.updateChart($scope.aggregatedChart, $scope.preparedAggregatedData, 'newVal', true);
      })

      $scope.socket.on('initialize_tweet_not_aggregated', function(data){
        $scope.prepareChart($scope.nonAggregatedChart, data, $scope.preparedNotAggregatedData);
        $scope.updateChart($scope.nonAggregatedChart, $scope.preparedNotAggregatedData, 'newValNonAgg', false);
      })

      $scope.socket.on('new_tweets_aggregates', function(data){
        $scope.newVal = data;
      })

      $scope.socket.on('new_tweets', function(data){
        $scope.newValNonAgg = data;
      })

      $scope.applyClass = applyClass;
      $scope.applyHighlight = applyHighlight;
      $scope.prepareChart = prepareChart;
      $scope.updateChart = updateChart;
      $scope.updateCounters = updateCounters;

      function applyHighlight(index){
        return index == 0
      }

      function applyClass(params){
        if(!params){
          return;
        }
        return params.split(' ').join('-').toLowerCase();
      }

      function prepareChart(chart, data, chartData){
        angular.forEach(data, function(value, index){
          var key = Object.keys(value)[0]
          chartData['time'].push(key)
          angular.forEach(value[key], function(val,key){
            chartData[key].push(val);
          })
        })
        chart.load({
          json: chartData
        });
      }

      function updateChart(chart, chartData, newValListener, updateCounters){
        $interval(function(){
          var date = new Date();
          var current_time =  d3.time.format("%H:%M")(new Date(date.getUTCFullYear(), date.getUTCMonth(),
              date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds()));
          var time = false;
          angular.forEach(chartData['time'], function(value, index){
            if(value == current_time){
              time = true;
            }
          })
          if(!time){
            chartData['time'].unshift(current_time);
            chartData['time'].pop();
            angular.forEach(chartData, function(value, key){
              if(key != 'time'){
                value.pop();
                value.unshift(value[0]);
              }
            });
            chart.load({
              json: chartData
            });
          }
          if($scope[newValListener]){
            var counter_key = Object.keys($scope[newValListener])[0]
            if(updateCounters){
              $scope.counters.length = 0;
              $scope.updateCounters($scope[newValListener][counter_key])
            }
            angular.forEach($scope[newValListener][counter_key], function(newValue, key){
              if(!time){
                chartData[key].unshift(newValue);
                if(chartData[key].length > 60){
                  chartData[key].pop();
                }
              }else{
                chartData[key][0] = newValue;
              }
            })
            chart.load({
              json: chartData
            });
            $scope[newValListener] = null;
          }
        }, 1000)
      }

      function updateCounters(data){
        angular.forEach(data, function(value, key){
          $scope.counters.push({value: value, name: key})
        });
        $scope.counters = $filter('orderBy')($scope.counters, 'value', true);
      }

    })<|endoftext|>


<commit_before>/**
 * @module ol/style/RegularShape
 */

import ImageState from '../ImageState.js';
import ImageStyle from './Image.js';
import {asArray} from '../color.js';
import {asColorLike} from '../colorlike.js';
import {createCanvasContext2D} from '../dom.js';
import {
  defaultFillStyle,
  defaultLineCap,
  defaultLineJoin,
  defaultLineWidth,
  defaultMiterLimit,
  defaultStrokeStyle,
} from '../render/canvas.js';

/**
 * Specify radius for regular polygons, or radius1 and radius2 for stars.
 * @typedef {Object} Options
 * @property {import("./Fill.js").default} [fill] Fill style.
 * @property {number} points Number of points for stars and regular polygons. In case of a polygon, the number of points
 * is the number of sides.
 * @property {number} [radius] Radius of a regular polygon.
 * @property {number} [radius1] Outer radius of a star.
 * @property {number} [radius2] Inner radius of a star.
 * @property {number} [angle=0] Shape's angle in radians. A value of 0 will have one of the shape's point facing up.
 * @property {Array<number>} [displacement=[0,0]] Displacement of the shape
 * @property {import("./Stroke.js").default} [stroke] Stroke style.
 * @property {number} [rotation=0] Rotation in radians (positive rotation clockwise).
 * @property {boolean} [rotateWithView=false] Whether to rotate the shape with the view.
 * @property {number|import("../size.js").Size} [scale=1] Scale. Unless two dimensional scaling is required a better
 * result may be obtained with appropriate settings for `radius`, `radius1` and `radius2`.
 */

/**
 * @typedef {Object} RenderOptions
 * @property {import("../colorlike.js").ColorLike} [strokeStyle]
 * @property {number} strokeWidth
 * @property {number} size
 * @property {CanvasLineCap} lineCap
 * @property {Array<number>} lineDash
 * @property {number} lineDashOffset
 * @property {CanvasLineJoin} lineJoin
 * @property {number} miterLimit
 */

/**
 * @classdesc
 * Set regular shape style for vector features. The resulting shape will be
 * a regular polygon when `radius` is provided, or a star when `radius1` and
 * `radius2` are provided.
 * @api
 */
class RegularShape extends ImageStyle {
  /**
   * @param {Options} options Options.
   */
  constructor(options) {
    /**
     * @type {boolean}
     */
    const rotateWithView =
      options.rotateWithView !== undefined ? options.rotateWithView : false;

    super({
      opacity: 1,
      rotateWithView: rotateWithView,
      rotation: options.rotation !== undefined ? options.rotation : 0,
      scale: options.scale !== undefined ? options.scale : 1,
      displacement:
        options.displacement !== undefined ? options.displacement : [0, 0],
    });

    /**
     * @private
     * @type {Object<number, HTMLCanvasElement>}
     */
    this.canvas_ = {};

    /**
     * @private
     * @type {HTMLCanvasElement}
     */
    this.hitDetectionCanvas_ = null;

    /**
     * @private
     * @type {import("./Fill.js").default}
     */
    this.fill_ = options.fill !== undefined ? options.fill : null;

    /**
     * @private
     * @type {Array<number>}
     */
    this.origin_ = [0, 0];

    /**
     * @private
     * @type {number}
     */
    this.points_ = options.points;

    /**
     * @protected
     * @type {number}
     */
    this.radius_ =
      options.radius !== undefined ? options.radius : options.radius1;

    /**
     * @private
     * @type {number|undefined}
     */
    this.radius2_ = options.radius2;

    /**
     * @private
     * @type {number}
     */
    this.angle_ = options.angle !== undefined ? options.angle : 0;

    /**
     * @private
     * @type {import("./Stroke.js").default}
     */
    this.stroke_ = options.stroke !== undefined ? options.stroke : null;

    /**
     * @private
     * @type {Array<number>}
     */
    this.anchor_ = null;

    /**
     * @private
     * @type {import("../size.js").Size}
     */
    this.size_ = null;

    /**
     * @private
     * @type {import("../size.js").Size}
     */
    this.imageSize_ = null;

    /**
     * @private
     * @type {import("../size.js").Size}
     */
    this.hitDetectionImageSize_ = null;

    this.render();
  }

  /**
   * Clones the style.
   * @return {RegularShape} The cloned style.
   * @api
   */
  clone() {
    const scale = this.getScale();
    const style = new RegularShape({
      fill: this.getFill() ? this.getFill().clone() : undefined,
      points: this.getPoints(),
      radius: this.getRadius(),
      radius2: this.getRadius2(),
      angle: this.getAngle(),
      stroke: this.getStroke() ? this.getStroke().clone() : undefined,
      rotation: this.getRotation(),
      rotateWithView: this.getRotateWithView(),
      scale: Array.isArray(scale) ? scale.slice() : scale,
      displacement: this.getDisplacement().slice(),
    });
    style.setOpacity(this.getOpacity());
    return style;
  }

  /**
   * Get the anchor point in pixels. The anchor determines the center point for the
   * symbolizer.
   * @return {Array<number>} Anchor.
   * @api
   */
  getAnchor() {
    return this.anchor_;
  }

  /**
   * Get the angle used in generating the shape.
   * @return {number} Shape's rotation in radians.
   * @api
   */
  getAngle() {
    return this.angle_;
  }

  /**
   * Get the fill style for the shape.
   * @return {import("./Fill.js").default} Fill style.
   * @api
   */
  getFill() {
    return this.fill_;
  }

  /**
   * @return {HTMLCanvasElement} Image element.
   */
  getHitDetectionImage() {
    if (!this.hitDetectionCanvas_) {
      const renderOptions = this.createRenderOptions();

      this.createHitDetectionCanvas_(renderOptions);
    }
    return this.hitDetectionCanvas_;
  }

  /**
   * Get the image icon.
   * @param {number} pixelRatio Pixel ratio.
   * @return {HTMLCanvasElement} Image or Canvas element.
   * @api
   */
  getImage(pixelRatio) {
    if (!this.canvas_[pixelRatio || 1]) {
      const renderOptions = this.createRenderOptions();

      const context = createCanvasContext2D(
        renderOptions.size * pixelRatio || 1,
        renderOptions.size * pixelRatio || 1
      );

      this.draw_(renderOptions, context, 0, 0, pixelRatio || 1);

      this.canvas_[pixelRatio || 1] = context.canvas;
    }
    return this.canvas_[pixelRatio || 1];
  }

  /*
   * Get the image pixel ratio.
   * @param {number} pixelRatio Pixel ratio.
   * */
  getPixelRatio(pixelRatio) {
    return pixelRatio;
  }

  /**
   * @return {import("../size.js").Size} Image size.
   */
  getImageSize() {
    return this.imageSize_;
  }

  /**
   * @return {import("../size.js").Size} Size of the hit-detection image.
   */
  getHitDetectionImageSize() {
    return this.hitDetectionImageSize_;
  }

  /**
   * @return {import("../ImageState.js").default} Image state.
   */
  getImageState() {
    return ImageState.LOADED;
  }

  /**
   * Get the origin of the symbolizer.
   * @return {Array<number>} Origin.
   * @api
   */
  getOrigin() {
    return this.origin_;
  }

  /**
   * Get the number of points for generating the shape.
   * @return {number} Number of points for stars and regular polygons.
   * @api
   */
  getPoints() {
    return this.points_;
  }

  /**
   * Get the (primary) radius for the shape.
   * @return {number} Radius.
   * @api
   */
  getRadius() {
    return this.radius_;
  }

  /**
   * Get the secondary radius for the shape.
   * @return {number|undefined} Radius2.
   * @api
   */
  getRadius2() {
    return this.radius2_;
  }

  /**
   * Get the size of the symbolizer (in pixels).
   * @return {import("../size.js").Size} Size.
   * @api
   */
  getSize() {
    return this.size_;
  }

  /**
   * Get the stroke style for the shape.
   * @return {import("./Stroke.js").default} Stroke style.
   * @api
   */
  getStroke() {
    return this.stroke_;
  }

  /**
   * @param {function(import("../events/Event.js").default): void} listener Listener function.
   */
  listenImageChange(listener) {}

  /**
   * Load not yet loaded URI.
   */
  load() {}

  /**
   * @param {function(import("../events/Event.js").default): void} listener Listener function.
   */
  unlistenImageChange(listener) {}

  /**
   * @returns {RenderOptions}  The render options
   * @protected
   */
  createRenderOptions() {
    let lineCap = defaultLineCap;
    let lineJoin = defaultLineJoin;
    let miterLimit = 0;
    let lineDash = null;
    let lineDashOffset = 0;
    let strokeStyle;
    let strokeWidth = 0;

    if (this.stroke_) {
      strokeStyle = this.stroke_.getColor();
      if (strokeStyle === null) {
        strokeStyle = defaultStrokeStyle;
      }
      strokeStyle = asColorLike(strokeStyle);
      strokeWidth = this.stroke_.getWidth();
      if (strokeWidth === undefined) {
        strokeWidth = defaultLineWidth;
      }
      lineDash = this.stroke_.getLineDash();
      lineDashOffset = this.stroke_.getLineDashOffset();
      lineJoin = this.stroke_.getLineJoin();
      if (lineJoin === undefined) {
        lineJoin = defaultLineJoin;
      }
      lineCap = this.stroke_.getLineCap();
      if (lineCap === undefined) {
        lineCap = defaultLineCap;
      }
      miterLimit = this.stroke_.getMiterLimit();
      if (miterLimit === undefined) {
        miterLimit = defaultMiterLimit;
      }
    }

    const size = 2 * (this.radius_ + strokeWidth) + 1;

    return {
      strokeStyle: strokeStyle,
      strokeWidth: strokeWidth,
      size: size,
      lineCap: lineCap,
      lineDash: lineDash,
      lineDashOffset: lineDashOffset,
      lineJoin: lineJoin,
      miterLimit: miterLimit,
    };
  }

  /**
   * @protected
   */
  render() {
    const renderOptions = this.createRenderOptions();

    const context = createCanvasContext2D(
      renderOptions.size,
      renderOptions.size
    );

    this.draw_(renderOptions, context, 0, 0, 1);

    this.canvas_[1] = context.canvas;

    // canvas.width and height are rounded to the closest integer
    const size = context.canvas.width;
    const imageSize = size;
    const displacement = this.getDisplacement();

    this.hitDetectionImageSize_ = [renderOptions.size, renderOptions.size];
    this.createHitDetectionCanvas_(renderOptions);

    this.anchor_ = [size / 2 - displacement[0], size / 2 + displacement[1]];
    this.size_ = [size, size];
    this.imageSize_ = [imageSize, imageSize];
  }

  /**
   * @private
   * @param {RenderOptions} renderOptions Render options.
   * @param {CanvasRenderingContext2D} context The rendering context.
   * @param {number} x The origin for the symbol (x).
   * @param {number} y The origin for the symbol (y).
   * @param {number} pixelRatio The pixel ratio.
   */
  draw_(renderOptions, context, x, y, pixelRatio) {
    let i, angle0, radiusC;

    // reset transform
    context.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);

    // then move to (x, y)
    context.translate(x, y);

    context.beginPath();

    let points = this.points_;
    if (points === Infinity) {
      context.arc(
        renderOptions.size / 2,
        renderOptions.size / 2,
        this.radius_,
        0,
        2 * Math.PI,
        true
      );
    } else {
      const radius2 =
        this.radius2_ !== undefined ? this.radius2_ : this.radius_;
      if (radius2 !== this.radius_) {
        points = 2 * points;
      }
      for (i = 0; i <= points; i++) {
        angle0 = (i * 2 * Math.PI) / points - Math.PI / 2 + this.angle_;
        radiusC = i % 2 === 0 ? this.radius_ : radius2;
        context.lineTo(
          renderOptions.size / 2 + radiusC * Math.cos(angle0),
          renderOptions.size / 2 + radiusC * Math.sin(angle0)
        );
      }
    }

    if (this.fill_) {
      let color = this.fill_.getColor();
      if (color === null) {
        color = defaultFillStyle;
      }
      context.fillStyle = asColorLike(color);
      context.fill();
    }
    if (this.stroke_) {
      context.strokeStyle = renderOptions.strokeStyle;
      context.lineWidth = renderOptions.strokeWidth;
      if (context.setLineDash && renderOptions.lineDash) {
        context.setLineDash(renderOptions.lineDash);
        context.lineDashOffset = renderOptions.lineDashOffset;
      }
      context.lineCap = renderOptions.lineCap;
      context.lineJoin = renderOptions.lineJoin;
      context.miterLimit = renderOptions.miterLimit;
      context.stroke();
    }
    context.closePath();
  }

  /**
   * @private
   * @param {RenderOptions} renderOptions Render options.
   */
  createHitDetectionCanvas_(renderOptions) {
    this.hitDetectionCanvas_ = this.getImage(1);
    if (this.fill_) {
      let color = this.fill_.getColor();

      // determine if fill is transparent (or pattern or gradient)
      let opacity = 0;
      if (typeof color === 'string') {
        color = asArray(color);
      }
      if (color === null) {
        opacity = 1;
      } else if (Array.isArray(color)) {
        opacity = color.length === 4 ? color[3] : 1;
      }
      if (opacity === 0) {
        // if a transparent fill style is set, create an extra hit-detection image
        // with a default fill style
        const context = createCanvasContext2D(
          renderOptions.size,
          renderOptions.size
        );
        this.hitDetectionCanvas_ = context.canvas;

        this.drawHitDetectionCanvas_(renderOptions, context, 0, 0);
      }
    }
  }

  /**
   * @private
   * @param {RenderOptions} renderOptions Render options.
   * @param {CanvasRenderingContext2D} context The context.
   * @param {number} x The origin for the symbol (x).
   * @param {number} y The origin for the symbol (y).
   */
  drawHitDetectionCanvas_(renderOptions, context, x, y) {
    // move to (x, y)
    context.translate(x, y);

    context.beginPath();

    let points = this.points_;
    if (points === Infinity) {
      context.arc(
        renderOptions.size / 2,
        renderOptions.size / 2,
        this.radius_,
        0,
        2 * Math.PI,
        true
      );
    } else {
      const radius2 =
        this.radius2_ !== undefined ? this.radius2_ : this.radius_;
      if (radius2 !== this.radius_) {
        points = 2 * points;
      }
      let i, radiusC, angle0;
      for (i = 0; i <= points; i++) {
        angle0 = (i * 2 * Math.PI) / points - Math.PI / 2 + this.angle_;
        radiusC = i % 2 === 0 ? this.radius_ : radius2;
        context.lineTo(
          renderOptions.size / 2 + radiusC * Math.cos(angle0),
          renderOptions.size / 2 + radiusC * Math.sin(angle0)
        );
      }
    }

    context.fillStyle = defaultFillStyle;
    context.fill();
    if (this.stroke_) {
      context.strokeStyle = renderOptions.strokeStyle;
      context.lineWidth = renderOptions.strokeWidth;
      if (renderOptions.lineDash) {
        context.setLineDash(renderOptions.lineDash);
        context.lineDashOffset = renderOptions.lineDashOffset;
      }
      context.stroke();
    }
    context.closePath();
  }
}

export default RegularShape;
<commit_msg>Clear this.canvas_ whenever render() is called<commit_after>/**
 * @module ol/style/RegularShape
 */

import ImageState from '../ImageState.js';
import ImageStyle from './Image.js';
import {asArray} from '../color.js';
import {asColorLike} from '../colorlike.js';
import {createCanvasContext2D} from '../dom.js';
import {
  defaultFillStyle,
  defaultLineCap,
  defaultLineJoin,
  defaultLineWidth,
  defaultMiterLimit,
  defaultStrokeStyle,
} from '../render/canvas.js';

/**
 * Specify radius for regular polygons, or radius1 and radius2 for stars.
 * @typedef {Object} Options
 * @property {import("./Fill.js").default} [fill] Fill style.
 * @property {number} points Number of points for stars and regular polygons. In case of a polygon, the number of points
 * is the number of sides.
 * @property {number} [radius] Radius of a regular polygon.
 * @property {number} [radius1] Outer radius of a star.
 * @property {number} [radius2] Inner radius of a star.
 * @property {number} [angle=0] Shape's angle in radians. A value of 0 will have one of the shape's point facing up.
 * @property {Array<number>} [displacement=[0,0]] Displacement of the shape
 * @property {import("./Stroke.js").default} [stroke] Stroke style.
 * @property {number} [rotation=0] Rotation in radians (positive rotation clockwise).
 * @property {boolean} [rotateWithView=false] Whether to rotate the shape with the view.
 * @property {number|import("../size.js").Size} [scale=1] Scale. Unless two dimensional scaling is required a better
 * result may be obtained with appropriate settings for `radius`, `radius1` and `radius2`.
 */

/**
 * @typedef {Object} RenderOptions
 * @property {import("../colorlike.js").ColorLike} [strokeStyle]
 * @property {number} strokeWidth
 * @property {number} size
 * @property {CanvasLineCap} lineCap
 * @property {Array<number>} lineDash
 * @property {number} lineDashOffset
 * @property {CanvasLineJoin} lineJoin
 * @property {number} miterLimit
 */

/**
 * @classdesc
 * Set regular shape style for vector features. The resulting shape will be
 * a regular polygon when `radius` is provided, or a star when `radius1` and
 * `radius2` are provided.
 * @api
 */
class RegularShape extends ImageStyle {
  /**
   * @param {Options} options Options.
   */
  constructor(options) {
    /**
     * @type {boolean}
     */
    const rotateWithView =
      options.rotateWithView !== undefined ? options.rotateWithView : false;

    super({
      opacity: 1,
      rotateWithView: rotateWithView,
      rotation: options.rotation !== undefined ? options.rotation : 0,
      scale: options.scale !== undefined ? options.scale : 1,
      displacement:
        options.displacement !== undefined ? options.displacement : [0, 0],
    });

    /**
     * @private
     * @type {Object<number, HTMLCanvasElement>}
     */
    this.canvas_ = {};

    /**
     * @private
     * @type {HTMLCanvasElement}
     */
    this.hitDetectionCanvas_ = null;

    /**
     * @private
     * @type {import("./Fill.js").default}
     */
    this.fill_ = options.fill !== undefined ? options.fill : null;

    /**
     * @private
     * @type {Array<number>}
     */
    this.origin_ = [0, 0];

    /**
     * @private
     * @type {number}
     */
    this.points_ = options.points;

    /**
     * @protected
     * @type {number}
     */
    this.radius_ =
      options.radius !== undefined ? options.radius : options.radius1;

    /**
     * @private
     * @type {number|undefined}
     */
    this.radius2_ = options.radius2;

    /**
     * @private
     * @type {number}
     */
    this.angle_ = options.angle !== undefined ? options.angle : 0;

    /**
     * @private
     * @type {import("./Stroke.js").default}
     */
    this.stroke_ = options.stroke !== undefined ? options.stroke : null;

    /**
     * @private
     * @type {Array<number>}
     */
    this.anchor_ = null;

    /**
     * @private
     * @type {import("../size.js").Size}
     */
    this.size_ = null;

    /**
     * @private
     * @type {import("../size.js").Size}
     */
    this.imageSize_ = null;

    /**
     * @private
     * @type {import("../size.js").Size}
     */
    this.hitDetectionImageSize_ = null;

    this.render();
  }

  /**
   * Clones the style.
   * @return {RegularShape} The cloned style.
   * @api
   */
  clone() {
    const scale = this.getScale();
    const style = new RegularShape({
      fill: this.getFill() ? this.getFill().clone() : undefined,
      points: this.getPoints(),
      radius: this.getRadius(),
      radius2: this.getRadius2(),
      angle: this.getAngle(),
      stroke: this.getStroke() ? this.getStroke().clone() : undefined,
      rotation: this.getRotation(),
      rotateWithView: this.getRotateWithView(),
      scale: Array.isArray(scale) ? scale.slice() : scale,
      displacement: this.getDisplacement().slice(),
    });
    style.setOpacity(this.getOpacity());
    return style;
  }

  /**
   * Get the anchor point in pixels. The anchor determines the center point for the
   * symbolizer.
   * @return {Array<number>} Anchor.
   * @api
   */
  getAnchor() {
    return this.anchor_;
  }

  /**
   * Get the angle used in generating the shape.
   * @return {number} Shape's rotation in radians.
   * @api
   */
  getAngle() {
    return this.angle_;
  }

  /**
   * Get the fill style for the shape.
   * @return {import("./Fill.js").default} Fill style.
   * @api
   */
  getFill() {
    return this.fill_;
  }

  /**
   * @return {HTMLCanvasElement} Image element.
   */
  getHitDetectionImage() {
    if (!this.hitDetectionCanvas_) {
      const renderOptions = this.createRenderOptions();

      this.createHitDetectionCanvas_(renderOptions);
    }
    return this.hitDetectionCanvas_;
  }

  /**
   * Get the image icon.
   * @param {number} pixelRatio Pixel ratio.
   * @return {HTMLCanvasElement} Image or Canvas element.
   * @api
   */
  getImage(pixelRatio) {
    if (!this.canvas_[pixelRatio || 1]) {
      const renderOptions = this.createRenderOptions();

      const context = createCanvasContext2D(
        renderOptions.size * pixelRatio || 1,
        renderOptions.size * pixelRatio || 1
      );

      this.draw_(renderOptions, context, 0, 0, pixelRatio || 1);

      this.canvas_[pixelRatio || 1] = context.canvas;
    }
    return this.canvas_[pixelRatio || 1];
  }

  /*
   * Get the image pixel ratio.
   * @param {number} pixelRatio Pixel ratio.
   * */
  getPixelRatio(pixelRatio) {
    return pixelRatio;
  }

  /**
   * @return {import("../size.js").Size} Image size.
   */
  getImageSize() {
    return this.imageSize_;
  }

  /**
   * @return {import("../size.js").Size} Size of the hit-detection image.
   */
  getHitDetectionImageSize() {
    return this.hitDetectionImageSize_;
  }

  /**
   * @return {import("../ImageState.js").default} Image state.
   */
  getImageState() {
    return ImageState.LOADED;
  }

  /**
   * Get the origin of the symbolizer.
   * @return {Array<number>} Origin.
   * @api
   */
  getOrigin() {
    return this.origin_;
  }

  /**
   * Get the number of points for generating the shape.
   * @return {number} Number of points for stars and regular polygons.
   * @api
   */
  getPoints() {
    return this.points_;
  }

  /**
   * Get the (primary) radius for the shape.
   * @return {number} Radius.
   * @api
   */
  getRadius() {
    return this.radius_;
  }

  /**
   * Get the secondary radius for the shape.
   * @return {number|undefined} Radius2.
   * @api
   */
  getRadius2() {
    return this.radius2_;
  }

  /**
   * Get the size of the symbolizer (in pixels).
   * @return {import("../size.js").Size} Size.
   * @api
   */
  getSize() {
    return this.size_;
  }

  /**
   * Get the stroke style for the shape.
   * @return {import("./Stroke.js").default} Stroke style.
   * @api
   */
  getStroke() {
    return this.stroke_;
  }

  /**
   * @param {function(import("../events/Event.js").default): void} listener Listener function.
   */
  listenImageChange(listener) {}

  /**
   * Load not yet loaded URI.
   */
  load() {}

  /**
   * @param {function(import("../events/Event.js").default): void} listener Listener function.
   */
  unlistenImageChange(listener) {}

  /**
   * @returns {RenderOptions}  The render options
   * @protected
   */
  createRenderOptions() {
    let lineCap = defaultLineCap;
    let lineJoin = defaultLineJoin;
    let miterLimit = 0;
    let lineDash = null;
    let lineDashOffset = 0;
    let strokeStyle;
    let strokeWidth = 0;

    if (this.stroke_) {
      strokeStyle = this.stroke_.getColor();
      if (strokeStyle === null) {
        strokeStyle = defaultStrokeStyle;
      }
      strokeStyle = asColorLike(strokeStyle);
      strokeWidth = this.stroke_.getWidth();
      if (strokeWidth === undefined) {
        strokeWidth = defaultLineWidth;
      }
      lineDash = this.stroke_.getLineDash();
      lineDashOffset = this.stroke_.getLineDashOffset();
      lineJoin = this.stroke_.getLineJoin();
      if (lineJoin === undefined) {
        lineJoin = defaultLineJoin;
      }
      lineCap = this.stroke_.getLineCap();
      if (lineCap === undefined) {
        lineCap = defaultLineCap;
      }
      miterLimit = this.stroke_.getMiterLimit();
      if (miterLimit === undefined) {
        miterLimit = defaultMiterLimit;
      }
    }

    const size = 2 * (this.radius_ + strokeWidth) + 1;

    return {
      strokeStyle: strokeStyle,
      strokeWidth: strokeWidth,
      size: size,
      lineCap: lineCap,
      lineDash: lineDash,
      lineDashOffset: lineDashOffset,
      lineJoin: lineJoin,
      miterLimit: miterLimit,
    };
  }

  /**
   * @protected
   */
  render() {
    const renderOptions = this.createRenderOptions();

    const context = createCanvasContext2D(
      renderOptions.size,
      renderOptions.size
    );

    this.draw_(renderOptions, context, 0, 0, 1);

    this.canvas_ = {};
    this.canvas_[1] = context.canvas;

    // canvas.width and height are rounded to the closest integer
    const size = context.canvas.width;
    const imageSize = size;
    const displacement = this.getDisplacement();

    this.hitDetectionImageSize_ = [renderOptions.size, renderOptions.size];
    this.createHitDetectionCanvas_(renderOptions);

    this.anchor_ = [size / 2 - displacement[0], size / 2 + displacement[1]];
    this.size_ = [size, size];
    this.imageSize_ = [imageSize, imageSize];
  }

  /**
   * @private
   * @param {RenderOptions} renderOptions Render options.
   * @param {CanvasRenderingContext2D} context The rendering context.
   * @param {number} x The origin for the symbol (x).
   * @param {number} y The origin for the symbol (y).
   * @param {number} pixelRatio The pixel ratio.
   */
  draw_(renderOptions, context, x, y, pixelRatio) {
    let i, angle0, radiusC;

    // reset transform
    context.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);

    // then move to (x, y)
    context.translate(x, y);

    context.beginPath();

    let points = this.points_;
    if (points === Infinity) {
      context.arc(
        renderOptions.size / 2,
        renderOptions.size / 2,
        this.radius_,
        0,
        2 * Math.PI,
        true
      );
    } else {
      const radius2 =
        this.radius2_ !== undefined ? this.radius2_ : this.radius_;
      if (radius2 !== this.radius_) {
        points = 2 * points;
      }
      for (i = 0; i <= points; i++) {
        angle0 = (i * 2 * Math.PI) / points - Math.PI / 2 + this.angle_;
        radiusC = i % 2 === 0 ? this.radius_ : radius2;
        context.lineTo(
          renderOptions.size / 2 + radiusC * Math.cos(angle0),
          renderOptions.size / 2 + radiusC * Math.sin(angle0)
        );
      }
    }

    if (this.fill_) {
      let color = this.fill_.getColor();
      if (color === null) {
        color = defaultFillStyle;
      }
      context.fillStyle = asColorLike(color);
      context.fill();
    }
    if (this.stroke_) {
      context.strokeStyle = renderOptions.strokeStyle;
      context.lineWidth = renderOptions.strokeWidth;
      if (context.setLineDash && renderOptions.lineDash) {
        context.setLineDash(renderOptions.lineDash);
        context.lineDashOffset = renderOptions.lineDashOffset;
      }
      context.lineCap = renderOptions.lineCap;
      context.lineJoin = renderOptions.lineJoin;
      context.miterLimit = renderOptions.miterLimit;
      context.stroke();
    }
    context.closePath();
  }

  /**
   * @private
   * @param {RenderOptions} renderOptions Render options.
   */
  createHitDetectionCanvas_(renderOptions) {
    this.hitDetectionCanvas_ = this.getImage(1);
    if (this.fill_) {
      let color = this.fill_.getColor();

      // determine if fill is transparent (or pattern or gradient)
      let opacity = 0;
      if (typeof color === 'string') {
        color = asArray(color);
      }
      if (color === null) {
        opacity = 1;
      } else if (Array.isArray(color)) {
        opacity = color.length === 4 ? color[3] : 1;
      }
      if (opacity === 0) {
        // if a transparent fill style is set, create an extra hit-detection image
        // with a default fill style
        const context = createCanvasContext2D(
          renderOptions.size,
          renderOptions.size
        );
        this.hitDetectionCanvas_ = context.canvas;

        this.drawHitDetectionCanvas_(renderOptions, context, 0, 0);
      }
    }
  }

  /**
   * @private
   * @param {RenderOptions} renderOptions Render options.
   * @param {CanvasRenderingContext2D} context The context.
   * @param {number} x The origin for the symbol (x).
   * @param {number} y The origin for the symbol (y).
   */
  drawHitDetectionCanvas_(renderOptions, context, x, y) {
    // move to (x, y)
    context.translate(x, y);

    context.beginPath();

    let points = this.points_;
    if (points === Infinity) {
      context.arc(
        renderOptions.size / 2,
        renderOptions.size / 2,
        this.radius_,
        0,
        2 * Math.PI,
        true
      );
    } else {
      const radius2 =
        this.radius2_ !== undefined ? this.radius2_ : this.radius_;
      if (radius2 !== this.radius_) {
        points = 2 * points;
      }
      let i, radiusC, angle0;
      for (i = 0; i <= points; i++) {
        angle0 = (i * 2 * Math.PI) / points - Math.PI / 2 + this.angle_;
        radiusC = i % 2 === 0 ? this.radius_ : radius2;
        context.lineTo(
          renderOptions.size / 2 + radiusC * Math.cos(angle0),
          renderOptions.size / 2 + radiusC * Math.sin(angle0)
        );
      }
    }

    context.fillStyle = defaultFillStyle;
    context.fill();
    if (this.stroke_) {
      context.strokeStyle = renderOptions.strokeStyle;
      context.lineWidth = renderOptions.strokeWidth;
      if (renderOptions.lineDash) {
        context.setLineDash(renderOptions.lineDash);
        context.lineDashOffset = renderOptions.lineDashOffset;
      }
      context.stroke();
    }
    context.closePath();
  }
}

export default RegularShape;
<|endoftext|>