Pith - grit
grit/grit_chrome/grit.js [2.0 kb]
Modified: 18:55:48 154 026 (20 Aug 026)
3 Days Ago
(() => {
  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)/;
  const FIELD = /^(?:INPUT|TEXTAREA)$/;

  function fieldRange(el) {
    if (!el || !FIELD.test(el.tagName)) return null;
    try {
      return el.selectionStart === el.selectionEnd ? null : [el.selectionStart, el.selectionEnd];
    } catch {
      return null;
    }
  }

  function readSelection() {
    const el = document.activeElement;
    const r = fieldRange(el);
    if (r) return el.value.slice(r[0], r[1]);
    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 el = document.activeElement;
    const r = fieldRange(el);
    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();
    try {
      document.execCommand("copy");
    } finally {
      ta.remove();
    }

    if (r) {
      el.focus();
      el.setSelectionRange(r[0], r[1]);
    } else if (saved) {
      sel.removeAllRanges();
      sel.addRange(saved);
    }
  }

  const text = readSelection();
  if (text) copy(grit(text));
})();
Updates
Kerf - Android 157.026
Kiln - Android 157.026
Wedge - Android 156.026
Whittle - Linux 155.026
Grit - Firefox/Chrome 154.026

Menu
Calendar
Project Tin (024/029)
Miter
RSS Feed
User Avatar
@vgmlr
=SUM(parts)
0.00605
256,972 (+226)