User:Polygnotus/Scripts/FavouriteTemplates.js
Appearance
From Wikipedia, the free encyclopedia
Code that you insert on this page could contain malicious content capable of compromising your account. If you import a script from another page with "importScript", "mw.loader.load", "iusc", or "lusc", take note that this causes you to dynamically load a remote script, which could be changed by others. Editors are responsible for all edits and actions they perform, including by scripts. User scripts are not centrally supported and may malfunction or become inoperable due to software changes. A guide to help you find broken scripts is available. If you are unsure whether code you are adding to this page is safe, you can ask at the appropriate village pump.
This code will be executed when previewing this page.
This code will be executed when previewing this page.
Documentation for this user script can be added at User:Polygnotus/Scripts/FavouriteTemplates.
// Add Favorite Templates to WikiEditor 2010 toolbar // Place this code in your common.js file // Check if we're editing a page if(['edit','submit'].indexOf(mw.config.get('wgAction'))!==-1){ // Add a hook handler mw.hook('wikiEditor.toolbarReady').add(function($textarea){ // Function to get favorite templates from user preferences asyncfunctiongetFavoriteTemplates(){ try{ constapiUrl=mw.config.get('wgScriptPath')+'/api.php'; constparams={ action:'query', meta:'userinfo', uiprop:'options', format:'json' }; constresponse=await$.get(apiUrl,params); if(response.query&&response.query.userinfo&&response.query.userinfo.options){ constoptions=response.query.userinfo.options; // Get the favorite templates constfavoriteTemplates=options['templatedata-favorite-templates']; if(favoriteTemplates){ console.log('Favorite Templates (Page IDs):',favoriteTemplates); // Parse as JSON array lettemplateIds=[]; if(typeoffavoriteTemplates==='string'){ try{ templateIds=JSON.parse(favoriteTemplates); }catch(e){ console.log('Could not parse favorites as JSON'); return[]; } }else{ templateIds=favoriteTemplates; } console.log('Template IDs:',templateIds); // Convert IDs to template names if(templateIds.length>0){ consttemplateNames=awaitgetTemplateNames(templateIds); console.log('Template Names:',templateNames); returntemplateNames; } return[]; }else{ console.log('No favorite templates found.'); return[]; } } return[]; }catch(error){ console.error('Error retrieving favorite templates:',error); return[]; } } // Function to convert Page IDs to template names asyncfunctiongetTemplateNames(pageIds){ try{ constapiUrl=mw.config.get('wgScriptPath')+'/api.php'; // Convert array to pipe-separated string for the API constpageIdsString=pageIds.join('|'); constparams={ action:'query', pageids:pageIdsString, format:'json' }; constresponse=await$.get(apiUrl,params); if(response.query&&response.query.pages){ constpages=response.query.pages; consttemplateNames=[]; console.log('\n=== Template Details ==='); for(constpageIdofpageIds){ constpage=pages[pageId]; if(page&&page.title){ console.log(`ID ${pageId}: ${page.title}`); templateNames.push({ id:pageId, title:page.title, namespace:page.ns }); }else{ console.log(`ID ${pageId}: Template not found`); templateNames.push({ id:pageId, title:'Unknown', namespace:null }); } } returntemplateNames; } return[]; }catch(error){ console.error('Error retrieving template names:',error); return[]; } } // Function to create a safe button ID from template title functioncreateButtonId(title){ // Remove Template: prefix if present constcleanTitle=title.replace(/^Template:/,''); // Replace spaces and special characters with hyphens returncleanTitle.replace(/[^a-zA-Z0-9]/g,'-').toLowerCase(); } // Function to create template syntax functioncreateTemplateSyntax(title){ // Remove Template: prefix if present constcleanTitle=title.replace(/^Template:/,''); return`{{${cleanTitle}}}`; } // Function to add favorite template buttons asyncfunctionaddFavoriteTemplateButtons(){ constfavoriteTemplates=awaitgetFavoriteTemplates(); if(favoriteTemplates&&favoriteTemplates.length>0){ // First, add the section $textarea.wikiEditor('addToToolbar',{ sections:{ 'favorite-templates':{ type:'toolbar', label:'Favorite Templates' } } }); // Create the tools object for the buttons consttemplateTools={}; // Add each favorite template as a tool for(consttemplateoffavoriteTemplates){ constbuttonId=createButtonId(template.title); consttemplateSyntax=createTemplateSyntax(template.title); constdisplayTitle=template.title.replace(/^Template:/,''); templateTools[buttonId]={ type:'element', element:$('<button>') .addClass('tool tool-button') .text(displayTitle) .css({ 'padding':'4px 8px', 'margin':'2px', 'border':'1px solid #a2a9b1', 'border-radius':'2px', 'background':'#f8f9fa', 'cursor':'pointer', 'font-size':'11px', 'font-family':'sans-serif' }) .hover( function(){$(this).css('background','#eaecf0');}, function(){$(this).css('background','#f8f9fa');} ) .click((function(syntax){ returnfunction(e){ e.preventDefault(); // Get the textarea consttextarea=$('#wpTextbox1')[0]; if(textarea){ // Insert the template syntax at cursor position conststart=textarea.selectionStart; constend=textarea.selectionEnd; consttext=textarea.value; textarea.value=text.substring(0,start)+syntax+text.substring(end); // Move cursor to end of inserted text textarea.selectionStart=textarea.selectionEnd=start+syntax.length; textarea.focus(); } }; })(templateSyntax)) }; } // Then add the group with all tools $textarea.wikiEditor('addToToolbar',{ section:'favorite-templates', groups:{ 'favorites':{ tools:templateTools } } }); console.log(`Added ${favoriteTemplates.length} favorite template buttons to toolbar`); }else{ console.log('No favorite templates to add to toolbar'); } } // Execute the function to add buttons addFavoriteTemplateButtons(); }); }