search.js

来自「Hippo CMS是一个以信息为中心的开源内容管理系统。Hippo CMS目标是」· JavaScript 代码 · 共 427 行

JS
427
字号
/*
* Copyright 2001-2007 Hippo (www.hippo.nl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var batchOperationResult = '';

var Dialog = new Object();

Dialog._arguments={};
Dialog._return = function(val){ 
 if (this._dialogType == 'property') 
   fireEvent('afterPropertyEdit');
 this._dialogType = '';
}

var latestAjaxResponse = null;

var pickerWrapper = new Object();
pickerWrapper.locked=false;
pickerWrapper.reference=null;
function choose(){
  pickerWrapper.reference.choose(arguments);
}

function searchCallback(event, params) 
{
  var found=false;
  var url='';
  for(var i=0; i<params.length; i++)
  {
    if(params[i].key=='url')
    {
      url = params[i].val;
    }
    else if(params[i].key=='standardUIAction' && params[i].val=='hippo.cms.save')
    {
      found=true;      
    }    
  }
  if(found)
  {
    var options = {
      method: 'post',
      onSuccess: function(t) {
        if(t.responseText.indexOf('true')>-1)
        { 
          window.top.window.frames['topframe'].Application.sm.lookup('framework.eventmanager').fireEvent(event, params);
        }
        else
        {
          alert(t.responseText);
        }        
      },
      // Handle 404
      on404: function(t) {
          alert('Error 404: location "' + t.statusText + '" was not found.');
      },
      // Handle other errors
      onFailure: function(t) {
          alert('Error ' + t.status + ' -- ' + t.statusText + t.responseText);
      }    
    };
    new Ajax.Request('/actions/editFromSearch'+url, options);
  }
  else
  {
    window.top.window.frames['topframe'].Application.sm.lookup('framework.eventmanager').fireEvent(event, params);
  }
  
}


function changeFormElementsAndSend(formId,elements){
  var formElement;
  var error = false;
  var i;
  
  for (i=0; i< elements.length; i++){
    formElement=elements[i];
    if (document.forms[formId] != null &&
          document.forms[formId].elements[formElement.name] != null)  
       document.forms[formId].elements[formElement.name].value=formElement.value;
    else{
      error=true;
      break;
    }
  }
  if (!error) doSearch(formId);
}


function reportSourcePick(linkedField,captionField, captionInputField, defaultValue,callback){
  var el = document.getElementById(linkedField);
  var captionEl = document.getElementById(captionField);
  var captionInpEl = document.getElementById(captionInputField);
  if (el != null){    
    var initValue=(el.value=='')?defaultValue:el.value;
    var myPicker = new ResourcePopup2('/search/scope-picker'+initValue+'?type=collection');
    var fn = function(values){
      el.value=values.uri;
      if (captionEl != null) captionEl.innerHTML=values.caption;  
      if (captionInpEl != null) captionInpEl.value=values.caption;  
    }  
    myPicker.select(fn);
  } else {
     alert('Non existing field: '+linkedField);
  }
}

function trimAll(sString)
{
  while (sString.substring(0,1) == ' ')
  {
    sString = sString.substring(1, sString.length);
  }
  while (sString.substring(sString.length-1, sString.length) == ' ')
  {
    sString = sString.substring(0,sString.length-1);
  }
  return sString;
}

function simpleTextSearch(reportID, inputID){
  var el= document.getElementById(inputID);
  if (el != null && el.value != ''){
    var val = trimAll(el.value);
    if (val != ''){
      fireEvent('doSearch',
             [{'key':'reportID','val':reportID},
              {'key':'value','val':val}]);    
    }
  }
}
function reportError(req){
  //alert('Sorry, an error occurred.');
}
function getCallback(obj){

  return function(req){
    obj.callback(req);
  }
  
}

function evalResponseHandler(req){
  eval(req.responseText);
}

var Updater = Class.create();

Updater.prototype = {
  initialize: function(responseHandler, element, targetElement, requestTo, params){
    this.responseHandler = responseHandler;
    this.element=element;
    this.targetElement=targetElement;
    this.requestTo=requestTo;
    this.params=params;
    new Form.Element.EventObserver(element, getCallback(this));
  },
  callback: function(req){ 
    var reqStr='keyValue='+$F(this.element)+'&target='+this.targetElement;
    var i;
    for (i=0; i<this.params.length; i++){
      reqStr+='&'+this.params[i].key+'='+this.params[i].val;
    }
    var myAjax = new Ajax.Request(
      this.requestTo, 
      {
        method: 'get', 
        parameters: reqStr,
        onComplete: this.responseHandler
      });       
  },
  reportError: function(req){
    alert('An error occurred!');
  }
}; 

function doSearch(formId){
  setSearchStatus('search.loading');
  var values = Form.getElements(document.getElementById(formId));
  var params = array2KeyValues(values);
  searchCallback('doSearch2',params);
}

function serialize(arr){
  var i;
  var kvp = new Array();
  var tmp;
  var s = '';
  for (i=0; i< arr.length; i++){
    tmp = Form.Element.getValue(arr[i]);
    s+=(s==''?'?':'&')+arr[i][0]+'='+arr[i][1];
  }
  return s;
}

function array2KeyValues( arr ){
  var i;
  var kvp = new Array();
  var tmp;
  for (i=0; i< arr.length; i++){
    tmp = Form.Element.getValue(arr[i]);
    if (typeof tmp != 'undefined')
      kvp.push({key:arr[i].name,val:tmp});
  }
  return kvp;
}

function onEnterPressedDoSearch(event,formId){
  if (typeof event == 'object' && typeof formId == 'string'){
    var code;
    if (event.keyCode) code = event.keyCode;
      else 
    if (event.which) code = event.which;

    if (code == 13 && !event.altKey && !event.ctrlKey)
      doSearch(formId);
  }            
}

function i18n_translate(arr){
  var res='';
  var i;
  for (i=0; i< arr.length; i++)
    res+=(typeof i18n[arr[i]] != 'undefined')?i18n[arr[i]]:arr[i];
  return res;
}

function setSummary(summary_arr){
  var summary = i18n_translate(summary_arr);
  try{
    var summarySpan = window.top.frames["topframe"].document.getElementById('search_result_summary');
    summarySpan.innerHTML=summary;
  } catch(e){
  }
}

function setExtendedSummary(extended_summary){
  try{
    var extendedSummarySpan = window.top.frames["topframe"].document.getElementById('search_result_extended_summary');
    extendedSummarySpan.innerHTML=extended_summary;
  } catch(e){
  }
}

function setSearchStatus(message){
  var searchStatusDiv = document.getElementById('searchStatus');
  if (typeof i18n[message] != 'undefined')
    searchStatusDiv.innerHTML = i18n[message];
  else
    searchStatusDiv.innerHTML = message;
    
  new Element.addClassName('searchresults','hidden');
  new Element.removeClassName('searchStatus','hidden');
}

function refreshSearch(){
 searchCallback('doSearch2',[]);
}

function handleActionResponseOnSuccess(response){
  var searchStatusDiv = document.getElementById('searchStatus');
  searchStatusDiv.innerHTML='';
  searchStatusDiv.innerHTML = response.responseText;
}

/*
 Could be used later to copy results of a batch operation to the clipboard.
 Source: http://www.krikkit.net/howto_javascript_copy_clipboard.html
*/

/*
function copy_clip(meintext)
{
 if (window.clipboardData) 
   {
   
   // the IE-manier
   window.clipboardData.setData("Text", meintext);
   
   // waarschijnlijk niet de beste manier om Moz/NS te detecteren;
   // het is mij echter onbekend vanaf welke versie dit precies werkt:
   }
   else if (window.netscape) 
   { 
   
   // dit is belangrijk maar staat nergens duidelijk vermeld:
   // you have to sign the code to enable this, or see notes below 
   netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
   
   // maak een interface naar het clipboard
   var clip = Components.classes['@mozilla.org/widget/clipboard;1']
                 .createInstance(Components.interfaces.nsIClipboard);
   if (!clip) return;
   
   // maak een transferable
   var trans = Components.classes['@mozilla.org/widget/transferable;1']
                  .createInstance(Components.interfaces.nsITransferable);
   if (!trans) return;
   
   // specificeer wat voor soort data we op willen halen; text in dit geval
   trans.addDataFlavor('text/unicode');
   
   // om de data uit de transferable te halen hebben we 2 nieuwe objecten 
   // nodig om het in op te slaan
   var str = new Object();
   var len = new Object();
   
   var str = Components.classes["@mozilla.org/supports-string;1"]
                .createInstance(Components.interfaces.nsISupportsString);
   
   var copytext=meintext;
   
   str.data=copytext;
   
   trans.setTransferData("text/unicode",str,copytext.length*2);
   
   var clipid=Components.interfaces.nsIClipboard;
   
   if (!clip) return false;
   
   clip.setData(trans,null,clipid.kGlobalClipboard);
   
   }
   alert("Following info was copied to your clipboard:\n\n" + meintext);
   return false;
}
*/
function handleActionResponseOnFailure(response){
  alert('Search & replace failed: [enter fail message here]');
}

function BatchOpPopupWindow(url){
 var c;	
 c = new PopupWindow();
 c.setUrl(url);
 c.setSize(800,600);
 c.getXYPosition = BatchOpPopupWindow_getXYPosition;
 c.windowProperties="toolbar=no,location=no,status=no,menubar=no,scrollbars=auto,resizable,titlebar=no";
  
 return c;
}

function BatchOpPopupWindow_getXYPosition(){
}

function showBatchOpResultsWindow(title,text){
  batchOperationResult=text; // store results in temporary global variable, to be fecthed by the opened window
  var win = new BatchOpPopupWindow('/search/batchOpResults.html?title='+title);
  win.showPopup();
}

function doSearchReplace(
     formId, // id of active form
     customActionParamName, // request param name to pass id of replace action
     customActionId, // id of replace action
     totalHits,  // nr of search results
     batchScopeRequestParam, // request param name to pass the scope of this batch operation
     selectionField){  // id of the radiogroup (!) that holds the selection type of this batch operation
                       // the batch operation can be applied to (1) selected documents or (2) all found results     
  var selectionMethod = '';
  if (typeof document.forms[formId].elements[selectionField] != 'undefined'){
    for (var i=0; i<document.forms[formId].elements[selectionField].length; i++)
      if (document.forms[formId].elements[selectionField][i].checked){
        selectionMethod = document.forms[formId].elements[selectionField][i].value; 
        break;
      }
  } else
    selectionMethod = 'all'; // default is to replace all found documents
  if (confirm(
     i18n_translate(['search.form.advanced.search-replace.confirmation.part1'])+
     totalHits+
     i18n_translate(['search.form.advanced.search-replace.confirmation.part2']))){
    var values = Form.serialize(document.getElementById(formId));
    values+='&'+customActionParamName+'='+customActionId+
            '&'+batchScopeRequestParam+'='+selectionMethod;
    setSearchStatus('search.replacing');
    var succ = function(response){
      
      // doSearch(formId);  
    }
    var fail = function(request){
      alert('Search & replace failed: [enter fail message here]');
    }
    
    new Ajax.Request('/search/doSearchReplace?'+values, {onSuccess:handleActionResponseOnSuccess, onFailure: handleActionResponseOnFailure});
  }
}

function selectAll(formId) {
	var field = document.forms[formId].selectedDocuments;		
	for (i = 0; i < field.length; i++)
    field[i].checked = true;
}

function unSelectAll(formId) {
	var field = document.forms[formId].selectedDocuments;		
	for (i = 0; i < field.length; i++)
    field[i].checked = false;
}

function addSelectedItemsToShelf(formId) {
	var field = document.forms[formId].selectedDocuments;		
    var uris="";
	for (i = 0; i < field.length; i++) {
	  if(field[i].checked==true){
	   if(uris=="") 
	     uris = uris + field[i].value;
	   else
	     uris = uris + "," + field[i].value;
     }
   }
   addItemsToShelf(uris);
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?