foxygit / foxygit Log in
A tiny read-only git web frontend — browse bare repos with just PHP and git, no database, no framework.
commits tags

/assets/app.js · 1.37 KB

raw
/* foxygit — the only JavaScript in the project: copy-to-clipboard for the
   clone command. Everything else works without JS, and so does this: without
   it the button is still a readable, selectable line of text. */

document.addEventListener('click', function (ev) {
  var btn = ev.target.closest('[data-copy]');
  if (!btn) return;

  copy(btn.dataset.copy).then(function (ok) {
    if (!ok) return;
    btn.classList.add('copied');
    clearTimeout(btn._copyTimer);
    btn._copyTimer = setTimeout(function () { btn.classList.remove('copied'); }, 1500);
  });
});

/* navigator.clipboard needs a secure context (https or localhost). Falls back
   to a hidden textarea + execCommand so plain-http access still works. */
function copy(text) {
  if (navigator.clipboard && window.isSecureContext) {
    return navigator.clipboard.writeText(text).then(function () { return true; },
                                                    function () { return legacyCopy(text); });
  }
  return Promise.resolve(legacyCopy(text));
}

function legacyCopy(text) {
  var ta = document.createElement('textarea');
  ta.value = text;
  ta.setAttribute('readonly', '');
  ta.style.position = 'fixed';
  ta.style.opacity = '0';
  document.body.appendChild(ta);
  ta.select();
  var ok = false;
  try { ok = document.execCommand('copy'); } catch (e) { ok = false; }
  document.body.removeChild(ta);
  return ok;
}