diff --git a/src/index.pug b/src/index.pug index d516a99..1079848 100644 --- a/src/index.pug +++ b/src/index.pug @@ -28,8 +28,9 @@ html(lang="en") label(for="text") Post text textarea#text(rows=6, name="text", required) section - label(for="instance") Mastodon instance URL - input#instance(type="url", name="instance", placeholder="https://", required) + datalist#instances_list + label(for="choose_instance") Choose your Mastodon instance + input#instance(type="url", name="instance", placeholder="https://", list="instances_list", required) section.remember input#remember(type="checkbox", name="remember") @@ -43,4 +44,4 @@ html(lang="en") section a(href="https://github.com/NickKaramoff/toot") This project on GitHub - script(src="index.js") \ No newline at end of file + script(src="index.js") diff --git a/src/script/index.js b/src/script/index.js index e0a697c..a2c3993 100644 --- a/src/script/index.js +++ b/src/script/index.js @@ -8,11 +8,13 @@ function normalizeUrl(url) { return url; } +const instance = document.getElementById('instance'); +const instances_list = document.getElementById('instances_list'); + var prefillInstance = window.localStorage.getItem('mastodon_instance'); var paramPairs = window.location.search.substr(1).split('&'); var paramPairsLength = paramPairs.length; - for (var i = 0; i < paramPairsLength; i++) { var paramPair = paramPairs[i].split('='); if (paramPair[0] === 'text') { @@ -24,10 +26,46 @@ for (var i = 0; i < paramPairsLength; i++) { delete i delete paramPair -if (prefillInstance != null) { - document.getElementById('instance').value = normalizeUrl(prefillInstance); +function instances_loading_error() { + console.error('Failed to fetch servers list from joinmastodon.'); } +function instances_loaded() { + if (this.status !== 200) { + instances_loading_error(); + return; + } + + const servers = JSON.parse(this.responseText); + + const chosen_instance = instance.value; + const domains = servers.map(obj => obj.domain); + if (chosen_instance && domains.indexOf(chosen_instance) === -1) { + domains.push(chosen_instance); + } + domains.sort(); + + for (const domain of domains) { + const opt = document.createElement('option'); + opt.value = normalizeUrl(domain); + instances_list.appendChild(opt); + } +} + +if (prefillInstance != null) { + instance.value = normalizeUrl(prefillInstance); +} + +instance.addEventListener('focus', function (e) { + if (instances_list.children.length === 0) { + const req = new XMLHttpRequest(); + req.addEventListener('load', instances_loaded); + req.addEventListener('error', instances_loading_error); + req.open('GET', 'https://api.joinmastodon.org/servers'); + req.send(); + } +}) + document .getElementById('form') .addEventListener('submit', function (e) { @@ -42,4 +80,4 @@ document var shareUrl = instance + "share?text=" + encodeURIComponent(text); window.open(shareUrl, '_blank', 'noopener,noreferrer') -}) + })