(() => {
const HEADER =
/^(?:diff --git |index |--- |\+\+\+ |@@ |old mode |new mode |new file mode |deleted file mode |similarity index |dissimilarity index |rename from |rename to |copy from |copy to |Binary files |\\ No newline)/;
function readSelection() {
const el = document.activeElement;
if (el && /^(?:INPUT|TEXTAREA)$/.test(el.tagName) && el.selectionStart !== el.selectionEnd) {
return el.value.slice(el.selectionStart, el.selectionEnd);
}
return String(window.getSelection() ?? "");
}
function grit(text) {
const lines = text.split("\n");
const isDiff = lines.some((l) => /^[+-]/.test(l) && !HEADER.test(l));
if (!isDiff) return text;
return lines
.map((line) => {
const eol = line.endsWith("\r") ? "\r" : "";
const body = eol ? line.slice(0, -1) : line;
if (HEADER.test(body)) return line;
if (/^[+-]/.test(body)) return body.slice(1) + eol;
if (body.startsWith(" ")) return body.slice(1) + eol;
return line;
})
.join("\n");
}
function copy(text) {
const sel = window.getSelection();
const saved = sel && sel.rangeCount ? sel.getRangeAt(0).cloneRange() : null;
const ta = document.createElement("textarea");
ta.value = text;
ta.setAttribute("readonly", "");
ta.style.cssText =
"position:fixed;top:0;left:0;width:1px;height:1px;padding:0;border:0;opacity:0";
(document.body ?? document.documentElement).appendChild(ta);
ta.select();
document.execCommand("copy");
ta.remove();
if (saved) {
sel.removeAllRanges();
sel.addRange(saved);
}
}
const text = readSelection();
if (text) copy(grit(text));
})();