MediaWiki:Common.js: Difference between revisions

From The Seven Sages of Rome
No edit summary
Tag: Manual revert
No edit summary
Line 44: Line 44:
   var pageTitle = mw.config.get('wgPageName');  // Get the current page title
   var pageTitle = mw.config.get('wgPageName');  // Get the current page title
    
    
   // Get the latest revision content of the current page
   // Step 1: Fetch the edit token
   $.ajax({
   $.ajax({
     url: mw.util.wikiScript('api'),
     url: mw.util.wikiScript('api'),
Line 51: Line 51:
       format: 'json',
       format: 'json',
       titles: pageTitle,
       titles: pageTitle,
       prop: 'revisions',
       meta: 'tokens',  // Request tokens for the current user
      rvprop: 'content',  // Get only the content of the latest revision
      rvlimit: 1 // Only the latest revision
     },
     },
     success: function(response) {
     success: function(response) {
       var pages = response.query.pages;
       var editToken = response.query.tokens.csrftoken;  // Get the edit token
      var latestContent = '';
        
      for (var pageId in pages) {
       if (!editToken) {
        var page = pages[pageId];
         console.error('Failed to retrieve edit token.');
        if (page.revisions && page.revisions.length > 0) {
          latestContent = page.revisions[0]['*'];  // Get the content of the latest revision
        }
       }
 
      // If no content was found, log and exit
       if (!latestContent) {
         console.error('No content found in the latest revision.');
         return;
         return;
       }
       }


       // Find all EmbeddedStory templates in the content
       // Step 2: Get the latest revision content of the current page
      var stories = latestContent.match(/\{\{EmbeddedStory[^}]*\}\}/g);  // Regex to match all EmbeddedStory templates
      var targetContent = stories ? stories.join('\n') : '';
 
      // If no stories are found, log and exit
      if (!targetContent) {
        console.error('No embedded stories found.');
        return;
      }
 
      // Use the MediaWiki API to update the target page
       $.ajax({
       $.ajax({
         url: mw.util.wikiScript('api'),
         url: mw.util.wikiScript('api'),
        method: 'POST',
         data: {
         data: {
           action: 'edit',
           action: 'query',
           title: targetPage,
           format: 'json',
           text: targetContent,
           titles: pageTitle,
           summary: 'Copying embedded stories',
           prop: 'revisions',
           token: mw.user.tokens.get('editToken'),
           rvprop: 'content', // Get only the content of the latest revision
           format: 'json'
           rvlimit: 1  // Only the latest revision
         },
         },
         success: function(response) {
         success: function(response) {
           if (response.error) {
           var pages = response.query.pages;
             console.error('API Error:', response.error);
          var latestContent = '';
             alert('Failed to copy Embedded Stories. API Error: ' + response.error.info);
          for (var pageId in pages) {
          } else {
             var page = pages[pageId];
            alert('Embedded Stories copied successfully!');
             if (page.revisions && page.revisions.length > 0) {
              latestContent = page.revisions[0]['*']; // Get the content of the latest revision
            }
           }
           }
          // If no content was found, log and exit
          if (!latestContent) {
            console.error('No content found in the latest revision.');
            return;
          }
          // Find all EmbeddedStory templates in the content
          var stories = latestContent.match(/\{\{EmbeddedStory[^}]*\}\}/g);  // Regex to match all EmbeddedStory templates
          var targetContent = stories ? stories.join('\n') : '';
          // If no stories are found, log and exit
          if (!targetContent) {
            console.error('No embedded stories found.');
            return;
          }
          // Step 3: Use the MediaWiki API to update the target page with the content
          $.ajax({
            url: mw.util.wikiScript('api'),
            method: 'POST',
            data: {
              action: 'edit',
              title: targetPage,
              text: targetContent,
              summary: 'Copying embedded stories',
              token: editToken,  // Pass the correct edit token
              format: 'json'
            },
            success: function(response) {
              if (response.error) {
                console.error('API Error:', response.error);
                alert('Failed to copy Embedded Stories. API Error: ' + response.error.info);
              } else {
                alert('Embedded Stories copied successfully!');
              }
            },
            error: function(xhr, status, error) {
              console.error('AJAX Error:', status, error);
              alert('An error occurred while copying Embedded Stories. Please try again.');
            }
          });
         },
         },
         error: function(xhr, status, error) {
         error: function(xhr, status, error) {
           console.error('AJAX Error:', status, error);
           console.error('AJAX Error:', status, error);
           alert('An error occurred while copying Embedded Stories. Please try again.');
           alert('Failed to fetch the latest revision. Please try again.');
         }
         }
       });
       });
     },
     },
     error: function(xhr, status, error) {
     error: function(xhr, status, error) {
       console.error('AJAX Error:', status, error);
       console.error('Failed to fetch edit token:', status, error);
       alert('Failed to fetch the latest revision. Please try again.');
       alert('Failed to fetch edit token. Please try again.');
     }
     }
   });
   });

Revision as of 12:26, 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 copy embedded stories from the current page to the target page
function copyEmbeddedStories(targetPage) {
  var pageTitle = mw.config.get('wgPageName');  // Get the current page title
  
  // Step 1: Fetch the edit token
  $.ajax({
    url: mw.util.wikiScript('api'),
    data: {
      action: 'query',
      format: 'json',
      titles: pageTitle,
      meta: 'tokens',  // Request tokens for the current user
    },
    success: function(response) {
      var editToken = response.query.tokens.csrftoken;  // Get the edit token
      
      if (!editToken) {
        console.error('Failed to retrieve edit token.');
        return;
      }

      // Step 2: Get the latest revision content of the current page
      $.ajax({
        url: mw.util.wikiScript('api'),
        data: {
          action: 'query',
          format: 'json',
          titles: pageTitle,
          prop: 'revisions',
          rvprop: 'content',  // Get only the content of the latest revision
          rvlimit: 1  // Only the latest revision
        },
        success: function(response) {
          var pages = response.query.pages;
          var latestContent = '';
          for (var pageId in pages) {
            var page = pages[pageId];
            if (page.revisions && page.revisions.length > 0) {
              latestContent = page.revisions[0]['*'];  // Get the content of the latest revision
            }
          }

          // If no content was found, log and exit
          if (!latestContent) {
            console.error('No content found in the latest revision.');
            return;
          }

          // Find all EmbeddedStory templates in the content
          var stories = latestContent.match(/\{\{EmbeddedStory[^}]*\}\}/g);  // Regex to match all EmbeddedStory templates
          var targetContent = stories ? stories.join('\n') : '';

          // If no stories are found, log and exit
          if (!targetContent) {
            console.error('No embedded stories found.');
            return;
          }

          // Step 3: Use the MediaWiki API to update the target page with the content
          $.ajax({
            url: mw.util.wikiScript('api'),
            method: 'POST',
            data: {
              action: 'edit',
              title: targetPage,
              text: targetContent,
              summary: 'Copying embedded stories',
              token: editToken,  // Pass the correct edit token
              format: 'json'
            },
            success: function(response) {
              if (response.error) {
                console.error('API Error:', response.error);
                alert('Failed to copy Embedded Stories. API Error: ' + response.error.info);
              } else {
                alert('Embedded Stories copied successfully!');
              }
            },
            error: function(xhr, status, error) {
              console.error('AJAX Error:', status, error);
              alert('An error occurred while copying Embedded Stories. Please try again.');
            }
          });
        },
        error: function(xhr, status, error) {
          console.error('AJAX Error:', status, error);
          alert('Failed to fetch the latest revision. Please try again.');
        }
      });
    },
    error: function(xhr, status, error) {
      console.error('Failed to fetch edit token:', status, error);
      alert('Failed to fetch edit token. Please try again.');
    }
  });
}

/** 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.");
        });
    });
});