Skip to content

Instantly share code, notes, and snippets.

@shomah4a
Last active April 27, 2016 00:53
Show Gist options
  • Save shomah4a/24fbbef61f8511605b27bf36116be590 to your computer and use it in GitHub Desktop.
Save shomah4a/24fbbef61f8511605b27bf36116be590 to your computer and use it in GitHub Desktop.
issue のコメントへのリンクをクリックすると展開するグリモン
(function () {
'use strict';
var arr = Array.prototype;
function getCommentLinks() {
var result = [];
var elems = document.getElementsByClassName('issue-link');
return Array.prototype.filter.call(elems, function (e) {
return e.getAttribute('href').includes('#issuecomment-');
});
}
var cache = {};
function makeKey(url) {
var u = new URL(url);
u.hash = '';
var key = u.toString();
return key;
}
function getFromCache(url) {
var key = makeKey(url);
if (key in cache) {
return cache[key];
}
return null;
}
function putToCache(url, value) {
cache[makeKey(url)] = value;
}
function __get(url, cb) {
var cached = getFromCache(url);
if (cached !== null) {
cb(cached);
return;
}
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
cb(xhr);
putToCache(url, xhr);
}
};
xhr.send(null);
}
getCommentLinks().forEach(function (e) {
var href = e.getAttribute('href');
var url = new URL(href);
var id = url.hash.slice(1);
// wrap element
var wrapped = document.createElement('span');
// clone
var cloned = document.createElement('a');
cloned.setAttribute('class', 'issue-link js-issue-link');
cloned.setAttribute('href', href);
cloned.innerHTML = e.innerHTML;
// link
var link = document.createElement('a');
link.setAttribute('class', 'issue-link js-issue-link');
link.setAttribute('href', href);
link.innerHTML = '⇒';
link.setAttribute('target', '_blank');
// placeholder
var holder = document.createElement('span');
holder.style.setProperty('display', 'none');
var n = document.createElement('span');
n.innerHTML = ' ';
wrapped.appendChild(cloned);
wrapped.appendChild(n);
wrapped.appendChild(link);
wrapped.appendChild(holder);
e.replaceWith(wrapped);
cloned.onclick = function () {
function dispSwitch() {
var d = holder.style.display;
if (d == 'none') {
holder.style.setProperty('display', 'inline');
} else {
holder.style.setProperty('display', 'none');
}
}
if (!holder.loaded) {
__get(href, function(xhr) {
var txt = xhr.responseText;
var elem = document.createElement('div');
elem.innerHTML = txt;
var comments = arr.filter.call(elem.getElementsByClassName('comment'), function (e) {
return e.getAttribute('id') == id;
});
if (comments.length === 0) {
return;
}
var comment = comments[0];
holder.appendChild(comment);
holder.loaded = true;
dispSwitch();
});
} else {
dispSwitch();
}
return false;
};
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment