// ==UserScript== // @name AO3: Reading Time & Quality Score // @description Combined reading time and quality scoring. Highly customizable. // @author BlackBatCat // @version 1.3 // @match *://archiveofourown.org/ // @match *://archiveofourown.org/tags/*/works* // @match *://archiveofourown.org/works* // @match *://archiveofourown.org/users/* // @match *://archiveofourown.org/collections/* // @match *://archiveofourown.org/bookmarks* // @match *://archiveofourown.org/series/* // @license MIT // @grant none // @namespace https://greasyfork.org/users/1498004 // @downloadURL none // ==/UserScript== (function () { "use strict"; // DEFAULT CONFIGURATION const DEFAULTS = { // Feature Toggles enableReadingTime: true, enableQualityScore: true, // Reading Time Settings wpm: 375, alwaysCountReadingTime: true, readingTimeLvl1: 120, readingTimeLvl2: 360, // Quality Score Settings alwaysCountQualityScore: true, alwaysSortQualityScore: false, hideHitcount: false, useNormalization: false, userMaxScore: 32, minKudosToShowScore: 100, colorThresholdLow: 10, colorThresholdHigh: 20, // Shared Color Settings colorGreen: "#3e8fb0", colorYellow: "#f6c177", colorRed: "#eb6f92", colorText: "#ffffff", enableBarColors: true, }; // Current config, loaded from localStorage let CONFIG = { ...DEFAULTS }; // Variables to track the state of the page let countable = false; let sortable = false; let statsPage = false; // --- HELPER FUNCTIONS --- const $ = (selector, root = document) => root.querySelectorAll(selector); const $1 = (selector, root = document) => root.querySelector(selector); // Load user settings from localStorage const loadUserSettings = () => { if (typeof Storage === "undefined") return; const savedConfig = localStorage.getItem("ao3_reading_quality_config"); if (savedConfig) { try { const parsedConfig = JSON.parse(savedConfig); CONFIG = { ...DEFAULTS, ...parsedConfig }; } catch (e) { console.error("Error loading saved config, using defaults:", e); CONFIG = { ...DEFAULTS }; } } }; // Save all settings to localStorage const saveAllSettings = () => { if (typeof Storage !== "undefined") { localStorage.setItem( "ao3_reading_quality_config", JSON.stringify(CONFIG) ); } }; // Save a specific setting const saveSetting = (key, value) => { CONFIG[key] = value; saveAllSettings(); }; // Reset all settings to defaults const resetAllSettings = () => { if (confirm("Reset all settings to defaults?")) { if (typeof Storage !== "undefined") { localStorage.removeItem("ao3_reading_quality_config"); } CONFIG = { ...DEFAULTS }; countRatio(); calculateReadtime(); } }; // Robust number extraction from element const getNumberFromElement = (element) => { if (!element) return NaN; let text = element.getAttribute("data-ao3e-original") || element.textContent; if (text === null) return NaN; let cleanText = text.replace(/[,\s ]/g, ""); if (element.matches("dd.chapters")) { cleanText = cleanText.split("/")[0]; } const number = parseInt(cleanText, 10); return isNaN(number) ? NaN : number; }; // --- READING TIME FUNCTIONS --- const checkCountable = () => { const foundStats = $("dl.stats"); if (foundStats.length === 0) return; // Cache common parent selectors for efficiency for (const stat of foundStats) { const li = stat.closest("li.work, li.bookmark"); if (li) { countable = true; sortable = true; return; } if (stat.closest(".statistics")) { countable = true; sortable = true; statsPage = true; return; } if (stat.closest("dl.work")) { countable = true; return; } } }; const calculateReadtime = () => { if (!countable || !CONFIG.enableReadingTime) return; $("dl.stats").forEach((statsElement) => { // Check if readtime already exists to avoid duplicates if ($1("dt.readtime", statsElement)) return; const wordsElement = $1("dd.words", statsElement); if (!wordsElement) return; const words_count = getNumberFromElement(wordsElement); if (isNaN(words_count)) return; const minutes = words_count / CONFIG.wpm; const hrs = Math.floor(minutes / 60); const mins = (minutes % 60).toFixed(0); const minutes_print = hrs > 0 ? hrs + "h" + mins + "m" : mins + "m"; // Create elements with optimized styling const readtime_label = document.createElement("dt"); readtime_label.className = "readtime"; readtime_label.textContent = "Readtime:"; const readtime_value = document.createElement("dd"); readtime_value.className = "readtime"; readtime_value.textContent = minutes_print; // Apply base styling Object.assign(readtime_value.style, { borderRadius: "4px", padding: "0 6px", fontWeight: "bold", display: "inline-block", verticalAlign: "middle", }); if (CONFIG.enableBarColors) { readtime_value.style.color = CONFIG.colorText; if (minutes < CONFIG.readingTimeLvl1) { readtime_value.style.backgroundColor = CONFIG.colorGreen; } else if (minutes < CONFIG.readingTimeLvl2) { readtime_value.style.backgroundColor = CONFIG.colorYellow; } else { readtime_value.style.backgroundColor = CONFIG.colorRed; } } // Inherit font size and line height from dl.stats const parentStats = readtime_value.closest("dl.stats"); if (parentStats) { const computed = window.getComputedStyle(parentStats); readtime_value.style.lineHeight = computed.lineHeight; readtime_value.style.fontSize = computed.fontSize; } // Insert after words_value wordsElement.insertAdjacentElement("afterend", readtime_label); readtime_label.insertAdjacentElement("afterend", readtime_value); }); }; // --- QUALITY SCORE FUNCTIONS --- const calculateWordBasedScore = (kudos, hits, words) => { if (hits === 0 || words === 0 || kudos === 0) return 0; const effectiveChapters = words / 5000; const adjustedHits = hits / Math.sqrt(effectiveChapters); return (100 * kudos) / adjustedHits; }; const countRatio = () => { if (!countable || !CONFIG.enableQualityScore) return; $("dl.stats").forEach((statsElement) => { // Check if score already exists to avoid duplicates if ($1("dt.kudoshits", statsElement)) return; const hitsElement = $1("dd.hits", statsElement); const kudosElement = $1("dd.kudos", statsElement); const wordsElement = $1("dd.words", statsElement); const parentLi = statsElement.closest("li"); try { const hits = getNumberFromElement(hitsElement); const kudos = getNumberFromElement(kudosElement); const words = getNumberFromElement(wordsElement); if (isNaN(hits) || isNaN(kudos) || isNaN(words)) return; // Hide score if kudos below threshold if (kudos < CONFIG.minKudosToShowScore) { // Remove any previous score elements if (statsElement.querySelector("dt.kudoshits")) statsElement.querySelector("dt.kudoshits").remove(); if (statsElement.querySelector("dd.kudoshits")) statsElement.querySelector("dd.kudoshits").remove(); return; } let rawScore = calculateWordBasedScore(kudos, hits, words); if (kudos < 10) rawScore = 1; let displayScore = rawScore; // Normalize thresholds if normalization is enabled let thresholdLow = CONFIG.colorThresholdLow; let thresholdHigh = CONFIG.colorThresholdHigh; if (CONFIG.useNormalization) { displayScore = (rawScore / CONFIG.userMaxScore) * 100; displayScore = Math.min(100, displayScore); displayScore = Math.ceil(displayScore); // round up, no decimals thresholdLow = Math.ceil( (CONFIG.colorThresholdLow / CONFIG.userMaxScore) * 100 ); thresholdHigh = Math.ceil( (CONFIG.colorThresholdHigh / CONFIG.userMaxScore) * 100 ); } else { displayScore = Math.round(displayScore * 10) / 10; } const ratioLabel = document.createElement("dt"); ratioLabel.className = "kudoshits"; ratioLabel.textContent = "Score:"; const ratioValue = document.createElement("dd"); ratioValue.className = "kudoshits"; ratioValue.textContent = displayScore; ratioValue.style.borderRadius = "4px"; ratioValue.style.padding = "0 6px"; ratioValue.style.fontWeight = "bold"; ratioValue.style.display = "inline-block"; ratioValue.style.verticalAlign = "middle"; if (CONFIG.enableBarColors) { ratioValue.style.color = CONFIG.colorText; ratioValue.style.fontWeight = "bold"; if (displayScore >= thresholdHigh) { ratioValue.style.backgroundColor = CONFIG.colorGreen; } else if (displayScore >= thresholdLow) { ratioValue.style.backgroundColor = CONFIG.colorYellow; } else { ratioValue.style.backgroundColor = CONFIG.colorRed; } } else { ratioValue.style.backgroundColor = ""; ratioValue.style.color = "inherit"; ratioValue.style.fontWeight = "inherit"; } // Inherit font size and line height from dl.stats const parentStats = ratioValue.closest("dl.stats"); if (parentStats) { const computed = window.getComputedStyle(parentStats); ratioValue.style.lineHeight = computed.lineHeight; ratioValue.style.fontSize = computed.fontSize; } hitsElement.insertAdjacentElement("afterend", ratioValue); hitsElement.insertAdjacentElement("afterend", ratioLabel); if (CONFIG.hideHitcount && !statsPage && hitsElement) { hitsElement.style.display = "none"; } if (parentLi) parentLi.setAttribute("kudospercent", displayScore); } catch (error) { console.error("Error calculating score:", error); } }); }; const sortByRatio = (ascending = false) => { if (!sortable) return; $("dl.stats").forEach((statsElement) => { const parentLi = statsElement.closest("li"); const list = parentLi?.parentElement; if (!list) return; const listElements = Array.from(list.children); listElements.sort((a, b) => { const aPercent = parseFloat(a.getAttribute("kudospercent")) || 0; const bPercent = parseFloat(b.getAttribute("kudospercent")) || 0; return ascending ? aPercent - bPercent : bPercent - aPercent; }); list.innerHTML = ""; list.append(...listElements); }); }; // --- SETTINGS POPUP --- const showSettingsPopup = () => { // Get AO3 input field background color let inputBg = "#fffaf5"; // fallback const testInput = document.createElement("input"); document.body.appendChild(testInput); try { const computedBg = window.getComputedStyle(testInput).backgroundColor; if ( computedBg && computedBg !== "rgba(0, 0, 0, 0)" && computedBg !== "transparent" ) { inputBg = computedBg; } } catch (e) {} testInput.remove(); const popup = document.createElement("div"); popup.style.cssText = ` position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); background: ${inputBg}; padding: 20px; border-radius: 8px; box-shadow: 0 0 20px rgba(0,0,0,0.2); z-index: 10000; width: 90%; max-width: 500px; max-height: 80vh; overflow-y: auto; font-family: inherit; font-size: 16px; box-sizing: border-box; `; // Ensure headings inherit font family const style = document.createElement("style"); style.textContent = ` #ao3-rtqs-popup h3, #ao3-rtqs-popup h4 { font-family: inherit !important; } `; popup.id = "ao3-rtqs-popup"; document.head.appendChild(style); const form = document.createElement("form"); // Calculate values for display const displayThresholdLow = CONFIG.useNormalization ? Math.ceil((CONFIG.colorThresholdLow / CONFIG.userMaxScore) * 100) : CONFIG.colorThresholdLow; const displayThresholdHigh = CONFIG.useNormalization ? Math.ceil((CONFIG.colorThresholdHigh / CONFIG.userMaxScore) * 100) : CONFIG.colorThresholdHigh; form.innerHTML = `