// ==UserScript==
// @name AO3: Fic's Style, Blacklist, Bookmarks
// @namespace https://codeberg.org/schegge
// @description Change font, size, width and background of a work + blacklist: hide works that contain certains tags or text, have too many tags/fandoms/relations/chapters/words and other options + fullscreen reading mode + bookmarks: save the position you stopped reading a fic + number of words for each chapter and estimated reading time
// @version 3.6.3
// @author Schegge
// @match *://archiveofourown.org/*
// @match *://www.archiveofourown.org/*
// @grant GM_getValue
// @grant GM_setValue
// @grant GM.getValue
// @grant GM.setValue
// @downloadURL none
// ==/UserScript==
// gm4 polyfill https://greasemonkey.github.io/gm4-polyfill/gm4-polyfill.js
if (typeof GM == 'undefined') {
this.GM = {};
Object.entries({
'GM_getValue': 'getValue',
'GM_setValue': 'setValue'
}).forEach(([oldKey, newKey]) => {
let old = this[oldKey];
if (old && (typeof GM[newKey] == 'undefined')) {
GM[newKey] = function(...args) {
return new Promise((resolve, reject) => {
try { resolve(old.apply(this, args)); } catch (e) { reject(e); }
});
};
}
});
}
(async function() {
const SN = 'stblbm';
// check which page
const Check = {
// script version
version: async function() {
if (await getStorage('version', '1') !== 363) {
setStorage('version', 363);
return true;
}
return false;
},
// on search pages but not on personal user profile
black: function() {
let user = document.querySelector('#greeting .user a[href*="/users/"]') || false;
user = user && window.location.pathname.includes(user.href.split('/users/')[1]);
return document.querySelector('li.blurb.group:not(.collection):not(.tagset):not(.skins)') && !user;
},
// include /works/(numbers) and /works/(numbers)/chapters/(numbers)
// and exclude /works/(whatever)navigate
work: function() {
return /\/works\/\d+(\/chapters\/\d+)?(?!.*navigate)/.test(window.location.pathname);
},
// Full Screen
fullScreen: false
};
// new version check
if (await Check.version()) {
document.body.insertAdjacentHTML('beforeend',
`
- you can now add tags and authors to your blacklist with ALT + click on the tag/author's name;
- bug fixed: the text in the blacklist menu is now visible also on the 'Reversi' site skin;
- minor changes for better compatibility on mobile.
`;
document.querySelector('#header ul.primary.navigation.actions').appendChild(featureMenu);
document.getElementById(`${SN}-feature-save`).addEventListener('click', function() {
Feature.style = document.getElementById(`${SN}-feature-style`).checked;
Feature.book = document.getElementById(`${SN}-feature-book`).checked;
Feature.black = document.getElementById(`${SN}-feature-black`).checked;
let wpm = document.getElementById(`${SN}-feature-wpm`).value.trim();
Feature.wpm = wpm ? Math.min(Math.max(parseInt(wpm), 0), 1000) : 0;
setStorage('feature', Feature);
this.textContent = 'SAVING...';
window.location.reload();
});
// add estimated reading time for every fic found
if (Feature.wpm) {
for (let work of document.querySelectorAll('dl.stats dd.words')) {
let numWords = work.textContent.replace(/,/g, '');
work.insertAdjacentHTML('afterend', `
Time:
${countTime(numWords)}
`);
}
}
/** BOOKMARKS **/
if (Feature.book) {
const Bookmarks = {
list: [],
getValues: async function() {
this.list = await getStorage('bookmarks', '[]');
},
setValues: function() {
setStorage('bookmarks', this.list);
},
fromBook: window.location.search === '?bookmark',
getUrl: window.location.pathname.split('/works/')[1],
getTitle: function() {
let title = document.querySelector('#workskin .preface.group h2.title.heading')
.textContent.trim().substring(0, 28);
// get the number of the chapter if chapter by chapter
if (this.getUrl.includes('/chapters/')) {
title += ` (${
document.querySelector('#chapters > .chapter > .chapter.preface.group > h3 > a')
.textContent.replace('Chapter ', 'ch')
})`;
}
return title;
},
getPosition: function() {
let position = getScroll();
// calculate % if chapter by chapter view or work completed (number/number is the same)
if (window.location.pathname.includes('/chapters/') ||
/(\d+)\/\1/.test(document.querySelector('dl.stats dd.chapters').textContent)) {
position = (position / getDocHeight()).toFixed(4) + '%';
}
return position;
},
checkIfExist: function(what, link) {
let url = link || this.getUrl;
let found = false;
for (let [index, bookmark] of this.list.entries()) {
// check if the same fic already exists
if (bookmark[0].split('/chapters/')[0] !== url.split('/chapters/')[0]) {
continue;
}
// i need the index to delete the old bookmark (for change or delete)
if (what === 'cancel') {
found = index;
break;
// check if the same chapter
} else if (bookmark[0] === url) {
// retrieve the bookmark position
if (what === 'book') {
found = bookmark[2];
// if the bookmark is in %
if (found.toString().includes('%')) {
found = parseFloat(found.replace('%', '')) * getDocHeight();
}
} else {
// just check if a bookmark exist
found = true;
}
break;
}
}
return found;
},
cancel: function(url) {
let found = this.checkIfExist('cancel', url);
// !== false because it can return 0 for the index
if (found !== false) this.list.splice(found, 1);
},
getNew: function() {
this.cancel();
this.list.push([this.getUrl, this.getTitle(), this.getPosition()]);
this.setValues();
},
html: function() {
let bookMenu = document.createElement('li');
bookMenu.id = `${SN}-book`;
bookMenu.className = 'dropdown';
bookMenu.setAttribute('aria-haspopup', 'true');
bookMenu.innerHTML = 'Bookmarks';
let bookMenuDrop = document.createElement('ul');
bookMenuDrop.className = 'menu dropdown-menu';
bookMenu.appendChild(bookMenuDrop);
document.querySelector('#header ul.primary.navigation.actions').appendChild(bookMenu);
if (this.list.length) {
let self = this;
let clickDelete = function() {
self.cancel(this.getAttribute('data-url'));
self.setValues();
this.style.display = 'none';
this.previousSibling.style.opacity = '.4';
};
for (let item of this.list) {
let bookMenuLi = document.createElement('li');
bookMenuLi.className = `${SN}-opts`;
bookMenuLi.innerHTML = `${item[1]}`;
let bookMenuDelete = document.createElement('a');
bookMenuDelete.className = `${SN}-book-delete`;
bookMenuDelete.title = 'delete bookmark';
bookMenuDelete.setAttribute('data-url', item[0]);
bookMenuDelete.textContent = 'x';
bookMenuDelete.addEventListener('click', clickDelete);
bookMenuLi.appendChild(bookMenuDelete);
bookMenuDrop.appendChild(bookMenuLi);
}
} else {
bookMenuDrop.innerHTML = '
`;
if ('options' in input) {
h += `';
} else {
h += ``;
}
h += '
';
}
styleMenu.innerHTML = `
${h}
`;
document.body.appendChild(styleMenu);
document.getElementById(`${SN}-style-save`).addEventListener('click', () => {
let pos = getScroll() / getDocHeight();
for (const name in inputs) {
this.opts[name] = styleMenu.querySelector(`#${name}`).value;
}
this.setValues();
setScroll(pos * getDocHeight());
});
document.getElementById(`${SN}-style-reset`).addEventListener('click', () => {
let pos = getScroll() / getDocHeight();
styleMenu.parentElement.removeChild(styleMenu);
for (const [name, input] of Object.entries(inputs)) {
this.opts[name] = input.default;
}
this.html();
setScroll(pos * getDocHeight());
});
document.getElementById(`${SN}-style-button`).addEventListener('click', () => {
styleMenu.classList.toggle(`${SN}-style-hide`);
});
}
};
await Styling.getValues();
Styling.html();
} // END Feature.style
// # words and time for every chapter, if the fic has chapters
if (Feature.wpm) {
for (let chapter of document.querySelectorAll('#chapters > .chapter > div.userstuff.module')) {
// -2 because of hidden
Chapter Text
let numWords = chapter.textContent.replace(/['’‘-]/g, '').match(/\w+/g).length - 2;
chapter.parentElement.insertAdjacentHTML('afterbegin',
`
this chapter has ${numWords} words (time: ${
countTime(numWords)})
`);
}
}
// remove all the non-breaking white spaces
document.getElementById('chapters').innerHTML = document.getElementById('chapters')
.innerHTML.replace(/ /g, ' ');
} // END Check.work()
/** BLACKLIST **/
if (Feature.black && Check.black()) {
addCSS(`${SN}-blacklisting`,
`[data-${SN}-visibility="remove"],
[data-${SN}-visibility="hide"] > :not(.header),
[data-${SN}-visibility="hide"] > .header > :not(h4) { display: none !important; }
[data-${SN}-visibility="hide"] > .header,
[data-${SN}-visibility="hide"] > .header > h4 {
margin: 0 !important; min-height: auto; font-size: .9em; font-style: italic; }
[data-${SN}-visibility="hide"] { opacity: .6; }
[data-${SN}-visibility="hide"]::before {
content: "\\2573 " attr(data-${SN}-reasons); font-size: .8em; }`
);
const Blacklist = {
lists : {
Tag: [],
Text: [],
Author: []
},
opts: {
show: true,
pause: false,
maxTags: 0,
maxRelations: 0,
minIncomplete: 0,
minFandoms: 0,
maxFandoms: 0,
minChapters: 0,
maxChapters: 0,
minWords: 0,
maxWords: 0,
langs: ''
},
blurb: 'li.blurb.group',
getValues: async function() {
this.lists.Tag = await getStorage('blacklistTags', '[]');
this.lists.Text = await getStorage('blacklistText', '[]');
this.lists.Author = await getStorage('blacklistAuthors', '[]');
Object.assign(this.opts, await getStorage('blacklistOpts', '{}'));
},
findTags: function(work) {
return this.opts.maxTags &&
work.querySelectorAll('.tag').length > this.opts.maxTags;
},
findRelations: function(work) {
return this.opts.maxRelations &&
work.querySelectorAll('.tags .relationships .tag').length > this.opts.maxRelations;
},
findLangs: function(work) {
return this.opts.langs && work.querySelector('dd.language') &&
!this.opts.langs.toLowerCase().includes(work.querySelector('dd.language').textContent.toLowerCase().trim());
},
getFandoms: function(work) {
if ((this.opts.minFandoms || this.opts.maxFandoms) && work.querySelector('.header .fandoms .tag')) {
let numFandoms = work.querySelectorAll('.header .fandoms .tag').length;
if (this.opts.minFandoms && numFandoms < this.opts.minFandoms ||
this.opts.maxFandoms && numFandoms > this.opts.maxFandoms) {
return `Fandoms: ${numFandoms}`;
}
}
return [];
},
getChapters: function(work) {
if ((this.opts.minChapters || this.opts.maxChapters) &&
work.querySelector('dd.chapters')) {
let numCh = Number(work.querySelector('dd.chapters').textContent.split('/')[0]);
if (this.opts.minChapters && numCh < this.opts.minChapters ||
this.opts.maxChapters && numCh > this.opts.maxChapters) {
return `Chapters: ${numCh}`;
}
}
return [];
},
getWords: function(work) {
if ((this.opts.minWords || this.opts.maxWords) && work.querySelector('dd.words')) {
let numWords = Number(work.querySelector('dd.words').textContent.replace(/,/g, '')) / 1000;
if (this.opts.minWords && numWords < this.opts.minWords ||
this.opts.maxWords && numWords > this.opts.maxWords) {
return `Words: ${Math.round(numWords * 1000)}`;
}
}
return [];
},
getIncomplete: function(work) {
if (this.opts.minIncomplete && work.querySelector('.required-tags .complete-no')) {
// millisecs in an average month = 30.4days*24hrs*60mins*60secs*1000
let updated = (
Date.now() - new Date(work.querySelector('.datetime').textContent).getTime()
) / (30.4*24*60*60*1000);
if (updated > this.opts.minIncomplete) {
return `Updated: ${Math.floor(updated)}mnth ago`;
}
}
return [];
},
ifMatch: function(elem, list, flag) {
let found = false;
for (let value of this.lists[list]) {
let pattern = value.trim().replace(/[.+?^${}()|[\]\\]/g, '\\$&');
if (!pattern) break;
// wildcard
pattern = pattern.replace(/\*/g, '.*');
// match 2 words in any order
pattern = pattern.replace(/(.+)&&(.+)/, '(?=.*$1)(?=.*$2).*');
// only otp
if (elem.parent === 'relationships') {
// to delete fandom's name in the tag
elem.text = elem.text.replace(/\(.+\)$/, '');
pattern = pattern.replace(/(.+)&!(.+)/, '(?=.*\\/)((?=.*$1)(?!.*$2)|(?=.*$2)(?!.*$1)).*');
}
let regex;
if (flag === 'free') regex = new RegExp(pattern, 'i'); // for text
else regex = new RegExp(`^${pattern}$`, 'i');
if (regex.test(elem.text)) {
if (flag === 'free') found = `${list}: ${value}`; // show the rule that matched (for text)
else if (elem.parent === 'heading') found = list; // show only list name (for author)
else found = `${list}: ${elem.text}`; // show the entire matched tag
break;
}
}
return found;
},
getReasons: function(work, list, where, flag = '') {
if (!this.lists[list].length) return [];
let filtered = [];
for (let elem of work.querySelectorAll(where)) {
let found = this.ifMatch({
text: elem.textContent.trim(),
parent: elem.parentElement.className
}, list, flag);
if (found) filtered.push(found);
}
return filtered;
},
setVisibility: function() {
for (let el of document.querySelectorAll(`${this.blurb}[data-${SN}-visibility]`)) {
el.removeAttribute(`data-${SN}-visibility`);
el.removeAttribute(`data-${SN}-reasons`);
}
if (this.opts.pause) return;
for (let work of document.querySelectorAll(this.blurb)) {
let reasons = []
.concat(this.getReasons(work, 'Author', 'h4.heading a[rel="author"]'))
.concat(this.getIncomplete(work))
.concat(this.getWords(work))
.concat(this.getChapters(work))
.concat(this.getFandoms(work))
.concat(this.getReasons(work, 'Text', 'h4.heading a:first-child, .summary', 'free'))
.concat(this.getReasons(work, 'Tag',
'.tags .tag, .required-tags span:not(.warnings) span.text, .header .fandoms .tag'));
if (this.findRelations(work)) reasons.unshift('Relations');
if (this.findTags(work)) reasons.unshift('Tags');
if (this.findLangs(work)) reasons.unshift('Language');
if (!reasons.length) continue;
if (this.opts.show) {
work.setAttribute(`data-${SN}-visibility`, 'hide');
work.setAttribute(`data-${SN}-reasons`, reasons.join(' - '));
} else {
work.setAttribute(`data-${SN}-visibility`, 'remove');
}
}
},
getArray: function(string) {
return string.trim() ? string.split(',').map(s => s.trim()).filter(s => s.length) : [];
},
getInt: function(string, min = 0) {
let number = string.trim() ? Math.max(parseInt(string), 0) : 0;
if (number < min) number = 0;
return number;
},
setValues: function() {
// when changes are made manually on the menu
this.lists.Tag = this.getArray(document.getElementById(`${SN}-black-tags`).value);
this.lists.Text = this.getArray(document.getElementById(`${SN}-black-text`).value);
this.lists.Author = this.getArray(document.getElementById(`${SN}-black-authors`).value);
this.opts.maxTags = this.getInt(document.getElementById(`${SN}-black-maxTags`).value);
this.opts.maxRelations = this.getInt(document.getElementById(`${SN}-black-maxRelations`).value);
this.opts.minIncomplete = this.getInt(document.getElementById(`${SN}-black-minIncomplete`).value);
this.opts.minFandoms = this.getInt(document.getElementById(`${SN}-black-minFandoms`).value);
this.opts.maxFandoms = this.getInt(document.getElementById(`${SN}-black-maxFandoms`).value);
this.opts.minChapters = this.getInt(document.getElementById(`${SN}-black-minChapters`).value);
this.opts.maxChapters = this.getInt(document.getElementById(`${SN}-black-maxChapters`).value, this.opts.minChapters);
this.opts.minWords = this.getInt(document.getElementById(`${SN}-black-minWords`).value);
this.opts.maxWords = this.getInt(document.getElementById(`${SN}-black-maxWords`).value, this.opts.minWords);
this.opts.langs = document.getElementById(`${SN}-black-langs`).value;
this.opts.show = document.getElementById(`${SN}-black-show`).checked;
this.opts.pause = document.getElementById(`${SN}-black-pause`).checked;
setStorage('blacklistTags', this.lists.Tag);
setStorage('blacklistText', this.lists.Text);
setStorage('blacklistAuthors', this.lists.Author);
setStorage('blacklistOpts', this.opts);
this.setVisibility();
},
updateValues: function() {
// when new tags or authors are added by click
document.getElementById(`${SN}-black-tags`).value = this.lists.Tag.join(', ');
document.getElementById(`${SN}-black-authors`).value = this.lists.Author.join(', ');
setStorage('blacklistTags', this.lists.Tag);
setStorage('blacklistAuthors', this.lists.Author);
this.setVisibility();
},
html: function() {
let blackMenu = document.createElement('li');
blackMenu.id = `${SN}-black`;
blackMenu.className = 'dropdown';
blackMenu.setAttribute('aria-haspopup', 'true');
blackMenu.innerHTML = `Blacklist