Skip to content

Instantly share code, notes, and snippets.

@benjamine
Last active September 23, 2016 02:56
Show Gist options
  • Save benjamine/ab571f87d9123d5a34312b7d7ba48d1b to your computer and use it in GitHub Desktop.
Save benjamine/ab571f87d9123d5a34312b7d7ba48d1b to your computer and use it in GitHub Desktop.
Enhances Github Markdown Diffs
// ==UserScript==
// @name GithubMarkdownDiffRichify
// @namespace http://tampermonkey.net/
// @version 0.1
// @description enhances markdown diffs in github, makes links clickable and embeds images (only images in the repo)
// @author https://github.com/benjamine
// @match https://github.com/*/pull/*
// @match https://github.com/*/compare/*
// @match https://github.com/*/commit/*
// @grant none
// ==/UserScript==
(function() {
'use strict';
function markdownDiffRichify() {
let appliedCount = 0;
const headRef = document.querySelector('.head-ref');
let sourceMatch, username, repo, branch;
if (headRef) {
sourceMatch = /^([^\/]+)\/([^:]+):(.+)$/.exec(headRef.getAttribute('title'));
} else if (/\/compare\//.test(document.location.href)) {
sourceMatch = /github.com\/([^\/]+)\/([^\/]+)\/compare\/.+\.\.\.(.+)$/.exec(document.location.href);
} else if (/\/commit\//.test(document.location.href)) {
sourceMatch = /github.com\/([^\/]+)\/([^\/]+)\/commit\/(.+)$/.exec(document.location.href);
} else {
return;
}
username = sourceMatch[1];
repo = sourceMatch[2];
branch = sourceMatch[3];
if (/:/.test(branch)) {
sourceMatch = branch.split(':');
username = sourceMatch[0];
branch = sourceMatch[1];
}
function toArray(list) {
return Array.prototype.slice.call(list);
}
function getAbsoluteUrl(url, isImage) {
const isRelative = !/^(\w+\:)?\/\//.test(url);
if (!isRelative) {
return url;
}
var blob = /\.(md|txt|markdown)$/.test(url);
return 'https://github.com/' + username + '/' + repo +
(blob ? '/blob/' : '/raw/') + branch + '/' + url;
}
function richify(element) {
let lines = toArray(element.querySelectorAll('.blob-code-inner'));
lines.forEach(function(line) {
let html = line.innerHTML;
html = html.replace(/(\!?)\[([^\]]+)\]\(([^\)]+)\)/g, function(match, isImage, title, url) {
const isRelative = !/^(\w+\:)?\/\//.test(url);
const absoluteUrl = getAbsoluteUrl(url, isImage);
return '<a href="' + absoluteUrl + '" target="_blank">[' + title + '](' + url + ')' +
((isImage && isRelative) ? '<br/><img style="max-width:100%" src="' +
absoluteUrl + '" />' : '') +
'</a>';
});
if (html === line.innerHTML) {
return;
}
line.innerHTML = html;
appliedCount++;
});
}
toArray(document.querySelectorAll('.file-header')).filter(function(file) {
return /\.(md|markdown)$/.test(file.getAttribute('data-path'));
}).forEach(function(file) {
richify(file.nextElementSibling);
});
if (appliedCount < 0) {
return;
}
console.log('markdown diffs richified');
}
markdownDiffRichify();
document.addEventListener('pjax:end', markdownDiffRichify);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment