diff options
| author | Carson Fleming <cflems@cflems.net> | 2023-10-20 23:37:28 -0400 |
|---|---|---|
| committer | Carson Fleming <cflems@cflems.net> | 2023-10-20 23:37:28 -0400 |
| commit | 5636edd5b6af3486284b430f660b1b9e309a3671 (patch) | |
| tree | f065d63d75ba3aa08eefa51c2cab407dcac859c6 /static/js | |
| parent | 5b4f8c220bbcbe1ee4b684f91db7cc419e423a41 (diff) | |
| download | fle.ms-5636edd5b6af3486284b430f660b1b9e309a3671.tar.gz | |
Bring it all together and nitpick the appearance
Diffstat (limited to 'static/js')
| -rw-r--r-- | static/js/ajax.js | 47 | ||||
| -rw-r--r-- | static/js/slug.js | 10 |
2 files changed, 57 insertions, 0 deletions
diff --git a/static/js/ajax.js b/static/js/ajax.js new file mode 100644 index 0000000..e31a009 --- /dev/null +++ b/static/js/ajax.js @@ -0,0 +1,47 @@ +(function () { + const btn = document.querySelector('#shortenButton'); + const inpUrl = document.querySelector('#url'); + const inpSlug = document.querySelector('#slug'); + + function shorten (e) { + if (!inpUrl.value) return; + + const req = new XMLHttpRequest(); + req.addEventListener('load', () => { + const reply = JSON.parse(req.responseText); + if (req.status != 201) { + btn.innerText = reply.uiString || 'API Error'; + btn.classList.add('error'); + console.error(req.status, reply.errorMessage); + return; + } + + inpUrl.value = reply.data.shortUrl; + inpSlug.value = ''; + btn.removeEventListener('click', shorten); + btn.classList.remove('error'); + btn.innerText = 'Copy'; + btn.addEventListener('click', copyUrl); + inpUrl.focus(); + inpUrl.select(); + }); + req.addEventListener('error', () => { + btn.innerText = 'Connection Error'; + btn.classList.add('error'); + }) + + if (inpSlug.value) + req.open('PUT', '/'+encodeURIComponent(inpSlug.value)); + else + req.open('POST', '/'); + req.setRequestHeader('Content-Type', 'application/json'); + req.send(JSON.stringify({url: encodeURI(inpUrl.value)})); + } + + async function copyUrl(e) { + await navigator.clipboard.writeText(encodeURI(inpUrl.value)); + btn.innerText = 'Copied!'; + } + + btn.addEventListener('click', shorten); +})();
\ No newline at end of file diff --git a/static/js/slug.js b/static/js/slug.js new file mode 100644 index 0000000..f82635c --- /dev/null +++ b/static/js/slug.js @@ -0,0 +1,10 @@ +function generateSlug (len = 5) { + const ALPHA_SIZE = 36; + const MIN = 36**(len-1); + const MAX = 36**len; + const slugNumeric = Math.floor(Math.random() * (MAX-MIN))+MIN; + return slugNumeric.toString(ALPHA_SIZE); +} + +if (typeof module !== 'undefined') + module.exports = {generateSlug}; |
