393 lines
15 KiB
JavaScript
393 lines
15 KiB
JavaScript
/*!
|
||
* MozOut Mozambique domain search widget 1.0.0
|
||
* Plain JavaScript, no dependencies, no cookies. MIT License, Copyright (c) 2026 RLX Holdings.
|
||
* Usage: <div data-domain-search></div> <script src="domain-search.js" defer></script>
|
||
*/
|
||
(function (window, document) {
|
||
'use strict';
|
||
|
||
var API_URL = 'https://api.mozout.co.mz';
|
||
var DEFAULT_TLD = '.co.mz';
|
||
var TIMEOUT_MS = 15000;
|
||
|
||
var TEXT = {
|
||
en: {
|
||
label: 'Find your domain',
|
||
placeholder: 'mybusiness' + DEFAULT_TLD,
|
||
search: 'Search',
|
||
checking: 'Checking…',
|
||
available: '{d} is available',
|
||
registered: '{d} is already registered',
|
||
unknown: 'We could not confirm {d} right now. Try again in a moment.',
|
||
notAllowed: 'The name {d} is not allowed.',
|
||
perYear: '{p} per year',
|
||
premium: 'Premium name',
|
||
quote: 'Price on request',
|
||
freeWith: 'Free with {plan} ({cycle})',
|
||
register: 'Register',
|
||
registerName: 'Register {d}',
|
||
transfer: 'Is it yours? Transfer it',
|
||
alternatives: 'Other free names',
|
||
extensions: 'Other extensions',
|
||
free: 'Available',
|
||
taken: 'Registered',
|
||
invalid: 'Type a domain name, such as mybusiness' + DEFAULT_TLD + '.',
|
||
notSupported: 'We do not sell this extension yet.',
|
||
rate: 'Too many lookups. Try again in {s} seconds.',
|
||
network: 'We could not check right now. Try again later.'
|
||
},
|
||
pt: {
|
||
label: 'Encontre o seu domínio',
|
||
placeholder: 'omeunegocio' + DEFAULT_TLD,
|
||
search: 'Pesquisar',
|
||
checking: 'A verificar…',
|
||
available: '{d} está livre',
|
||
registered: '{d} já está registado',
|
||
unknown: 'Não conseguimos confirmar {d} agora. Tente daqui a pouco.',
|
||
notAllowed: 'O nome {d} não é permitido.',
|
||
perYear: '{p} por ano',
|
||
premium: 'Nome premium',
|
||
quote: 'Preço sob consulta',
|
||
freeWith: 'Grátis com {plan} ({cycle})',
|
||
register: 'Registar',
|
||
registerName: 'Registar {d}',
|
||
transfer: 'É seu? Transfira-o',
|
||
alternatives: 'Outros nomes livres',
|
||
extensions: 'Outras extensões',
|
||
free: 'Livre',
|
||
taken: 'Registado',
|
||
invalid: 'Escreva um nome de domínio, como omeunegocio' + DEFAULT_TLD + '.',
|
||
notSupported: 'Ainda não vendemos esta extensão.',
|
||
rate: 'Demasiadas pesquisas. Tente de novo daqui a {s} segundos.',
|
||
network: 'Não conseguimos verificar agora. Tente mais tarde.'
|
||
}
|
||
};
|
||
|
||
var CSS =
|
||
'.dsw{font:inherit;color:inherit;max-width:640px}' +
|
||
'.dsw *{box-sizing:border-box}' +
|
||
'.dsw-sr{position:absolute!important;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}' +
|
||
'.dsw-form{display:flex;gap:8px;flex-wrap:wrap}' +
|
||
'.dsw-input{flex:1 1 220px;min-width:0;font:inherit;padding:10px 12px;border:1px solid var(--dsw-border,#8a8f98);border-radius:var(--dsw-radius,8px);background:var(--dsw-field,#fff);color:var(--dsw-field-text,#1f2328)}' +
|
||
'.dsw-btn,.dsw-go{font:inherit;font-weight:600;padding:10px 18px;border:0;border-radius:var(--dsw-radius,8px);background:var(--dsw-accent,#0b5cad);color:var(--dsw-accent-text,#fff);cursor:pointer;text-decoration:none;display:inline-block;line-height:1.3}' +
|
||
'.dsw-btn:hover,.dsw-go:hover{filter:brightness(1.1)}' +
|
||
'.dsw-input:focus-visible,.dsw-btn:focus-visible,.dsw-go:focus-visible,.dsw a:focus-visible{outline:3px solid var(--dsw-focus,#f2a900);outline-offset:2px}' +
|
||
'.dsw-out{margin-top:12px}' +
|
||
'.dsw-card{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:10px;padding:14px;border:1px solid var(--dsw-border,#8a8f98);border-radius:var(--dsw-radius,8px)}' +
|
||
'.dsw-title{font-weight:700;margin:0;overflow-wrap:anywhere}' +
|
||
'.dsw-ok .dsw-title{color:var(--dsw-ok,#146c2e)}' +
|
||
'.dsw-no .dsw-title{color:var(--dsw-no,#a1271d)}' +
|
||
'.dsw-meta{margin:4px 0 0;font-size:.92em}' +
|
||
'.dsw-meta a{color:var(--dsw-link,inherit);text-decoration:underline}' +
|
||
'.dsw-list{list-style:none;margin:8px 0 0;padding:0}' +
|
||
'.dsw-list li{display:flex;flex-wrap:wrap;justify-content:space-between;align-items:center;gap:8px;padding:8px 0;border-top:1px solid var(--dsw-line,rgba(127,127,127,.3))}' +
|
||
'.dsw-name{overflow-wrap:anywhere}' +
|
||
'.dsw-h{font-size:1em;margin:14px 0 0}' +
|
||
'.dsw-msg{margin:0;padding:10px 0}' +
|
||
'.dsw-tag{font-size:.85em;margin-left:6px;opacity:.85}' +
|
||
'.dsw-spin{display:inline-block;width:1em;height:1em;margin-right:8px;vertical-align:-2px;border:2px solid currentColor;border-right-color:transparent;border-radius:50%;animation:dsw-r .8s linear infinite}' +
|
||
'@keyframes dsw-r{to{transform:rotate(360deg)}}' +
|
||
'@media (prefers-reduced-motion:reduce){.dsw-spin{animation:none;border-right-color:currentColor;opacity:.5}}' +
|
||
'@media (prefers-color-scheme:dark){.dsw-input{background:var(--dsw-field,#1f2328);color:var(--dsw-field-text,#f0f3f6)}.dsw-ok .dsw-title{color:var(--dsw-ok,#5fd38a)}.dsw-no .dsw-title{color:var(--dsw-no,#ff8a80)}}';
|
||
|
||
var counter = 0;
|
||
|
||
function addStyle() {
|
||
if (document.getElementById('dsw-style')) return;
|
||
var s = document.createElement('style');
|
||
s.id = 'dsw-style';
|
||
s.textContent = CSS;
|
||
(document.head || document.documentElement).appendChild(s);
|
||
}
|
||
|
||
function pickLang(wanted) {
|
||
var list = wanted ? [wanted] : (navigator.languages && navigator.languages.length ? navigator.languages : [navigator.language || 'en']);
|
||
for (var i = 0; i < list.length; i++) {
|
||
var l = String(list[i] || '').toLowerCase().slice(0, 2);
|
||
if (l === 'pt' || l === 'en') return l;
|
||
}
|
||
return 'en';
|
||
}
|
||
|
||
function fill(text, values) {
|
||
return text.replace(/\{(\w+)\}/g, function (m, k) {
|
||
return values[k] !== undefined ? values[k] : m;
|
||
});
|
||
}
|
||
|
||
function el(tag, cls, text) {
|
||
var e = document.createElement(tag);
|
||
if (cls) e.className = cls;
|
||
if (text !== undefined) e.textContent = text;
|
||
return e;
|
||
}
|
||
|
||
function safeUrl(url) {
|
||
return typeof url === 'string' && /^https:\/\/[^\s"'<>]+$/i.test(url) ? url : null;
|
||
}
|
||
|
||
// "https://www.Example.co.mz/path" -> "example.co.mz"; "example" -> "example" + extension
|
||
function normalise(value, tld) {
|
||
var v = String(value || '').trim().toLowerCase();
|
||
v = v.replace(/^[a-z]+:\/\//, '').replace(/^www\./, '').replace(/[\/?#].*$/, '').replace(/\.+$/, '');
|
||
v = v.replace(/\s+/g, '');
|
||
if (!v) return '';
|
||
if (v.indexOf('.') === -1) v += tld;
|
||
return /^[a-z0-9 -]([a-z0-9 --]*[a-z0-9 -])?(\.[a-z0-9 --]+)+$/.test(v) ? v : null;
|
||
}
|
||
|
||
function request(path, params, signal) {
|
||
var qs = [];
|
||
for (var k in params) {
|
||
if (params[k]) qs.push(encodeURIComponent(k) + '=' + encodeURIComponent(params[k]));
|
||
}
|
||
var url = API_URL + path + (qs.length ? '?' + qs.join('&') : '');
|
||
return fetch(url, {
|
||
method: 'GET',
|
||
headers: { Accept: 'application/json' },
|
||
credentials: 'omit',
|
||
mode: 'cors',
|
||
signal: signal
|
||
}).then(function (res) {
|
||
return res.json().catch(function () { return {}; }).then(function (body) {
|
||
if (res.ok) return body;
|
||
var err = new Error((body.error && body.error.message) || 'HTTP ' + res.status);
|
||
err.status = res.status;
|
||
err.code = body.error && body.error.code;
|
||
err.reason = body.error && body.error.details && body.error.details.reason;
|
||
err.retryAfter = parseInt(res.headers.get('Retry-After') || (body.error && body.error.details && body.error.details.retry_after) || '60', 10);
|
||
throw err;
|
||
});
|
||
});
|
||
}
|
||
|
||
function priceText(item, t) {
|
||
var p = item.price;
|
||
if (item.quote_required || (p && p.quote_required)) return t.quote;
|
||
if (typeof p === 'string') return fill(t.perYear, { p: p });
|
||
if (p && p.formatted && p.formatted.register) return fill(t.perYear, { p: p.formatted.register });
|
||
if (p && typeof p.register === 'number') return fill(t.perYear, { p: p.register.toFixed(2) + ' ' + (p.currency || '') });
|
||
return '';
|
||
}
|
||
|
||
function goButton(url, name, t) {
|
||
var href = safeUrl(url);
|
||
if (!href) return null;
|
||
var a = el('a', 'dsw-go', t.register);
|
||
a.href = href;
|
||
a.setAttribute('aria-label', fill(t.registerName, { d: name }));
|
||
return a;
|
||
}
|
||
|
||
function Widget(root, options) {
|
||
this.root = root;
|
||
this.lang = pickLang(options.lang);
|
||
this.t = TEXT[this.lang];
|
||
this.currency = (options.currency || '').toUpperCase();
|
||
var exts = String(options.extensions || '').split(',').map(function (x) {
|
||
x = x.trim().toLowerCase();
|
||
return x && x.charAt(0) !== '.' ? '.' + x : x;
|
||
}).filter(Boolean);
|
||
this.extensions = exts.length ? exts.slice(0, 10) : [DEFAULT_TLD];
|
||
this.controller = null;
|
||
this.build();
|
||
}
|
||
|
||
Widget.prototype.build = function () {
|
||
var t = this.t;
|
||
var id = 'dsw-' + (++counter);
|
||
addStyle();
|
||
this.root.classList.add('dsw');
|
||
this.root.setAttribute('lang', this.lang);
|
||
this.root.textContent = '';
|
||
|
||
var form = el('form', 'dsw-form');
|
||
form.setAttribute('role', 'search');
|
||
form.noValidate = true;
|
||
var label = el('label', 'dsw-sr', t.label);
|
||
label.htmlFor = id + '-q';
|
||
var input = el('input', 'dsw-input');
|
||
input.type = 'text';
|
||
input.id = id + '-q';
|
||
input.name = 'domain';
|
||
input.placeholder = t.placeholder;
|
||
input.autocomplete = 'off';
|
||
input.setAttribute('autocapitalize', 'none');
|
||
input.setAttribute('autocorrect', 'off');
|
||
input.spellcheck = false;
|
||
input.setAttribute('inputmode', 'url');
|
||
input.setAttribute('enterkeyhint', 'search');
|
||
input.setAttribute('aria-describedby', id + '-out');
|
||
var btn = el('button', 'dsw-btn', t.search);
|
||
btn.type = 'submit';
|
||
form.appendChild(label);
|
||
form.appendChild(input);
|
||
form.appendChild(btn);
|
||
|
||
var out = el('div', 'dsw-out');
|
||
out.id = id + '-out';
|
||
out.setAttribute('aria-live', 'polite');
|
||
|
||
this.root.appendChild(form);
|
||
this.root.appendChild(out);
|
||
this.input = input;
|
||
this.out = out;
|
||
|
||
var self = this;
|
||
form.addEventListener('submit', function (e) {
|
||
e.preventDefault();
|
||
self.search(input.value);
|
||
});
|
||
};
|
||
|
||
Widget.prototype.message = function (text, busy) {
|
||
this.out.textContent = '';
|
||
var p = el('p', 'dsw-msg');
|
||
if (busy) p.appendChild(el('span', 'dsw-spin'));
|
||
p.appendChild(document.createTextNode(text));
|
||
this.out.appendChild(p);
|
||
this.out.setAttribute('aria-busy', busy ? 'true' : 'false');
|
||
};
|
||
|
||
Widget.prototype.errorText = function (err) {
|
||
var t = this.t;
|
||
if (err && err.status === 429) return fill(t.rate, { s: err.retryAfter || 60 });
|
||
if (err && err.reason === 'extension_not_supported') return t.notSupported;
|
||
if (err && err.status === 422) return t.invalid;
|
||
return t.network;
|
||
};
|
||
|
||
Widget.prototype.search = function (value) {
|
||
var t = this.t;
|
||
var domain = normalise(value, this.extensions[0]);
|
||
if (!domain) {
|
||
this.message(t.invalid);
|
||
this.input.setAttribute('aria-invalid', 'true');
|
||
this.input.focus();
|
||
return;
|
||
}
|
||
this.input.removeAttribute('aria-invalid');
|
||
if (this.controller) this.controller.abort();
|
||
var controller = typeof AbortController === 'function' ? new AbortController() : null;
|
||
this.controller = controller;
|
||
var timer = controller ? setTimeout(function () { controller.abort(); }, TIMEOUT_MS) : null;
|
||
var signal = controller ? controller.signal : undefined;
|
||
var params = { language: this.lang, currency: this.currency };
|
||
var self = this;
|
||
this.message(t.checking, true);
|
||
|
||
var label = domain.split('.')[0];
|
||
var others = this.extensions
|
||
.map(function (x) { return label + x; })
|
||
.filter(function (d) { return d !== domain; });
|
||
|
||
var main = request('/v1/whois/' + encodeURIComponent(domain), params, signal);
|
||
var more = others.length
|
||
? request('/v1/whois', { domains: others.join(','), language: params.language, currency: params.currency }, signal).catch(function () { return null; })
|
||
: Promise.resolve(null);
|
||
|
||
Promise.all([main, more]).then(function (r) {
|
||
if (self.controller !== controller) return;
|
||
self.render(r[0].data || {}, r[1] && r[1].data ? r[1].data : []);
|
||
}).catch(function (err) {
|
||
if (self.controller !== controller) return;
|
||
self.message(self.errorText(err));
|
||
}).then(function () {
|
||
if (timer) clearTimeout(timer);
|
||
});
|
||
};
|
||
|
||
Widget.prototype.render = function (d, extra) {
|
||
var t = this.t;
|
||
var name = d.domain || '';
|
||
this.out.textContent = '';
|
||
this.out.setAttribute('aria-busy', 'false');
|
||
|
||
var card = el('div', 'dsw-card');
|
||
var info = el('div');
|
||
var title = el('p', 'dsw-title');
|
||
var meta = el('p', 'dsw-meta');
|
||
info.appendChild(title);
|
||
card.appendChild(info);
|
||
|
||
if (d.status === 'available') {
|
||
card.classList.add('dsw-ok');
|
||
title.textContent = fill(t.available, { d: name });
|
||
var bits = [priceText(d, t)];
|
||
if (d.price && d.price.premium) bits.push(t.premium);
|
||
if (d.price && d.price.free_with_hosting && d.price.free_with_hosting.plan) {
|
||
var cycle = String(d.price.free_with_hosting.cycle || '');
|
||
if (this.lang === 'pt') cycle = cycle.replace(/^1 years?$/, '1 ano').replace(/^(\d+) years$/, '$1 anos');
|
||
bits.push(fill(t.freeWith, { plan: d.price.free_with_hosting.plan, cycle: cycle }));
|
||
}
|
||
meta.textContent = bits.filter(Boolean).join(' · ');
|
||
if (meta.textContent) info.appendChild(meta);
|
||
var go = goButton(d.register_url, name, t);
|
||
if (go) card.appendChild(go);
|
||
} else if (d.status === 'registered') {
|
||
card.classList.add('dsw-no');
|
||
title.textContent = fill(t.registered, { d: name });
|
||
var tr = safeUrl(d.transfer_url);
|
||
if (tr) {
|
||
var a = el('a', '', t.transfer);
|
||
a.href = tr;
|
||
meta.appendChild(a);
|
||
info.appendChild(meta);
|
||
}
|
||
} else if (d.status === 'not_allowed') {
|
||
title.textContent = fill(t.notAllowed, { d: name });
|
||
} else {
|
||
title.textContent = fill(t.unknown, { d: name });
|
||
}
|
||
this.out.appendChild(card);
|
||
|
||
this.list(t.alternatives, (d.alternatives || []).slice(0, 4));
|
||
this.list(t.extensions, (extra || []).filter(function (x) { return x && x.status !== 'error'; }));
|
||
};
|
||
|
||
Widget.prototype.list = function (heading, items) {
|
||
if (!items.length) return;
|
||
var t = this.t;
|
||
this.out.appendChild(el('h3', 'dsw-h', heading));
|
||
var ul = el('ul', 'dsw-list');
|
||
items.forEach(function (x) {
|
||
var li = el('li');
|
||
var left = el('span', 'dsw-name', x.domain);
|
||
var free = x.status ? x.status === 'available' : true;
|
||
left.appendChild(el('span', 'dsw-tag', free ? t.free : t.taken));
|
||
var price = free ? priceText(x, t) : '';
|
||
if (price) left.appendChild(el('span', 'dsw-tag', price));
|
||
li.appendChild(left);
|
||
if (free) {
|
||
var go = goButton(x.register_url, x.domain, t);
|
||
if (go) li.appendChild(go);
|
||
}
|
||
ul.appendChild(li);
|
||
});
|
||
this.out.appendChild(ul);
|
||
};
|
||
|
||
function mount(node, options) {
|
||
if (!node || node.__dsw) return node && node.__dsw;
|
||
var ds = node.dataset || {};
|
||
var o = options || {};
|
||
node.__dsw = new Widget(node, {
|
||
lang: o.lang || ds.lang,
|
||
currency: o.currency || ds.currency,
|
||
extensions: o.extensions || ds.extensions
|
||
});
|
||
return node.__dsw;
|
||
}
|
||
|
||
function init() {
|
||
var nodes = document.querySelectorAll('[data-domain-search]');
|
||
for (var i = 0; i < nodes.length; i++) mount(nodes[i]);
|
||
}
|
||
|
||
window.DomainSearchWidget = { mount: mount, init: init, version: '1.0.0' };
|
||
if (document.readyState === 'loading') {
|
||
document.addEventListener('DOMContentLoaded', init);
|
||
} else {
|
||
init();
|
||
}
|
||
})(window, document);
|