MediaWiki:Common.js: Difference between revisions

From The Seven Sages of Rome
No edit summary
No edit summary
 
(15 intermediate revisions by the same user not shown)
Line 1: Line 1:
/** Test **/
mw.loader.load('/index.php?title=MediaWiki:CopyEmbeddedStory.js&action=raw&ctype=text/javascript');
$(document).ready(function() {
  // Trigger modal when the button is clicked
  $('#copyEmbeddedStories').click(function() {
    $('#storyModal').modal('show');
  });


  // Handle autocomplete for page names
window.addEventListener('scroll', function() {
  $('#page-name').on('input', function() {
  const navbar = document.getElementById('mw-navigation');
    var query = $(this).val();
  if (window.scrollY > 0) {
    if (query.length > 2) {
    navbar.classList.add('scrolled');
      $.ajax({
   } else {
        url: mw.util.wikiScript('api'),
     navbar.classList.remove('scrolled');
        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 copyEmbeddedStories(targetPage) {
  var currentPageTitle = mw.config.get('wgPageName'); // Get the current page title
  // Fetch the current page content using the API
  $.ajax({
    url: mw.util.wikiScript('api'),
    method: 'GET',
    data: {
      action: 'query',
      prop: 'revisions',
      titles: currentPageTitle,
      rvslots: '*',
      rvprop: 'content',
      format: 'json'
    },
    success: function(response) {
      console.log("API Response:", response); // Log the entire response to check for issues
      // Check if there was a valid page and revision content
      var page = response.query.pages[Object.keys(response.query.pages)[0]];
      if (page && page.revisions && page.revisions[0] && page.revisions[0]['*']) {
        var pageContent = page.revisions[0]['*']; // Get the content of the page
        // Debugging: Check if pageContent is not empty
        console.log("Page content fetched successfully.");
       
        // Find all EmbeddedStory templates
        var stories = pageContent.match(/\{\{EmbeddedStory[^}]*\}\}/g);
        if (stories) {
          var targetContent = stories.join('\n'); // Join all the EmbeddedStory templates together
          // 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 {
          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.');
      }
    },
    error: function(xhr, status, error) {
      console.error("API request failed:", status, error); // Log the error details
      alert('Error: API request failed.');
    }
  });
}
/** Test End **/


function scrollToAnchor(anchorId) {
function scrollToAnchor(anchorId) {
Line 162: Line 63:
     } );
     } );
})
})
$(document).ready(function() {
    $('[data-toggle="tooltip"]').tooltip();
});
$(document).ready(function () {
$(document).ready(function () {
    $('#copyButton').on('click', function () {
  $('#tree-filter').on('input', function () {
        var targetPage = $("#targetPageInput").val().trim();
    const query = $(this).val().toLowerCase();
        var embeddedStories = $("#embeddedStoryTemplates").text();


        if (!targetPage) {
    $('#motif-tree li').each(function () {
            alert("Please select a target page.");
      const $li = $(this);
            return;
      const $link = $li.children('a');
        }
      const text = $link.text().toLowerCase();


        if (!embeddedStories) {
      const matches = text.includes(query);
            alert("No EmbeddedStory templates found on the source page.");
            return;
        }


        // Confirm action
      // Initially hide everything
        if (!confirm("Are you sure you want to copy the EmbeddedStory templates to " + targetPage + "?")) {
      $li.data('match', matches).hide();
            return;
    });
        }


        // Use MediaWiki API to append templates to the target page
    // Show matching items and their ancestors
        $.post(mw.util.wikiScript('api'), {
    $('#motif-tree li').each(function () {
            action: 'edit',
      const $li = $(this);
            title: targetPage,
      if ($li.data('match')) {
            appendtext: "\n" + embeddedStories,
        $li.show();
            token: mw.user.tokens.get('csrfToken'),
         $li.parentsUntil('#motif-tree', 'li').show();
            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.");
        });
     });
     });
    // If input is empty, show all
    if (query === '') {
      $('#motif-tree li').show();
    }
  });
});
});

Latest revision as of 10:25, 1 May 2025

mw.loader.load('/index.php?title=MediaWiki:CopyEmbeddedStory.js&action=raw&ctype=text/javascript');

window.addEventListener('scroll', function() {
  const navbar = document.getElementById('mw-navigation');
  if (window.scrollY > 0) {
    navbar.classList.add('scrolled');
  } else {
    navbar.classList.remove('scrolled');
  }
});

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() {
    $('[data-toggle="tooltip"]').tooltip();
});

$(document).ready(function () {
  $('#tree-filter').on('input', function () {
    const query = $(this).val().toLowerCase();

    $('#motif-tree li').each(function () {
      const $li = $(this);
      const $link = $li.children('a');
      const text = $link.text().toLowerCase();

      const matches = text.includes(query);

      // Initially hide everything
      $li.data('match', matches).hide();
    });

    // Show matching items and their ancestors
    $('#motif-tree li').each(function () {
      const $li = $(this);
      if ($li.data('match')) {
        $li.show();
        $li.parentsUntil('#motif-tree', 'li').show();
      }
    });

    // If input is empty, show all
    if (query === '') {
      $('#motif-tree li').show();
    }
  });
});