MediaWiki:Common.js: verschil tussen versies

Uit Dorpsbelang Den Hout
Ga naar:navigatie, zoeken
Regel 99: Regel 99:
 
   if(settingsPreview != "false"){
 
   if(settingsPreview != "false"){
 
      
 
      
   
+
  $('.grid-img img').remove()
 
                      
 
                      
  
Regel 105: Regel 105:
 
     createPreviews(fileInput.files);
 
     createPreviews(fileInput.files);
 
   }   
 
   }   
  fileInput.closest('label').style.display = "none"
+
// fileInput.closest('label').style.display = "none"
  fileInput.closest('form').querySelector('[type="submit"]').style.display = "inline-block"
+
// fileInput.closest('form').querySelector('[type="submit"]').style.display = "inline-block"
  fileInput.closest('form').querySelector('[type="submit"]').addEventListener('click', uploadFiles, false)   
+
// fileInput.closest('form').querySelector('[type="submit"]').addEventListener('click', uploadFiles, false)   
 +
 
 
}
 
}
  

Versie van 6 nov 2020 12:32

// JavaScript die hier wordt geplaatst heeft invloed op alle pagina's voor alle gebruikers <script> 

//js for file uplaod

var counter = 0;
var dropped;

var fileInput = document.getElementById('widget-file-upload-files');   

var settingsPreview, settingsCaption, settingsDrop, settingsFilepagetemplate, settingsFilepageparameters, settingsFilename, settingsType;

if(fileInput){
 settingsPreview = fileInput.getAttribute('data-preview');
 settingsCaption = fileInput.getAttribute('data-caption');
 settingsDrop = fileInput.getAttribute('data-drop');
 settingsFilepagetemplate = fileInput.getAttribute('data-filepagetemplate');
 settingsFilepageparameters = fileInput.getAttribute('data-filepageparameters');
 settingsFilename = fileInput.getAttribute('data-filename');
 settingsType = fileInput.getAttribute('data-type');

 fileInput.addEventListener('change', handleFileSelect, false); //is a <input type="file" id="files" name="files[]" multiple />
}
                                                                                       
                                                                                               
function createFilename(filename){
  var output = settingsFilename;                                                                                          
  var regex = /<(\w+)>/gm;
  var m;
  var name = filename.split('.')[0];
  
  if(settingsType){
    var type = settingsType;
  }else{
    var type = filename.split('.')[1];   
  }
  
  while ((m = regex.exec(settingsFilename)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
      regex.lastIndex++;
    }    
    // The result can be accessed through the `m`-variable.
    m.forEach(function(match, groupIndex){
      
      if(match == "FILENAME"){
        output = output.replace('<'+match+'>', name);
      }else{
        var input = fileInput.closest('form').querySelector('[name="'+match+'"]');
        if(input){
          val = input.value;
          output = output.replace('<'+match+'>', val);
        }        
      }
      // console.log(`Found match, group ${groupIndex}: ${match}`);
    });
  }
  return output+'.'+type;
}                                                                                              

function createWikitext(filename, caption){
  var output = settingsFilepageparameters;                                                                                          
  var regex = /<(\w+)>/gm;
  var m;
  var name = filename.split('.')[0];
  var type = filename.split('.')[1]; 
  
  while ((m = regex.exec(settingsFilepageparameters)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
      regex.lastIndex++;
    } 
    // The result can be accessed through the `m`-variable.
    m.forEach(function(match, groupIndex){
      
      if(match == "FILENAME"){
        output = output.replace('<'+match+'>', name);
      }else{
        var input = fileInput.closest('form').querySelector('[name="'+match+'"]');
        if(input){
          val = input.value;
          output = output.replace('<'+match+'>', val);
        }
        
      }
      // console.log(`Found match, group ${groupIndex}: ${match}`);
    });
  }
  output = output.replace(/:/g,'=');
  output = output.replace(/;/g,'|');
  if(caption){
    output = '{{'+settingsFilepagetemplate+'|'+output+'|caption='+caption+'|type='+type+'}}';
  }else{
    output = '{{'+settingsFilepagetemplate+'|'+output+'|type='+type+'}}';
  }
  return output;
}                                                                                                    

function handleFileSelect() {  
  if(settingsPreview != "false"){
    
   $('.grid-img img').remove()
                     

    
    createPreviews(fileInput.files);
  }  
 // fileInput.closest('label').style.display = "none"
 // fileInput.closest('form').querySelector('[type="submit"]').style.display = "inline-block"
 // fileInput.closest('form').querySelector('[type="submit"]').addEventListener('click', uploadFiles, false)  
  
}

function uploadFiles(evt){
  if(evt){
     evt.preventDefault();
  }
  if(dropped){
    var files = dropped;
  }else{
    var files = fileInput.files;
  }
  var proms = []; 
  for(i = 0; i < files.length; ++i){
    file = files[i];
    var fileName = files[i].name;
    
    if(settingsType && settingsType == 'png' && fileName.split('.')[1] != 'png'){
   
    //convert jpg to png !!! yeah so cool
       var fileReader = new FileReader();

      fileReader.onload = function(fileLoadedEvent) {
        var srcData = fileLoadedEvent.target.result; // <--- data: base64


        var image = new Image();
        image.onload = function() { 

          var canvas = document.createElement("canvas");
          canvas.width = image.width;
          canvas.height = image.height;
          canvas.getContext("2d").drawImage(image, 0, 0);

          //   var png = new Image();
          //    png.src = canvas.toDataURL("image/png");

           canvas.toBlob(function(blob) {

            var prom =  doApiCall(blob, fileName);
            proms.push(prom)
            //  return blob;

          },'image/png', 1)
          //   return dt;
          //  document.getElementById("widget-file-upload-preview").appendChild(png)
          }
        image.src = srcData;
      }
      fileReader.readAsDataURL(file);

    }else{
     var prom =  doApiCall(file, fileName);
     proms.push(prom)
    }
    
   
  }
  Promise.all(proms).then(function(values) {
 // fileInput.closest('form').submit();
    $('#real-submit').click();
  });
}


function jpgtopng(file){
var fs = "";
     
    

}


function doApiCall(fileToUpload,fileName){
  return new Promise(function(resolve, reject){
    
    
       
    
    
    formdata = new FormData(); 
    formdata.append("action", "upload");
    formdata.append("filename", createFilename(fileName));
    //formdata.append("filename", fileName);
    formdata.append("token", mw.user.tokens.get( 'editToken' ) );
    formdata.append("file", fileToUpload);
    formdata.append("ignorewarnings", "true");
    formdata.append("format", "json");
    
    
    //as we now have created the data to send, we send it...
    $.ajax( { //http://stackoverflow.com/questions/6974684/how-to-send-formdata-objects-with-ajax-requests-in-jquery
      url: mw.util.wikiScript( 'api' ), //url to api.php 
      contentType:false,
      processData:false,
      type:'POST',
      data: formdata,//the formdata object we created above
      success:function(data){
        resolve(data)
        //  setTimeout(function(){
        editFilePage(fileName);
        //  },100)
      },
      error:function(xhr,status, error){
        console.log(error)
        reject(error)
      }
    });
  });
}


function createPreviews(filesSelected){
  if (filesSelected.length > 0) {
    
    for(i = 0; i < filesSelected.length; ++i){
      
      var fileToLoad = filesSelected[i];
      var fname = fileToLoad.name;
        var name = fname.split('.')[0];
        var type = fname.split('.')[1];  
      
      if(type == "pdf" || type == "doc" || type == "docx"){
      	
      	var newImage = document.createElement('img');
          newImage.src = "https://handhavingsupport.wiki/images/d/da/File.svg";
          var dt = filesSelected[counter]
          counter = counter + 1;
        
          if(settingsCaption){
            
            document.getElementById("widget-file-upload-preview").innerHTML = document.getElementById("widget-file-upload-preview").innerHTML+'<div class="upload-group">'+newImage.outerHTML+'<p>'+fname+'</p><input data="'+dt.name+'" type="text" placeholder="caption" class="form-control"  /></div>';
            
          }else{
            document.getElementById("widget-file-upload-preview").innerHTML = document.getElementById("widget-file-upload-preview").innerHTML+'<div class="upload-group">'+newImage.outerHTML+'<p>'+fname+'</p></div>';
          }
        
      }else {
        
        var fileReader = new FileReader();
        
        fileReader.onload = function(fileLoadedEvent) {
          var srcData = fileLoadedEvent.target.result; // <--- data: base64
          
          var newImage = document.createElement('img');
          newImage.src = srcData;
          var dt = filesSelected[counter]
          counter = counter + 1;
          
          if(settingsCaption){
            
            document.getElementById("widget-file-upload-preview").innerHTML = document.getElementById("widget-file-upload-preview").innerHTML+'<div class="upload-group">'+newImage.outerHTML+'<input data="'+dt.name+'" type="text" placeholder="caption" class="form-control"  /></div>';
            
          }else{
            document.getElementById("widget-file-upload-preview").innerHTML = document.getElementById("widget-file-upload-preview").innerHTML+'<div class="upload-group">'+newImage.outerHTML+'</div>';
          }
        }
        
        fileReader.readAsDataURL(fileToLoad);
      }
    }
  }
}

function editFilePage(file){
  
  if(settingsCaption){
    var caption = document.querySelector('[data="'+file+'"]').value;
    var newWikitextEdit = createWikitext(file, caption);
  }else{
    var newWikitextEdit = createWikitext(file);
  }
  
  var params = {
    action: 'edit',
    title: 'File:'+createFilename(file),
    text: newWikitextEdit,
    format: 'json'
  },
  api = new mw.Api();
  
  api.postWithToken( 'csrf', params ).done( function ( data ) {
    console.log( data );
  } );
  
}



var dropArea = document.getElementById('drop-area');

if(dropArea){
  
  
  ;['dragenter', 'dragover', 'dragleave', 'drop'].forEach(function(eventName){
    dropArea.addEventListener(eventName, preventDefaults, false)
  })
  
  function preventDefaults (e) {
    e.preventDefault()
    e.stopPropagation()
  } 
  
  ;['dragenter', 'dragover'].forEach(function(eventName){
    dropArea.addEventListener(eventName, highlight, false)
  })
  
  ;['dragleave', 'drop'].forEach(function(eventName){
    dropArea.addEventListener(eventName, unhighlight, false)
  })
  
  function highlight(e) {
    dropArea.classList.add('highlight')
  }
  
  function unhighlight(e) {
    dropArea.classList.remove('highlight')
  }
  
  dropArea.addEventListener('drop', handleDrop, false)
  
  function handleDrop(e) {
    var dt = e.dataTransfer
    var files = dt.files
    dropped = files;
    
    if(settingsPreview != "false"){
      createPreviews(files);
    }   
    
    fileInput.closest('form').querySelector('[type="submit"]').addEventListener('click', uploadFiles, false)
  }  
  
}

function removeFile(el, file){
  
  var message = confirm("Weet je zeker dat je dit bestand wilt verwijderen?")
  if(message == true){
    var params = {
    action: 'delete',
    title: file,
    format: 'json'
  },
  api = new mw.Api();

  api.postWithToken( 'csrf', params ).done( function ( data ) {
    console.log( data );
    el.closest('div').remove();
  } );
  }
}


function postBericht(el, template, mode){
  var titel = "";
  var domein = "";
  var parameters = "";
  var prefix = "";
  var page = "";
  var multiparameters = {};
  var inputs = el.closest('form').querySelectorAll('textarea, input:not([name="mwreturn"] ):not([name="mwdb"] ):not([name="mwtoken"] ):not([type="file"]):not([name="mwaction"]):not([name="exclude"])'), i;
  for(i = 0; i < inputs.length; ++i){
   if(inputs[i].name == "Titel"){titel = inputs[i].value};
   if(inputs[i].name == "Pagename"){page = inputs[i].value};
   if(inputs[i].name == "Prefix"){prefix = inputs[i].value};
   if(inputs[i].name == "Domein"){domein = inputs[i].value};
   if(inputs[i].type == "radio"){ 
       if(inputs[i].checked){ 
          parameters += '|'+inputs[i].name+'='+inputs[i].value;
       }
   }else{
    if(inputs[i].name.includes("[]")){
      if(!multiparameters[inputs[i].name.replace('[]', '')]){
         multiparameters[inputs[i].name.replace('[]', '')] = [];
      }
      multiparameters[inputs[i].name.replace('[]', '')].push(inputs[i].value);
    }else{
    parameters += '|'+inputs[i].name+'='+inputs[i].value;
  }
  }
  }
  if(mode == "domein"){
     var url = domein.replace('.','-');
  }else{
    if(page){
      var url = page;
    }else{
      var regex = /[\s'"?’!@\n\|_&,.\/\{\}\[\]]/gm;
      var url = prefix.replace('.','-')+'/'+titel.replace(regex, '-');
    }
    
  }
  
    var multi = "";
    for(i = 0; i < Object.keys(multiparameters).length; ++i){
      multi += '|'+Object.keys(multiparameters)[i]+'='+multiparameters[Object.keys(multiparameters)[i]].toString(); 

    }
    
  var wikitext = '{{'+template+parameters+multi+'}}'
 console.log(wikitext) 
var params = {
					action: 'edit',
					title: url,
					text: wikitext,
					format: 'json'
				},
				api = new mw.Api();

			api.postWithToken( 'csrf', params ).done( function ( html ) {
                        window.location.href = window.location.origin+'/index.php/'+url;
           })
}

var multiselect = document.querySelector('#multi-select2');

if(multiselect){
   multiselect.addEventListener('change', function(){
 

var sp = document.createElement('div')

sp.innerHTML = this.value+'<input type="hidden" name="tags[]" value="'+this.value+'">';
sp.classList.add('botn');
sp.addEventListener('click', function(){
   this.remove();
}, false)
document.querySelector('.out').appendChild(sp)

this.value = ""}, false);
}


//js voor menu
 document.addEventListener('click', function(e){
   
  // if(!e.target.closest('.main-menu li')){
       document.querySelectorAll('.main-menu .hover').forEach(function(e){e.classList.remove('hover')})
     
  // }
     if(e.target.closest('.main-menu li')){
    //    if(!e.target.href && !e.target.closest('li').classList.contains('hover')){
     //      e.target.closest('li').classList.add('hover')
       
addthehover(e.target.closest('li'))
    //    }else{
     //     e.target.closest('li').classList.remove('hover')

     //   }
      }
    
  })

function addthehover(el){
  el.classList.add('hover')
  var ml = el.closest('li');
  
  if(ml == typeof Object){
    console.log('?',ml)
   addthehover(ml)
  }
}


var _onPaste_StripFormatting_IEPaste = false;

    function OnPaste_StripFormatting(elem, e) {

        if (e.originalEvent && e.originalEvent.clipboardData && e.originalEvent.clipboardData.getData) {
            e.preventDefault();
            var text = e.originalEvent.clipboardData.getData('text/plain');
            window.document.execCommand('insertText', false, text);
        }
        else if (e.clipboardData && e.clipboardData.getData) {
            e.preventDefault();
            var text = e.clipboardData.getData('text/plain');
            window.document.execCommand('insertText', false, text);
        }
        else if (window.clipboardData && window.clipboardData.getData) {
            // Stop stack overflow
            if (!_onPaste_StripFormatting_IEPaste) {
                _onPaste_StripFormatting_IEPaste = true;
                e.preventDefault();
                window.document.execCommand('ms-pasteTextOnly', false);
            }
            _onPaste_StripFormatting_IEPaste = false;
        }

    }