לדלג לתוכן

משתמש:ואולם חי אני/תיוג תמונות.js

מתוך המכלול, האנציקלופדיה היהודית

לתשומת ליבך: לאחר הפרסום, ייתכן שיהיה צורך לנקות את זיכרון המטמון (cache) של הדפדפן כדי להבחין בשינויים.

  • פיירפוקס / ספארי: להחזיק את המקש Shift בעת לחיצה על טעינה מחדש (Reload) או ללחוץ על צירוף המקשים Ctrl-F5 או Ctrl-R (במחשב מק: ⌘-R).
  • גוגל כרום: ללחוץ על צירוף המקשים Ctrl-Shift-R (במחשב מק: ⌘-Shift-R).
  • אדג': להחזיק את המקש Ctrl בעת לחיצה על רענן (Refresh) או ללחוץ על צירוף המקשים Ctrl-F5.
//<nowiki>
$(document).ready(function () {
  function addButtonView() {
      const portletLink = mw.util.addPortletLink(
          $("#p-בדיקת_תוכן").length > 0 ? "p-בדיקת_תוכן" : "p-tb",
          "#",
          "תיוג בודקי תמונות",
          null,
          "שליחת תמונות לבודקי התמונות"
      );

      $(portletLink).click(openImageSelection);
  }

  function openImageSelection() {
      const images = $("#mw-content-text img:not(.logo-img img")
          .filter((_, img) => img.naturalWidth >= 50 && img.naturalHeight >= 50)
          .toArray();

      if (!images.length) { 
          alert("אין תמונות בדף");
          return;
      }

      const $form = $('<form>').attr('id', 'image-selection-form');
      images.forEach((img) => {
          if ($(img).hasClass('processed')) return;
          $form.append(createImageBlock(img));
          $(img).addClass('processed');
      });

      const $textInput = $('<textarea>')
          .attr({ id: 'userTextInput', placeholder: 'אם יש לך הערות נוספות, כתוב אותן כאן.' })
          .css({ width: '100%', marginTop: '10px', padding: '8px', fontSize: '14px', borderRadius: '4px', border: '1px solid #ddd' });

      const $dialogContent = $('<div>').append($form, $('<br>'), $textInput);
      openDialog($dialogContent);
  }

  function createImageBlock(img) {
      const caption = img.alt || $(img).closest('figure').find('figcaption').text() || "אין תיאור";
      const previewSrc = img.src;
      const imgSrc = mw.util.parseImageUrl(previewSrc)?.name ? `:קובץ:${mw.util.parseImageUrl(previewSrc).name}` : previewSrc;

      const $imageBlock = $('<label>')
          .css({ display: 'flex', alignItems: 'center', margin: '4px 0', padding: '10px', border: '1px solid #ddd', borderRadius: '8px', backgroundColor: '#f9f9f9', cursor: 'pointer' });
      const $checkbox = $('<input>')
          .attr({ type: 'checkbox', name: 'selectedImages', value: imgSrc })
          .css({ margin: '0 10px 0 0', width: '20px', height: '20px' });
      const $image = $('<img>')
          .attr('src', previewSrc)
          .css({ width: '80px', height: 'auto', borderRadius: '4px' });
      const $caption = $('<span>')
          .css({ margin: '10px', fontSize: '14px', color: '#333' })
          .text(caption);

      return $imageBlock.append($checkbox, $image, $caption);
  }

  function openDialog(content) {
      function ImageSelectionDialog(config) {
          ImageSelectionDialog.super.call(this, config);
      }
      OO.inheritClass(ImageSelectionDialog, OO.ui.ProcessDialog);

      ImageSelectionDialog.static.name = 'imageSelectionDialog';
      ImageSelectionDialog.static.title = 'בחירת תמונות לבדיקה';
      ImageSelectionDialog.static.actions = [
          { action: 'accept', label: 'שלח', flags: ['primary', 'progressive'] },
          { action: 'reject', label: 'בטל', flags: 'safe' }
      ];

      ImageSelectionDialog.prototype.initialize = function () {
          ImageSelectionDialog.super.prototype.initialize.apply(this, arguments);
          this.content = new OO.ui.PanelLayout({ padded: true, expanded: false });
          this.content.$element.append(content);
          this.$body.append(this.content.$element);
      };

      ImageSelectionDialog.prototype.getActionProcess = function (action) {
          const dialog = this;
          return action === 'accept' ? processSelection(dialog) : new OO.ui.Process(() => {
              $(".processed").removeClass('processed');
              dialog.close();
          });
      };

      const windowManager = new OO.ui.WindowManager();
      $(document.body).append(windowManager.$element);
      const dialog = new ImageSelectionDialog();
      windowManager.addWindows([dialog]);
      windowManager.openWindow(dialog);
  }

  function processSelection(dialog) {
      return new OO.ui.Process(async () => {
          const selectedImages = $('.oo-ui-window-active #image-selection-form input[name="selectedImages"]:checked').map((_, el) => {
              const $el = $(el);
              return { src: $el.val(), caption: $el.siblings('span').text() };
          }).get();

          const userInput = $('#userTextInput').val();
          try {
              await sendImagesToReviewer(selectedImages, userInput);
              mw.notify("התמונות נשלחו לבדיקה, תודה על שיתוף הפעולה 👍", { type: "success" });
          } catch {
              alert("ההודעה לא נשמרה, נא לבקש ידנית");
          } finally {
              $(".processed").removeClass('processed');
              dialog.close(); 
          }
      });
  }

  function sendImagesToReviewer(selectedImages, userInput) {
      return new Promise((resolve, reject) => {
          if (selectedImages.length === 0) {
              alert('לא נבחרו תמונות');
              reject();
          }

          let message = "" +
              selectedImages.map(img => `#[[${img.src}]] - '''${img.caption}'''\n`).join('');
          if (userInput) message += `\n'''הערות מהמשתמש:''' ${userInput}`;

          mw.loader.using("mediawiki.api", function () {
              new mw.Api().newSection(
                  "המכלול:בדיקת תמונות",
                  `תמונות מהדף [[:${mw.config.get("wgPageName").replace(/_/g, " ")}]]`,
                  `${message}. ~~~~`,
                  { watchlist: "nochange" }
              ).done((data) => {
                  if (data?.edit?.result === "Success") {
                      resolve();
                  } else {
                      reject();
                  }
              });
          });
      });
  }

  if (mw.config.get("wgNamespaceNumber") % 2 === 0) addButtonView();
});
//</nowiki>