MediaWiki:Common.js: Difference between revisions

From The Seven Sages of Rome
No edit summary
No edit summary
Line 39: Line 39:
   });
   });
});
});
function copyEmbeddedStories(targetPage) {
// Function to fetch the latest revision content of a MediaWiki page
   var currentPageTitle = mw.config.get('wgPageName'); // Get the current page title
function fetchLatestRevisionContent(pageTitle) {
 
   const apiUrl = 'https://your-mediawiki-url/api.php';
   // Fetch the current page content using the API
    
   $.ajax({
   const params = {
     url: mw.util.wikiScript('api'),
     action: 'query',
     method: 'GET',
     format: 'json',
     data: {
     titles: pageTitle,
      action: 'query',
    prop: 'revisions',
      prop: 'revisions',
    rvprop: 'content', // Only get the content of the latest revision
      titles: currentPageTitle,
    rvlimit: 1,  // Limit to the latest revision
      rvslots: '*',
  };
      rvprop: 'content',
 
      format: 'json'
  // Make the API call
    },
  $.get(apiUrl, params, function(data) {
    success: function(response) {
    // Check if the page exists and has a revision
      console.log("API Response:", response); // Log the entire response to check for issues
    if (data.query && data.query.pages) {
 
      const pages = data.query.pages;
      // Check if there was a valid page and revision content
       for (let pageId in pages) {
      var page = response.query.pages[Object.keys(response.query.pages)[0]];
         const page = pages[pageId];
 
          
       if (page && page.revisions && page.revisions[0] && page.revisions[0]['*']) {
         // Extract the content of the latest revision
         var pageContent = page.revisions[0]['*']; // Get the content of the page
         if (page.revisions && page.revisions.length > 0) {
 
           const latestRevisionContent = page.revisions[0]['*'];
        // Log the raw page content for debugging purposes
         
        console.log("Raw Page Content:", pageContent);
           // Process the content as needed (for example, inserting into a div)
 
          $('#page-content').html(latestRevisionContent);
         // Clean up the content by trimming and removing excess spaces/newlines
         pageContent = pageContent.replace(/\n+/g, '\n').trim();
        console.log("Cleaned Page Content:", pageContent); // Log the cleaned content
 
        // Check if the content has any EmbeddedStory templates
        var stories = pageContent.match(/\{\{EmbeddedStory[^\}]*\}\}/g);
         if (stories && stories.length > 0) {
           console.log("Found Embedded Stories:", stories); // Log all found stories
 
          // Join all the EmbeddedStory templates together to be copied to the target page
          var targetContent = stories.join('\n');
 
           // Use the MediaWiki API to update the target page
          $.ajax({
            url: mw.util.wikiScript('api'),
            method: 'POST',
            data: {
              action: 'edit',
              title: targetPage,
              text: targetContent,
              summary: 'Copying embedded stories',
              token: mw.user.tokens.get('editToken'),
              format: 'json'
            },
            success: function() {
              alert('Embedded Stories copied successfully!');
            },
            error: function() {
              console.error("Error copying stories to target page.");
              alert('Error: Could not copy the stories to the target page.');
            }
          });
         } else {
         } else {
           console.log("No EmbeddedStories found.");
           console.error('No revisions found for this page.');
          alert('No EmbeddedStories found on the current page.');
         }
         }
      } else {
        console.error("Failed to retrieve page content:", page);
        alert('Error: Could not fetch the page content.');
       }
       }
     },
     } else {
    error: function(xhr, status, error) {
       console.error('Page not found or no revisions available.');
       console.error("API request failed:", status, error); // Log the error details
      alert('Error: API request failed.');
     }
     }
  }).fail(function() {
    console.error('API request failed.');
   });
   });
}
}
// Example usage: fetch content for the page "Hebrew Group A"
fetchLatestRevisionContent('Hebrew Group A');





Revision as of 12:20, 13 March 2025

/** Test **/
$(document).ready(function() {
  // Trigger modal when the button is clicked
  $('#copyEmbeddedStories').click(function() {
    $('#storyModal').modal('show');
  });

  // Handle autocomplete for page names
  $('#page-name').on('input', function() {
    var query = $(this).val();
    if (query.length > 2) {
      $.ajax({
        url: mw.util.wikiScript('api'),
        data: {
          action: 'query',
          list: 'allpages',
          apprefix: query,
          format: 'json'
        },
        success: function(response) {
          var pages = response.query.allpages;
          var suggestions = pages.map(function(page) {
            return page.title;
          });
          // Here you can implement a way to show these suggestions to the user, 
          // such as a custom autocomplete dropdown
        }
      });
    }
  });

  // Process the data when the "Process" button is clicked
  $('#process').click(function() {
    var targetPage = $('#page-name').val();
    if (targetPage) {
      copyEmbeddedStories(targetPage);
    }
    $('#storyModal').modal('hide');  // Close the modal
  });
});
// Function to fetch the latest revision content of a MediaWiki page
function fetchLatestRevisionContent(pageTitle) {
  const apiUrl = 'https://your-mediawiki-url/api.php';
  
  const params = {
    action: 'query',
    format: 'json',
    titles: pageTitle,
    prop: 'revisions',
    rvprop: 'content',  // Only get the content of the latest revision
    rvlimit: 1,  // Limit to the latest revision
  };
  
  // Make the API call
  $.get(apiUrl, params, function(data) {
    // Check if the page exists and has a revision
    if (data.query && data.query.pages) {
      const pages = data.query.pages;
      for (let pageId in pages) {
        const page = pages[pageId];
        
        // Extract the content of the latest revision
        if (page.revisions && page.revisions.length > 0) {
          const latestRevisionContent = page.revisions[0]['*'];
          
          // Process the content as needed (for example, inserting into a div)
          $('#page-content').html(latestRevisionContent);
        } else {
          console.error('No revisions found for this page.');
        }
      }
    } else {
      console.error('Page not found or no revisions available.');
    }
  }).fail(function() {
    console.error('API request failed.');
  });
}

// Example usage: fetch content for the page "Hebrew Group A"
fetchLatestRevisionContent('Hebrew Group A');



/** Test End **/

function scrollToAnchor(anchorId) {
    const element = document.getElementById(anchorId);
    const navbarHeight = 50;
    if (element) {
        // Calculate the adjusted scroll position
        const elementPosition = element.getBoundingClientRect().top + window.pageYOffset;
        const offsetPosition = elementPosition - navbarHeight;

        // Scroll to the adjusted position
        window.scrollTo({
            top: offsetPosition,
            behavior: 'smooth'
        });
    }
}
function drilldownswitcher() {
    $('#drilldown-switch:contains("Show all filters")').length ? ($(".drilldown-filter-values:has(a)").css("display", "block"),
            $(".drilldown-values-toggle").each(function () {
                $("img").each(function () {
                    $(this).attr("src", $(this).attr("src").replace("right-arrow.png", "down-arrow.png"));
                });
            }),
            (document.getElementById("drilldown-switch").innerHTML = 'Hide all filters <i class="fa fa-minus"></i>'))
        : $('#drilldown-switch:contains("Hide all filters")').length &&
        ($(".drilldown-filter-values:has(a)").css("display", "none"),
            $(".drilldown-values-toggle").each(function () {
                $("img").each(function () {
                    $(this).attr("src", $(this).attr("src").replace("down-arrow.png", "right-arrow.png"));
                });
            }),
            (document.getElementById("drilldown-switch").innerHTML = 'Show all filters <i class="fa fa-plus"></i>'));
}
$(document).ready(function () {
    $(".drilldown-results").css({ "-webkit-filter": "blur(0)", "-moz-filter": "blur(0)", "-o-filter": "blur(0)", "-ms-filter": "blur(0)", filter: "blur(0)" }), $(".drilldown-filter-values:has(a)").css("display", "none");
    $('<br /><h3 class="drilldown-pre-header">1. Selected Filters</h3>').insertBefore("#drilldown-applied-filters"),
    $('<h3 class="drilldown-pre-filters">2. Available Filters</h3>').insertBefore("#drilldown-applicable-filters"),
    $('<h3 class="drilldown-post-filters">3. Filtered Results</h3>').insertAfter("#drilldown-applicable-filters"),
    $('<html><div class="drilldown-btn-wrapper"><a class="btn primary-btn" href="javascript:;" onclick="drilldownswitcher()" id="drilldown-switch">Show all filters <i class="fa fa-plus"></i></a></div></html>').insertBefore("#drilldown-filters");
    $(".drilldown-values-toggle").each(function () {
    	$("img").each(function () {
        	$(this).attr("src", $(this).attr("src").replace("down-arrow.png", "right-arrow.png"));
    	});
    });

    if( mw.storage.get( "wip-dismissed" ) === null || JSON.parse(mw.storage.get( "wip-dismissed" )) === false){
    	$( ".wip-alert" ).fadeIn( "slow", function() {});
    }
    
    $( "#close-wip" ).on( "click", function() {
	  mw.storage.set( "wip-dismissed", true );
	  $( ".wip-alert" ).fadeOut( "slow", function() {});
    } );
})
$(document).ready(function () {
    $('#copyButton').on('click', function () {
        var targetPage = $("#targetPageInput").val().trim();
        var embeddedStories = $("#embeddedStoryTemplates").text();

        if (!targetPage) {
            alert("Please select a target page.");
            return;
        }

        if (!embeddedStories) {
            alert("No EmbeddedStory templates found on the source page.");
            return;
        }

        // Confirm action
        if (!confirm("Are you sure you want to copy the EmbeddedStory templates to " + targetPage + "?")) {
            return;
        }

        // Use MediaWiki API to append templates to the target page
        $.post(mw.util.wikiScript('api'), {
            action: 'edit',
            title: targetPage,
            appendtext: "\n" + embeddedStories,
            token: mw.user.tokens.get('csrfToken'),
            format: 'json'
        })
        .done(function (data) {
            if (data && data.edit && data.edit.result === 'Success') {
                alert("EmbeddedStory templates copied successfully to " + targetPage + "!");
            } else {
                alert("An error occurred: " + (data.error && data.error.info));
            }
        })
        .fail(function () {
            alert("An error occurred while trying to copy the EmbeddedStory templates.");
        });
    });
});