Auto-redirect in presence of search parameters

This commit is contained in:
2023-12-13 23:11:22 +01:00
parent dbe74f4ed1
commit f5f4e85e50
4 changed files with 45 additions and 18 deletions

View File

@@ -1,24 +1,38 @@
const storageType = 'localStorage'
var data = {}
let data = {}
const infoEl = document.getElementById('info')
const formEl = document.getElementById('search')
const errors = {
missingQuery: new TypeError('Query is missing.'),
noFoundInstances: new TypeError('No instances were found.'),
}
function buildSearchURL (opts = {}) {
if (typeof opts.query !== 'string') throw errors.missingQuery
if (!('instances' in data)) throw errors.noFoundInstances
if (data.instances.length === 0) throw errors.noFoundInstances
// Random instance
const n = Math.floor(Math.random() * data.instances.length)
const instanceURL = data.instances[n]
// Build URL
const params = new URLSearchParams({
q: opts.query
})
const url = `${instanceURL}?${params.toString()}`
return url
}
// Register event listeners
formEl.addEventListener('submit', (event) => {
event.preventDefault()
if ('instances' in data && data.instances.length > 0) {
// Random instance
const n = Math.floor(Math.random() * data.instances.length)
const instanceURL = data.instances[n]
// Assign URL
const params = new URLSearchParams({
q: formEl.query.value
})
const url = `${instanceURL}?${params.toString()}`
location.assign(url)
}
location.assign(buildSearchURL({
query: formEl.query.value
}))
})
function locallyGetInstances () {
@@ -73,9 +87,19 @@ if (Date.now() > timestamp + 3_600_000 /* 1 hour */) {
}
}
// Auto-redirect in presence of search parameters
if (location.search.length > 0) {
const searchParams = new URLSearchParams(location.search.slice(1))
if (searchParams.has('q')) {
location.assign(buildSearchURL({
query: searchParams.get('q')
}))
}
}
if (data.instances.length > 0) {
infoEl.textContent = `${data.instances.length} instances`
} else {
infoEl.classList.add('error')
infoEl.textContent = '0 instances'
}
}