Diferencia entre revisiones de «MediaWiki:Filtros.js»

De Diccionario Interactivo Ceán Bermúdez
Ir a la navegación Ir a la búsqueda
Línea 84: Línea 84:
 
  }
 
  }
 
});
 
});
 +
 +
// Ponemos número de búsquedas:
 +
for (var lt in abbrsLetters) {
 +
var lnum = abbrsLetters[lt];
 +
console.log(lt + ">" + lnum)
 +
}
 
 
 
   }
 
   }

Revisión del 08:39 11 mar 2021

jQuery(document).ready(function($){
	
	function listFilter(input, list) { 
    var sc = true;
    $(input)
      .change( function () {
        var filter = $(this).val();        
        if(filter) {
          $(list).find("li:not(:Contains(" + filter + "))").slideUp(function(){
              if($(this).closest('.mw-category-group').find('li:visible').length == 0){ 
                if($(this).closest('.mw-category-group').is(':visible')) { 
                  $(this).closest('.mw-category-group').slideUp();                
                }
              } else {
                if(!$(this).closest('.mw-category-group').is(':visible')) {
                  $(this).closest('.mw-category-group').slideDown();
                }
              }            
          });

          $(list).find("li:Contains(" + filter + ")").slideDown(function(){
            if(!$(this).closest('.mw-category-group').is(':visible')) {
              $(this).closest('.mw-category-group').slideDown();            
            }
          });
          
          
        } else {
          $(list).find("li").slideDown();
          $('.mw-category-group').slideDown();
        }
        return false;
      })
    .keyup( function () { 
        $(this).change();
         if(sc) {$("html, body").animate({ scrollTop: $(".filtro").offset().top - 80 }, 500);sc=false;}
    });
  }
  
  if($('.mw-category').length > 0){
  	var filtro = $('<div class="filtro"><img src="/skins/Vector/images/search.png?39f97"><input type="text" id="filtro" /></div>');
  	$('.mw-category').prepend(filtro);
	listFilter($('#filtro'),$('.mw-category '));	
  }
  
  if($('#listwidget-1-nav').length > 0){
  	var filtro = $('<div class="filtro"><img src="/skins/Vector/images/search.png?39f97"><input type="text" class="createboxInput" id="filtro" /></div>');
  	$('#listwidget-1-nav').append(filtro);
  	
  	var abbrs = {};
	$("ul#listwidget-1 li a").each(function (i) {
		var letter1 = this.firstChild.nodeValue.toLowerCase().trim();
	    abbrs[letter1] = this;
	});
	var abbrsLetters = {};
	$(".ln-letters a").each(function (i) {
		var letter =  this.firstChild.nodeValue.toLowerCase().trim();
		letter = letter.replace("-", "");
		if(letter == "09") letter="_";
		if(letter == "...") letter="-"; 
		console.log("#listwidget-1 li.ln-" + letter)
	    abbrsLetters[letter] = $("#listwidget-1 li.ln-" + letter ).length;
	});
	console.log(abbrsLetters)
	
	$("#filtro").on("keyup", function() {
	  var filterBy = this.value.toLowerCase().trim();
	  if(filterBy.length > 3){
		for (var abbr in abbrs) {
			var li = abbrs[abbr];
		    if (abbr.indexOf(filterBy) !== -1) {
		        $(li).parent().parent().parent().show()
		        console.log(li)
		        // show li
		    }else{
		    	$(li).parent().parent().parent().hide()
		    }
		}
	  }else{
	  	for (var abbr in abbrs) {
			var li = abbrs[abbr];
	        $(li).parent().parent().parent().show()
		}
	  }
	});	
	
	// Ponemos número de búsquedas:
	for (var lt in abbrsLetters) {
		var lnum = abbrsLetters[lt];
		console.log(lt + ">" + lnum)
	}
	
  }
  
});

// Control de parámetros para búsqueda resaltada
	var paramresalte = "find";
	//Recuperamos parámetros
	var get_params = function(search_string) {
	
	    var parse = function(params, pairs) {
	      var pair = pairs[0];
	      var parts = pair.split('=');
	      var key = decodeURIComponent(parts[0]);
	      var value = decodeURIComponent(parts.slice(1).join('='));
	  
	      // Handle multiple parameters of the same name
	      if (typeof params[key] === "undefined") {
	        params[key] = value;
	      } else {
	        params[key] = [].concat(params[key], value);
	      }
	  
	      return pairs.length == 1 ? params : parse(params, pairs.slice(1))
	    }
	  
	    // Get rid of leading ?
	    return search_string.length == 0 ? {} : parse({}, search_string.substr(1).split('&'));
	  }

	var params = get_params(location.search);
	if(params["search"]){
		document.querySelectorAll(".mw-search-result-heading a").forEach(a => {
            a.href = a.href + "?"+paramresalte+"="+params["search"];
        });
	}
	
	
	var InstantSearch = {

    "highlight": function (container, highlightText)
    {
        var internalHighlighter = function (options)
        {

            var id = {
                container: "container",
                tokens: "tokens",
                all: "all",
                token: "token",
                className: "className",
                sensitiveSearch: "sensitiveSearch"
            },
            tokens = options[id.tokens],
            allClassName = options[id.all][id.className],
            allSensitiveSearch = options[id.all][id.sensitiveSearch];


            function checkAndReplace(node, tokenArr, classNameAll, sensitiveSearchAll)
            {
                var nodeVal = node.nodeValue, parentNode = node.parentNode,
                    i, j, curToken, myToken, myClassName, mySensitiveSearch,
                    finalClassName, finalSensitiveSearch,
                    foundIndex, begin, matched, end,
                    textNode, span, isFirst;

                for (i = 0, j = tokenArr.length; i < j; i++)
                {
                    curToken = tokenArr[i];
                    myToken = curToken[id.token];
                    myClassName = curToken[id.className];
                    mySensitiveSearch = curToken[id.sensitiveSearch];

                    finalClassName = (classNameAll ? myClassName + " " + classNameAll : myClassName);

                    finalSensitiveSearch = (typeof sensitiveSearchAll !== "undefined" ? sensitiveSearchAll : mySensitiveSearch);

                    isFirst = true;
                    while (true)
                    {
                        if (finalSensitiveSearch)
                            foundIndex = nodeVal.indexOf(myToken);
                        else
                            foundIndex = nodeVal.toLowerCase().indexOf(myToken.toLowerCase());

                        if (foundIndex < 0)
                        {
                            if (isFirst)
                                break;

                            if (nodeVal)
                            {
                                textNode = document.createTextNode(nodeVal);
                                parentNode.insertBefore(textNode, node);
                            } // End if (nodeVal)

                            parentNode.removeChild(node);
                            break;
                        } // End if (foundIndex < 0)

                        isFirst = false;


                        begin = nodeVal.substring(0, foundIndex);
                        matched = nodeVal.substr(foundIndex, myToken.length);

                        if (begin)
                        {
                            textNode = document.createTextNode(begin);
                            parentNode.insertBefore(textNode, node);
                        } // End if (begin)

                        span = document.createElement("span");
                        span.className += finalClassName;
                        span.appendChild(document.createTextNode(matched));
                        parentNode.insertBefore(span, node);

                        nodeVal = nodeVal.substring(foundIndex + myToken.length);
                    } // Whend

                } // Next i 
            }; // End Function checkAndReplace 

            function iterator(p)
            {
                if (p === null) return;

                var children = Array.prototype.slice.call(p.childNodes), i, cur;

                if (children.length)
                {
                    for (i = 0; i < children.length; i++)
                    {
                        cur = children[i];
                        if (cur.nodeType === 3)
                        {
                            checkAndReplace(cur, tokens, allClassName, allSensitiveSearch);
                        }
                        else if (cur.nodeType === 1)
                        {
                            iterator(cur);
                        }
                    }
                }
            }; // End Function iterator

            iterator(options[id.container]);
        } // End Function highlighter
        ;


        internalHighlighter(
            {
                container: container
                , all:
                    {
                        className: "highlighter"
                    }
                , tokens: [
                    {
                        token: highlightText
                        , className: "highlight"
                        , sensitiveSearch: false
                    }
                ]
            }
        ); // End Call internalHighlighter 

    } // End Function highlight

};
	
	
	if(params[paramresalte]){
		var container = document.getElementById("mw-content-text");
		var findWord = params[paramresalte];
		findWord = findWord.replace(",", "");
		const regex = /(?<=")[^"]+(?=")/;
		var find1 = findWord.match(regex);
		console.log(find1);
		if(find1!=null){
			findWord = find1[0].replace("+", " ");
		}
		var findWordArr =  findWord.split("+");
		//$('html,body').animate({scrollTop:( )},1000,function(){});
		findWordArr.forEach(a => {
            InstantSearch.highlight(container, a);
        });
    	
	}
	
	$("#footer-info-lastmod").append(" El Diccionario interactivo de Ceán Bermúdez está subvencionado por la Dirección General de Bibliotecas, Archivos y Museos (Área de Gobierno de Cultura, Turismo y Deporte) del Ayuntamiento de Madrid con cargo a los presupuestos municipales del año 2020")