User:JPxG/ThinkOutDaBox.js

Source: Wikipedia, the free encyclopedia.
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
// Takes images from infobice and formats them into thumb image frames, which it puts before the infobox.

function doMove() {
	//alert("This part works");
	wikitext = String(document.editform.wpTextbox1.value);
	// Get the text from the edit box and store it as "tbox".
	//alert("This part works too");
	// Find the name of the Infobox.
  // Find the name of the Infobox.
  const infoboxRegex = /{{\s*infobox\s+([^{]*)/i;
  const infoboxMatch = wikitext.match(infoboxRegex);
  var infoboxWhole = infoboxMatch[1].trim();
  console.log(infoboxWhole)

  // Split the Infobox fields into an array.
  const fields = wikitext.split(/\|\s*(?![^[]*\])/);

  // Find the image, caption, and alt fields in the Infobox.
  let imageMatch, captionMatch, altMatch;
  fields.forEach((field) => {
    if (field.match(/^\s*image\s*=/i)) {
      imageMatch = field.match(/image\s*=\s*([^\n|]*)/i);
    }
    if (field.match(/^\s*image_caption\s*=/i)) {
      captionMatch = field.match(/image_caption\s*=\s*(.*)/is);
    }
    if (field.match(/^\s*image_alt\s*=/i)) {
      altMatch = field.match(/image_alt\s*=\s*([^\n|]*)/i);
    }
  });

  // If any of the fields are found, remove them from the Infobox.
  //if (imageMatch || captionMatch || altMatch) {
  //  const filteredFields = fields.filter((field) => {
  //    return !field.match(/^(image|image_caption|image_alt)\s*=/i);
  //  });
  //  wikitext = filteredFields.join('|');
  //}
  
  //human-written line to hack a bug out
  infoboxWhole = infoboxWhole.replaceAll(imageMatch[1].trim(), "");
  infoboxWhole = infoboxWhole.replaceAll(captionMatch[1].trim(), "");
  infoboxWhole = infoboxWhole.replaceAll(altMatch[1].trim(), "");

  // Construct the image frame string and insert it above the Infobox.
  if (imageMatch && captionMatch && altMatch) {
    const imageFrame = `[[${imageMatch[1].trim()}|thumb|${captionMatch[1].trim()}|alt=${altMatch[1].trim()}]]\n\n`;
    wikitext = wikitext.replace(infoboxRegex, imageFrame + `{{Infobox ${infoboxWhole}`);
  }

	document.editform.wpTextbox1.value = wikitext;
	// Edit summary.
	sumbox = String(document.getElementById("wpSummary").value);
	sumbox += " Move image from infobox to thumb frame using [[User:JPxG/ThinkOutDaBox.js|ThinkOutDaBox]]"
	document.getElementById("wpSummary").value = sumbox;
} // function to replace the stuff with the other stuff

addOnloadHook(function() {
	if (document.editform) {
		mw.util.addPortletLink("p-cactions", "javascript:doMove()", "Out da box", "ca-outdabox", "Move image out of infobox", "");
	}
}); // onloadhook
// </nowiki>