// ==UserScript== // @name TorrentBD - Persistent Sort Forum Posts by Likes //…
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
// ==UserScript== // @name TorrentBD - Persistent Sort Forum Posts by Likes // @namespace http://tampermonkey.net/ // @version 1.5 // Incremented version for persistence // @description Adds a button to sort forum posts by likes on TorrentBD, persisting across pagination for the same topic. // @author Your Name Here // @match https://www.torrentbd.net/forums.php?action=viewtopic&* // @grant none // @license MIT // ==/UserScript==
(function() { 'use strict';
console.log("TorrentBD Persistent Sort by Likes script starting (v1.5)...");
const buttonId = 'sort-by-likes-button';
let currentTopicId = null;
let storageKey = null;
/**
* Extracts the topic ID from the current URL.
* @returns {string|null} The topic ID or null if not found.
*/
function getTopicId() {
try {
const urlParams = new URLSearchParams(window.location.search);
return urlParams.get('topicid');
} catch (e) {
console.error("Error parsing URL parameters:", e);
return null;
}
}
/**
* Checks if sorting is enabled for the current topic in sessionStorage.
* @returns {boolean} True if sorting is enabled, false otherwise.
*/
function isSortEnabledForTopic() {
if (!storageKey) return false;
try {
return sessionStorage.getItem(storageKey) === 'true';
} catch (e) {
console.error("Error reading sessionStorage:", e);
return false;
}
}
/**
* Enables or disables sorting persistence for the current topic.
* @param {boolean} enable - True to enable (store flag), false to disable (remove flag).
*/
function setSortPersistence(enable) {
if (!storageKey) return;
try {
if (enable) {
sessionStorage.setItem(storageKey, 'true');
console.log(`Sort preference saved for topic ${currentTopicId}`);
} else {
sessionStorage.removeItem(storageKey);
console.log(`Sort preference removed for topic ${currentTopicId}`);
}
} catch (e) {
console.error("Error writing to sessionStorage:", e);
}
}
/**
* Extracts the like count from a post element.
* @param {HTMLElement} postElement - The container element of a single post.
* @returns {number} The number of likes, or 0 if not found/invalid.
*/
function getLikeCount(postElement) {
// Existing function - unchanged
const likeSpan = postElement.querySelector('.like-dislike .forum-rating span[id^="likesfor"]');
if (likeSpan && likeSpan.textContent) {
const count = parseInt(likeSpan.textContent.trim(), 10);
return isNaN(count) ? 0 : count;
}
return 0;
}
/**
* Sorts the posts currently visible on the page by their like count.
* @param {boolean} [isInitialSort=false] - True if this is the automatic sort on page load.
*/
function sortPostsByLikes(isInitialSort = false) {
console.log("Attempting to sort posts...");
const postSelector = '#middle-block .col.s12[id^="post"]';
const posts = Array.from(document.querySelectorAll(postSelector));
console.log(`Found ${posts.length} elements matching post selector ('${postSelector}').`);
if (posts.length < 2) {
console.log("Not enough posts to sort.");
if (!isInitialSort) alert("Not enough posts on this page to sort.");
return; // Don't proceed if nothing to sort
}
const parentContainer = posts[0].parentNode;
if (!parentContainer) {
console.error("Critical Error: Could not find a parent container for the posts.");
if (!isInitialSort) alert("Error: Could not find the container element holding the posts.");
return;
}
console.log(`Identified parent container for posts: <${parentContainer.tagName} id="${parentContainer.id || ''}" class="${parentContainer.className || ''}">`);
const lastPostOriginalSibling = posts[posts.length - 1].nextSibling;
console.log("Reference node (sibling after last post):", lastPostOriginalSibling);
const postsData = posts.map(post => ({
element: post,
likes: getLikeCount(post)
}));
postsData.sort((a, b) => b.likes - a.likes);
console.log("Post data after sorting:", postsData.map(p => ({ id: p.element.id, likes: p.likes })));
// Detach all posts from the DOM *before* re-inserting
posts.forEach(post => post.remove());
// Re-insert posts back into their original parent container in sorted order
postsData.forEach(postData => {
parentContainer.insertBefore(postData.element, lastPostOriginalSibling);
});
console.log(`Posts have been re-inserted into parent in sorted order (Highest: ${postsData[0]?.likes}, Lowest: ${postsData[postsData.length - 1]?.likes})`);
// Set persistence ONLY if it wasn't the initial sort triggered by persistence
if (!isInitialSort) {
setSortPersistence(true);
// Update button state immediately after manual sort
updateButtonState(true, 'Sorted!'); // Show temporary feedback
setTimeout(() => updateButtonState(true), 1500); // Revert to standard "Sorted" state
} else {
// If it was an initial sort, just ensure the button state is correct
updateButtonState(true);
}
}
/**
* Handles the click event on the sort/unsort button.
*/
function handleButtonClick() {
const isCurrentlySorted = isSortEnabledForTopic();
const sortButton = document.getElementById(buttonId);
if (!sortButton) return;
if (isCurrentlySorted) {
// --- Unsort Action ---
console.log("Unsort button clicked.");
setSortPersistence(false);
sortButton.textContent = 'Reloading...';
sortButton.disabled = true;
window.location.reload(); // Reload page to get original order
} else {
// --- Sort Action ---
console.log("Sort button clicked.");
sortButton.textContent = 'Sorting...';
sortButton.disabled = true;
// Use setTimeout to allow the UI to update before potentially heavy sort operation
setTimeout(() => {
sortPostsByLikes(false); // false indicates it's a manual sort
// sortPostsByLikes will call updateButtonState after completion
}, 50);
}
}
/**
* Updates the button's appearance and behavior based on the sorted state.
* @param {boolean} isSorted - Whether the content is currently considered sorted.
* @param {string} [tempText=null] - Optional temporary text (like 'Sorting...' or 'Sorted!').
*/
function updateButtonState(isSorted, tempText = null) {
const sortButton = document.getElementById(buttonId);
if (!sortButton) return;
sortButton.disabled = false; // Re-enable by default
if (isSorted) {
sortButton.textContent = tempText || 'Unsort (Reload Page)';
sortButton.title = 'Click to remove sorting and reload the page for the original order.';
// Optional: Change style for "unsort" state if desired
// sortButton.style.backgroundColor = '#ff9800'; // Example: Orange for unsort
} else {
sortButton.textContent = tempText || 'Sort by Likes';
sortButton.title = 'Sort posts on this page by number of likes (descending). This preference will be remembered for this topic in this session.';
// Ensure original style is applied
sortButton.style.backgroundColor = 'rgb(33, 150, 243)'; // Restore blue
}
// If tempText is provided, it usually implies a temporary disabled state
if (tempText && (tempText === 'Sorting...' || tempText === 'Reloading...')) {
sortButton.disabled = true;
}
}
/**
* Creates and adds the Sort/Unsort button to the page.
*/
function addSortButton() {
console.log("Attempting to add sort button...");
const targetContainer = document.querySelector('#ftta-container');
if (!targetContainer) {
console.error("Could not find target container (#ftta-container) for sort button.");
return; // Exit if target container not found
}
if (document.getElementById(buttonId)){
console.log("Sort button already exists.");
return; // Exit if button already exists
}
const sortButton = document.createElement('button');
sortButton.id = buttonId;
sortButton.type = 'button';
// --- Style Application (Material UI Look) ---
sortButton.classList.add('btn-small', 'waves-effect', 'waves-light');
sortButton.style.backgroundColor = 'rgb(33, 150, 243)';
sortButton.style.color = 'white';
sortButton.style.border = 'none';
sortButton.style.borderRadius = '4px';
sortButton.style.padding = '6px 16px';
sortButton.style.fontSize = '0.875rem';
sortButton.style.fontWeight = '500';
sortButton.style.textTransform = 'none';
sortButton.style.letterSpacing = '0.02857em';
sortButton.style.boxShadow = '0px 3px 1px -2px rgba(0,0,0,0.2), 0px 2px 2px 0px rgba(0,0,0,0.14), 0px 1px 5px 0px rgba(0,0,0,0.12)';
sortButton.style.transition = 'background-color 250ms cubic-bezier(0.4, 0, 0.2, 1) 0ms, box-shadow 250ms cubic-bezier(0.4, 0, 0.2, 1) 0ms';
sortButton.style.lineHeight = '1.75';
sortButton.style.cursor = 'pointer';
sortButton.style.outline = 'none';
sortButton.style.marginLeft = '10px';
sortButton.style.verticalAlign = 'middle';
// --- End Style Application ---
sortButton.addEventListener('click', handleButtonClick);
targetContainer.appendChild(sortButton);
console.log("Sort button added successfully.");
// Initial button state check AFTER adding it to the DOM
updateButtonState(isSortEnabledForTopic());
}
// --- Main Execution ---
currentTopicId = getTopicId();
if (currentTopicId) {
storageKey = `tbd_sort_likes_topic_${currentTopicId}`;
console.log(`Operating on Topic ID: ${currentTopicId}. Storage key: ${storageKey}`);
// Function to run setup logic (add button, check/apply sort)
const setup = () => {
addSortButton(); // Creates the button and sets initial text/state
// If persistence is enabled for this topic, sort automatically
if (isSortEnabledForTopic()) {
console.log("Sort preference found for this topic. Applying sort automatically.");
// Use timeout to ensure DOM is fully ready after load event
setTimeout(() => sortPostsByLikes(true), 100); // true = initial sort
}
};
// Wait for the page content to be fully loaded
if (document.readyState === "complete" || document.readyState === "interactive") {
console.log("DOM ready state is complete/interactive.");
setup();
} else {
console.log("Adding 'load' event listener for setup.");
window.addEventListener('load', setup);
}
} else {
console.warn("Could not determine Topic ID from URL. Sort persistence disabled for this page.");
// Optionally, you could still add the button but without persistence:
// if (document.readyState === "complete" || document.readyState === "interactive") { addSortButton(); }
// else { window.addEventListener('load', addSortButton); }
// But the current logic implicitly handles this by not proceeding if topicId is null.
}
})();
Explain this javascript code for me
This is a JavaScript code written as a UserScript (also known as a Greasemonkey or Tampermonkey script). It's designed to run on a specific website, https://www.torrentbd.net/forums.php?action=viewtopic&*, and enhances the forum's functionality by adding a button to sort forum posts by the number of likes they receive. The sorting preference is persistent across pagination for the same topic, meaning if you sort posts by likes on page 1, it will remember your preference even when you navigate to page 2, 3, etc., of the same topic discussion.
The script uses sessionStorage to store the sorting preference temporarily (until the browser tab is closed). It's written in a modular fashion with clear functions for each task, making it maintainable and easy to understand.
// ==UserScript== ... // ==/UserScript==)This section provides information about the script to the UserScript manager (like Tampermonkey):
// @name TorrentBD - Persistent Sort Forum Posts by Likes
// @namespace http://tampermonkey.net/
// @version 1.5
// @description Adds a button to sort forum posts by likes on TorrentBD, persisting across pagination.
// @author Your Name Here
// @match https://www.torrentbd.net/forums.php?action=viewtopic&*
// @grant none
// @license MIT
@name: The name of the script.@namespace: A unique identifier (not critical here).@version: The current version of the script (helps with updates).@description: What the script does.@author: Who wrote it.@match: Only run this script on URLs matching this pattern. In this case, it's TorrentBD forum topic view pages.@grant none: This script doesn't need special permissions (like accessing cross-origin resources).@license: The script is under the MIT license (permissive open-source).The entire code is wrapped in:
(function() {
'use strict';
// ... all the code ...
})();
window) namespace.'use strict'; enables strict mode, which helps catch common coding mistakes (e.g., undeclared variables).const buttonId = 'sort-by-likes-button';
let currentTopicId = null;
let storageKey = null;
buttonId: The ID of the button element the script will create (sort-by-likes-button).currentTopicId: Extracted from the URL, identifies the current forum topic.storageKey: A dynamic key for sessionStorage, based on currentTopicId.getTopicId() FunctionExtracts the topicid parameter from the URL:
function getTopicId() {
try {
const urlParams = new URLSearchParams(window.location.search);
return urlParams.get('topicid');
} catch (e) {
console.error("Error parsing URL parameters:", e);
return null;
}
}
URLSearchParams API to parse ?action=viewtopic&topicid=12345.topicid value (e.g., "12345"), or null if there's an error.Example: For URL https://www.torrentbd.net/forums.php?action=viewtopic&topicid=4211, getTopicId() returns "4211".
isSortEnabledForTopic(), setSortPersistence(enable)Checking if sorting is enabled for the current topic:
function isSortEnabledForTopic() {
if (!storageKey) return false;
try {
return sessionStorage.getItem(storageKey) === 'true';
} catch (e) {
console.error("Error reading sessionStorage:", e);
return false;
}
}
storageKey isn't set (e.g., no topicid in URL), returns false.sessionStorage[storageKey]; if it's 'true', sorting is enabled.Enabling/disabling sorting persistence:
function setSortPersistence(enable) {
if (!storageKey) return;
try {
if (enable) {
sessionStorage.setItem(storageKey, 'true');
} else {
sessionStorage.removeItem(storageKey);
}
} catch (e) {
console.error("Error writing to sessionStorage:", e);
}
}
enable === true, stores 'true' in sessionStorage[storageKey].enable === false, removes the key from sessionStorage.Why sessionStorage? It's ideal here because:
tbd_sort_likes_topic_4211, tbd_sort_likes_topic_4212, etc.).getLikeCount(postElement)Extracts the like count from a single post element:
function getLikeCount(postElement) {
const likeSpan = postElement.querySelector('.like-dislike .forum-rating span[id^="likesfor"]');
if (likeSpan && likeSpan.textContent) {
const count = parseInt(likeSpan.textContent.trim(), 10);
return isNaN(count) ? 0 : count;
}
return 0;
}
<span id="likesforXXX">12</span> inside .like-dislike > .forum-rating.0 if invalid.Example Post HTML Snippet:
<div id="post123" class="col s12">
<!-- other post content -->
<div class="like-dislike">
<div class="forum-rating">
<span id="likesfor123">7</span> <!-- getLikeCount() extracts '7' -->
</div>
</div>
</div>
sortPostsByLikes(isInitialSort = false)The core sorting function:
function sortPostsByLikes(isInitialSort = false) {
const posts = Array.from(document.querySelectorAll('#middle-block .col.s12[id^="post"]'));
if (posts.length < 2) return; // Nothing to sort
const parentContainer = posts[0].parentNode;
const lastPostOriginalSibling = posts[posts.length - 1].nextSibling;
const postsData = posts.map(post => ({
element: post,
likes: getLikeCount(post)
}));
postsData.sort((a, b) => b.likes - a.likes); // Descending order
posts.forEach(post => post.remove()); // Detach from DOM
postsData.forEach(postData => {
parentContainer.insertBefore(postData.element, lastPostOriginalSibling);
});
if (!isInitialSort) {
setSortPersistence(true); // Save preference
updateButtonState(true, 'Sorted!'); // Feedback
setTimeout(() => updateButtonState(true), 1500); // Revert text
} else {
updateButtonState(true); // Just ensure button state is correct
}
}
Step-by-Step:
#middle-block .col.s12[id^="post"]).postsData array: { element: DOM_Post, likes: Number } for each post.postsData by likes (highest first)..remove()).insertBefore).!isInitialSort):
setSortPersistence(true))."Sorted!" briefly, then back to "Unsort (Reload Page)".handleButtonClick()What happens when the user clicks the Sort/Unsort button:
function handleButtonClick() {
const isCurrentlySorted = isSortEnabledForTopic();
if (isCurrentlySorted) {
// "Unsort" action: Reload page (to get original order)
setSortPersistence(false);
sortButton.textContent = 'Reloading...';
sortButton.disabled = true;
window.location.reload();
} else {
// "Sort" action
sortButton.textContent = 'Sorting...';
sortButton.disabled = true;
setTimeout(() => {
sortPostsByLikes(false); // Manual sort
}, 50);
}
}
isCurrentlySorted === true):
setSortPersistence(false))."Reloading...", disables it.window.location.reload()). This restores the original post order."Sorting...", disables it (to prevent double-clicks).sortPostsByLikes(false).updateButtonState(isSorted, tempText = null)Updates the Sort/Unsort button's appearance:
function updateButtonState(isSorted, tempText = null) {
const sortButton = document.getElementById(buttonId);
if (isSorted) {
sortButton.textContent = tempText || 'Unsort (Reload Page)';
// Optional: Style changes for "unsort" state
} else {
sortButton.textContent = tempText || 'Sort by Likes';
// Restore original style
}
sortButton.disabled = (tempText === 'Sorting...' || tempText === 'Reloading...');
}
isSorted === true: Button says "Unsort (Reload Page)".isSorted === false: Button says "Sort by Likes".tempText is set (e.g., "Sorting..."), disables the button temporarily.addSortButton()Creates and styles the button, appends it to the page:
function addSortButton() {
const targetContainer = document.querySelector('#ftta-container');
if (!targetContainer || document.getElementById(buttonId)) return;
const sortButton = document.createElement('button');
sortButton.id = buttonId;
sortButton.classList.add('btn-small', 'waves-effect', 'waves-light');
// ... extensive styling to match Material UI look ...
sortButton.addEventListener('click', handleButtonClick);
targetContainer.appendChild(sortButton);
updateButtonState(isSortEnabledForTopic()); // Initial state
}
#ftta-container (the target element where the button will be added).click event listener to handleButtonClick.updateButtonState() to set the initial button text based on whether sorting is already enabled.currentTopicId = getTopicId();
if (currentTopicId) {
storageKey = `tbd_sort_likes_topic_${currentTopicId}`;
const setup = () => {
addSortButton();
if (isSortEnabledForTopic()) {
setTimeout(() => sortPostsByLikes(true), 100); // Auto-sort if preference found
}
};
if (document.readyState === "complete" || document.readyState === "interactive") {
setup();
} else {
window.addEventListener('load', setup);
}
} else {
console.warn("Could not determine Topic ID.");
}
currentTopicId from the URL.storageKey (e.g., tbd_sort_likes_topic_4211).setup() function:
addSortButton() (creates the button).sortPostsByLikes(true)).setup() either immediately (if DOM is ready) or on window.load (if DOM is still loading).topicid (e.g., 4211).sessionStorage to see if sorting was previously enabled for topic_4211."Unsort (Reload Page)".sessionStorage."Unsort (Reload Page)".sessionStorage flag.sessionStorage).The code is robust: it handles errors, waits for the DOM, and provides clear console logs for debugging. The Material UI styling ensures the button blends well with the site's design. Happy sorting!