Unfix Fixed Elements

Intelligently reverses ill-conceived element fixing on sites like Medium.com

  1. // ==UserScript==
  2. // @name Unfix Fixed Elements
  3. // @namespace http://tampermonkey.net/
  4. // @version 3.0
  5. // @description Intelligently reverses ill-conceived element fixing on sites like Medium.com
  6. // @author reagent
  7. // @match *://*/*
  8. // @noframes
  9. // @grant GM.getValue
  10. // @grant GM.setValue
  11. // @run-at document_start
  12. // ==/UserScript==
  13.  
  14. (function () {
  15. 'use strict';
  16. let classNames = ["anti-fixing"]; // Odds of colliding with another class must be low
  17. let exemptions = [];
  18.  
  19. const inlineElements = [ // Non-block elements (along with html & body) which we will ignore
  20. "html", "script", "head", "meta", "title", "style", "script", "body",
  21. "a", "b", "label", "form", "abbr", "legend", "address", "link",
  22. "area", "mark", "audio", "meter", "b", "cite", "optgroup",
  23. "code", "option", "del", "q", "details", "small", "dfn", "select",
  24. "command", "source", "datalist", "span", "em", "strong", "font",
  25. "sub", "i", "summary", "iframe", "sup", "img", "tbody", "input",
  26. "td", "ins", "time", "kbd", "var"
  27. ];
  28. const fullBlockSelector = inlineElements.map(tag => ":not(" + tag + ")").join("");
  29. const ltdBlockSelector = "div,header,footer,nav";
  30.  
  31. class FixedWatcher {
  32. constructor(thorough = true) {
  33. this.watcher = new MutationObserver(this.onMutation.bind(this));
  34. this.selector = thorough ? fullBlockSelector : ltdBlockSelector;
  35. this.awaitingTick = false;
  36. this.modal = false;
  37. this.body = null;
  38. this.top = [];
  39. this.bottom = [];
  40. this.onScroll = this.onScroll.bind(this);
  41. }
  42.  
  43. start() {
  44. this.trackAll();
  45. this.watcher.observe(document, {
  46. childList: true,
  47. attributes: true,
  48. subtree: true,
  49. attributeFilter: ["class", "style"],
  50. attributeOldValue: true
  51. });
  52. window.addEventListener("scroll", this.onScroll);
  53. }
  54. onScroll() {
  55. if (this.awaitingTick || this.modal) return;
  56. this.awaitingTick = true;
  57. window.requestAnimationFrame(() => {
  58. const max = document.body.scrollHeight - window.innerHeight;
  59. const y = window.scrollY;
  60.  
  61. for (const item of this.top) {
  62. item.className = item.el.className;
  63. if (y === 0) {
  64. this.unFix(item.el);
  65. } else {
  66. this.fix(item.el);
  67. }
  68. }
  69.  
  70. for (const item of this.bottom) {
  71. item.className = item.el.className;
  72. if (y === max) {
  73. this.unFix(item.el);
  74. } else {
  75. this.fix(item.el);
  76. }
  77. }
  78. this.awaitingTick = false;
  79. })
  80. }
  81. onMutation(mutations) {
  82. for (let mutation of mutations) {
  83. if (mutation.type === "childList") {
  84. for (let node of mutation.removedNodes)
  85. this.untrack(node)
  86. for (let node of mutation.addedNodes) {
  87. if (node.nodeType !== Node.ELEMENT_NODE) continue;
  88.  
  89. if (node.matches(this.selector)) this.track(node);
  90. node.querySelectorAll(this.selector).forEach(el => this.track(el));
  91. }
  92. } else if (mutation.type === "attributes") {
  93. if (this.friendlyMutation(mutation)) continue;
  94.  
  95.  
  96. if (mutation.target.matches(this.selector)) {
  97. this.track(mutation.target);
  98. }
  99. if(mutation.target === document.body){
  100. const style = this.body || (this.body = getComputedStyle(document.body));
  101. if(this.modal = style.overflowY === "hidden"){
  102. window.requestAnimationFrame(() => this.restore());
  103. }
  104. }
  105. }
  106. }
  107.  
  108. }
  109.  
  110. friendlyMutation(mutation) { // Mutation came from us
  111. if (mutation.attributeName === "class") {
  112. if (this.top.findIndex(({ el, className }) => el === mutation.target && className === mutation.oldValue) !== -1) return true;
  113. if (this.bottom.findIndex(({ el, className }) => el === mutation.target && className === mutation.oldValue) !== -1) return true;
  114. }
  115. return false;
  116. }
  117. untrack(_el) {
  118. let i = this.top.findIndex(({ el }) => el.isSameNode(_el) || _el.contains(el));
  119. if (i !== -1) return !!this.top.splice(i, 1);
  120. i = this.bottom.findIndex(({ el }) => el.isSameNode(_el) || _el.contains(el));
  121. if (i !== -1) return !!this.bottom.splice(i, 1);
  122. return false;
  123. }
  124. trackAll() {
  125. const els = document.querySelectorAll(this.selector);
  126. for (const el of els)
  127. this.track(el);
  128. }
  129. fix(el) {
  130. for (const className of classNames)
  131. el.classList.add(className);
  132. }
  133. unFix(el) {
  134. for (const className of classNames)
  135. el.classList.remove(className);
  136. }
  137. getClassAttribs(el) {
  138. // Last-ditch effort to help figure out if the developer intended the fixed element to be fullscreen
  139. // i.e. explicitly defined both the top and bottom rules. If they did, then we leave the element alone.
  140. // Unfortunately, we can't get this info from .style or computedStyle, since .style only
  141. // applies when the rules are added directly to the element, and computedStyle automatically generates a value
  142. // for top/bottom if the opposite is set. Leaving us no way to know if the developer actually set the other value.
  143. const rules = [];
  144. for (const styleSheet of document.styleSheets) {
  145. try {
  146. for (const rule of styleSheet.cssRules) {
  147. if (el.matches(rule.selectorText)) {
  148. rules.push({ height: rule.style.height, top: rule.style.top, bottom: rule.style.bottom });
  149. }
  150. }
  151. } catch (e) {
  152. continue;
  153. }
  154. }
  155.  
  156. return rules.reduce((current, next) => ({
  157. height: next.height || current.height,
  158. top: next.top || current.top,
  159. bottom: next.bottom || current.bottom
  160. }), {
  161. height: "",
  162. top: "",
  163. bottom: ""
  164. });
  165. }
  166.  
  167. isAutoBottom(el, style) {
  168. if (style.bottom === "auto") return true;
  169. if (style.bottom === "0px") return false;
  170. if (el.style.bottom.length) return false;
  171. const { height, bottom } = this.getClassAttribs(el);
  172.  
  173. if (height === "100%" || bottom.length) return false;
  174.  
  175. return true;
  176. }
  177. isAutoTop(el, style) {
  178. if (style.top === "auto") return true;
  179. if (style.top === "0px") return false;
  180. if (el.style.top.length) return false;
  181. const { height, top } = this.getClassAttribs(el);
  182.  
  183. if (height === "100%" || top.length) return false;
  184.  
  185. return true;
  186. }
  187. topTracked(el) {
  188. return this.top.findIndex(({ el: _el }) => _el === el) !== -1;
  189. }
  190. bottomTracked(el) {
  191. return this.bottom.findIndex(({ el: _el }) => _el === el) !== -1;
  192. }
  193. isTop(el, style){
  194. const top = parseFloat(style.top);
  195. if(top > 0){
  196. const i = this.top.findIndex(({style}) => parseFloat(style.top)
  197. + parseFloat(style.height)
  198. + parseFloat(style.paddingTop)
  199. + parseFloat(style.paddingBottom) === top);
  200. if(i === -1) return false;
  201. }
  202. return !this.topTracked(el) && this.isAutoBottom(el, style);
  203. }
  204. isBottom(el, style){
  205. const bottom = parseFloat(style.bottom);
  206. if(bottom > 0){
  207. const i = this.bottom.findIndex(({style}) => parseFloat(style.bottom)
  208. + parseFloat(style.height)
  209. + parseFloat(style.paddingTop)
  210. + parseFloat(style.paddingBottom) === bottom);
  211. if(i === -1) return false;
  212. }
  213. return !this.bottomTracked(el) && this.isAutoTop(el, style);
  214. }
  215. track(el) {
  216. const style = window.getComputedStyle(el);
  217.  
  218. if (style.position === "fixed" || style.position === "sticky") {
  219. if (this.isTop(el, style)) {
  220. this.top.push({ el, style, className: el.className});
  221. this.onScroll();
  222. } else if (this.isBottom(el, style)) {
  223. this.bottom.push({ el, style, className: el.className });
  224. this.onScroll();
  225. }
  226. }
  227. }
  228.  
  229. stop() {
  230. this.watcher.disconnect();
  231. window.removeEventListener("scroll", this.onScroll);
  232. }
  233.  
  234. restore() {
  235. const all = this.top.concat(this.bottom);
  236.  
  237. for (let {el} of all) {
  238. for(const className of classNames){
  239. el.classList.remove(className);
  240. }
  241. }
  242. }
  243.  
  244. }
  245. const getSelectors = cssRule => cssRule.selectorText.split(",")[0].split(".").filter(i => i.length);
  246. const rankSelector = selector => selector.selectorText.split(".").length * -1;
  247. const getBestClass = cssRules => cssRules.reduce((bestSelector, curSelector) => rankSelector(bestSelector) < rankSelector(curSelector) ? curSelector :bestSelector)
  248. const getSurrogates = () => {
  249. const applicableRules = Array.from(document.styleSheets)
  250. .filter(sheet => { try { sheet.cssRules; return true } catch (e) { return false } })
  251. .map(sheet => Array.from(sheet.cssRules))
  252. .flat()
  253. .filter(cssClass => cssClass.style
  254. && cssClass.style.length === 1
  255. && cssClass.style[0] === "display"
  256. && cssClass.style.display === "none"
  257. && !cssClass.selectorText.match(/[\ \[\]\:\>\~\+]/g));
  258. if (!applicableRules.length) return;
  259.  
  260. const narrowed = applicableRules.filter(cssClass => cssClass.style.getPropertyPriority("display") === "important");
  261.  
  262. return narrowed.length ? getBestClass(narrowed) : getBestClass(applicableRules);
  263. }
  264. const insertSheet = () => new Promise((resolve, reject) => {
  265. document.documentElement.appendChild((() => {
  266. let el = document.createElement("style");
  267. el.setAttribute("type", "text/css");
  268. el.appendChild(document.createTextNode(`.${classNames[0]}{ display: none !important }`));
  269. el.addEventListener("load", resolve);
  270. return el;
  271. })());
  272. setTimeout(reject, 50);
  273. });
  274.  
  275. const isExempt = host => exemptions.indexOf(host) !== -1;
  276. const addExempt = host => !isExempt(host) && exemptions.push(host) && saveExempt();
  277. const removeExempt = host => (exemptions = exemptions.filter(e => e !== host)) && saveExempt();
  278. const saveExempt = () => GM.setValue("exemptions", JSON.stringify(exemptions));
  279. const init = () => {
  280. insertSheet()
  281. .catch(() => new Promise(resolve => {
  282. const surrogates = getSurrogates();
  283. if (!surrogates) throw "Unable to create stylesheet, and unable to find suitable alternatives";
  284. console.log("Unable to create stylesheet, using alternative selectors:", surrogates);
  285. classNames = getSelectors(surrogates);
  286. resolve();
  287. }))
  288. .then(async () => JSON.parse(await GM.getValue("exemptions", "[]")))
  289. .then(_exemptions => {
  290. exemptions = _exemptions;
  291.  
  292. if (!isExempt(document.location.host)) {
  293. window.fixer = new FixedWatcher();
  294. window.fixer.start();
  295. }
  296. })
  297. .then(() => window.addEventListener("keydown", e => {
  298. if (e.altKey && e.key === "F") { // ALT + SHIFT + F
  299. e.preventDefault();
  300. if (window.fixer) {
  301. const host = document.location.host;
  302. console.log("Removing fixer and exempting", host, "from fixing");
  303. addExempt(host);
  304.  
  305. window.fixer.stop();
  306. window.fixer.restore();
  307. window.fixer = null;
  308. } else {
  309. console.log("Adding fixer");
  310. removeExempt(document.location.host);
  311.  
  312. window.fixer = new FixedWatcher();
  313. window.fixer.start();
  314. }
  315. }
  316. }))
  317. }
  318.  
  319. init();
  320. })()