Jump to content
Wikimedia Meta-Wiki

User:Aram/total of table.js

From Meta, a Wikimedia project coordination wiki
This is an archived version of this page, as edited by Aram (talk | contribs) at 20:44, 21 September 2024 (A new user script to: Total of Table). It may differ significantly from the current version .
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

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.
 /**
  * Title: Total of Table
  * Description: Visually, adds total of tables using 'total-x', 'total-y' or 'total-z' classes into the wikitable
  * Documentation: [[m:User:Aram/total of table]]
  * Version: 1.0.0
  */

 $(document).ready(function(){
 // Get the language-specific separators for thousands and decimals
 constlangData=mw.language.getSeparatorTransformTable();
 constthousandsSeparator=langData[',']||',';
 constdecimalSeparator=langData['.']||'.';

 // Function to convert text (with localized number formatting) into a standard float
 functionconvertToStandardDigits(text){
 if(!text)return0;// Return 0 if text is empty

 // Remove thousands separators and normalize the number string
 letnormalizedText=text.replace(newRegExp(`\\${thousandsSeparator}`,'g'),'');
 letparts=normalizedText.split(newRegExp(`\\${decimalSeparator}|\\.`));// Split integer and decimal parts
 letintegerPart=mw.language.convertNumber(parts[0],'en');// Convert integer part to standard format
 letdecimalPart=parts[1]?mw.language.convertNumber(parts[1],'en'):'';// Convert decimal part if exists

 // Return combined float or integer as a number
 returndecimalPart?parseFloat(`${integerPart}.${decimalPart}`):parseFloat(integerPart);
 }

 // Function to format a given number back into localized format
 functionformatNumber(value){
 returnmw.language.convertNumber(value);// Convert standard number to localized format
 }

 // Load required MediaWiki modules and then load the necessary messages
 $.when(mw.loader.using(['mediawiki.api','mediawiki.jqueryMsg']),$.ready)
 .then(()=>newmw.Api().loadMessagesIfMissing(['sitematrix-sitetotal']))// Load the 'sitematrix-sitetotal' message if not already loaded
 .then(()=>{
 constlocalizedTotal=mw.message('sitematrix-sitetotal').text();// Get the localized 'Total' message

 // Function to update the table totals (for tables with 'total-x', 'total-y' or 'total-z' class)
 functionupdateTotals(){
 $('table.wikitable').each(function(){
 const$table=$(this);
 constcolumnTotals=[];// Stores total of each column
 constrowTotals=[];// Stores total of each row

 // Calculate row and column totals
 $table.find('tbody tr').each(function(){
 letrowSum=0;
 $(this).find('td').each(function(index){
 constvalue=convertToStandardDigits($(this).text().trim());// Convert each cell value to standard number
 if(!isNaN(value)){
 rowSum+=value;// Add value to row total
 columnTotals[index]=(columnTotals[index]||0)+value;// Add value to column total
 }
 });
 rowTotals.push(rowSum);// Push row total to array
 });

 let$tfoot=$table.find('tfoot');
 if($tfoot.length===0){
 $tfoot=$('<tfoot></tfoot>').appendTo($table);// If no <tfoot> exists, create one
 }

 // Handle 'total-x' class: Add a row to display column totals
 if($table.hasClass('total-x')){
 const$lastRow=$('<tr style="font-weight: bold; background-color: #f0f0f0;"></tr>');
 columnTotals.forEach(total=>{
 $lastRow.append(`<td>${formatNumber(total||0)}</td>`);// Display each column total in a new row
 });
 $tfoot.append($lastRow);

 // Add a full-width row at the bottom with localized 'Total' label
 constfullWidthCell=$('<tr style="font-weight: bold; background-color: #f0f0f0;"><td colspan="'+columnTotals.length+'" style="text-align: center;">'+localizedTotal+'</td></tr>');
 $tfoot.append(fullWidthCell);// Append the full-width cell with localized total message
 }

 // Handle 'total-y' class: Add a column to display row totals
 if($table.hasClass('total-y')){
 $table.find('tbody tr').each(function(rowIndex){
 const$lastCell=$('<td style="font-weight: bold; background-color: #f0f0f0;"></td>').text(formatNumber(rowTotals[rowIndex]||0));// Append row totals
 $(this).append($lastCell);
 });

 // Add the 'Total' header to the last column
 if(!$tfoot.find('th.total-header').length){
 const$lastHeader=$(`<th class="total-header" style="font-weight: bold;">${localizedTotal}</th>`);
 $table.find('thead tr').append($lastHeader);// Append header for totals column
 }
 }

 // Handle 'total-z' class: Add both row and column totals, along with the localized total label
 if($table.hasClass('total-z')){
 const$lastRow=$('<tr style="font-weight: bold; background-color: #f0f0f0;"></tr>');
 columnTotals.forEach(total=>{
 $lastRow.append(`<td>${formatNumber(total||0)}</td>`);// Display column totals
 });
 $tfoot.append($lastRow);

 // Add row totals for each row
 $table.find('tbody tr').each(function(rowIndex){
 const$lastCell=$('<td style="font-weight: bold; background-color: #f0f0f0;"></td>').text(formatNumber(rowTotals[rowIndex]||0));
 $(this).append($lastCell);// Append row totals
 });

 // Add full-width row at the bottom for localized 'Total' label
 constfullWidthCell=$('<tr style="font-weight: bold; background-color: #f0f0f0;"><td colspan="'+columnTotals.length+'" style="text-align: center;">'+localizedTotal+'</td></tr>');
 $tfoot.append(fullWidthCell);// Append the localized total message as full-width row

 // Add 'Total' header to the first column
 const$lastHeader=$(`<th class="total-header" style="font-weight: bold; text-align: center;">${localizedTotal}</th>`);
 $table.find('thead tr').append($lastHeader);// Append header to the first column
 }
 });
 }

 updateTotals();// Call the function to update totals for all tables
 });
 });

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