mutations

GitHub mutations observer library script

Verzia zo dňa 12.04.2017. Pozri najnovšiu verziu.

Tento skript by nemal byť nainštalovaný priamo. Je to knižnica pre ďalšie skripty, ktorú by mali používať cez meta príkaz // @require https://update.greasyforks.org/scripts/28721/187823/mutations.js

/* GitHub mutations observer library script v0.1.3
 * Detect changes to various elements and trigger an event
 * Copyright © 2017 Rob Garrison
 * License: MIT
 */
/* jshint esnext:true, unused:true */
(() => {
	"use strict";

	// prefix for event & document body class name, e.g. "ghmo:container"
	const prefix = "ghmo",
		targets = {
			// pjax container (covers general, repo & gists)
			"[data-pjax-container]": {
				count: 0,
				name: "container"
			},
			// comment preview active
			".js-preview-body": {
				count: 0,
				name: "preview"
			},
			// progressively loaded comments; "# items not shown"
			// example: https://github.com/isaacs/github/issues/18
			".js-discussion": {
				count: 0,
				name: "comments"
			},
			// progressively loaded content (diff files)
			".js-diff-progressive-container, .data.blob-wrapper, .js-diff-load-container": {
				count: 0,
				name: "diff"
			}
		},
		list = Object.keys(targets),
		container = document.querySelector("body");

	let timer;

	function fireEvents() {
		list.forEach(selector => {
			if (targets[selector].count > 0) {
				// event => "ghmo:container", "ghmo:comments"
				const event = new Event(prefix + ":" + targets[selector].name);
				document.dispatchEvent(event);
			}
			targets[selector].count = 0;
		});
	}

	// prevent script from installing more than once
	if (!container.classList.contains(prefix + "-enabled")) {
		container.classList.add(prefix + "-enabled");

		new MutationObserver(mutations => {
			mutations.forEach(mutation => {
				clearTimeout(timer);
				const target = mutation.target;
				if (target) {
					list.forEach(selector => {
						if (target.matches(selector)) {
							targets[selector].count++;
console.log('mutation observed on', target.className);
						}
					});
				}
				timer = setTimeout(() => {
					fireEvents();
				}, 200);
			});
		}).observe(container, {
			childList: true,
			subtree: true
		});

	}

})();
长期地址
遇到问题?请前往 GitHub 提 Issues。