Jump to content
Wikimedia Meta-Wiki

User:HaeB/WRN import adjustments.js

From Meta, a Wikimedia project coordination wiki
This is an archived version of this page, as edited by HaeB (talk | contribs) at 05:44, 21 November 2024 (handle section (anchor) self-links). It may differ significantly from the current version .

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5.
 // To be used on a page imported from enwiki, for converting internal links to interwiki links pointing back to the originally linked page (excluding File: and Media: links). Adds a button in source editing mode (only for "Research:Newsletter" pages) that triggers the conversion and opens "Show changes", for the user to review and save the result. 
 // By [[User:HaeB]] (using ChatGPT o1-preview and Claude 3.5 Sonnet (new))

 (function(){
 'use strict';
 letinterwikiPrefixes=[];// To store the fetched interwiki prefixes
 consttargetInterwikiPrefix=':w:';// The interwiki prefix to be added to the links (e.g., :w: for Wikipedia)

 // Load the necessary modules
 mw.loader.using(['oojs-ui','mediawiki.util','mediawiki.api']).then(function(){
 // Check if the page title starts with "Research:Newsletter" and we're in editing mode
 constpageTitle=mw.config.get('wgPageName');
 if(!pageTitle.startsWith('Research:Newsletter')||mw.config.get('wgAction')!=='edit')return;

 // Fetch interwiki prefixes from the API
 fetchInterwikiPrefixes().then(function(){
 // Create a button in the toolbar once prefixes are fetched
 constbutton=newOO.ui.ButtonWidget({
 label:'Convert links and templates',
 icon:'edit',
 flags:['progressive']
 });
 button.on('click',function(){
 performConversions();
 });
 // Add the button to the toolbar in the edit page
 $('#wpTextbox1').before(button.$element);
 });
 });

 // Function to fetch interwiki prefixes from the API
 functionfetchInterwikiPrefixes(){
 constapi=newmw.Api();
 returnapi.get({
 action:'query',
 meta:'siteinfo',
 siprop:'interwikimap'
 }).then(function(data){
 // Filter out the 'wikipedia' prefix to avoid conflicts with the Wikipedia namespace
 interwikiPrefixes=data.query.interwikimap
 .map(entry=>entry.prefix.toLowerCase())
 .filter(prefix=>prefix!=='wikipedia');
 });
 }

 // Helper function to parse template parameters while respecting nested structures
 functionparseTemplateParams(paramsString){
 constparams={};
 letcurrentKey='';
 letcurrentValue='';
 letinValue=false;
 letnestLevel=0;// Track nesting level of [[...]] and {{...}}
 letcaptureBuffer='';

 // Helper to add completed parameter to params object
 functionaddParam(){
 if(currentKey){
 constkey=currentKey.trim();
 constvalue=currentValue.trim();
 if(key&&value){
 params[key]=value;
 }
 }
 currentKey='';
 currentValue='';
 inValue=false;
 }

 // Process character by character
 for(leti=0;i<paramsString.length;i++){
 constchar=paramsString[i];
 constnextChar=paramsString[i+1]||'';

 // Handle nested structures
 if(char==='['&&nextChar==='['){
 nestLevel++;
 captureBuffer+='[[';
 i++;// Skip next [
 continue;
 }
 if(char===']'&&nextChar===']'){
 nestLevel--;
 captureBuffer+=']]';
 i++;// Skip next ]
 continue;
 }
 if(char==='{'&&nextChar==='{'){
 nestLevel++;
 captureBuffer+='{{';
 i++;// Skip next {
 continue;
 }
 if(char==='}'&&nextChar==='}'){
 nestLevel--;
 captureBuffer+='}}';
 i++;// Skip next }
 continue;
 }

 // Only process pipes and equals when not in nested structure
 if(nestLevel===0){
 if(char==='|'){
 if(inValue){
 currentValue+=captureBuffer;
 }else{
 currentKey=captureBuffer;
 }
 captureBuffer='';
 addParam();
 continue;
 }
 if(char==='='&&!inValue){
 currentKey=captureBuffer;
 captureBuffer='';
 inValue=true;
 continue;
 }
 }

 captureBuffer+=char;
 }

 // Add final parameter
 if(captureBuffer){
 if(inValue){
 currentValue=captureBuffer;
 }else{
 currentKey=captureBuffer;
 }
 addParam();
 }

 returnparams;
 }

 // Function to convert image templates to File syntax
 functionconvertImageTemplates(content){
 // Regular expressions for both template types
 consttemplateRegexes=[
 /\{\{Wikipedia:Wikipedia Signpost\/Templates\/Inline image\s*\|((?:[^{}]|\{\{[^{}]*\}\})*)\}\}/g,
 /\{\{Wikipedia:Wikipedia Signpost\/Templates\/Filler image-v2\s*\n?\s*\|((?:[^{}]|\{\{[^{}]*\}\})*)\}\}/g
 ];

 letnewContent=content;

 // Process each template type
 templateRegexes.forEach(regex=>{
 newContent=newContent.replace(regex,function(match,params){
 // Parse parameters using the new parser
 constparamMap=parseTemplateParams(params);

 // Construct File syntax
 letfileString='[[File:';
 // Add image name
 if(paramMap.image){
 fileString+=paramMap.image.replace(/^(?:File:|Media:)/i,'');
 }

 // Add standard parameters
 fileString+='|thumb';
 if(paramMap.size){
 fileString+='|'+paramMap.size;
 }
 if(paramMap.align){
 fileString+='|'+paramMap.align;
 }
 if(paramMap.alt){
 fileString+='|alt='+paramMap.alt;
 }
 if(paramMap.caption){
 fileString+='|'+paramMap.caption;
 }

 fileString+=']]';
 returnfileString;
 });
 });

 returnnewContent;
 }

 // Function to perform all conversions
 functionperformConversions(){
 consteditor=document.getElementById('wpTextbox1');
 if(!editor)return;

 // Define interwiki regex dynamically based on fetched prefixes
 constinterwikiRegex=newRegExp(`^\\s*:?(${interwikiPrefixes.join('|')}):`,'i');
 // Regular expression to match wikilinks, 
 // excluding File:, Media: and within-page section (anchor) links
 constlinkRegex=/\[\[(?!\s*(?:File|Media):|\s*#)([^\]|]+)(\|[^\]]+)?\]\]/g;


 // Get content and perform both conversions
 letnewContent=editor.value;

 // First convert the templates
 newContent=convertImageTemplates(newContent);

 // Then convert internal links to interwiki links
 newContent=newContent.replace(linkRegex,function(match,p1,p2){
 // Trim whitespace from the link target
 constlinkTarget=p1.trim();
 // If the link already has an interwiki prefix, skip it
 if(interwikiRegex.test(linkTarget)){
 returnmatch;
 }
 // Construct the new link
 if(p2){
 // Piped link: [[Target|Display]]
 return`[[${targetInterwikiPrefix}${linkTarget}${p2}]]`;
 }else{
 // Unpiped link: [[Target]]
 return`[[${targetInterwikiPrefix}${linkTarget}|]]`;
 }
 });

 editor.value=newContent;
 // Click the "Show changes" button to preview changes
 document.getElementById('wpDiff').click();
 }
 })();

AltStyle によって変換されたページ (->オリジナル) /