/* Urutau - página Geografia: mapa coroplético, zoom em país, estados e cidades. Todos os dados externos (cidade, região, AS) entram só via textContent. */ (function () { 'use strict'; var U = window.Urutau; if (!U || typeof U.registerPage !== 'function') return; // ---------------------------------------------------------------- i18n U.registerI18n({ en: { 'geo.title': 'Geography', 'geo.world': 'World', 'geo.nav': 'Location path', 'geo.back': 'Back', 'geo.back.hint': 'Back (Esc)', 'geo.map.label': 'Map of attack origins. Use the list to choose a country.', 'geo.map.country.label': 'Map of {of} with the cities that attack the most', 'geo.lead.world': '{events} from {ips} across {countries} {range}; {top} leads with {pct}.', 'geo.lead.country': '{country} originated {events} from {ips} {range}; {region} leads with {pct}.', 'geo.lead.country.flat': '{country} originated {events} from {ips} {range}.', 'geo.lead.region': '{region} ({country}) originated {events} from {ips} {range}; {city} leads with {pct}.', 'geo.lead.region.flat': '{region} ({country}) originated {events} from {ips} {range}.', 'geo.lead.empty': 'No geolocated attacks {range}.', 'geo.lead.city': '{city} ({region}, {country}) originated {events} from {ips} {range}, {pct} of {region}.', 'geo.lead.empty.region': 'No attacks from {region} ({country}) {range}.', 'geo.lead.empty.city': 'No attacks from {city}, {region} {range}.', 'geo.legend.state': 'Events per state / region (log scale)', 'geo.map.state.label': 'Map of {of} by state or region. Use the list to choose one.', 'geo.map.region.label': 'Map of {region} ({country}) with its cities', 'geo.unmapped': '{events} come from regions that are not drawn on the map.', 'geo.cities.in': 'Cities in {region}', 'geo.cats.in': 'Attack categories in {region}', 'geo.ips.city': 'Top IPs in {city}', 'geo.ips.city.none': 'None of the top IPs of this region are in this city.', 'geo.ips.city.note': 'Only the region\'s top IPs are listed.', 'geo.all_cities': 'All cities', 'geo.pick.city': 'Show IPs from {name}: {events}', 'geo.tip.nodata': 'No events in this range', 'geo.lead.empty.country': 'No attacks from {of} {range}.', 'geo.u.events.one': '{n} event', 'geo.u.events.other': '{n} events', 'geo.u.ips.one': '{n} IP', 'geo.u.ips.other': '{n} IPs', 'geo.u.countries.one': '{n} country', 'geo.u.countries.other': '{n} countries', 'geo.range.1h': 'hour', 'geo.range.24h': '24 hours', 'geo.range.7d': '7 days', 'geo.legend': 'Events per country (log scale)', 'geo.tip.events': 'Events', 'geo.tip.ips': 'IPs', 'geo.tip.hostile': 'Hostile', 'geo.tip.region': 'Region', 'geo.countries': 'Countries', 'geo.regions': 'States / regions', 'geo.regions.of': 'States / regions of {of}', 'geo.cities': 'Cities', 'geo.cats': 'Attack categories', 'geo.ips': 'Top IPs', 'geo.unknown': 'Unknown', 'geo.all_regions': 'All regions', 'geo.pick': 'Open {name}: {events}', 'geo.pick.region': 'Filter by {name}: {events}', 'geo.city.pick': 'Filter by region {name}', 'geo.nocoords.one': '{n} city has no coordinates and is not on the map.', 'geo.nocoords.other': '{n} cities have no coordinates and are not on the map.', 'geo.empty': 'Nothing to show for this range.', 'geo.empty.list': 'No data.', 'geo.loading': 'Loading…', 'geo.error': 'Could not load geography data.', 'geo.retry': 'Try again', 'geo.level.hostile': 'hostile', 'geo.level.suspicious': 'suspicious', 'geo.level.clean': 'clean', 'geo.level.low': 'low', 'geo.level.unknown': 'unknown', 'geo.score': 'score {n}', 'geo.open_ip': 'Open details of {ip}', 'geo.hostile_suspicious': '{h} hostile, {s} suspicious', 'geo.cat.notfound': 'not found', 'geo.cat.scanner': 'scanner', 'geo.cat.bruteforce': 'brute force', 'geo.cat.exploit': 'exploit', 'geo.cat.ssh-fail': 'SSH failures', 'geo.cat.ssh-probe': 'SSH probe', 'geo.cat.ban': 'ban' }, 'pt-BR': { 'geo.title': 'Geografia', 'geo.world': 'Mundo', 'geo.nav': 'Caminho da localização', 'geo.back': 'Voltar', 'geo.back.hint': 'Voltar (Esc)', 'geo.map.label': 'Mapa das origens dos ataques. Use a lista para escolher um país.', 'geo.map.country.label': 'Mapa {of} com as cidades que mais atacam', 'geo.lead.world': '{events} de {ips} em {countries} {range}; {top} lidera com {pct}.', 'geo.lead.country': '{country} originou {events} de {ips} {range}; {region} lidera com {pct}.', 'geo.lead.country.flat': '{country} originou {events} de {ips} {range}.', 'geo.lead.region': '{region} ({country}) originou {events} de {ips} {range}; {city} lidera com {pct}.', 'geo.lead.region.flat': '{region} ({country}) originou {events} de {ips} {range}.', 'geo.lead.empty': 'Nenhum ataque geolocalizado {range}.', 'geo.lead.city': '{city} ({region}, {country}) originou {events} de {ips} {range}, {pct} de {region}.', 'geo.lead.empty.region': 'Nenhum ataque de {region} ({country}) {range}.', 'geo.lead.empty.city': 'Nenhum ataque de {city}, {region} {range}.', 'geo.legend.state': 'Eventos por estado / região (escala log)', 'geo.map.state.label': 'Mapa {of} por estado ou região. Use a lista para escolher um.', 'geo.map.region.label': 'Mapa de {region} ({country}) com as cidades', 'geo.unmapped': '{events} vêm de regiões que não estão desenhadas no mapa.', 'geo.cities.in': 'Cidades de {region}', 'geo.cats.in': 'Categorias de ataque em {region}', 'geo.ips.city': 'IPs que mais atacam em {city}', 'geo.ips.city.none': 'Nenhum dos IPs que mais atacam esta região está nesta cidade.', 'geo.ips.city.note': 'Só os IPs que mais atacam a região são listados.', 'geo.all_cities': 'Todas as cidades', 'geo.pick.city': 'Mostrar IPs de {name}: {events}', 'geo.tip.nodata': 'Sem eventos neste período', 'geo.lead.empty.country': 'Nenhum ataque {of} {range}.', 'geo.u.events.one': '{n} evento', 'geo.u.events.other': '{n} eventos', 'geo.u.ips.one': '{n} IP', 'geo.u.ips.other': '{n} IPs', 'geo.u.countries.one': '{n} país', 'geo.u.countries.other': '{n} países', 'geo.range.1h': 'hora', 'geo.range.24h': '24 horas', 'geo.range.7d': '7 dias', 'geo.legend': 'Eventos por país (escala log)', 'geo.tip.events': 'Eventos', 'geo.tip.ips': 'IPs', 'geo.tip.hostile': 'Hostis', 'geo.tip.region': 'Região', 'geo.countries': 'Países', 'geo.regions': 'Estados / regiões', 'geo.regions.of': 'Estados / regiões {of}', 'geo.cities': 'Cidades', 'geo.cats': 'Categorias de ataque', 'geo.ips': 'IPs que mais atacam', 'geo.unknown': 'Desconhecido', 'geo.all_regions': 'Todas as regiões', 'geo.pick': 'Abrir {name}: {events}', 'geo.pick.region': 'Filtrar por {name}: {events}', 'geo.city.pick': 'Filtrar pela região {name}', 'geo.nocoords.one': '{n} cidade sem coordenadas não aparece no mapa.', 'geo.nocoords.other': '{n} cidades sem coordenadas não aparecem no mapa.', 'geo.empty': 'Nada para mostrar neste período.', 'geo.empty.list': 'Sem dados.', 'geo.loading': 'Carregando…', 'geo.error': 'Não foi possível carregar os dados de geografia.', 'geo.retry': 'Tentar de novo', 'geo.level.hostile': 'hostil', 'geo.level.suspicious': 'suspeito', 'geo.level.clean': 'limpo', 'geo.level.low': 'baixo', 'geo.level.unknown': 'desconhecido', 'geo.score': 'pontuação {n}', 'geo.open_ip': 'Abrir detalhes de {ip}', 'geo.hostile_suspicious': '{h} hostis, {s} suspeitos', 'geo.cat.notfound': 'não encontrado', 'geo.cat.scanner': 'scanner', 'geo.cat.bruteforce': 'força bruta', 'geo.cat.exploit': 'exploit', 'geo.cat.ssh-fail': 'falhas SSH', 'geo.cat.ssh-probe': 'sondagem SSH', 'geo.cat.ban': 'banimento' } }); // ---------------------------------------------------------------- helpers var NS = 'http://www.w3.org/2000/svg'; var CAT_CLASS = { notfound: 1, scanner: 1, bruteforce: 1, exploit: 1, 'ssh-fail': 1, 'ssh-probe': 1, ban: 1 }; var LEVELS = { hostile: 1, suspicious: 1, clean: 1, low: 1, unknown: 1 }; var RANGES = { '1h': 1, '24h': 1, '7d': 1 }; var LAT_TOP = 84, LAT_SPAN = 142; function t(k, v) { return U.t(k, v); } function h(tag, cls, text) { var e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; } function sv(tag, attrs) { var e = document.createElementNS(NS, tag); if (attrs) for (var k in attrs) e.setAttribute(k, attrs[k]); return e; } function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); } function nf(n) { try { if (U.fmt && U.fmt.num) return U.fmt.num(n); } catch (e) { /* fallback */ } return new Intl.NumberFormat(lang).format(n); } function pct(x) { return Math.round(x * 100) + '%'; } function unit(kind, n) { return t('geo.u.' + kind + (n === 1 ? '.one' : '.other'), { n: nf(n) }); } function flagOf(cc) { try { return (U.fmt && U.fmt.flag && U.fmt.flag(cc)) || ''; } catch (e) { return ''; } } var dn = null, dnLang = ''; function countryName(cc) { try { if (!dn || dnLang !== lang) { dn = new Intl.DisplayNames([lang], { type: 'region' }); dnLang = lang; } return dn.of(cc) || cc; } catch (e) { return cc; } } // DB-IP names stay the API key; the shown name comes from the admin-1 file in the UI language when it has one // pt-BR: "de" contracted with the country's article ("do Brasil", "da Alemanha", "dos Estados Unidos"); // countries without an article ("de Portugal") and any other language fall back to "de " / the bare name var PT_ART = {}; [['do', 'BR CA MX JP CL EC UY PY PE GB PA SN CG GA KE NE SD TD TG YE LB IQ IR KW QA BH EG AF BT NP PK VN ZW MW LA KH AZ'], ['da', 'AR DE FR CN IN RU ES IT CO BO VE AU ZA KR KP DK NO SE FI PL UA TR GR HU RO BG CH AT IE IS NZ ID AL AM GE LT LV EE SK SI HR RS BA MK MD CZ LY DZ ET ER SO SY JO BE CD CI NG TN MY ZM DO SA CR TH'], ['dos', 'US NL AE'], ['das', 'PH BS SC MV KM']].forEach(function (g) { g[1].split(' ').forEach(function (cc) { PT_ART[cc] = g[0]; }); }); function ofCountry(cc) { var n = countryName(cc); if (lang !== 'pt-BR') return n; return (PT_ART[cc] || 'de') + ' ' + n; } function regionName(r) { if (!r) return t('geo.unknown'); if (A1) { var i = a1Match(A1, r), lb = i >= 0 && A1.regions[i].label; if (lb) return (lang === 'pt-BR' ? lb.pt : lb.en) || r; } return r; } function catLabel(c) { var k = 'geo.cat.' + c, v = t(k); return v && v !== k ? v : c; } function catCls(c) { return CAT_CLASS[c] ? 'geo-c-' + c : 'geo-c-other'; } // the real slice, as the shell words it ("the last 6 hours", "from 1 Nov to 5 Nov") function rangeLabel(r) { try { if (typeof U.rangeLabel === 'function') { var x = U.rangeLabel({ inline: true }); if (x) return x; } } catch (e) { /* fallback */ } return t('geo.range.' + (RANGES[r] ? r : '24h')); } function sum(o) { var s = 0; for (var k in o) s += o[k]; return s; } function isNum(n) { return typeof n === 'number' && isFinite(n); } // Name matching between DB-IP region names and the admin-1 files. These two functions are the // same as in scripts/gen-admin1.mjs (the files carry names ready for them); keep them identical. var STOP = {}; ('province provincia department departamento region regional state county district governorate municipality parish prefecture oblast oblisi kray republic city of the de del la el and autonomous canton division zone voivodeship commune raion okrug territory') .split(' ').forEach(function (w) { STOP[w] = 1; }); function normStrict(s) { return String(s).normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase().replace(/&/g, ' and ') .replace(/\([^)]*\)/g, ' ').replace(/['’`ʼ]/g, '').replace(/[^a-z0-9]+/g, ' ').trim(); } function normLoose(s) { return normStrict(s).split(' ').filter(function (w) { return w && !STOP[w]; }).join(' '); } // ---------------------------------------------------------------- geometry var world = null, bboxCache = {}; function projX(lon) { return (lon + 180) / 360 * world.w; } function projY(lat) { return (LAT_TOP - lat) / LAT_SPAN * world.h; } // Bbox of a country's path: main land masses only (drops far-away small islands). function bboxOf(cc) { if (bboxCache[cc]) return bboxCache[cc]; var d = world.paths[cc]; if (!d) return null; var re = /([MmLlzZ])|(-?\d+(?:\.\d+)?)/g, m, cmd = '', nums = [], subs = [], cur = null, cx = 0, cy = 0, sx = 0, sy = 0; function flush() { for (var i = 0; i + 1 < nums.length; i += 2) { if (cmd === 'M' && i === 0) { cx = nums[i]; cy = nums[i + 1]; sx = cx; sy = cy; cur = [cx, cy, cx, cy]; subs.push(cur); } else { if (cmd === 'l' || cmd === 'm') { cx += nums[i]; cy += nums[i + 1]; } else { cx = nums[i]; cy = nums[i + 1]; } if (cur) { if (cx < cur[0]) cur[0] = cx; if (cy < cur[1]) cur[1] = cy; if (cx > cur[2]) cur[2] = cx; if (cy > cur[3]) cur[3] = cy; } } } nums = []; } while ((m = re.exec(d))) { if (m[1]) { flush(); cmd = m[1]; if (cmd === 'z' || cmd === 'Z') { cx = sx; cy = sy; } } else nums.push(parseFloat(m[2])); } flush(); var maxA = 0; subs.forEach(function (b) { var a = (b[2] - b[0]) * (b[3] - b[1]); if (a > maxA) maxA = a; }); var out = null; subs.forEach(function (b) { var a = (b[2] - b[0]) * (b[3] - b[1]); if (a < maxA * 0.12 && subs.length > 1) return; if (!out) out = b.slice(); else { out[0] = Math.min(out[0], b[0]); out[1] = Math.min(out[1], b[1]); out[2] = Math.max(out[2], b[2]); out[3] = Math.max(out[3], b[3]); } }); bboxCache[cc] = out; return out; } // ---------------------------------------------------------------- admin-1 (states) files // admin1-.json: regions with path in a local projection of the country (x=(lon-lon0)*kx, // y=(lat1-lat)*ky). They are drawn inside a group whose transform maps them onto the world map's // coordinates, so the page keeps a single viewBox for every level. var a1index = null, a1files = {}; var PATH_OK = /^[MmLlZz0-9 .\-]*$/; function fetchJSON1(url) { return fetch(url, { credentials: 'same-origin' }).then(function (r) { return r.ok ? r.json() : null; }); } function a1Index() { if (!a1index) a1index = fetchJSON1('/admin1-index.json').then(function (j) { var m = {}; ((j && j.cc) || []).forEach(function (c) { if (/^[A-Z]{2}$/.test(c)) m[c] = 1; }); return m; }).catch(function () { return {}; }); return a1index; } function prepA1(a) { if (!a || !Array.isArray(a.regions) || !a.proj || !isNum(a.proj.kx) || !isNum(a.proj.ky) || !isNum(a.proj.lon0) || !isNum(a.proj.lat1) || !Array.isArray(a.bbox) || !Array.isArray(a.main)) return null; a.regions = a.regions.filter(function (r) { return r && typeof r.path === 'string' && PATH_OK.test(r.path) && Array.isArray(r.b); }); a.strict = Object.create(null); a.loose = Object.create(null); a.memo = Object.create(null); a.regions.forEach(function (r, i) { var names = Array.isArray(r.names) ? r.names.slice() : []; names.push(r.name); names.forEach(function (n) { if (typeof n !== 'string') return; var s = normStrict(n), l = normLoose(n); if (s && !(s in a.strict)) a.strict[s] = i; if (l && !(l in a.loose)) a.loose[l] = i; }); }); return a.regions.length > 1 ? a : null; } function a1Load(cc) { if (!a1files[cc]) a1files[cc] = a1Index().then(function (m) { return m[cc] ? fetchJSON1('/admin1-' + cc.toLowerCase() + '.json') : null; }).then(prepA1).catch(function () { return null; }); return a1files[cc]; } function a1Match(a, name) { if (!name) return -1; if (name in a.memo) return a.memo[name]; var s = normStrict(name), l = normLoose(name), i = -1; if (s in a.strict) i = a.strict[s]; else if (l in a.loose) i = a.loose[l]; a.memo[name] = i; return i; } function a1Tf(a) { return { sx: (world.w / 360) / a.proj.kx, sy: (world.h / LAT_SPAN) / a.proj.ky, tx: projX(a.proj.lon0), ty: projY(a.proj.lat1) }; } function a1Box(a, b) { var f = a1Tf(a); return [f.tx + b[0] * f.sx, f.ty + b[1] * f.sy, f.tx + b[2] * f.sx, f.ty + b[3] * f.sy]; } // longitudes of countries across the antimeridian are unwrapped in the files (e.g. -185 for the Aleutians) function a1Lon(a, lon) { var lo = a.bbox[0] - 8, hi = a.bbox[2] + 8, ks = [0, -360, 360]; for (var i = 0; i < 3; i++) { var v = lon + ks[i]; if (v >= lo && v <= hi) return v; } return lon; } // ---------------------------------------------------------------- state var lang = 'en', ctx = null, root = null, ui = null, alive = false; var S = { cc: '', region: '', city: '' }; var data = { world: null, country: null, full: null, a1file: null, error: false, loading: false }; var A1 = null, A1m = null; // active admin-1 file for the shown country and how API regions map onto it var lastSig = ''; function ctxSig(c) { return JSON.stringify([c.range, c.from, c.to, c.host, c.domain, c.lang]); } var seq = 0, cache = {}, view = null, anim = 0, cityEls = [], ro = null; function parseHash() { // the shell owns the query (#/geo/BR/Pernambuco?r=24h); the page owns the path segments var raw = location.hash || '', qi = raw.indexOf('?'); if (qi >= 0) raw = raw.slice(0, qi); var m = /^#\/geo(?:\/([A-Za-z]{2})(?:\/(.*))?)?$/.exec(raw); var cc = '', region = '', city = ''; if (m && m[1]) { cc = m[1].toUpperCase(); if (m[2]) { var parts = m[2].split('/'); try { region = decodeURIComponent(parts[0]); } catch (e) { region = ''; } if (region && parts[1]) { try { city = decodeURIComponent(parts[1]); } catch (e) { city = ''; } } } } return { cc: cc, region: region, city: city }; } function writeHash() { var segs = S.cc ? [S.cc].concat(S.region ? [S.region].concat(S.city ? [S.city] : []) : []) : []; var hsh; if (typeof U.href === 'function') hsh = U.href('geo', segs); else hsh = '#/geo' + segs.map(function (x) { return '/' + encodeURIComponent(x); }).join(''); // assigning the hash lets the shell update its own state (params, slice) like for any navigation if (location.hash !== hsh) location.hash = hsh; } function go(cc, region, focus, city) { if (world && cc && !world.paths[cc]) cc = ''; S.cc = cc || ''; S.region = cc ? (region || '') : ''; S.city = S.region ? (city || '') : ''; writeHash(); load(true); if (focus && ui) setTimeout(function () { try { ui.lead.focus({ preventScroll: true }); } catch (e) { /* ignore */ } }, 0); } function goBack() { if (S.city) go(S.cc, S.region, true); else if (S.region) go(S.cc, '', true); else if (S.cc) go('', '', true); } function onHash() { if (!alive) return; var p = parseHash(); if (p.cc === S.cc && p.region === S.region && p.city === S.city) return; S.cc = p.cc; S.region = p.region; S.city = p.city; load(true); } function onKey(e) { if (!alive || e.key !== 'Escape' || e.defaultPrevented) return; var tg = e.target && e.target.tagName; if (tg === 'INPUT' || tg === 'SELECT' || tg === 'TEXTAREA') return; if (S.cc) { e.preventDefault(); goBack(); } } // ---------------------------------------------------------------- data function sliceParams() { try { if (typeof U.rangeParams === 'function') { var r = U.rangeParams(); if (r) return r; } } catch (e) { /* fallback */ } return { range: ctx.range }; } function key(extra) { return [JSON.stringify(sliceParams()), ctx.host || '', extra || ''].join('|'); } function fetchJSON(params) { var p = sliceParams(); if (ctx.host) p.host = ctx.host; for (var k in params) p[k] = params[k]; return Promise.resolve(U.api('/api/v1/geo', p)); } function cached(k, params) { if (cache[k]) return Promise.resolve(cache[k]); return fetchJSON(params).then(function (d) { cache[k] = d; return d; }); } function load(refit) { var my = ++seq; data.loading = true; data.error = false; paintState(); var cc = S.cc, region = S.region; var jobs = [cached(key('w'), {})]; if (cc) { jobs.push(cached(key('c:' + cc), { cc: cc })); jobs.push(region ? cached(key('r:' + cc + ':' + region), { cc: cc, region: region }) : null); jobs.push(a1Load(cc)); } Promise.all(jobs).then(function (r) { if (my !== seq || !alive) return; data.world = r[0]; data.full = cc ? r[1] : null; data.country = cc ? (region ? r[2] : r[1]) : null; data.a1file = cc ? r[3] : null; mapA1(); data.loading = false; render(refit); }).catch(function () { if (my !== seq || !alive) return; data.loading = false; data.error = true; render(false); }); } // Maps the API's regions onto the shapes of the admin-1 file. The map of states is used only when // most of the country's events fall in regions that exist in the file; otherwise the page keeps // drawing cities over the country's outline. function mapA1() { A1 = null; A1m = null; var a = data.a1file; if (!S.cc || !a || !data.full) return; var ev = [], ips = [], nm = [], best = [], tot = 0, mt = 0; (data.full.regions || []).forEach(function (r) { if (!r.name) return; tot += r.events; var i = a1Match(a, r.name); if (i < 0) return; mt += r.events; ev[i] = (ev[i] || 0) + r.events; ips[i] = (ips[i] || 0) + (r.ips || 0); if (!(best[i] >= r.events)) { best[i] = r.events; nm[i] = r.name; } }); if (tot === 0 || mt / tot >= 0.5) { A1 = a; A1m = { ev: ev, ips: ips, name: nm, tot: tot, mt: mt }; } } function selShape() { return A1 && S.region ? a1Match(A1, S.region) : -1; } // ---------------------------------------------------------------- build function build(el) { clear(el); root = h('div', 'geo'); var top = h('div', 'geo-top'); var nav = h('nav', 'geo-crumbs'); nav.setAttribute('aria-label', t('geo.nav')); var back = h('button', 'geo-back', '‹ ' + t('geo.back')); back.type = 'button'; back.title = t('geo.back.hint'); back.addEventListener('click', goBack); top.appendChild(nav); top.appendChild(back); var lead = h('h2', 'geo-lead'); lead.tabIndex = -1; lead.setAttribute('aria-live', 'polite'); var leadBox = h('div', 'lead geo-leadbox'); leadBox.appendChild(lead); var err = h('div', 'geo-err'); err.setAttribute('role', 'alert'); err.hidden = true; var errMsg = h('span', '', t('geo.error')), retry = h('button', 'geo-retry', t('geo.retry')); retry.type = 'button'; retry.addEventListener('click', function () { cache = {}; a1files = {}; a1index = null; load(false); }); err.appendChild(errMsg); err.appendChild(retry); var main = h('div', 'geo-main'); var mapPanel = h('section', 'geo-panel geo-mappanel'); var box = h('div', 'geo-map'); var svg = sv('svg', { 'class': 'geo-svg', role: 'img', preserveAspectRatio: 'xMidYMid meet' }); var gC = sv('g', { 'class': 'geo-countries' }), gA = sv('g', { 'class': 'geo-states' }), gCity = sv('g', { 'class': 'geo-cities' }); svg.appendChild(gC); svg.appendChild(gA); svg.appendChild(gCity); var paths = {}; Object.keys(world.paths).forEach(function (cc) { var p = sv('path', { d: world.paths[cc], 'class': 'geo-cn', 'data-cc': cc }); paths[cc] = p; gC.appendChild(p); }); var tip = h('div', 'geo-tip'); tip.hidden = true; tip.setAttribute('role', 'presentation'); var ld = h('div', 'geo-loading', t('geo.loading')); ld.hidden = true; box.appendChild(svg); box.appendChild(tip); box.appendChild(ld); var legend = h('div', 'geo-legend'); var lg = h('div', 'geo-legend-bar'); lg.setAttribute('aria-hidden', 'true'); var lmin = h('span', '', '1'), lmax = h('span', '', ''), ltx = h('span', 'geo-legend-t', t('geo.legend')); legend.appendChild(lmin); legend.appendChild(lg); legend.appendChild(lmax); legend.appendChild(ltx); var unmapped = h('div', 'geo-note geo-unmapped'); unmapped.hidden = true; mapPanel.appendChild(box); mapPanel.appendChild(legend); mapPanel.appendChild(unmapped); var side = h('section', 'geo-panel geo-side'); var sideH = h('h2', '', ''); sideH.tabIndex = -1; var sideList = h('div', 'geo-list'); side.appendChild(sideH); side.appendChild(sideList); main.appendChild(mapPanel); main.appendChild(side); var detail = h('div', 'geo-detail'); function panel(title) { var p = h('section', 'geo-panel'), hd = h('h2', '', title), body = h('div', 'geo-body'); p.appendChild(hd); p.appendChild(body); detail.appendChild(p); return { p: p, h: hd, body: body }; } var pCities = panel(''), pCats = panel(''), pIps = panel(''); root.appendChild(top); root.appendChild(leadBox); root.appendChild(err); root.appendChild(main); root.appendChild(detail); el.appendChild(root); ui = { nav: nav, back: back, lead: lead, err: err, errMsg: errMsg, retry: retry, svg: svg, gA: gA, gCity: gCity, paths: paths, box: box, tip: tip, loading: ld, legendMax: lmax, legendText: ltx, legend: legend, legendBar: lg, unmapped: unmapped, side: side, sideH: sideH, sideList: sideList, detail: detail, pCities: pCities, pCats: pCats, pIps: pIps, shapes: [], a1key: '' }; gC.addEventListener('click', function (e) { var cc = e.target && e.target.getAttribute && e.target.getAttribute('data-cc'); if (cc && hit(cc) && !(A1 && cc === S.cc)) go(cc, '', true); }); gC.addEventListener('mousemove', function (e) { var cc = e.target && e.target.getAttribute && e.target.getAttribute('data-cc'); var r = cc && hit(cc); if (!r || (A1 && cc === S.cc)) { ui.tip.hidden = true; return; } showTip(e, [[flagOf(cc) + ' ' + countryName(cc), ''], [t('geo.tip.events'), nf(r.events)], [t('geo.tip.ips'), nf(r.ips)], [t('geo.tip.hostile'), nf(r.hostile || 0)]]); }); gC.addEventListener('mouseleave', function () { ui.tip.hidden = true; }); gCity.addEventListener('mouseleave', function () { ui.tip.hidden = true; }); function shapeOf(e) { var i = e.target && e.target.getAttribute && e.target.getAttribute('data-i'); return i == null ? -1 : parseInt(i, 10); } gA.addEventListener('mousemove', function (e) { var i = shapeOf(e); if (!A1 || i < 0 || !A1.regions[i]) { ui.tip.hidden = true; return; } var ev = A1m.ev[i], nm = A1m.name[i] ? regionName(A1m.name[i]) : A1.regions[i].name; var rows = [[nm, '']]; if (ev) rows.push([t('geo.tip.events'), nf(ev)], [t('geo.tip.ips'), nf(A1m.ips[i] || 0)]); else rows.push([t('geo.tip.nodata'), '']); showTip(e, rows); }); gA.addEventListener('mouseleave', function () { ui.tip.hidden = true; }); gA.addEventListener('click', function (e) { var i = shapeOf(e); if (!A1 || i < 0 || !A1m.name[i] || i === selShape()) return; go(S.cc, A1m.name[i], true); }); if (window.ResizeObserver) { ro = new ResizeObserver(function () { if (alive && data.world && !data.error && !anim) { fitNow(); drawCities(); } }); ro.observe(box); } } function hit(cc) { var cs = data.world && data.world.countries; if (!cs) return null; for (var i = 0; i < cs.length; i++) if (cs[i].cc === cc) return cs[i]; return null; } function showTip(e, rows) { var tip = ui.tip; clear(tip); rows.forEach(function (r, i) { var d = h('div', i === 0 ? 'geo-tip-h' : 'geo-tip-r'); d.appendChild(h('span', '', r[0])); if (r[1] !== '') d.appendChild(h('b', '', r[1])); tip.appendChild(d); }); tip.hidden = false; var b = ui.box.getBoundingClientRect(); var x = e.clientX - b.left + 14, y = e.clientY - b.top + 14; var w = tip.offsetWidth, hh = tip.offsetHeight; if (x + w > b.width - 4) x = Math.max(4, e.clientX - b.left - w - 14); if (y + hh > b.height - 4) y = Math.max(4, e.clientY - b.top - hh - 14); tip.style.left = x + 'px'; tip.style.top = y + 'px'; } // The admin-1 layer is rebuilt only when the country changes. function buildShapes() { var want = A1 ? S.cc : ''; if (ui.a1key === want) return; clear(ui.gA); ui.shapes = []; ui.a1key = want; if (!A1) { ui.gA.removeAttribute('transform'); return; } var f = a1Tf(A1); ui.gA.setAttribute('transform', 'translate(' + f.tx.toFixed(3) + ' ' + f.ty.toFixed(3) + ') scale(' + f.sx.toFixed(5) + ' ' + f.sy.toFixed(5) + ')'); A1.regions.forEach(function (r, i) { var p = sv('path', { d: r.path, 'class': 'geo-st', 'data-i': String(i) }); ui.shapes[i] = p; ui.gA.appendChild(p); }); } // ---------------------------------------------------------------- map view function boxSize() { var r = ui.box.getBoundingClientRect(); return { w: r.width || 800, h: r.height || 360 }; } function cityXY(c) { return [projX(A1 ? a1Lon(A1, c.lon) : c.lon), projY(c.lat)]; } // box (world units) the view should frame, and its margin factor function targetBox() { var bb, margin = 1.22; if (!S.cc) { bb = [0, 0, world.w, world.h]; margin = 1; } else { bb = bboxOf(S.cc) || [0, 0, world.w, world.h]; var si = selShape(); if (A1) { bb = a1Box(A1, A1.main); margin = 1.1; } if (si >= 0 && A1.regions[si]) { bb = a1Box(A1, A1.regions[si].b); margin = 1.2; } else if (S.region && data.country && data.country.cities) { var pts = data.country.cities.filter(function (c) { return isNum(c.lat) && isNum(c.lon); }); if (pts.length) { var x0 = 1e9, y0 = 1e9, x1 = -1e9, y1 = -1e9; pts.forEach(function (c) { var p = cityXY(c); x0 = Math.min(x0, p[0]); x1 = Math.max(x1, p[0]); y0 = Math.min(y0, p[1]); y1 = Math.max(y1, p[1]); }); bb = [x0, y0, x1, y1]; margin = 1.5; } } } return { bb: bb, margin: margin }; } // the map is as tall as the framed area needs (a state is not wide like the world), within limits function fitAspect() { if (!S.cc || !world) { ui.box.style.aspectRatio = ''; return; } var tb = targetBox(), w = Math.max(tb.bb[2] - tb.bb[0], 1), hh = Math.max(tb.bb[3] - tb.bb[1], 1); var narrow = boxSize().w < 560, a = Math.max(1, Math.min(narrow ? 1.4 : 2.5, w / hh)); ui.box.style.aspectRatio = a.toFixed(3) + ' / 1'; } function targetView() { var sz = boxSize(), asp = sz.w / sz.h, tb = targetBox(), bb = tb.bb, margin = tb.margin; var bw = Math.max(bb[2] - bb[0], 36), bh = Math.max(bb[3] - bb[1], 36 / asp); var vw = Math.max(bw * margin, bh * margin * asp); var vh = vw / asp; var cx = (bb[0] + bb[2]) / 2, cy = (bb[1] + bb[3]) / 2; return [cx - vw / 2, cy - vh / 2, vw, vh]; } function setView(v) { if (!(v[2] > 0 && v[3] > 0)) return; view = v; ui.svg.setAttribute('viewBox', v.map(function (n) { return n.toFixed(2); }).join(' ')); } function fitNow() { setView(targetView()); } function reduced() { try { return window.matchMedia('(prefers-reduced-motion: reduce)').matches; } catch (e) { return false; } } function animateTo(to, done) { cancelAnimationFrame(anim); anim = 0; if (!view || reduced()) { setView(to); done(); return; } var from = view.slice(), t0 = performance.now(), dur = 420; (function step(now) { var k = Math.min(1, (now - t0) / dur), e = 1 - Math.pow(1 - k, 3); setView(from.map(function (f, i) { return f + (to[i] - f) * e; })); if (k < 1) anim = requestAnimationFrame(step); else { anim = 0; done(); } })(t0); } // O contrato repete a chave "ips" (contagem e lista); aceita os dois formatos. function ipList(d) { return Array.isArray(d.top_ips) ? d.top_ips : (Array.isArray(d.ips) ? d.ips : []); } function ipCount(d) { if (isNum(d.ips)) return d.ips; var k = ['ip_count', 'ips_total', 'unique_ips', 'ips_count']; for (var i = 0; i < k.length; i++) if (isNum(d[k[i]])) return d[k[i]]; if (S.region && data.full) { var rs = data.full.regions || []; for (var j = 0; j < rs.length; j++) if (rs[j].name === S.region) return rs[j].ips; } var w = hit(S.cc); if (w && !S.region) return w.ips; return (d.cities || []).reduce(function (a, c) { return a + (c.ips || 0); }, 0); } function sameCity(a, b) { return !!a && !!b && (a === b || normStrict(a) === normStrict(b)); } function cityEntry() { var cs = (data.country && data.country.cities) || []; if (!S.city) return null; for (var i = 0; i < cs.length; i++) if (sameCity(cs[i].name, S.city)) return cs[i]; return null; } // click on a city (circle or list): inside a region it toggles the city, from the country it opens region and city function pickCity(c) { if (!c.name) return; if (S.region) go(S.cc, S.region, true, sameCity(c.name, S.city) ? '' : c.name); else if (c.region) go(S.cc, c.region, true, c.name); } function drawCities() { clear(ui.gCity); cityEls = []; var d = data.country; if (!S.cc || !d || !d.cities || !view) return; var sz = boxSize(), upp = view[2] / sz.w, max = 1; d.cities.forEach(function (c) { if (c.events > max) max = c.events; }); var rmax = sz.w < 560 ? 16 : 26; var drawn = []; d.cities.forEach(function (c, i) { if (!isNum(c.lat) || !isNum(c.lon)) return; var p = cityXY(c), x = p[0], y = p[1]; if (x < view[0] - 20 || x > view[0] + view[2] + 20 || y < view[1] - 20 || y > view[1] + view[3] + 20) return; var r = Math.max(3, rmax * Math.sqrt(c.events / max)) * upp; var sel = !!S.city && sameCity(c.name, S.city); var el = sv('circle', { cx: x.toFixed(2), cy: y.toFixed(2), r: r.toFixed(2), 'class': 'geo-city' + (sel ? ' sel' : '') }); el.addEventListener('mousemove', function (e) { var rows = [[c.name || t('geo.unknown'), '']]; if (c.region) rows.push([t('geo.tip.region'), regionName(c.region)]); rows.push([t('geo.tip.events'), nf(c.events)], [t('geo.tip.ips'), nf(c.ips)]); showTip(e, rows); }); el.addEventListener('mouseleave', function () { ui.tip.hidden = true; }); if (c.name && (S.region || c.region)) { el.addEventListener('click', function () { pickCity(c); }); el.classList.add('geo-city-click'); } cityEls[i] = el; drawn.push({ c: c, x: x, y: y, r: r, el: el, sel: sel }); }); // larger circles first so small ones stay clickable on top drawn.sort(function (a, b) { return b.r - a.r; }); drawn.forEach(function (o) { if (o.sel) { var ring = sv('circle', { cx: o.x.toFixed(2), cy: o.y.toFixed(2), r: (o.r + 5 * upp).toFixed(2), 'class': 'geo-ring' }); ui.gCity.appendChild(ring); } ui.gCity.appendChild(o.el); }); if (S.region) drawLabels(drawn, upp); } // names of the largest cities (and of the chosen one), skipping those that would overlap function drawLabels(drawn, upp) { var fs = 11 * upp, boxes = [], n = 0; var ord = drawn.slice().sort(function (a, b) { return (b.sel ? 1e12 : b.c.events) - (a.sel ? 1e12 : a.c.events); }); for (var i = 0; i < ord.length && n < 8; i++) { var o = ord[i], nm = o.c.name; if (!nm) continue; var w = nm.length * fs * 0.6, x = o.x + o.r + 3 * upp, y = o.y + fs * 0.35, anchor = 'start'; if (x + w > view[0] + view[2] - 4 * upp) { x = o.x - o.r - 3 * upp; anchor = 'end'; } var bx = anchor === 'start' ? x : x - w, by = y - fs; if (bx < view[0] || bx + w > view[0] + view[2] || by < view[1] || by + fs * 1.2 > view[1] + view[3]) continue; var clash = boxes.some(function (b) { return bx < b[2] && bx + w > b[0] && by < b[3] && by + fs * 1.2 > b[1]; }); if (clash && !o.sel) continue; boxes.push([bx, by, bx + w, by + fs * 1.2]); var tx = sv('text', { x: x.toFixed(2), y: y.toFixed(2), 'text-anchor': anchor, 'font-size': fs.toFixed(2), 'stroke-width': (3 * upp).toFixed(2), 'class': 'geo-lbl' + (o.sel ? ' sel' : '') }); tx.textContent = nm; ui.gCity.appendChild(tx); n++; } } // ---------------------------------------------------------------- render function paintState() { if (!ui) return; ui.loading.hidden = !data.loading || !!data.world; root.classList.toggle('is-busy', data.loading); } function crumbs() { var nav = ui.nav; clear(nav); function sep() { var s = h('span', 'geo-sep', '›'); s.setAttribute('aria-hidden', 'true'); nav.appendChild(s); } var parts = [{ txt: t('geo.world'), act: S.cc ? function () { go('', '', true); } : null }]; if (S.cc) parts.push({ txt: flagOf(S.cc) + ' ' + countryName(S.cc), act: S.region ? function () { go(S.cc, '', true); } : null }); if (S.region) parts.push({ txt: regionName(S.region), act: S.city ? function () { go(S.cc, S.region, true); } : null }); if (S.city) parts.push({ txt: S.city, act: null }); parts.forEach(function (p, i) { if (i) sep(); var n; if (p.act) { n = h('button', 'geo-crumb', p.txt); n.type = 'button'; n.addEventListener('click', p.act); } else { n = h('span', 'geo-crumb cur', p.txt); n.setAttribute('aria-current', 'page'); } nav.appendChild(n); }); ui.back.hidden = !S.cc; } function lead() { var rl = rangeLabel(ctx.range), L = ui.lead; if (data.error || !data.world) { L.textContent = ''; return; } var cs = data.world.countries || []; if (!S.cc) { var tot = 0, ips = 0; cs.forEach(function (c) { tot += c.events; ips += c.ips; }); if (!cs.length) { L.textContent = t('geo.lead.empty', { range: rl }); return; } var top = cs.slice().sort(function (a, b) { return b.events - a.events; })[0]; L.textContent = t('geo.lead.world', { events: unit('events', tot), ips: unit('ips', ips), countries: unit('countries', cs.length), range: rl, top: countryName(top.cc), pct: pct(top.events / tot) }); return; } var d = data.country, cn = countryName(S.cc); if (!d || !d.events) { if (S.region) L.textContent = t('geo.lead.empty.region', { region: regionName(S.region), country: cn, range: rl }); else L.textContent = t('geo.lead.empty.country', { of: ofCountry(S.cc), range: rl }); return; } var base = { country: cn, events: unit('events', d.events), ips: unit('ips', ipCount(d)), range: rl }; if (S.region) { base.region = regionName(S.region); if (S.city) { var ce = cityEntry(); if (!ce) { L.textContent = t('geo.lead.empty.city', { city: S.city, region: base.region, range: rl }); return; } L.textContent = t('geo.lead.city', { city: S.city, region: base.region, country: cn, events: unit('events', ce.events), ips: unit('ips', ce.ips || 0), range: rl, pct: pct(ce.events / d.events) }); return; } var c0 = (d.cities || [])[0]; if (c0 && c0.name) { base.city = c0.name; base.pct = pct(c0.events / d.events); L.textContent = t('geo.lead.region', base); } else L.textContent = t('geo.lead.region.flat', base); return; } var r0 = ((d.regions || []).filter(function (r) { return r.name; })[0]); if (r0 && d.regions.length > 1) { base.region = regionName(r0.name); base.pct = pct(r0.events / d.events); L.textContent = t('geo.lead.country', base); } else L.textContent = t('geo.lead.country.flat', base); } function colorize() { var cs = (data.world && data.world.countries) || [], max = 1, by = {}; cs.forEach(function (c) { by[c.cc] = c; if (c.events > max) max = c.events; }); var lm = Math.log(1 + max); var zoomed = !!S.cc; ui.svg.setAttribute('class', 'geo-svg' + (zoomed ? ' zoomed' : '') + (A1 ? ' a1' : '') + (A1 && S.region ? ' reg' : '')); Object.keys(ui.paths).forEach(function (cc) { var p = ui.paths[cc], c = by[cc], cls = 'geo-cn'; // other countries fade while one is shown (fill-opacity, not opacity: big translucent layers glitch in some renderers) var fade = zoomed && cc !== S.cc ? 0.35 : 1; if (c) { cls += ' hit'; p.style.fillOpacity = ((0.2 + 0.8 * Math.log(1 + c.events) / lm) * fade).toFixed(3); } else p.style.fillOpacity = fade < 1 ? '0.05' : ''; if (cc === S.cc) cls += ' sel'; p.setAttribute('class', cls); }); // states buildShapes(); var legendKey = 'geo.legend', lmx = max; ui.unmapped.hidden = true; if (A1) { var smax = 1, si = selShape(); A1m.ev.forEach(function (v) { if (v > smax) smax = v; }); var slm = Math.log(1 + smax); ui.shapes.forEach(function (p, i) { var v = A1m.ev[i], cls = 'geo-st', fade = si >= 0 && i !== si ? 0.55 : 1; if (v) { cls += ' hit'; p.style.fillOpacity = ((0.2 + 0.8 * Math.log(1 + v) / slm) * fade).toFixed(3); } else p.style.fillOpacity = fade < 1 ? '0.08' : ''; if (i === si) cls += ' sel'; else if (si >= 0) cls += ' dim'; p.setAttribute('class', cls); }); legendKey = 'geo.legend.state'; lmx = smax; if (A1m.tot > A1m.mt) { ui.unmapped.textContent = t('geo.unmapped', { events: unit('events', A1m.tot - A1m.mt) }); ui.unmapped.hidden = false; } } ui.legendMax.textContent = nf(lmx); ui.legendText.textContent = t(legendKey); var hasData = A1 ? A1m.ev.some(function (v) { return v > 0; }) : cs.length > 0; ui.legend.hidden = (zoomed && !A1) || !hasData; // nothing to scale: no "1 - 1" bar var lbl; if (!S.cc) lbl = t('geo.map.label'); else if (A1 && S.region) lbl = t('geo.map.region.label', { region: regionName(S.region), country: countryName(S.cc) }); else if (A1) lbl = t('geo.map.state.label', { of: ofCountry(S.cc) }); else lbl = t('geo.map.country.label', { of: ofCountry(S.cc) }); ui.svg.setAttribute('aria-label', lbl); } function emptyNote(txt) { return h('div', 'geo-empty', txt); } function row(opts) { // opts: name, sub, n, frac, onClick, label, pressed, rank, cls var r = h(opts.onClick ? 'button' : 'div', 'geo-row' + (opts.cls ? ' ' + opts.cls : '')); if (opts.onClick) { r.type = 'button'; r.addEventListener('click', opts.onClick); if (opts.label) r.setAttribute('aria-label', opts.label); if (opts.pressed != null) r.setAttribute('aria-pressed', opts.pressed ? 'true' : 'false'); } var top = h('span', 'geo-row-top'); if (opts.rank) top.appendChild(h('span', 'geo-rank', String(opts.rank))); var nm = h('span', 'geo-name', opts.name); top.appendChild(nm); if (opts.sub) top.appendChild(h('span', 'geo-sub', opts.sub)); top.appendChild(h('span', 'geo-num', nf(opts.n))); r.appendChild(top); var bar = h('span', 'geo-bar'), i = h('i'); i.style.width = Math.max(2, opts.frac * 100) + '%'; bar.appendChild(i); r.appendChild(bar); return r; } // ranking of the country's regions; the chosen one is highlighted and a click picks it function regionRows(L, withChip) { var rs = (data.full && data.full.regions) || []; if (!rs.length) { L.appendChild(emptyNote(t('geo.empty.list'))); return; } if (S.region && withChip) { var all = h('button', 'geo-chip', t('geo.all_regions')); all.type = 'button'; all.addEventListener('click', function () { go(S.cc, '', true); }); L.appendChild(all); } var mx = rs[0].events || 1, si = selShape(); rs.forEach(function (r, i) { var can = !!r.name; var on = can && (S.region === r.name || (si >= 0 && a1Match(A1, r.name) === si)); var el = row({ rank: i + 1, name: regionName(r.name), sub: unit('ips', r.ips), n: r.events, frac: r.events / mx, cls: on ? 'on' : '', pressed: can ? on : null, label: can ? t('geo.pick.region', { name: regionName(r.name), events: unit('events', r.events) }) : '', onClick: can ? function () { go(S.cc, on ? '' : r.name, true); } : null }); if (A1 && can) { var k = a1Match(A1, r.name); el.addEventListener('mouseenter', function () { if (ui.shapes[k]) ui.shapes[k].classList.add('hl'); }); el.addEventListener('mouseleave', function () { if (ui.shapes[k]) ui.shapes[k].classList.remove('hl'); }); } L.appendChild(el); }); } // ranking of the shown cities; hovering a row highlights its circle function cityRows(B, limit, withChip) { var d = data.country, cs = (d && d.cities) || []; if (!cs.length) { B.appendChild(emptyNote(t('geo.empty.list'))); return; } if (S.city && withChip) { var all = h('button', 'geo-chip', t('geo.all_cities')); all.type = 'button'; all.addEventListener('click', function () { go(S.cc, S.region, true); }); B.appendChild(all); } var mx = cs[0].events || 1, nocoord = 0; cs.slice(0, limit).forEach(function (c, i) { var can = !!c.name && (!!S.region || !!c.region); var on = !!S.city && sameCity(c.name, S.city); var r = row({ rank: i + 1, name: c.name || t('geo.unknown'), sub: S.region ? '' : (c.region ? regionName(c.region) : ''), n: c.events, frac: c.events / mx, cls: on ? 'on' : '', pressed: can && S.region ? on : null, label: can ? t(S.region ? 'geo.pick.city' : 'geo.city.pick', S.region ? { name: c.name, events: unit('events', c.events) } : { name: c.region }) : '', onClick: can ? function () { pickCity(c); } : null }); r.addEventListener('mouseenter', function () { if (cityEls[i]) cityEls[i].classList.add('hl'); }); r.addEventListener('mouseleave', function () { if (cityEls[i]) cityEls[i].classList.remove('hl'); }); B.appendChild(r); }); cs.forEach(function (c) { if (!isNum(c.lat) || !isNum(c.lon)) nocoord++; }); if (nocoord) B.appendChild(h('div', 'geo-note', t(nocoord === 1 ? 'geo.nocoords.one' : 'geo.nocoords.other', { n: nf(nocoord) }))); } function renderSide() { var L = ui.sideList; clear(L); if (!S.cc) { ui.sideH.textContent = t('geo.countries'); var cs = ((data.world && data.world.countries) || []).slice().sort(function (a, b) { return b.events - a.events; }); if (!cs.length) { L.appendChild(emptyNote(t('geo.empty'))); return; } var max = cs[0].events || 1; cs.forEach(function (c, i) { var nm = countryName(c.cc); L.appendChild(row({ rank: i + 1, name: flagOf(c.cc) + ' ' + nm, n: c.events, frac: c.events / max, label: t('geo.pick', { name: nm, events: unit('events', c.events) }), onClick: function () { go(c.cc, '', true); } })); }); return; } if (A1 && S.region) { // state level: the side list is the state's cities, the regions go below the map ui.sideH.textContent = t('geo.cities.in', { region: regionName(S.region) }); cityRows(L, 40, true); return; } ui.sideH.textContent = t('geo.regions'); regionRows(L, true); } function renderDetail() { var show = !!S.cc && !!data.country; ui.detail.hidden = !show; if (!show) return; var d = data.country; // first panel: cities, or (with the state map and a state chosen) the country's regions var B = ui.pCities.body; clear(B); if (A1 && S.region) { ui.pCities.h.textContent = t('geo.regions.of', { of: ofCountry(S.cc) }); regionRows(B, false); } else { ui.pCities.h.textContent = S.region ? t('geo.cities.in', { region: regionName(S.region) }) : t('geo.cities'); cityRows(B, 15, !!S.region); } // categories ui.pCats.h.textContent = S.region ? t('geo.cats.in', { region: regionName(S.region) }) : t('geo.cats'); B = ui.pCats.body; clear(B); var cats = d.cats || {}, keys = Object.keys(cats).sort(function (a, b) { return cats[b] - cats[a]; }), tot = sum(cats); if (!keys.length || !tot) B.appendChild(emptyNote(t('geo.empty.list'))); else { var st = h('div', 'geo-stack'); st.setAttribute('aria-hidden', 'true'); keys.forEach(function (k) { var s = h('span', catCls(k)); s.style.flexGrow = String(cats[k]); st.appendChild(s); }); B.appendChild(st); var ul = h('ul', 'geo-chips'); keys.forEach(function (k) { var li = h('li', 'geo-chipcat'), dot = h('i', catCls(k)); dot.setAttribute('aria-hidden', 'true'); li.appendChild(dot); li.appendChild(h('span', '', catLabel(k))); li.appendChild(h('b', '', nf(cats[k]) + ' · ' + pct(cats[k] / tot))); ul.appendChild(li); }); B.appendChild(ul); if (d.hostile || d.suspicious) B.appendChild(h('div', 'geo-note', t('geo.hostile_suspicious', { h: nf(d.hostile || 0), s: nf(d.suspicious || 0) }))); } // ips: of the country/region, or of the chosen city (filtered from the region's top IPs) var ips = ipList(d); if (S.city) { ui.pIps.h.textContent = t('geo.ips.city', { city: S.city }); ips = ips.filter(function (x) { return sameCity(x.city, S.city); }); } else ui.pIps.h.textContent = t('geo.ips'); B = ui.pIps.body; clear(B); if (!ips.length) B.appendChild(emptyNote(t(S.city ? 'geo.ips.city.none' : 'geo.empty.list'))); else ips.slice(0, 12).forEach(function (x) { var b = h('button', 'geo-ip'); b.type = 'button'; b.setAttribute('aria-label', t('geo.open_ip', { ip: x.ip })); b.addEventListener('click', function () { U.openIP(x.ip); }); var l1 = h('span', 'geo-ip-l1'); l1.appendChild(h('code', '', x.ip)); var lv = LEVELS[x.level] ? x.level : 'unknown'; l1.appendChild(h('span', 'geo-lv geo-lv-' + lv, t('geo.level.' + lv))); if (isNum(x.score)) l1.appendChild(h('span', 'geo-score', t('geo.score', { n: nf(x.score) }))); b.appendChild(l1); var where = [x.city, x.region].filter(Boolean).join(', '), who = [x.asn, x.as_org].filter(Boolean).join(' '); var l2 = h('span', 'geo-ip-l2', [where, who].filter(Boolean).join(' · ')); b.appendChild(l2); if (x.last) { var ago = ''; try { ago = U.fmt.ago(x.last); } catch (e) { ago = ''; } if (ago) b.appendChild(h('span', 'geo-ip-l3', String(ago))); } B.appendChild(b); }); if (S.city && ips.length) B.appendChild(h('div', 'geo-note', t('geo.ips.city.note'))); } function render(refit) { if (!ui) return; paintState(); ui.err.hidden = !data.error; ui.loading.hidden = true; crumbs(); if (data.error || !data.world) { A1 = null; A1m = null; lead(); ui.detail.hidden = true; clear(ui.sideList); clear(ui.gCity); ui.legend.hidden = true; ui.unmapped.hidden = true; buildShapes(); ui.svg.setAttribute('class', 'geo-svg'); setView(targetView()); Object.keys(ui.paths).forEach(function (cc) { ui.paths[cc].style.fillOpacity = ''; ui.paths[cc].setAttribute('class', 'geo-cn'); }); return; } colorize(); lead(); renderSide(); renderDetail(); fitAspect(); clear(ui.gCity); cityEls = []; var to = targetView(); if (refit === false) { setView(to); drawCities(); } else animateTo(to, drawCities); } // ---------------------------------------------------------------- page U.registerPage({ id: 'geo', icon: '', titleKey: 'geo.title', mount: function (el, c) { ctx = c; lang = c.lang || 'en'; world = U.world || window.URUTAU_WORLD; alive = true; cache = {}; view = null; A1 = null; A1m = null; lastSig = ctxSig(c); if (!world || !world.paths) { clear(el); el.appendChild(h('div', 'geo-empty', t('geo.error'))); return; } var p = parseHash(); S.cc = world.paths[p.cc] ? p.cc : ''; S.region = S.cc ? p.region : ''; S.city = S.region ? p.city : ''; build(el); window.addEventListener('hashchange', onHash); window.addEventListener('popstate', onHash); document.addEventListener('keydown', onKey); load(false); }, update: function (c) { var langChanged = (c.lang || 'en') !== lang, sig = ctxSig(c), changed = sig !== lastSig; ctx = c; lang = c.lang || 'en'; lastSig = sig; if (!alive || !ui) return; // navigation inside the page (path segments) is driven by the hash, not by update() if (!changed && !langChanged) return; cache = {}; if (langChanged) { var el = root.parentNode; build(el); } load(false); }, unmount: function () { alive = false; seq++; cancelAnimationFrame(anim); anim = 0; window.removeEventListener('hashchange', onHash); window.removeEventListener('popstate', onHash); document.removeEventListener('keydown', onKey); if (ro) { ro.disconnect(); ro = null; } ui = null; root = null; } }); })();