Unfix Fixed Elements

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

当前为 2019-06-06 提交的版本,查看 最新版本

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

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址