2022-04-29 23:53:42 +00:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
(() => {
|
|
|
|
document.addEventListener('DOMContentLoaded', (_) => {
|
2022-04-30 00:36:15 +00:00
|
|
|
let waiting = false;
|
2022-04-29 23:53:42 +00:00
|
|
|
let xhr;
|
|
|
|
|
2022-04-30 00:36:15 +00:00
|
|
|
const shortened = document.getElementById('shortened');
|
|
|
|
const info = document.getElementById('info');
|
2022-04-29 23:53:42 +00:00
|
|
|
const field = document.getElementById('url');
|
|
|
|
const form = document.getElementById('form');
|
|
|
|
|
2022-04-30 00:36:15 +00:00
|
|
|
// Select the full link with one click
|
|
|
|
shortened.onclick = () => {
|
|
|
|
this.focus();
|
|
|
|
this.select();
|
|
|
|
};
|
|
|
|
|
|
|
|
// Set up the actual submission
|
2022-04-29 23:53:42 +00:00
|
|
|
form.addEventListener('submit', (event) => {
|
|
|
|
// We need to create a different body, so prevent the default submission.
|
|
|
|
event.preventDefault();
|
|
|
|
|
|
|
|
if (waiting) {
|
|
|
|
// Prevent multiple requests.
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get the URL the user is trying to shorten.
|
2022-04-30 00:36:15 +00:00
|
|
|
let url = document.getElementById('url').value;
|
|
|
|
|
|
|
|
// If it doesn't have a protocol, assume https.
|
|
|
|
if (!/^\w+:\/\/.*$/.test(url)) {
|
|
|
|
url = 'https://' + url;
|
|
|
|
}
|
2022-04-29 23:53:42 +00:00
|
|
|
|
|
|
|
// Encode the URL as Base64.
|
|
|
|
const encoded = btoa(encodeURIComponent(url).replace(/%([0-9A-F]{2})/g, (match, p1) =>
|
|
|
|
String.fromCharCode('0x' + p1)
|
|
|
|
));
|
|
|
|
|
|
|
|
// POST the body to /shorten.
|
|
|
|
xhr = new XMLHttpRequest();
|
|
|
|
xhr.open('POST', '/shorten', true);
|
|
|
|
xhr.overrideMimeType('text/plain');
|
|
|
|
xhr.send(encoded);
|
|
|
|
xhr.onload = () => {
|
2022-04-30 00:36:15 +00:00
|
|
|
waiting = false;
|
2022-04-29 23:53:42 +00:00
|
|
|
switch (xhr.status) {
|
|
|
|
case 200:
|
|
|
|
let slug = xhr.response;
|
2022-04-30 00:36:15 +00:00
|
|
|
const short_link = `${window.location.href}l/${slug}`;
|
|
|
|
|
|
|
|
// Display to the user
|
|
|
|
|
|
|
|
shortened.innerText = short_link;
|
|
|
|
|
|
|
|
info.setAttribute('state', 'info');
|
|
|
|
info.innerText = 'Link successfully shortened and copied to your clipboard.';
|
|
|
|
|
|
|
|
// Copy the link to the clipboard
|
|
|
|
|
|
|
|
navigator.clipboard.writeText(short_link);
|
|
|
|
break;
|
2022-04-29 23:53:42 +00:00
|
|
|
default:
|
2022-04-30 00:36:15 +00:00
|
|
|
info.setAttribute('state', 'error');
|
|
|
|
info.innerText = xhr.response;
|
|
|
|
break;
|
2022-04-29 23:53:42 +00:00
|
|
|
}
|
|
|
|
};
|
|
|
|
xhr.onerror = () => {
|
2022-04-30 00:36:15 +00:00
|
|
|
waiting = false;
|
|
|
|
info.setAttribute('state', 'error');
|
|
|
|
info.innerText = "Failed to shorten the URL. Please try again.";
|
2022-04-29 23:53:42 +00:00
|
|
|
};
|
|
|
|
});
|
|
|
|
});
|
|
|
|
})();
|