// Calculate sum of all file size displayed on a category page
// © 2025 [[User:RoyZuo]]
// Feedback ☞ [[c:User talk:RoyZuo]]
mw.hook('wikipage.content').add(function($content) {
// Only run if the namespace is "Category" (wgNamespaceNumber == 14)
if (mw.config.get('wgNamespaceNumber') === 14) {
let totalSizeMB = 0;
let totalFiles = 0;
// Regex to match file size patterns like '2.56 MB', '500 KB', '2048 bytes', etc.
let sizeRegex = /(\d+(\.\d+)?)\s*(bytes|KB|MB|GB)/g;
// Extract and sum all sizes, counting total files
$content.find("li.gallerybox").each(function() {
let sizeText = $(this).find("div.gallerytext").text();
let match;
while ((match = sizeRegex.exec(sizeText)) !== null) {
let size = parseFloat(match[1]);
let unit = match[3].toUpperCase();
// Convert the size to MB
if (unit === "BYTES") {
size /= (1024 * 1024); // Convert bytes to MB
} else if (unit === "KB") {
size /= 1024; // Convert KB to MB
} else if (unit === "GB") {
size *= 1024; // Convert GB to MB
}
totalSizeMB += size;
totalFiles++; // Count each file
}
});
// Convert total size to the appropriate unit (KB, MB, or GB)
let totalSize = totalSizeMB;
let unit = "MB";
if (totalSize >= 1024) {
totalSize /= 1024;
unit = "GB";
} else if (totalSize < 1) {
totalSize *= 1024;
unit = "KB";
}
// Handle the case where the total size is exactly 1024 MB, to display it as 1 GB
if (unit === "MB" && totalSize >= 1024) {
totalSize /= 1024;
unit = "GB";
}
// Create the message displaying the total files and total size
let fileWord = totalFiles === 1 ? "file" : "files";
let totalSizeMessage = `On this page: ${totalSize.toFixed(2)} ${unit} (${totalFiles} ${fileWord})`;
// Create a paragraph element with the message
let totalSizeElement = $("<p>").text(totalSizeMessage).css({
"font-size": "16px"
});
// Insert the message as the last element inside <h1 id="firstHeading">
$("#firstHeading").append(totalSizeElement);
}
});