// ==UserScript== // @name Extend "AO3: Kudosed and seen history" | Export/Import + Standalone Light/Dark mode toggle // @description Add Export/Import history to TXT buttons at the bottom of the page │ Fix back-navigation not being collapsed │ Color and rename the Seen/Unseen buttons │ Add skip button │ Enhance the title │ Fix "Mark as seen on open" triggering on external links ║ Standalone feature: Light/Dark site skin toggle button. // @author C89sd // @version 1.35 // @match https://archiveofourown.org/* // @grant GM_xmlhttpRequest // @grant GM_addStyle // @namespace https://greasyfork.org/users/1376767 // @downloadURL none // ==/UserScript== 'use strict'; const ENHANCED_SEEN_BUTTON = true; // Seen button is colored and renamed / Immediately mark seen / Blink when navigating back const COLORED_TITLE_LINK = true; // |- Title becomes a colored link const ENHANCED_MARK_SEEN_ON_OPEN = true; // Autoclick the seen button on open. Change text to "SEEN Now" or "Old SEEN" based on original state (can only do that if original setting is disabled because this script runs after.) const IGNORE_EXTERNAL_LINKS = true; // |- Mark as seen when a link is clicked on AO3, not from other sites (e.g. link on reddit). If false, autosee all links but still mark 'SEEN Now' to you if it was a new or old link. const SITE_SKINS = [ "Default", "Reversi" ]; // -------------------------------------------------------------------------- // Skip Button // -------------------------------------------------------------------------- let currentSkipState; // Copied from @Min_ https://greasyfork.org/en/scripts/5835-ao3-kudosed-and-seen-history var KHList = { init: function(name, max_length) { this.name = name; this.max_length = max_length || 200000; this.list = localStorage.getItem('kudoshistory_' + this.name) || ','; return this; }, reload: function() { this.list = localStorage.getItem('kudoshistory_' + this.name) || this.list; return this; }, save: function() { try { localStorage.setItem('kudoshistory_' + this.name, this.list.slice(0, this.max_length)); } catch (e) { localStorage.setItem('kudoshistory_' + this.name, this.list.slice(0, this.list.length * 0.9)); } return this; }, hasId: function(work_id) { if (this.list.indexOf(',' + work_id + ',') > -1) { this.list = ',' + work_id + this.list.replace(',' + work_id + ',', ','); return true; } return false; }, add: function(work_id) { this.list = ',' + work_id + this.list.replace(',' + work_id + ',', ','); return this; }, remove: function(work_id) { this.list = this.list.replace(',' + work_id + ',', ','); return this; }, }; let skipped; function getWorkId() { const match = location.pathname.match(/\/works\/(\d+)/); return match ? match[1] : null; } const skipOff = ''; // '·' const skipOn = 'unskip'; function createSkipButton(workId, seenBtn) { skipped = Object.create(KHList).init('skipped'); const li = document.createElement('li'); li.style.padding = '0' const a = document.createElement('a'); currentSkipState = skipped.hasId(workId); a.textContent = currentSkipState ? skipOn : skipOff; a.className = 'khx-skip-btn'; a.style.color = getComputedStyle(seenBtn).color; // default text color is gray? copy other buttons. if (currentSkipState) { a.classList.add('hkx-skipped'); } a.addEventListener('click', function(e) { skipped.reload(); currentSkipState = skipped.hasId(workId); if (currentSkipState) { skipped.remove(workId); a.textContent = skipOff; a.classList.remove('hkx-skipped'); } else { skipped.add(workId); a.textContent = skipOn; a.classList.add('hkx-skipped'); } currentSkipState = !currentSkipState; skipped.save(); a.blur() }); li.appendChild(a); return li; } function insertSkipButton() { const workId = getWorkId(); if (!workId) return; const seenBtn = document.querySelector('#main .kh-seen-button'); if (!seenBtn || !seenBtn.parentNode) return; const skipBtnLi = createSkipButton(workId, seenBtn); // wrap both buttons in container so they don't get separated const container = document.createElement('div'); container.style.display = 'inline-block'; seenBtn.parentNode.insertBefore(container, seenBtn); container.appendChild(skipBtnLi); container.appendChild(seenBtn); // seenBtn.parentNode.insertBefore(skipBtnLi, seenBtn.nextSibling); } GM_addStyle(` .khx-skip-btn { padding: 0.23em 0.4em !important; box-shadow: none !important; background-image: none !important; background-clip: padding-box !important; border-radius: 0.25em 0 0 0.25em !important; } .khx-seen-btn { border-radius: 0 0.25em 0.25em 0 !important; border-left: 0px !important; padding: 0.23em 0.5em !important; box-shadow: none !important; background-image: none !important; background-clip: padding-box !important; } .hkx-skipped { background-color: rgb(238, 151, 40) !important; padding: 0.23em 0.5em !important; } `); insertSkipButton(); // -------------------------------------------------------------------------- // Collapse links clicked from search page // -------------------------------------------------------------------------- // The AO3 Kudosed History script requires a manual reload after a link is clicked: // - Clicked fics are not collpased and when navigating back. // - Seen changes made from the other page are not taken into account. // // To fix this: // Intercept clicks on links to immediately trigger the 'seen' button collapse and various blink effects. // Write the current fic id/state to localStorage from fics. // When back-navigating, read it back and try to find its link on-screen to update its collapsed status. let currentSeenState = null; // Updated inside of fics (MutationObserver on the fic's seen button). if (ENHANCED_SEEN_BUTTON) { const isWork = /^https:\/\/archiveofourown\.org(?:\/collections\/[^\/]+)?(\/works\/\d+)/ let refererData = {}; // {} | { workSlashId + seenState + skipState } of the referrer page (lastest when navigating back and forth). // When clicking a link & navigating back before the page is loaded, it doesn't blink. // To make it blink, we push the clicked link to localStorage, notifying ourselves. let clickedLink = false; let clickedLinkHref; let clickedLinkSeen; // About to leave page: write state for the next page to load. window.addEventListener("pagehide", function (event) { // Note: Doing this in 'unload'(desktop) or 'beforeunload'(mobile) caused 'event.persisted' to be false. const match = (clickedLink ? clickedLinkHref : window.location.href).match(isWork); if (match) { // Note: sessionStorage did not work on desktop; and GM_setValue bechmarked 27% slower than localStorage. if (clickedLink) { // Link clicked on AO3. The DB will be updated after the original script finises loading (work loaded). If we navigate back before, it will not be marked seen! // To prevent this, we write ourselves a message that the work was clicked. I we navigate back before the next page load we will see this message and close it ourselves, else it will be overwritten on the other side. localStorage.setItem("C89AO3_state", JSON.stringify({"workSlashId": match[1], "seenState": (clickedLinkSeen), "skipState": (currentSkipState)})); } else if (currentSeenState === null && refererData?.workSlashId === match[1]) { // Carry seenState back over adult content warning pages (they have no seen button). localStorage.setItem("C89AO3_state", JSON.stringify({"workSlashId": match[1], "seenState": (refererData?.seenState), "skipState": (refererData?.skipState)})); } else { localStorage.setItem("C89AO3_state", JSON.stringify({"workSlashId": match[1], "seenState": (currentSeenState), "skipState": (currentSkipState)})); } } else { localStorage.setItem("C89AO3_state", '{}'); } }); // Navigated back: load state communicated from originating page. // updated on page load/back navigation/etc. window.addEventListener("pageshow", function (event) { let data = localStorage.getItem("C89AO3_state"); refererData = JSON.parse(data ? data : '{}'); //console.log('navigated back: data=', data, ', persisted=', event.persisted) }); // Blink functionality. const flashCSS = ` @keyframes flash-glow { 0% { box-shadow: 0 0 4px currentColor; } 100% { box-shadow: 0 0 4px transparent; } } @keyframes slide-left { 0% { transform: translateX(6px); } 100% { transform: translateX(0); } } /* When opening, slide down */ li[role="article"]:not(.marked-seen).blink div.header.module { transition: all 0.25s ease-out; //0.15s } /* Always blink border */ li.blink { animation: flash-glow 0.25s ease-in 1; } /* When closing, slide title left */ //li.blink.marked-seen div.header.module { // animation: slide-left 0.15s ease-out 1; //} //li.blink.marked-seen { // animation: flash-glow 0.2s ease-out 1; //} /* When collapsing, slide title in */ //li[role="article"].blink.marked-seen * h4.heading { // transition: all 0.300s ease-out; //} //li[role="article"]:not(.marked-seen) * ul.required-tags { // transition: all 0.1s ease-out; //}`; GM_addStyle(flashCSS); let blinkTimeout; function blink(article) { // console.log("BLINK from ", article) clearTimeout(blinkTimeout); article.classList.remove('blink'); void article.offsetWidth; // reflow article.classList.add('blink'); blinkTimeout = setTimeout(() => { article.classList.remove('blink'); }, 250); } // Navigated back: blink + update seen state. window.addEventListener('pageshow', (event) => { //console.log("navigated back, persisted=", event.persisted, ', referer=', refererData) if (event.persisted) { // If we navigated back. if (refererData?.workSlashId) { // If we read a fic id from localStorage. // Try finding the link of the fic we navigated back from and toggle its parent visibility. // Note: use *= because there can be: '.com/works/123' or '.com/collections/u1/works/132' or ?foo at the end. const titleLink = document.querySelector(`h4.heading > a[href*="${refererData.workSlashId}"]`); if (titleLink) { const article = titleLink.closest('li[role="article"]'); if (article) { blink(article); if ( refererData?.seenState === true && !article.classList.contains('marked-seen')) { article.classList.add('marked-seen'); } else if (refererData?.seenState === false && article.classList.contains('marked-seen')) { article.classList.remove('marked-seen'); } if ( refererData?.skipState === true ) { article.classList.add('skipped-work'); } else if (refererData?.skipState === false) { article.classList.remove('skipped-work'); } } } } } }); // Floating seen button click: blink. // The AO3 script calls event.stopPropagation() so document.addEventListener('click') does not work, we do his: function onKhToggleClick(e) { // console.log("click (floating seen .kh-toggle) ", event.target) const article = event.target.closest('li[role="article"]'); if (article) { if (e.target.textContent === 'seen') blink(article); } } function attachToAll() { document.querySelectorAll('.kh-toggle').forEach(el => { // avoid double-binding if (!el.__khListenerAttached) { el.addEventListener('click', onKhToggleClick, /* capture */ true); el.__khListenerAttached = true; } }); } attachToAll(); // Title click: blink + send click event to floating seen button + redirect. document.addEventListener('click', function(event) { // console.log("click (title) ", event.target) const titleLink = event.target.closest('h4.heading > a'); if (titleLink) { const article = titleLink.closest('li[role="article"]'); if (article) { const seenButton = article.querySelector('div.kh-toggles>a') if (seenButton) { // Give the "seen" action time to execute before loading the page. event.preventDefault(); blink(article); // Click the seen button (unless the fic is collapsed - that would unmark it!). if (!article.classList.contains('marked-seen')) { seenButton.click(); } // Wait for seenButton.click() to complete before reloading. requestIdleCallback(() => { clickedLink = true; clickedLinkHref = titleLink.href; clickedLinkSeen = article.classList.contains('marked-seen'); window.location.href = titleLink.href; }); } } } }); } // -------------------------------------------------------------------------- // Dark/Light mode toggle // -------------------------------------------------------------------------- // GET the preferences form, find the current skin_id, and POST the preferences form with updated next skin_id. function toggleSiteSkin(user) { // GET the preferences fetch(`https://archiveofourown.org/users/${user}/preferences`, { method: 'GET', headers: { 'Content-Type': 'text/html' } }) .then(response => response.text()) .then(responseText => { const doc = new DOMParser().parseFromString(responseText, 'text/html'); // Extract the authenticity token const authenticity_token = doc.querySelector('input[name="authenticity_token"]')?.value; if (authenticity_token) { // console.log('authenticity_token: ', authenticity_token); // Log the token } else { alert('[userscript:Extend AO3] Error\n[authenticity_token] not found!'); return; } // Find the
const form = doc.querySelector('form.edit_preference'); if (form) { // console.log('Form:', form); // Log the form // Extract the action URL for the form submission const formAction = form.getAttribute('action'); // console.log('Form Action:', formAction); // Find the element:', skinSelect); // Log the select const workSkinIds = []; let currentSkinId = null; let unmatchedSkins = [...SITE_SKINS]; // Loop through the const options = skinSelect.querySelectorAll('option'); options.forEach(option => { const optionValue = option.value; const optionText = option.textContent.trim(); if (SITE_SKINS.includes(optionText)) { // console.log('- option: value=', optionValue, ", text=", optionText, option.selected ? "SELECTED" : "."); workSkinIds.push(optionValue); // Remove matched name from unmatchedSkins unmatchedSkins = unmatchedSkins.filter(name => name !== optionText); if (option.selected) { //