MediaWiki:WikiEditor-insert-file-with-preview.js

Aus Bayernflora
Version vom 7. November 2018, 00:38 Uhr von Andreas Plank (Diskussion | Beiträge) (http --> https)

(Unterschied) ← Nächstältere Version | Aktuelle Version (Unterschied) | Nächstjüngere Version → (Unterschied)
Wechseln zu: Navigation, Suche

Hinweis: Leeren Sie nach dem Speichern den Browser-Cache, um die Änderungen sehen zu können.

  • Firefox/Safari: Umschalttaste drücken und gleichzeitig Aktualisieren anklicken oder entweder Strg+F5 oder Strg+R (⌘+R auf dem Mac) drücken
  • Google Chrome: Umschalttaste+Strg+R (⌘+Umschalttaste+R auf dem Mac) drücken
  • Internet Explorer: Strg+F5 drücken oder Strg drücken und gleichzeitig Aktualisieren anklicken
  • Opera: Extras → Internetspuren löschen … → Individuelle Auswahl → Den kompletten Cache löschen
/* <pre>*/
/* global $, mw */
/*jslint es5: true, sloppy: true, todo: true, white: true, indent: 2 */
/* 
  This script is specific to this Wiki
  insert a file with a preview of files from OpenMedia (https://species-id.net/openmedia/)

  DEPENDENCIES:
   * @requires: Extension Semantic Forms
   * @requires: in LocalSettings.php $sfgAutocompletionURLs['api-openmedia-files'] ='https://species-id.net/o/api.php?action=sfautocomplete&limit=10&namespace=File&format=json&substr=<substr>';
   * @requires: /extensions/WikiEditor/modules/images/toolbar/insert-file.png sometimes 'insert-file.png' is not loading
   * @requires: $.jI18n language resource dicionary
   * @requires: function $.resource gets language specific resource strings from $.jI18n.en, $.jI18n.de etc.
  USAGE:
   if (mw.config.get('wgAction') == "edit" || mw.config.get('wgAction') == "submit" ) {
     importScript("MediaWiki:this-file-name.js");// Wizard to insert a file with preview
   }
*/

/* Any JavaScript here will be loaded for all users on every page load.
   https://www.mediawiki.org/wiki/Extension:WikiEditor/Toolbar_customization
   Example stuff can be seen in the /extentions/WikiEditor/modules/jquery.wikiEditor.dialogs.config.js */
if (!$.jI18n) { 
  console.log("Dependency is missing: add language resource dicionary $.jI18n with $.jI18n.en, $.jI18n.de etc. in MediaWiki:Commons.js"); 
} else if (!$.resource) { 
  console.log("Dependency is missing: add function $.resource in MediaWiki:Commons.js that gets language specific resource strings."); 
} else {
  
  $.extend(true, $.jI18n, {/*  resource string dictionary

    Nomenclature proposal: if an extra plugin is used, strings can be designated as
    “plugin_toolTipSomthing” otherwise just “toolTipSomthing” (global string). So it’s more clear if
    somebody wants to deactivate a plugin and remove strings from the resource dictionary.
  */
    en: {
      plugin_insertFilePreview_intro:'Images from ↗&nbsp;<a href="https://species-id.net/openmedia/Hauptseite" target="_blank">OpenMedia</a> and ↗&nbsp;<a href="https://commons.wikimedia.org/wiki/Hauptseite" target="_blank">Commons WikiMedia</a> can be used here directly. If you do not find the image you are searching for you can upload it using the left sidebar “<span style="background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAgMAAABinRfyAAAADFBMVEX///95eXnd3d2dnZ3aAo3QAAAAAXRSTlMAQObYZgAAADFJREFUeF5dyzEKACAMA0CXolNe2Id09Kl5igZahWY4AiGjZwmIuS9GEcJfY63Ix88Bol4EYP1O7JMAAAAASUVORK5CYII=) left center no-repeat;padding-left:1.5em;">Toolbox</span>” and ↗&nbsp;<a href="https://species-id.net/openmedia/Special:UploadWizard?uselang=en" target="_blank" title="upload file to OpenMedia (new window)">upload file to OpenMedia</a> (use the same account there as in this Wiki).',
      plugin_insertFilePreview_preview_restriction:'(Size of preview is limited to 200x200px)',
      plugin_insertFilePreview_no_file_found:'No file found',
      plugin_insertFilePreview_hint_link_tip:'<b>Tip:</b> using <code>|link=</code> you can remove the deafult link or specify a different target',
      plugin_insertFilePreview_placeholder_insert_file:'insert file name',
      plugin_insertFilePreview_wikiEditor_label:'(preview)'
    },
    de: {
      plugin_insertFilePreview_intro:'Bilder aus ↗&nbsp;<a href="https://species-id.net/openmedia/Hauptseite" target="_blank">OpenMedia</a> und ↗&nbsp;<a href="https://commons.wikimedia.org/wiki/Hauptseite" target="_blank">Commons WikiMedia</a> können hier direkt benutzt werden. Falls Sie kein Bild finden, können Sie vom linken Randmenü „<span style="background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAgMAAABinRfyAAAADFBMVEX///95eXnd3d2dnZ3aAo3QAAAAAXRSTlMAQObYZgAAADFJREFUeF5dyzEKACAMA0CXolNe2Id09Kl5igZahWY4AiGjZwmIuS9GEcJfY63Ix88Bol4EYP1O7JMAAAAASUVORK5CYII=) left center no-repeat;padding-left:1.5em;">Werkzeuge</span>“ aus eine ↗&nbsp;<a href="https://species-id.net/openmedia/Special:UploadWizard?uselang=de" target="_blank" title="In neuem Fenster Datei hochlanden (mit selbem Benutzernamen)">Datei auf OpenMedia hochladen</a> (benutzen Sie Ihren Benutzernamen für die Anmeldung dort).',
      plugin_insertFilePreview_preview_restriction:'(Vorschaugröße ist auf 200x200px eingegrenzt)',
      plugin_insertFilePreview_no_file_found:'Nichts gefunden',
      plugin_insertFilePreview_hint_link_tip:'<b>Tip:</b> mit <code>|link=</code> können Sie den Datei-Link unterbinden oder ein anderes Linkziel vergeben',
      plugin_insertFilePreview_placeholder_insert_file:'Dateiname eingeben',
      plugin_insertFilePreview_wikiEditor_label:'(Bildvorschau)'
    }
  });//$.jI18n

  function hideDefaultInsertFileTool(){
    if($('#wikiEditor-ui-toolbar [title="'+mw.msg('wikieditor-toolbar-tool-file') + ' ' + $.resource('plugin_insertFilePreview_wikiEditor_label') +'"]') 
        && $('#wikiEditor-ui-toolbar [title="' + mw.msg('wikieditor-toolbar-tool-file') + '"]')){//if mytool is activated
      $('#wikiEditor-ui-toolbar [title="' + mw.msg('wikieditor-toolbar-tool-file') + '"]').hide();//hide the normal embed image button
    }
  }

  $('#wpTextbox1').on('wikiEditor-toolbar-doneInitialSections', function () {
    var fileToolWithAutocomplete = function () {
      return {
        dialogs: {
          'insert-file-with-autocomplete': {
            title: mw.msg('wikieditor-toolbar-tool-file') + ' ' + $.resource('plugin_insertFilePreview_wikiEditor_label'),
            id: 'wikieditor-toolbar-file-autocomplete-dialog',
            html: '\
            <fieldset>\
              <div class="wikieditor-toolbar-field-wrapper" style="padding: 0px 0px 5px;">\
              <p>' + $.resource('plugin_insertFilePreview_intro') + '</p>\
                <label for="wikieditor-toolbar-file-target" rel="wikieditor-toolbar-file-target" id="wikieditor-toolbar-tool-file-target-label"></label>\
                <input type="text" id="wikieditor-toolbar-file-target"/>\
              </div>\
              <div class="wikieditor-toolbar-field-wrapper" style="padding: 0px 0px 5px;">\
                <label for="wikieditor-toolbar-file-caption" rel="wikieditor-toolbar-file-caption"></label>\
                <textarea id="wikieditor-toolbar-file-caption" rows="2"></textarea>\
              </div>\
              <div class="wikieditor-toolbar-file-options">\
                <div class="wikieditor-toolbar-field-wrapper" style="padding: 0px 0px 5px;">\
                  <label for="wikieditor-toolbar-file-size" rel="wikieditor-toolbar-file-size"></label><br/>\
                  <input type="text" id="wikieditor-toolbar-file-size" size="5"/>\
                </div>\
                <div class="wikieditor-toolbar-field-wrapper" style="padding: 0px 0px 5px;">\
                  <label for="wikieditor-toolbar-file-float" rel="wikieditor-toolbar-file-float"></label><br/>\
                  <select type="text" id="wikieditor-toolbar-file-float">\
                  <option value="default" selected="selected" rel="wikieditor-toolbar-file-default"></option>\
                  <option data-i18n-magic="img_none"></option>\
                  <option data-i18n-magic="img_center"></option>\
                  <option data-i18n-magic="img_left"></option>\
                  <option data-i18n-magic="img_right"></option>\
                  </select>\
                </div>\
                <div class="wikieditor-toolbar-field-wrapper" style="padding: 0px 0px 5px;">\
                  <label for="wikieditor-toolbar-file-format" rel="wikieditor-toolbar-file-format"></label><br/>\
                  <select type="text" id="wikieditor-toolbar-file-format">\
                  <option selected="selected" data-i18n-magic="img_thumbnail">thumb</option>\
                  <option data-i18n-magic="img_framed"></option>\
                  <option data-i18n-magic="img_frameless"></option>\
                  <option value="default" rel="wikieditor-toolbar-file-format-none"></option>\
                  </select>\
                </div>\
                <div>' + $.resource('plugin_insertFilePreview_preview_restriction') + '</div>\
              </div>\
            </fieldset>\
            <div id="wikieditor-toolbar-show-thumb-file" style="max-height:300px;overflow-y:auto;"></div>',
          init: function () {
            var magicWordsI18N = mw.config.get( 'wgWikiEditorMagicWords' ),
              defaultMsg = mw.msg( 'wikieditor-toolbar-file-default' ),
              showThumbFilePreview = function () {
                  //  console.log("generateRefList(data)");
                  //  console.log(data);
                  var fileFloat=($('#wikieditor-toolbar-file-float').val() === "default" ? "" : "|" + $( '#wikieditor-toolbar-file-float' ).val()),
                    fileCaption = ($('#wikieditor-toolbar-file-caption').val().length ? "|" + $( '#wikieditor-toolbar-file-caption' ).val() : ""),
                    fileName = $('#wikieditor-toolbar-file-target' ).val(),
                    fileFormat = "|" + $( '#wikieditor-toolbar-file-format' ).val(),
                    fileSize = $('#wikieditor-toolbar-file-size').val(),
                    hasWidthXHeightRgx = /^\s*([0-9]+)\s*x\s*([0-9]+)\s*$/,
                    hasXHeightRgx = /^\s*x\s*([0-9]+)\s*$/,
                    hasWidthRgx = /^\s*([0-9]+)\s*$/,
                    fileWidth=null, fileHeight=null;
                  // check fileSize
                  fileSize=fileSize.length ? fileSize : "200x200px";
                  fileSize=fileSize.replace(/(.+?)\s*px\s*/,"$1");
                  if ( hasWidthXHeightRgx.test (fileSize)) {
                    fileWidth=parseInt(fileSize.replace(hasWidthXHeightRgx, "$1"));
                    fileHeight=parseInt(fileSize.replace(hasWidthXHeightRgx, "$2"));
                  } else if (hasXHeightRgx.test (fileSize)) {
                    fileHeight=parseInt(fileSize.replace(hasXHeightRgx, "$1"));
                    fileWidth=200;
                  } else if (hasWidthRgx.test (fileSize)) {
                    fileHeight=200;
                    fileWidth=parseInt(fileSize.replace(hasWidthRgx, "$1"));
                  } else {
                    fileHeight=200;
                    fileWidth=200;
                  }
                  fileHeight = fileHeight <= 200 ? fileHeight : 200 ;
                  fileWidth = fileWidth <= 200 ? fileWidth : 200 ;

                  if (fileName.length) {
                    $.ajax({
                      url: mw.config.get("wgServer") + mw.config.get("wgScriptPath") + "/api.php",
                      dataType: "json",
                      data: {
                        action: "parse",
                        text: (fileName.length ? "[[" + fileName.replace(/^/,mw.config.get("wgFormattedNamespaces")[6] + ":") 
                                + fileFormat 
                                + ("|" + fileWidth + "x" + fileHeight + "px") 
                                + fileCaption 
                                + fileFloat + "]]" : '<div>' + $.resource('plugin_insertFilePreview_no_file_found') + '</div>'),
                        format: "json"
                      }
                    })
                    .done(function(data) {
                      // console.log(data);
                      $('#wikieditor-toolbar-show-thumb-file').html('');
                      if (data.parse.images.length) {
                        $.map(data.parse.text, function(fileitem) {
                          $(fileitem)
                            .appendTo('#wikieditor-toolbar-show-thumb-file');
                        });// map
                        $('#wikieditor-toolbar-show-thumb-file')
                          .append('<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam …</p>')
                          .append('<p style="clear:both;">' + $.resource('plugin_insertFilePreview_hint_link_tip') + '</p>');
                      }
                    });
                  }
                };// function showThumbFile(fileName)
            $('#wikieditor-toolbar-file-size').on('change', function() { showThumbFilePreview(); });
            $('#wikieditor-toolbar-file-format').on('change', function() { showThumbFilePreview(); });
            $('#wikieditor-toolbar-file-caption').on('change', function() { showThumbFilePreview(); });
            $('#wikieditor-toolbar-file-float').on('change', function() { showThumbFilePreview(); });
            $( this )
              .find( '[data-i18n-magic]' )
                .text( function () {
                  return magicWordsI18N[ $( this ).attr( 'data-i18n-magic' ) ];
                })
                .removeAttr( 'data-i18n-magic' )
                .end()
              .find( '#wikieditor-toolbar-file-size' )
                .attr( 'placeholder', defaultMsg )
                // The message may be long in some languages
                .attr( 'size', defaultMsg.length )
                .end()
              .find( '[rel]' )
                .text( function () {
                  return mw.msg( $( this ).attr( 'rel' ) );
                })
                .removeAttr( 'rel' )
                .end();
              mw.loader.using("jquery.ui.autocomplete", function () {
                $( "#wikieditor-toolbar-file-target" )
                 .attr({'placeholder': $.resource('plugin_insertFilePreview_placeholder_insert_file')})
                  .autocomplete({
                  minLength : 3,
                  'create': function( event, ui ) {
                    $('<div id="wikieditor-toolbar-show-thumb-file"/>').appendTo("#wikieditor-toolbar-file-autocomplete-dialog");
                  },
                  'source': function( request, response ) {
                    $.ajax({
                      url: mw.config.get("wgServer") + mw.config.get("wgScriptPath") + "/api.php",
                      dataType: "json",
                      data: {
                        action: "sfautocomplete",
                        format: "json",
                        external_url: "api-openmedia-files",
                        substr: $('#wikieditor-toolbar-file-target').val().toLowerCase()
                      }
                    })
                    .done(function(data) {
                      //console.log(data);
                      response( $.map(data.sfautocomplete, function(item) {
                        return { label: item.title, value: item.title };
                      }));
                    });
                  },
                  'select': function( event, ui ) {// when selecting Autor
                    $('#wikieditor-toolbar-file-target' ).val(ui.item.value);// make sure there is the correct value
                    showThumbFilePreview();
                  }// select
                });// autocomplete-file
              });// ui autocomplete
          },
          dialog: {
            resizable: false,
            dialogClass: 'wikiEditor-toolbar-dialog',
            width: 590,
            buttons: {
              'wikieditor-toolbar-tool-file-insert': function () {
                var fileName, caption, fileFloat, fileFormat, fileSize, fileTitle,
                  options, fileUse,
                  hasPxRgx = /.+px$/;
                fileName = $( '#wikieditor-toolbar-file-target' ).val();
                caption = $( '#wikieditor-toolbar-file-caption' ).val();
                fileFloat = $( '#wikieditor-toolbar-file-float' ).val();
                fileFormat = $( '#wikieditor-toolbar-file-format' ).val();
                fileSize = $( '#wikieditor-toolbar-file-size' ).val();
                // Append px to end to size if not already contains it
                if ( fileSize !== '' && !hasPxRgx.test( fileSize ) ) {
                  fileSize += 'px';
                }
                if ( fileName !== '' ) {
                  fileTitle = new mw.Title( fileName );
                  // Append file namespace prefix to filename if not already contains it
                  if ( fileTitle.getNamespaceId() !== 6 ){
                    fileTitle = new mw.Title( fileName, 6 );
                  }
                  fileName = fileTitle.toText();
                }
                options = [ fileSize, fileFormat, fileFloat ];
                // Filter empty values
                options = $.grep( options, function ( val ) {
                  return val.length && val !== 'default';
                } );
                if ( caption.length ) {
                  options.push( caption );
                }
                fileUse = options.length === 0 ? fileName : ( fileName + '|' + options.join( '|' ) );
                $( this ).dialog( 'close' );
                $.wikiEditor.modules.toolbar.fn.doAction(
                  $( this ).data( 'context' ),
                  {
                    type: 'replace',
                    options: {
                      pre: '[[',
                      peri: fileUse,
                      post: ']]',
                      ownline: true
                    }
                  },
                  $( this )
                );

                // Restore form state
                $( ['#wikieditor-toolbar-file-target',
                  '#wikieditor-toolbar-file-caption',
                  '#wikieditor-toolbar-file-size',
                  '#wikieditor-toolbar-file-float',
                  '#wikieditor-toolbar-file-format'].join( ',' )
                ).val( '' );
              },
              'wikieditor-toolbar-tool-file-cancel': function () {
                $( this ).dialog( 'close' );
              }
            },
            open: function () {
              $( '#wikieditor-toolbar-file-target' ).focus();
              if ( !( $( this ).data( 'dialogkeypressset' ) ) ) {
                $( this ).data( 'dialogkeypressset', true );
                // Execute the action associated with the first button
                // when the user presses Enter
                $( this ).closest( '.ui-dialog' ).keypress( function( e ) {
                  if ( e.which === 13 ) {
                    var button = $( this ).data( 'dialogaction' ) ||
                      $( this ).find( 'button:first' );
                    button.click();
                    e.preventDefault();
                  }
                });

                // Make tabbing to a button and pressing
                // Enter do what people expect
                $( this ).closest( '.ui-dialog' ).find( 'button' ).focus( function() {
                  $( this ).closest( '.ui-dialog' ).data( 'dialogaction', this );
                });
              }
            }
          }
        }
        }
      };//end return object
    };//module fileToolWithAutocomplete
    $('#wpTextbox1').wikiEditor('addModule', fileToolWithAutocomplete());

    $('#wpTextbox1').wikiEditor('addToToolbar', {
      'section': 'main',
      'group': 'insert',
      'tools': {
        'fileWithAutocomplete': {
          'label': mw.msg('wikieditor-toolbar-tool-file') + ' ' + $.resource('plugin_insertFilePreview_wikiEditor_label'), // or use labelMsg for a localized label, see above
          'type': 'button',
          'icon': mw.config.get("wgServer") + mw.config.get("wgScriptPath") + "/extensions/WikiEditor/modules/images/toolbar/insert-file.png", // 'insert-file.png' is sometimes not loading
          'action': {
            'type': 'dialog',
            'module': 'insert-file-with-autocomplete'
          }
        }
      }
    });// END addToToolbar
    window.setTimeout(hideDefaultInsertFileTool, 500); //change toolbar after button has been inserted
  });
}// if check $.jI18n and $.resource

/* </pre>*/