- Where people connect from is a globe map now: live arcs from each
person to the server, grey ones for the last 24 h, 7 or 30 days, avatars
instead of dots, the server's own marker, and a light map in light mode;
it zooms to fit the people shown and follows them as they come and go
- Markers that overlap move apart with a pointer to their spot; people
next to the server fold into a count on it; a click zooms in and opens a
floating card (never clipped by the map), closing flies back
- The person page maps where they connected from, older places fading;
the device panel lists its places in order, and connections from the LAN
or through the router's own address stay off the maps ("LAN" in grey)
- Setup and new servers check the UDP port (taken by another program, a
forward or another server) and the subnet (three numbers + .x, a private
range not in use) as you type; the default port is 4500
- The personal portal can share the server's port number (TCP beside UDP);
its port is checked against forwards and other services
- A new server comes up at once: the kernel module is loaded and the
network restarted when OpenWrt doesn't know AmneziaWG yet
- A turned-off server is a state of its own: no "tunnel down" or DNS
warnings, "Turned off" in yellow, a white Turn on, and people on it are
not shown as paused
- Pause everyone is removed: turning a server off does the same (a router
left paused keeps its servers off after the update)
- People: a stopped person's card fades and says why across its bottom,
with the one action that lifts it (Resume, +10 GB, Extend 1 month);
people held by a limit or end date sort below the others, paused last
- The person page shows the state as text ("Paused") with a Resume
button, also while their server is off
- The portal tells a paused or ended person just that, even with the
server off, and lets them change nothing until the admin lifts it (the
router refuses too); its notices look like Overview's
- Automatic MTU: with the field empty the tunnel, computers and routers
get 1380 minus AmneziaWG S4 (1368 on Maximum), phones and tablets 1280;
a typed MTU still caps phones and tablets at 1280, and servers on the
old default 1380 move to automatic (phones and tablets get "Update
config", their old files keep working)
- Only procd's agent runs: a second copy (started by hand or left over)
refuses to start or is ended within 5 minutes, so no more stray paused
and resumed events; a device that leaves the tunnel is offline at once
- The installer picks the newest release (it took the lowest), DNS
lookups can't hang, and tooltips and floating cards close on scroll and
on leaving the page
This commit is contained in:
1 parent
29b1d7dfd7
commit
972e522518
60 files changed
+1966
-636
No files matched your search
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "dawnline-web",
|
||||
"version": "0.4.2",
|
||||
"version": "0.5.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "dawnline-web",
|
||||
"version": "0.4.2",
|
||||
"version": "0.5.0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"qrcode-generator": "1.4.4"
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "dawnline-web",
|
||||
"version": "0.4.2",
|
||||
"version": "0.5.0",
|
||||
"private": true,
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// luci.dawnline RPC bindings. The backend reports failures as { error }.
|
||||
|
||||
import type { Network, PortHold } from './netcheck';
|
||||
import type { AwgCaps, AwgState, Circle, ClientConfig, DayUsage, HealthCheck, LogEvent, MeshMode, Person, Status } from '../shared/types';
|
||||
|
||||
function call<T>(method: string, params: string[] = []) {
|
||||
@@ -23,7 +24,11 @@ export interface SetupDefaults {
|
||||
lan_zone: string;
|
||||
wan_zone: string;
|
||||
portal_port: number;
|
||||
taken: string[];
|
||||
/** Networks the tunnel must not overlap: the router's and the other servers'. */
|
||||
networks: Network[];
|
||||
/** UDP ports the server can't take, TCP ports the portal can't. */
|
||||
udp_taken: PortHold[];
|
||||
tcp_taken: PortHold[];
|
||||
awg: AwgCaps;
|
||||
awg_state?: AwgState;
|
||||
}
|
||||
@@ -176,7 +181,8 @@ export interface SettingsData {
|
||||
effective: Record<string, unknown>;
|
||||
services: { id: string; name: string; address: string; ports: string[] }[];
|
||||
cert: { path: string; self_signed: boolean; expires: string | null } | null;
|
||||
port_owners: string[];
|
||||
/** TCP ports the portal can't take. */
|
||||
tcp_taken: PortHold[];
|
||||
wan443_taken?: boolean;
|
||||
portal_public_port?: number;
|
||||
geo_cached: number;
|
||||
@@ -422,7 +428,7 @@ export const api = {
|
||||
uninstall: call<unknown>('uninstall', ['confirm']),
|
||||
status,
|
||||
setupDefaults: call<SetupDefaults>('setup_defaults'),
|
||||
serverCreate: call<{ id: string }>('server_create', [
|
||||
serverCreate: call<{ id: string; network_restart?: boolean }>('server_create', [
|
||||
'id',
|
||||
'name',
|
||||
'ifname',
|
||||
@@ -456,7 +462,6 @@ export const api = {
|
||||
personRegen: call<{ link: string | null }>('person_regen', ['id']),
|
||||
personDelete: call<unknown>('person_delete', ['id']),
|
||||
personUsage: call<{ person: DayUsage[]; devices: Record<string, DayUsage[]> }>('person_usage', ['id', 'days']),
|
||||
pauseAll: call<unknown>('pause_all', ['paused']),
|
||||
deviceCreate: call<{ id: string; config: ClientConfig }>('device_create', ['person', 'name', 'kind']),
|
||||
deviceConfig: call<ClientConfig>('device_config', ['id']),
|
||||
deviceUpdate: call<unknown>('device_update', ['id', 'name', 'disabled']),
|
||||
|
||||
@@ -258,7 +258,15 @@ async function applyDisguise(ctx: CoreCtx, srv: Server, m: Method, same: boolean
|
||||
export function settingsCard(ctx: CoreCtx, srv: Server): HTMLElement {
|
||||
const st: Status = ctx.st;
|
||||
const port = input(String(srv.port), { inputmode: 'numeric', class: 'cbi-input-text dl-w-port dl-mono' });
|
||||
const mtu = input(String(srv.mtu ?? ''), { placeholder: '1380', inputmode: 'numeric', class: 'cbi-input-text dl-w-port dl-mono' });
|
||||
const mtu = input(srv.mtu ? String(srv.mtu) : '', {
|
||||
placeholder: 'Auto',
|
||||
inputmode: 'numeric',
|
||||
class: 'cbi-input-text dl-w-port dl-mono',
|
||||
});
|
||||
const now = `${srv.mtus.computer} for computers and routers, ${srv.mtus.phone} for phones and tablets`;
|
||||
const mtuHint = srv.mtu
|
||||
? `Now ${now}. Empty = automatic.`
|
||||
: `Automatic by device type and disguise: now ${now}. Lower it if some sites hang.`;
|
||||
const ka = input(String(srv.keepalive ?? ''), { placeholder: '25', inputmode: 'numeric', class: 'cbi-input-text dl-w-port dl-mono' });
|
||||
const current = methodInfo(srv.preset) ? (srv.preset as Method) : undefined;
|
||||
let selected: Method = current ?? 'standard';
|
||||
@@ -266,22 +274,16 @@ export function settingsCard(ctx: CoreCtx, srv: Server): HTMLElement {
|
||||
const label = () =>
|
||||
dom.content(apply, selected === current ? [icon('reset'), ' Generate new values'] : [`Switch to ${methodInfo(selected)!.title}`]);
|
||||
label();
|
||||
const devs = st.people.filter((p) => p.server === srv.id).reduce((n, p) => n + p.devices.length, 0);
|
||||
const tools = st.awg_state?.tools !== false;
|
||||
return card(
|
||||
'',
|
||||
[
|
||||
coreHead(
|
||||
'AmneziaWG',
|
||||
srv.up ? 'ok' : 'bad',
|
||||
srv.up ? 'Running' : 'Not running',
|
||||
`${srv.ifname} · ${devs} device${devs === 1 ? '' : 's'}`,
|
||||
),
|
||||
coreHead('AmneziaWG', srv.ifname),
|
||||
group('globe', 'Listening', 'Where devices reach this core from the internet', [
|
||||
row('UDP port', port, 'Opened on the WAN firewall automatically.'),
|
||||
]),
|
||||
group('file', 'In every device configuration', 'Changing these marks devices “Update config” until they import again', [
|
||||
row('MTU', mtu, 'Lower it if some sites hang on mobile networks.'),
|
||||
row('MTU', mtu, mtuHint),
|
||||
row('Keep-alive', ka, 'Seconds between packets devices send to keep NAT open. 0 = off.'),
|
||||
]),
|
||||
group('shield', 'Disguise', 'So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard', [
|
||||
|
||||
@@ -31,11 +31,7 @@ export interface Core {
|
||||
file: { label: string; make(cfg: ClientConfig): { name: string; text: string } };
|
||||
}
|
||||
|
||||
/** Name, state pill and a short line: the head of a core's settings card. */
|
||||
export function coreHead(title: string, tone: 'ok' | 'bad' | 'off' | '', state: string, sub: string): HTMLElement {
|
||||
return E('div', { class: 'dl-corehead' }, [
|
||||
E('h3', {}, title),
|
||||
E('span', { class: `dl-pill ${tone}` }, state),
|
||||
sub ? E('span', { class: 'dl-sub' }, sub) : '',
|
||||
]);
|
||||
/** Name and a short line: the head of a core's settings card (the server's header already says whether it runs). */
|
||||
export function coreHead(title: string, sub: string): HTMLElement {
|
||||
return E('div', { class: 'dl-corehead' }, [E('h3', {}, title), sub ? E('span', { class: 'dl-sub' }, sub) : '']);
|
||||
}
|
||||
+60
-11
@@ -21,6 +21,8 @@ import { spark } from './widgets/spark';
|
||||
import { clearLogDialog, exportEvents, resetUsageDialog } from './logs';
|
||||
import { coreFor, coreOf, type Core } from './cores';
|
||||
import { onLiveChange } from './state/live';
|
||||
import { ConnectionMap, devicePlaces, rangeControl, type MapData, type Range } from './map';
|
||||
import { personUrl } from './urls';
|
||||
|
||||
/** What the page that opens a device hands over. */
|
||||
export interface DeviceOpts {
|
||||
@@ -139,8 +141,32 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
|
||||
if (ev) showLog(ev.events);
|
||||
};
|
||||
|
||||
// Where this device connected from, in time order (option B): a map with its trail and the list.
|
||||
let range: Range = '30d';
|
||||
let map: ConnectionMap | null = null;
|
||||
const places = E('div', { class: 'dl-dplaces' });
|
||||
const mapData = (): MapData => ({ geo: geo!, people: [p], now: now ?? Date.now() / 1000, person: p.id, device: d.id });
|
||||
const paintPlaces = () => {
|
||||
if (!geo?.enabled) return;
|
||||
const list = devicePlaces(mapData(), range);
|
||||
dom.content(
|
||||
places,
|
||||
list.length
|
||||
? list.map((x) =>
|
||||
E('div', { class: 'dl-dplace-row' }, [
|
||||
E('span', { class: `dl-dplace-n${x.online ? ' live' : ''}` }, x.online ? icon(d.kind) : String(x.n)),
|
||||
E('span', { class: 'dl-row-main dl-stack' }, [
|
||||
E('span', {}, [x.city || x.cc || 'Unknown city', x.org ? E('span', { class: 'dl-muted' }, ` · ${x.org}`) : '']),
|
||||
E('span', { class: 'dl-mono dl-faint' }, x.ip),
|
||||
]),
|
||||
E('span', { class: x.online ? 'dl-dplace-now' : 'dl-faint dl-nowrap' }, x.online ? 'now' : ago(x.ts, now)),
|
||||
]),
|
||||
)
|
||||
: E('div', { class: 'dl-sub' }, 'No locations in this period.'),
|
||||
);
|
||||
};
|
||||
|
||||
const paint = () => {
|
||||
const place = geo?.points.find((x) => x.device === d.id && x.ip === d.endpoint);
|
||||
dom.content(titleEl, [
|
||||
E('span', { class: `dl-dcard-ic${d.online ? ' on' : ''}` }, icon(d.kind)),
|
||||
E('div', { class: 'dl-stack' }, [
|
||||
@@ -176,15 +202,9 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
|
||||
E('div', { class: 'dl-kv2' }, [
|
||||
copyRow('Tunnel address', d.address),
|
||||
d.hostname && p.access !== 'internet' ? copyRow('Local address', d.hostname) : '',
|
||||
d.endpoint
|
||||
? row(
|
||||
'Client IP',
|
||||
E('span', {}, [
|
||||
d.endpoint,
|
||||
place ? E('span', { class: 'dl-muted' }, ` · ${[place.city, place.org].filter(Boolean).join(' · ')}`) : '',
|
||||
]),
|
||||
)
|
||||
: '',
|
||||
// Where it connects from is under Locations (with the place and network); from home
|
||||
// (not on the map) or without locations, here.
|
||||
d.endpoint && !geo?.points.some((x) => x.device === d.id && x.ip === d.endpoint) ? row('Client IP', d.endpoint) : '',
|
||||
row(
|
||||
'Total',
|
||||
E('span', { class: 'dl-kv-act' }, [
|
||||
@@ -269,6 +289,8 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
|
||||
now = st.now;
|
||||
today = todayOf(st.series);
|
||||
paint();
|
||||
map?.update(mapData());
|
||||
paintPlaces();
|
||||
};
|
||||
/** After a change made here: this drawer and the page. */
|
||||
const changed = async () => {
|
||||
@@ -339,13 +361,38 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
|
||||
log,
|
||||
]);
|
||||
const detailsSec = E('section', { class: 'dl-dsec' }, [E('div', { class: 'dl-dsec-head' }, E('h4', {}, 'Details')), details]);
|
||||
let locationsSec: HTMLElement | '' = '';
|
||||
if (geo?.enabled) {
|
||||
map = new ConnectionMap(
|
||||
{ openPerson: (id) => (location.href = personUrl(id)), openDevice: (id, dev) => (location.href = personUrl(id, dev)) },
|
||||
range,
|
||||
220,
|
||||
);
|
||||
locationsSec = E('section', { class: 'dl-dsec' }, [
|
||||
E('div', { class: 'dl-dsec-head' }, [
|
||||
E('h4', {}, 'Locations'),
|
||||
rangeControl(
|
||||
range,
|
||||
(r) => {
|
||||
range = r;
|
||||
map?.setRange(r);
|
||||
paintPlaces();
|
||||
},
|
||||
false,
|
||||
),
|
||||
]),
|
||||
E('div', { class: 'dl-dmap' }, map.el),
|
||||
places,
|
||||
]);
|
||||
paintPlaces();
|
||||
}
|
||||
// Connecting is what the drawer is for until the device is set up (or its configuration is old);
|
||||
// after that it goes to the bottom.
|
||||
const setUp = !d.handshake || d.config_stale;
|
||||
const body = E(
|
||||
'div',
|
||||
{ class: 'dl-stack gap16' },
|
||||
setUp ? [stats, connectSec, detailsSec, activitySec] : [stats, detailsSec, activitySec, connectSec],
|
||||
setUp ? [stats, connectSec, detailsSec, locationsSec, activitySec] : [stats, detailsSec, locationsSec, activitySec, connectSec],
|
||||
);
|
||||
void loadLog();
|
||||
// Live status and log: at once when something happens (state/live.ts), and every 30 s anyway.
|
||||
@@ -358,8 +405,10 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
|
||||
const handle = drawer(titleEl, body, foot, () => {
|
||||
clearInterval(watch);
|
||||
off();
|
||||
map?.destroy();
|
||||
});
|
||||
paint();
|
||||
if (map) requestAnimationFrame(() => map?.mount(mapData()));
|
||||
}
|
||||
|
||||
/** ⋯ on a device card: quick actions (everything else is in the panel; click the card). */
|
||||
|
||||
@@ -20,8 +20,6 @@ const CATEGORY: Record<string, LogCategory> = {
|
||||
person_changed: 'people',
|
||||
paused: 'people',
|
||||
resumed: 'people',
|
||||
paused_all: 'people',
|
||||
resumed_all: 'people',
|
||||
portal_blocked: 'problems',
|
||||
};
|
||||
|
||||
@@ -43,7 +41,7 @@ export const categoryOf = (type: string): LogCategory => CATEGORY[type] ?? 'prob
|
||||
|
||||
export const SYSTEM_SOURCE: Record<ServiceLogEntry['src'], string> = { awg: 'AmneziaWG', dawnline: 'Dawnline', portal: 'Portal' };
|
||||
|
||||
const ADMIN_TYPES = ['person_added', 'person_removed', 'person_changed', 'paused_all', 'resumed_all'];
|
||||
const ADMIN_TYPES = ['person_added', 'person_removed', 'person_changed'];
|
||||
|
||||
/** Who did it. Older events have no `by`: LuCI and the portal marked it in the detail. */
|
||||
export function eventBy(e: LogEvent): 'admin' | 'portal' | null {
|
||||
|
||||
@@ -21,8 +21,6 @@ const EVENT_TONE: Record<string, string> = {
|
||||
person_removed: '',
|
||||
paused: 'warn',
|
||||
resumed: 'ok',
|
||||
paused_all: 'warn',
|
||||
resumed_all: 'ok',
|
||||
portal_blocked: 'bad',
|
||||
person_changed: '',
|
||||
devices_removed: 'warn',
|
||||
@@ -37,8 +35,6 @@ const EVENT_ICON: Record<string, string> = {
|
||||
person_changed: 'edit',
|
||||
paused: 'pause',
|
||||
resumed: 'play',
|
||||
paused_all: 'pause',
|
||||
resumed_all: 'play',
|
||||
};
|
||||
|
||||
function eventIcon(st: Names, e: LogEvent): string {
|
||||
@@ -93,10 +89,6 @@ export function eventText(st: Pick<Status, 'people'>, e: LogEvent): Node[] {
|
||||
return [...you('issued new keys for'), kind('device'), b(devName), m(' of '), b(who), m(' · it needs its new configuration')];
|
||||
case 'link_changed':
|
||||
return [...you('issued a new link for'), kind('person'), b(who), m(' · the old link stopped working')];
|
||||
case 'paused_all':
|
||||
return [E('span', { class: 'dl-you' }, 'You'), m(' paused everyone')];
|
||||
case 'resumed_all':
|
||||
return [E('span', { class: 'dl-you' }, 'You'), m(' resumed everyone')];
|
||||
}
|
||||
switch (e.type) {
|
||||
case 'connect':
|
||||
@@ -147,10 +139,6 @@ export function eventText(st: Pick<Status, 'people'>, e: LogEvent): Node[] {
|
||||
return [kind('Person'), b(who), m(` paused — ${e.detail ?? ''}`)];
|
||||
case 'resumed':
|
||||
return [kind('Person'), b(who), m(' resumed'), ...(e.detail && e.detail !== 'active' ? [m(` — ${e.detail}`)] : [])];
|
||||
case 'paused_all':
|
||||
return [m('Everyone paused')];
|
||||
case 'resumed_all':
|
||||
return [m('Everyone resumed')];
|
||||
case 'portal_blocked':
|
||||
return [
|
||||
E('b', { class: 'dl-sys-src' }, 'Personal portal'),
|
||||
|
||||
@@ -160,7 +160,8 @@ export function accessCards(srv: Server, first: Status, refresh: () => Promise<u
|
||||
/** Tile colour: green while traffic really enters the LAN, orange when it should but can't. */
|
||||
function likeHomeTone(): string {
|
||||
const lh = d.like_home;
|
||||
if (!lanLike || !d.config.lan_like) return '';
|
||||
// A server that is off has no link on purpose.
|
||||
if (!lanLike || !d.config.lan_like || !srv.enabled) return '';
|
||||
return !d.needs?.length && lh.active && lh.bridged ? 'ok' : 'warn';
|
||||
}
|
||||
|
||||
@@ -174,6 +175,9 @@ export function accessCards(srv: Server, first: Status, refresh: () => Promise<u
|
||||
];
|
||||
if (!d.config.lan_like)
|
||||
return ['Internet traffic will enter the router from your LAN, so it is handled like any home device. Save to turn on.'];
|
||||
// A server that is off has no link on purpose: describe the setting, not its state.
|
||||
if (!srv.enabled)
|
||||
return ['Internet traffic enters the router from your LAN, so whatever handles home traffic (proxies, filters, DNS) handles it too.'];
|
||||
if (lh.active && lh.bridged)
|
||||
return [
|
||||
'Internet traffic enters ',
|
||||
|
||||
+626
-195
@@ -1,14 +1,18 @@
|
||||
// Connection map: MapLibre GL with a CARTO basemap (light or dark, following
|
||||
// the Outline theme), the router as origin, one marker per device and an arc
|
||||
// from the router to each one — solid and animated while the tunnel is live,
|
||||
// dashed for recently seen. MapLibre loads from a CDN on first use.
|
||||
// Connection map, drawn as mapcn's "Basic Arc" (mapcn.dev, MapLibre under a
|
||||
// React wrapper; the same look here without React): MapLibre GL on a globe
|
||||
// with a CARTO basemap (light or dark, following the Outline theme), the
|
||||
// router as the hub and a dashed arc to each place devices connect from —
|
||||
// blue while the tunnel is live, gray when seen recently. MapLibre loads from
|
||||
// a CDN on first use.
|
||||
|
||||
import type { Geo, GeoPoint, Person } from '../shared/types';
|
||||
import { E } from './e';
|
||||
import { ago } from '../shared/format';
|
||||
import { ago, initials } from '../shared/format';
|
||||
import { icon, iconSvg } from '../shared/icons';
|
||||
import { onNavigate } from './ui/nav';
|
||||
|
||||
const MAPLIBRE = 'https://unpkg.com/maplibre-gl@4.7.1/dist/maplibre-gl';
|
||||
// mapcn requires maplibre-gl ^6 (the globe projection came with 5): an ES module, its worker beside it.
|
||||
const MAPLIBRE = 'https://unpkg.com/maplibre-gl@6.14.0/dist';
|
||||
const STYLE_DARK = 'https://basemaps.cartocdn.com/gl/dark-matter-gl-style/style.json';
|
||||
const STYLE_LIGHT = 'https://basemaps.cartocdn.com/gl/positron-gl-style/style.json';
|
||||
|
||||
@@ -18,25 +22,26 @@ const WINDOW: Record<Range, number> = { online: 0, '24h': 86400, '7d': 7 * 86400
|
||||
let loading: Promise<any> | null = null;
|
||||
|
||||
/**
|
||||
* Load MapLibre once; tags go inside `host` so Outline's router is not
|
||||
* disturbed. The stylesheet goes into every map's own container: Outline
|
||||
* drops the previous page's DOM on navigation (and with it a shared link),
|
||||
* and without it HTML markers lose their positioning and vanish.
|
||||
* Load MapLibre once. The stylesheet goes into every map's own container:
|
||||
* Outline drops the previous page's DOM on navigation (and with it a shared
|
||||
* link), and without it HTML markers lose their positioning and vanish.
|
||||
* Since 6 it is an ES module: imported (the URL in a variable, so the bundler
|
||||
* leaves it alone), with the worker URL set as mapcn does.
|
||||
*/
|
||||
function loadMapLibre(host: HTMLElement): Promise<any> {
|
||||
const w = window as any;
|
||||
host.appendChild(E('link', { rel: 'stylesheet', href: `${MAPLIBRE}.css` }));
|
||||
if (w.maplibregl) return Promise.resolve(w.maplibregl);
|
||||
host.appendChild(E('link', { rel: 'stylesheet', href: `${MAPLIBRE}/maplibre-gl.css` }));
|
||||
if (loading) return loading;
|
||||
loading = new Promise((resolve, reject) => {
|
||||
const s = E('script', { src: `${MAPLIBRE}.js` }) as HTMLScriptElement;
|
||||
s.onload = () => (w.maplibregl ? resolve(w.maplibregl) : reject(new Error('MapLibre failed to load')));
|
||||
s.onerror = () => {
|
||||
const url = `${MAPLIBRE}/maplibre-gl.mjs`;
|
||||
loading = import(/* @vite-ignore */ url).then(
|
||||
(gl) => {
|
||||
if (!gl.getWorkerUrl()) gl.setWorkerUrl(`${MAPLIBRE}/maplibre-gl-worker.mjs`);
|
||||
return gl;
|
||||
},
|
||||
() => {
|
||||
loading = null;
|
||||
reject(new Error('Could not load the map library (no internet access from this browser?)'));
|
||||
};
|
||||
host.appendChild(s);
|
||||
});
|
||||
throw new Error('Could not load the map library (no internet access from this browser?)');
|
||||
},
|
||||
);
|
||||
return loading;
|
||||
}
|
||||
|
||||
@@ -46,24 +51,41 @@ function isDark(): boolean {
|
||||
return window.matchMedia?.('(prefers-color-scheme: dark)').matches ?? false;
|
||||
}
|
||||
|
||||
/** A gentle arc between two [lng, lat] points (quadratic Bézier in map space). */
|
||||
function arc(a: [number, number], b: [number, number], steps = 48): [number, number][] {
|
||||
const mx = (a[0] + b[0]) / 2;
|
||||
const my = (a[1] + b[1]) / 2;
|
||||
const dx = b[0] - a[0];
|
||||
const dy = b[1] - a[1];
|
||||
const len = Math.hypot(dx, dy) || 1;
|
||||
// Bend to the left of the direction of travel, proportional to distance.
|
||||
const k = Math.min(0.25 * len, 12);
|
||||
const cx = mx - (dy / len) * k;
|
||||
const cy = my + (dx / len) * k;
|
||||
const out: [number, number][] = [];
|
||||
for (let i = 0; i <= steps; i++) {
|
||||
const t = i / steps;
|
||||
const u = 1 - t;
|
||||
out.push([u * u * a[0] + 2 * u * t * cx + t * t * b[0], u * u * a[1] + 2 * u * t * cy + t * t * b[1]]);
|
||||
/** A click on a marker brings the map at least this close (a city). */
|
||||
const CLICK_ZOOM = 10;
|
||||
|
||||
/** mapcn's arc colours: its default blue for live tunnels, a neutral gray for recently seen. */
|
||||
const LIVE = '#3b82f6';
|
||||
const RECENT = '#8a8a8a';
|
||||
|
||||
/**
|
||||
* mapcn's arc (buildArcCoordinates): a quadratic Bézier between two
|
||||
* [lng, lat] points bent by `curvature` of their distance, `samples` steps.
|
||||
* The destination is unwrapped so |dx| <= 180: arcs across the antimeridian
|
||||
* take the short way (MapLibre draws longitudes past ±180 on the globe).
|
||||
*/
|
||||
export function arc(from: [number, number], to: [number, number], curvature = 0.2, samples = 64): [number, number][] {
|
||||
const [x0, y0] = from;
|
||||
const [xTo, y2] = to;
|
||||
const rawDx = xTo - x0;
|
||||
const x2 = rawDx > 180 ? xTo - 360 : rawDx < -180 ? xTo + 360 : xTo;
|
||||
const dx = x2 - x0;
|
||||
const dy = y2 - y0;
|
||||
const distance = Math.hypot(dx, dy);
|
||||
if (distance === 0 || curvature === 0) return [from, [x2, y2]];
|
||||
const nx = -dy / distance;
|
||||
const ny = dx / distance;
|
||||
const offset = distance * curvature;
|
||||
const cx = (x0 + x2) / 2 + nx * offset;
|
||||
const cy = (y0 + y2) / 2 + ny * offset;
|
||||
const points: [number, number][] = [];
|
||||
const segments = Math.max(2, Math.floor(samples));
|
||||
for (let i = 0; i <= segments; i += 1) {
|
||||
const t = i / segments;
|
||||
const inv = 1 - t;
|
||||
points.push([inv * inv * x0 + 2 * inv * t * cx + t * t * x2, inv * inv * y0 + 2 * inv * t * cy + t * t * y2]);
|
||||
}
|
||||
return out;
|
||||
return points;
|
||||
}
|
||||
|
||||
export interface MapCallbacks {
|
||||
@@ -77,29 +99,67 @@ export interface MapData {
|
||||
now: number;
|
||||
/** Restrict to one person (person page). */
|
||||
person?: string;
|
||||
/** Restrict to one of their devices (device window): its places in time order. */
|
||||
device?: string;
|
||||
}
|
||||
|
||||
/** Latest point per device inside the time window. */
|
||||
/**
|
||||
* The latest point per device inside the time window: per device and city on a
|
||||
* person's page, per city in a device's window.
|
||||
*/
|
||||
export function visiblePoints(data: MapData, range: Range): GeoPoint[] {
|
||||
const best = new Map<string, GeoPoint>();
|
||||
for (const p of data.geo.points) {
|
||||
if (data.person && p.person !== data.person) continue;
|
||||
if (data.device && p.device !== data.device) continue;
|
||||
if (range === 'online' ? !p.online : data.now - p.ts > WINDOW[range]) continue;
|
||||
const cur = best.get(p.device);
|
||||
if (!cur || (p.online && !cur.online) || (p.online === cur.online && p.ts > cur.ts)) best.set(p.device, p);
|
||||
// Where people are: each device once. A person's page: every city each device was in.
|
||||
const key = data.device ? `${p.city}|${p.cc}` : data.person ? `${p.device}|${p.city}|${p.cc}` : p.device;
|
||||
const cur = best.get(key);
|
||||
if (!cur || (p.online && !cur.online) || (p.online === cur.online && p.ts > cur.ts)) best.set(key, p);
|
||||
}
|
||||
return [...best.values()];
|
||||
}
|
||||
|
||||
/** A device's places, live first, then newest: `n` numbers the past ones (1 = most recent). */
|
||||
export function devicePlaces(data: MapData, range: Range): (GeoPoint & { n: number })[] {
|
||||
let i = 0;
|
||||
return visiblePoints(data, range)
|
||||
.sort((a, b) => Number(b.online) - Number(a.online) || b.ts - a.ts)
|
||||
.map((p) => ({ ...p, n: p.online ? 0 : ++i }));
|
||||
}
|
||||
|
||||
export class ConnectionMap {
|
||||
private map: any = null;
|
||||
private gl: any = null;
|
||||
private markers: any[] = [];
|
||||
private popup: any = null;
|
||||
private anim = 0;
|
||||
/** The open card: it floats over the page (not clipped by the map), pinned to its marker. */
|
||||
private popup: { card: HTMLElement; off: () => void } | null = null;
|
||||
private theme: MutationObserver | null = null;
|
||||
private resize: ResizeObserver | null = null;
|
||||
/** The last fit ran while the map had no size (a folded card): it is redone once it has one. */
|
||||
private fitBlind = false;
|
||||
private data: MapData | null = null;
|
||||
private range: Range;
|
||||
private fitted = false;
|
||||
/** The places the view was last fitted to: a change (someone came online or left) refits. */
|
||||
private fitKey: string | null = null;
|
||||
/** People's markers, for the hover highlight; the person in focus, kept across redraws. */
|
||||
private people: { el: HTMLElement; person: string }[] = [];
|
||||
/** Markers on the map: the server stays put (`fixed`), the others move aside when crowded. */
|
||||
private slots: { marker: any; el: HTMLElement; at: [number, number]; fixed: boolean; who?: string; where?: string }[] = [];
|
||||
/** People folded into the server while they would sit on top of it (their marker hidden). */
|
||||
private merged: { at: [number, number]; who: string; where: string; need: number }[] = [];
|
||||
/** Which markers were folded at the last redraw (by place key): a new marker starts that way. */
|
||||
private foldedKeys = new Set<string>();
|
||||
/** The zoom a programmatic zoom-out is heading for: markers fold for it at once, not on the way. */
|
||||
private targetZoom: number | null = null;
|
||||
/** The view before a click zoomed in on a marker: closing its popup goes back to it. */
|
||||
private before: { center: [number, number]; zoom: number } | null = null;
|
||||
/** The folded keys the layers were last filtered for (a filter only changes when they do). */
|
||||
private hiddenKey = '';
|
||||
private focused: string | null = null;
|
||||
private card: HTMLElement;
|
||||
readonly el: HTMLElement;
|
||||
private status: HTMLElement;
|
||||
|
||||
@@ -110,7 +170,8 @@ export class ConnectionMap {
|
||||
) {
|
||||
this.range = range;
|
||||
this.status = E('div', { class: 'dl-map-status' });
|
||||
this.el = E('div', { class: 'dl-geomap', style: `height:${height}px` }, this.status);
|
||||
this.card = E('div', { class: 'dl-map-card', 'aria-live': 'polite' });
|
||||
this.el = E('div', { class: 'dl-geomap', style: `height:${height}px` }, [this.status, this.card]);
|
||||
}
|
||||
|
||||
async mount(data: MapData) {
|
||||
@@ -125,70 +186,91 @@ export class ConnectionMap {
|
||||
container: this.el,
|
||||
style: isDark() ? STYLE_DARK : STYLE_LIGHT,
|
||||
center: [data.geo.home?.lon ?? 20, data.geo.home?.lat ?? 50],
|
||||
zoom: 3,
|
||||
zoom: 1,
|
||||
// mapcn's Map: MapLibre's own gestures (scroll zooms, drag spins the globe), no zoom buttons,
|
||||
// one world, the attribution behind its "i" (styled as mapcn's site, map.css).
|
||||
renderWorldCopies: false,
|
||||
attributionControl: { compact: true },
|
||||
dragRotate: false,
|
||||
pitchWithRotate: false,
|
||||
cooperativeGestures: true,
|
||||
// No further out than the whole globe filling the map.
|
||||
minZoom: 1,
|
||||
});
|
||||
this.map.addControl(new this.gl.NavigationControl({ showCompass: false }), 'bottom-right');
|
||||
this.map.on('load', () => {
|
||||
// City-level accuracy: a soft zone instead of a precise pin.
|
||||
this.map.addSource('dl-areas', { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
|
||||
this.map.addLayer({
|
||||
id: 'dl-area',
|
||||
type: 'circle',
|
||||
source: 'dl-areas',
|
||||
paint: {
|
||||
'circle-radius': ['interpolate', ['exponential', 2], ['zoom'], 2, 6, 6, 26, 9, 140, 12, 900],
|
||||
'circle-color': ['case', ['get', 'online'], '#40c977', isDark() ? '#ededed' : '#0d0d0d'],
|
||||
'circle-opacity': ['case', ['get', 'online'], 0.12, 0.06],
|
||||
'circle-stroke-width': 1,
|
||||
'circle-stroke-color': ['case', ['get', 'online'], '#40c977', isDark() ? '#ededed' : '#0d0d0d'],
|
||||
'circle-stroke-opacity': ['case', ['get', 'online'], 0.35, 0.15],
|
||||
},
|
||||
});
|
||||
this.map.addSource('dl-arcs', { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
|
||||
this.map.addLayer({
|
||||
id: 'dl-arc-recent',
|
||||
type: 'line',
|
||||
source: 'dl-arcs',
|
||||
filter: ['==', ['get', 'online'], false],
|
||||
layout: { 'line-cap': 'round' },
|
||||
paint: { 'line-color': isDark() ? '#ededed' : '#0d0d0d', 'line-opacity': 0.35, 'line-width': 1.5, 'line-dasharray': [2, 3] },
|
||||
});
|
||||
this.map.addLayer({
|
||||
id: 'dl-arc-glow',
|
||||
type: 'line',
|
||||
source: 'dl-arcs',
|
||||
filter: ['==', ['get', 'online'], true],
|
||||
layout: { 'line-cap': 'round' },
|
||||
paint: { 'line-color': '#40c977', 'line-opacity': 0.18, 'line-width': 7 },
|
||||
});
|
||||
this.map.addLayer({
|
||||
id: 'dl-arc-live',
|
||||
type: 'line',
|
||||
source: 'dl-arcs',
|
||||
filter: ['==', ['get', 'online'], true],
|
||||
layout: { 'line-cap': 'round' },
|
||||
paint: { 'line-color': '#40c977', 'line-width': 2 },
|
||||
});
|
||||
this.map.addLayer({
|
||||
id: 'dl-arc-flow',
|
||||
type: 'line',
|
||||
source: 'dl-arcs',
|
||||
filter: ['==', ['get', 'online'], true],
|
||||
layout: { 'line-cap': 'round' },
|
||||
paint: { 'line-color': '#ffffff', 'line-width': 2, 'line-opacity': 0.8, 'line-dasharray': [0, 4, 3] },
|
||||
});
|
||||
this.animate();
|
||||
this.draw();
|
||||
// Every style load (the first, and each theme switch) starts bare: the globe and our layers again.
|
||||
this.map.on('style.load', () => this.layers());
|
||||
// Crowded markers spread and come back together as the map zooms and pans.
|
||||
this.map.on('move', () => this.declutter());
|
||||
// MapLibre opens the credits once the sources have them: fold them away when the map is drawn.
|
||||
this.map.once('idle', () => {
|
||||
const attrib = this.el.querySelector('.maplibregl-ctrl-attrib');
|
||||
attrib?.classList.remove('maplibregl-compact-show');
|
||||
attrib?.removeAttribute('open');
|
||||
});
|
||||
// MapLibre follows the window, not its container (a card unfolding, the page reflowing).
|
||||
this.resize = new ResizeObserver(() => {
|
||||
if (!this.map || !this.el.clientWidth || !this.el.clientHeight) return;
|
||||
this.map.resize();
|
||||
if (this.fitBlind) {
|
||||
this.fitKey = null;
|
||||
this.draw();
|
||||
}
|
||||
});
|
||||
this.resize.observe(this.el);
|
||||
// Outline switches light and dark in place (html[data-darkmode]): the basemap follows.
|
||||
let dark = isDark();
|
||||
this.theme = new MutationObserver(() => {
|
||||
if (!this.map || isDark() === dark) return;
|
||||
dark = isDark();
|
||||
this.map.setStyle(dark ? STYLE_DARK : STYLE_LIGHT);
|
||||
});
|
||||
this.theme.observe(document.documentElement, { attributes: true, attributeFilter: ['data-darkmode'] });
|
||||
}
|
||||
|
||||
/** The globe (as mapcn's examples: projection={{ type: "globe" }}), accuracy zones and arcs. */
|
||||
private layers() {
|
||||
if (!this.map) return;
|
||||
this.hiddenKey = '';
|
||||
this.map.setProjection({ type: 'globe' });
|
||||
// City-level accuracy: a soft zone instead of a precise pin.
|
||||
this.map.addSource('dl-areas', { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
|
||||
this.map.addLayer({
|
||||
id: 'dl-area',
|
||||
type: 'circle',
|
||||
source: 'dl-areas',
|
||||
paint: {
|
||||
'circle-radius': ['interpolate', ['exponential', 2], ['zoom'], 2, 6, 6, 26, 9, 140, 12, 900],
|
||||
'circle-color': ['case', ['get', 'online'], LIVE, RECENT],
|
||||
'circle-opacity': ['case', ['get', 'online'], 0.12, 0.06],
|
||||
'circle-stroke-width': 1,
|
||||
'circle-stroke-color': ['case', ['get', 'online'], LIVE, RECENT],
|
||||
'circle-stroke-opacity': ['case', ['get', 'online'], 0.35, 0.15],
|
||||
},
|
||||
});
|
||||
// A device's trail through its places in time order (its window): fine gray dots.
|
||||
this.map.addSource('dl-trail', { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
|
||||
this.map.addLayer({
|
||||
id: 'dl-trail',
|
||||
type: 'line',
|
||||
source: 'dl-trail',
|
||||
layout: { 'line-join': 'round', 'line-cap': 'round' },
|
||||
paint: { 'line-color': RECENT, 'line-width': 1.5, 'line-opacity': 0.85, 'line-dasharray': [0, 2.5] },
|
||||
});
|
||||
// mapcn's MapArc paint (width 2, opacity 0.85, rounded) with the Basic Arc example's dashes;
|
||||
// recent arcs under live ones.
|
||||
this.map.addSource('dl-arcs', { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
|
||||
for (const live of [false, true])
|
||||
this.map.addLayer({
|
||||
id: live ? 'dl-arc-live' : 'dl-arc-recent',
|
||||
type: 'line',
|
||||
source: 'dl-arcs',
|
||||
filter: ['==', ['get', 'online'], live],
|
||||
layout: { 'line-join': 'round', 'line-cap': 'round' },
|
||||
paint: { 'line-color': live ? LIVE : RECENT, 'line-width': 2, 'line-opacity': 0.85, 'line-dasharray': [2, 2] },
|
||||
});
|
||||
this.draw();
|
||||
}
|
||||
|
||||
setRange(r: Range) {
|
||||
this.range = r;
|
||||
this.fitted = false;
|
||||
this.fitKey = null;
|
||||
this.draw();
|
||||
}
|
||||
|
||||
@@ -198,52 +280,23 @@ export class ConnectionMap {
|
||||
}
|
||||
|
||||
destroy() {
|
||||
cancelAnimationFrame(this.anim);
|
||||
this.dropCard();
|
||||
this.theme?.disconnect();
|
||||
this.resize?.disconnect();
|
||||
this.map?.remove();
|
||||
this.map = null;
|
||||
}
|
||||
|
||||
/** Moving highlight along live arcs (MapLibre "animated line" technique). */
|
||||
private animate() {
|
||||
const seq = [
|
||||
[0, 4, 3],
|
||||
[0.5, 4, 2.5],
|
||||
[1, 4, 2],
|
||||
[1.5, 4, 1.5],
|
||||
[2, 4, 1],
|
||||
[2.5, 4, 0.5],
|
||||
[3, 4, 0],
|
||||
[0, 0.5, 3, 3.5],
|
||||
[0, 1, 3, 3],
|
||||
[0, 1.5, 3, 2.5],
|
||||
[0, 2, 3, 2],
|
||||
[0, 2.5, 3, 1.5],
|
||||
[0, 3, 3, 1],
|
||||
[0, 3.5, 3, 0.5],
|
||||
];
|
||||
let step = -1;
|
||||
let last = 0;
|
||||
const tick = (t: number) => {
|
||||
if (!this.map) return;
|
||||
if (t - last > 70) {
|
||||
last = t;
|
||||
step = (step + 1) % seq.length;
|
||||
if (this.map.getLayer('dl-arc-flow')) this.map.setPaintProperty('dl-arc-flow', 'line-dasharray', seq[step]);
|
||||
}
|
||||
this.anim = requestAnimationFrame(tick);
|
||||
};
|
||||
this.anim = requestAnimationFrame(tick);
|
||||
}
|
||||
|
||||
/** Devices grouped by network operator and city: one marker per group. */
|
||||
/** A person's devices grouped by city: one marker per person and place. */
|
||||
private groups(pts: GeoPoint[]): Group[] {
|
||||
const map = new Map<string, Group>();
|
||||
for (const p of pts) {
|
||||
const key = `${p.asn || p.org || p.ip}|${p.city}|${p.cc}`;
|
||||
const key = `${p.person}|${p.city || `${p.lat.toFixed(1)},${p.lon.toFixed(1)}`}|${p.cc}`;
|
||||
let g = map.get(key);
|
||||
if (!g) {
|
||||
g = {
|
||||
key,
|
||||
person: p.person,
|
||||
lat: p.lat,
|
||||
lon: p.lon,
|
||||
city: p.city,
|
||||
@@ -268,24 +321,20 @@ export class ConnectionMap {
|
||||
if (!this.map || !this.data || !this.map.getSource('dl-arcs')) return;
|
||||
const data = this.data;
|
||||
const groups = this.groups(visiblePoints(data, this.range));
|
||||
const home = data.geo.home;
|
||||
// A person's page and a device's window are about their places alone: no server, no arcs to it.
|
||||
const home = data.person || data.device ? null : data.geo.home;
|
||||
for (const m of this.markers) m.remove();
|
||||
this.markers = [];
|
||||
|
||||
// Operators in the same city sit side by side so every marker stays clickable.
|
||||
const perCity = new Map<string, number>();
|
||||
const placed = groups.map((g) => {
|
||||
const c = `${g.lat.toFixed(2)},${g.lon.toFixed(2)}`;
|
||||
const n = perCity.get(c) ?? 0;
|
||||
perCity.set(c, n + 1);
|
||||
return { g, at: [g.lon + n * 0.25, g.lat] as [number, number] };
|
||||
});
|
||||
// Every marker at its real place; ones that would cover each other move aside on screen (declutter).
|
||||
const placed = groups.map((g) => ({ g, at: [g.lon, g.lat] as [number, number] }));
|
||||
this.slots = [];
|
||||
|
||||
this.map.getSource('dl-areas').setData({
|
||||
type: 'FeatureCollection',
|
||||
features: placed.map(({ g, at }) => ({
|
||||
type: 'Feature',
|
||||
properties: { online: g.online },
|
||||
properties: { online: g.online, key: g.key },
|
||||
geometry: { type: 'Point', coordinates: at },
|
||||
})),
|
||||
});
|
||||
@@ -294,57 +343,322 @@ export class ConnectionMap {
|
||||
features: home
|
||||
? placed.map(({ g, at }) => ({
|
||||
type: 'Feature',
|
||||
properties: { online: g.online },
|
||||
properties: { online: g.online, person: g.person, key: g.key },
|
||||
geometry: { type: 'LineString', coordinates: arc([home.lon, home.lat], at) },
|
||||
}))
|
||||
: [],
|
||||
});
|
||||
|
||||
// The server, where every arc starts: a tile in the theme's inverse colours (as the white
|
||||
// main buttons) on a frosted plate, its city on a blurred chip. People are round: who (their
|
||||
// initials) and from what (a device badge), blue while live, gray when seen recently.
|
||||
if (home) {
|
||||
const el = E('div', {
|
||||
class: 'dl-mk-home',
|
||||
title: `Home router${home.city ? ` · ${home.city}` : ''}${home.org ? ` · ${home.org}` : ''}`,
|
||||
});
|
||||
el.innerHTML = iconSvg('home', 'dl-mk-home-ic');
|
||||
this.markers.push(new this.gl.Marker({ element: el }).setLngLat([home.lon, home.lat]).addTo(this.map));
|
||||
const host = E('span', { class: 'dl-mk-host' });
|
||||
host.innerHTML = `<span class="dl-mk-host-tile">${iconSvg('server', 'dl-mk-host-ic')}</span><span class="dl-mk-host-n"></span>`;
|
||||
const el = E(
|
||||
'div',
|
||||
{ class: 'dl-mk-hub', title: `Home router${home.city ? ` · ${home.city}` : ''}${home.org ? ` · ${home.org}` : ''}` },
|
||||
[host, E('span', { class: 'dl-mk-label chip' }, home.city || 'Home')],
|
||||
);
|
||||
// Who is folded in here: listed on hover; a click zooms in until they stand apart.
|
||||
el.addEventListener('mouseenter', () => this.showMerged(home.city || 'the server'));
|
||||
el.addEventListener('mouseleave', () => this.focus(this.focused));
|
||||
el.addEventListener('click', () => this.zoomToMerged());
|
||||
this.add(el, [home.lon, home.lat], true);
|
||||
}
|
||||
|
||||
// A device's places joined oldest to newest, each step bowed like an arc.
|
||||
const steps = data.device ? [...placed].sort((a, b) => Number(a.g.online) - Number(b.g.online) || a.g.ts - b.g.ts) : [];
|
||||
this.map.getSource('dl-trail')?.setData({
|
||||
type: 'FeatureCollection',
|
||||
features:
|
||||
steps.length > 1
|
||||
? [
|
||||
{
|
||||
type: 'Feature',
|
||||
properties: {},
|
||||
geometry: { type: 'LineString', coordinates: steps.slice(1).flatMap((x, i) => arc(steps[i].at, x.at)) },
|
||||
},
|
||||
]
|
||||
: [],
|
||||
});
|
||||
const numbers = new Map(data.device ? devicePlaces(data, this.range).map((p) => [`${p.city}|${p.cc}`, p.n]) : []);
|
||||
|
||||
this.people = [];
|
||||
for (const { g, at } of placed) {
|
||||
const n = g.points.length;
|
||||
const person = data.people.find((x) => x.id === g.person);
|
||||
if (data.person) {
|
||||
const el = data.device
|
||||
? this.stepMarker(g, at, person, numbers.get(`${g.points[0].city}|${g.points[0].cc}`) ?? 0)
|
||||
: this.placeMarker(g, at, person);
|
||||
this.add(el, at);
|
||||
continue;
|
||||
}
|
||||
const kinds = g.points.map((p) => person?.devices.find((d) => d.id === p.device)?.kind ?? 'other');
|
||||
// One device: its icon; two: both; more: how many (the hover card lists them).
|
||||
const badge = E('span', { class: 'dl-mk-badge' });
|
||||
badge.innerHTML = n <= 2 ? kinds.map((k) => iconSvg(k, 'dl-mk-badge-ic')).join('') : String(n);
|
||||
const el = E(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
class: `dl-mk${g.online ? ' online' : ''}${n > 1 ? ' multi' : ''}`,
|
||||
'aria-label': `${n} device${n === 1 ? '' : 's'} via ${g.org || 'unknown network'} in ${g.city || 'unknown city'}`,
|
||||
class: `dl-mk${g.online ? ' online' : ''}`,
|
||||
'aria-label': `${person?.name ?? 'Someone'}: ${n} device${n === 1 ? '' : 's'} in ${g.city || 'an unknown city'}`,
|
||||
},
|
||||
n > 1 ? E('span', { class: 'dl-mk-count' }, String(n)) : E('span', { class: 'dl-mk-dot' }),
|
||||
[
|
||||
E('span', { class: 'dl-mk-av' }, [initials(person?.name ?? '?'), badge]),
|
||||
E('span', { class: 'dl-mk-label below' }, g.city || g.cc || '?'),
|
||||
],
|
||||
);
|
||||
const nearHome = !!home && Math.abs(at[0] - home.lon) < 0.02 && Math.abs(at[1] - home.lat) < 0.02;
|
||||
const shift: [number, number] = nearHome ? [22, -16] : [0, 0];
|
||||
el.addEventListener('mouseenter', () => this.focus(g.person));
|
||||
el.addEventListener('mouseleave', () => this.focus(null));
|
||||
this.people.push({ el, person: g.person });
|
||||
el.addEventListener('click', (ev) => {
|
||||
ev.stopPropagation();
|
||||
this.openPopup(g, at, shift);
|
||||
this.openPopup(g, at, el);
|
||||
});
|
||||
this.markers.push(new this.gl.Marker({ element: el, offset: shift }).setLngLat(at).addTo(this.map));
|
||||
this.add(el, at, false, person?.name ?? 'Someone', `${g.city || g.cc || '?'} · ${g.online ? 'now' : ago(g.ts, data.now)}`, g.key);
|
||||
}
|
||||
this.declutter();
|
||||
|
||||
if (!this.fitted) {
|
||||
const coords: [number, number][] = placed.map((x) => x.at);
|
||||
if (home && (coords.length === 0 || this.range !== 'online' || placed.some((x) => x.g.online))) coords.push([home.lon, home.lat]);
|
||||
this.fit(coords);
|
||||
// The view follows the places shown: the first one is set at once, later ones glide there.
|
||||
// Not while a popup is open (it would leave its marker); the next update catches up.
|
||||
const key = placed
|
||||
.map((x) => x.g.key)
|
||||
.sort()
|
||||
.join(';');
|
||||
if (key !== this.fitKey && !this.popup) {
|
||||
const animate = this.fitted && !this.fitBlind;
|
||||
this.fitBlind = !this.el.clientWidth || !this.el.clientHeight;
|
||||
this.fitKey = key;
|
||||
this.fitted = true;
|
||||
if (home && !placed.length) {
|
||||
// Nobody to show: the router up close, at the same zoom as the closest fit.
|
||||
const view = { center: [home.lon, home.lat], zoom: 12 };
|
||||
if (animate) this.glide(12, () => this.map.flyTo({ ...view, duration: 1200 }));
|
||||
else this.map.jumpTo(view);
|
||||
} else {
|
||||
const coords: [number, number][] = placed.map((x) => x.at);
|
||||
if (home && (coords.length === 0 || this.range !== 'online' || placed.some((x) => x.g.online))) coords.push([home.lon, home.lat]);
|
||||
this.fit(coords, animate);
|
||||
}
|
||||
}
|
||||
this.status.textContent = placed.length || home ? '' : 'No locations yet';
|
||||
this.status.style.display = this.status.textContent ? '' : 'none';
|
||||
this.focus(this.focused && this.people.some((x) => x.person === this.focused) ? this.focused : null);
|
||||
}
|
||||
|
||||
private add(el: HTMLElement, at: [number, number], fixed = false, who?: string, where?: string, key?: string) {
|
||||
// A redrawn marker keeps how it was (folded or not), with no fade in its first frame.
|
||||
if (key && this.foldedKeys.has(key)) el.classList.add('merged');
|
||||
el.dataset.key = key ?? '';
|
||||
el.classList.add('dl-mk-new');
|
||||
requestAnimationFrame(() => requestAnimationFrame(() => el.classList.remove('dl-mk-new')));
|
||||
const marker = new this.gl.Marker({ element: el }).setLngLat(at).addTo(this.map);
|
||||
this.markers.push(marker);
|
||||
this.slots.push({ marker, el, at, fixed, who, where });
|
||||
}
|
||||
|
||||
/**
|
||||
* Zoom to what matters: a single city fills the map at city level, a few
|
||||
* places get just enough room, and lone outliers never shrink everything to
|
||||
* a continent (the farthest 10% are left out when the rest are clustered).
|
||||
* Markers that would cover each other: someone on top of the server folds into a count on
|
||||
* its plate (moved aside they would look like another region, a dot would hide under it) and
|
||||
* comes back once there is room; markers crowding each other are pushed just clear, a thin
|
||||
* line pointing back to the real spot. The push grows with the overlap and fades to nothing
|
||||
* as the map zooms in, so markers glide back to their places instead of jumping.
|
||||
*/
|
||||
private fit(coords: [number, number][]) {
|
||||
private declutter() {
|
||||
if (!this.map) return;
|
||||
const items = this.slots.map((m) => {
|
||||
const p = this.map.project(m.at);
|
||||
const body = m.el.querySelector(':scope > .dl-mk-host, :scope > .dl-mk-av, :scope > .dl-mk-tile') as HTMLElement | null;
|
||||
return { x: p.x as number, y: p.y as number, r: (body?.offsetWidth || 24) / 2 + 3, fixed: m.fixed };
|
||||
});
|
||||
const fixed = items.filter((i) => i.fixed);
|
||||
this.merged = [];
|
||||
this.foldedKeys.clear();
|
||||
// Zooming out on its own (a new fit): distances as they will be, so folding happens at once.
|
||||
const ahead = this.targetZoom == null ? 1 : Math.min(1, 2 ** (this.targetZoom - this.map.getZoom()));
|
||||
items.forEach((it, i) => {
|
||||
if (it.fixed) return;
|
||||
const slot = this.slots[i];
|
||||
// A little more room to come back than to fold, so it doesn't flicker at the edge.
|
||||
const room = slot.el.classList.contains('merged') ? 12 : 6;
|
||||
const near = fixed.find((f) => Math.hypot(f.x - it.x, f.y - it.y) * ahead < f.r + it.r + room);
|
||||
slot.el.classList.toggle('merged', !!near);
|
||||
if (!near) return;
|
||||
if (slot.el.dataset.key) this.foldedKeys.add(slot.el.dataset.key);
|
||||
// How much closer the map has to come for them to stand apart.
|
||||
const need = (near.r + it.r + 14) / Math.max(1, Math.hypot(near.x - it.x, near.y - it.y));
|
||||
this.merged.push({ at: slot.at, who: slot.who ?? 'Someone', where: slot.where ?? '', need });
|
||||
Object.assign(it, { r: 0, fixed: true });
|
||||
});
|
||||
// A folded person leaves no trace either: their accuracy zone and arc go with their marker.
|
||||
const hidden = [...this.foldedKeys].sort().join('|');
|
||||
if (hidden !== this.hiddenKey) {
|
||||
this.hiddenKey = hidden;
|
||||
const shown = ['!', ['in', ['get', 'key'], ['literal', [...this.foldedKeys]]]];
|
||||
if (this.map.getLayer('dl-area')) this.map.setFilter('dl-area', shown);
|
||||
for (const live of [false, true]) {
|
||||
const id = live ? 'dl-arc-live' : 'dl-arc-recent';
|
||||
if (this.map.getLayer(id)) this.map.setFilter(id, ['all', ['==', ['get', 'online'], live], shown]);
|
||||
}
|
||||
}
|
||||
const count = this.slots.find((m) => m.fixed)?.el.querySelector('.dl-mk-host-n') as HTMLElement | null;
|
||||
if (count) {
|
||||
count.textContent = this.merged.length ? String(this.merged.length) : '';
|
||||
count.classList.toggle('on', this.merged.length > 0);
|
||||
}
|
||||
separate(items).forEach(([dx, dy], i) => {
|
||||
const m = this.slots[i];
|
||||
if (m.fixed) return;
|
||||
if (items[i].fixed) [dx, dy] = [0, 0];
|
||||
m.marker.setOffset([dx, dy]);
|
||||
pointer(m.el, dx, dy);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The card fades out and goes; the map goes back to the view before a click zoomed in. Closed
|
||||
* by a press, that waits for the release: MapLibre stops a camera move when a press begins.
|
||||
*/
|
||||
private closePopup(pressed = false) {
|
||||
const open = this.popup;
|
||||
if (!open || open.card.classList.contains('leaving')) return;
|
||||
open.card.classList.add('leaving');
|
||||
setTimeout(() => {
|
||||
if (this.popup === open) this.dropCard();
|
||||
}, 140);
|
||||
const back = this.before;
|
||||
this.before = null;
|
||||
if (!back) return;
|
||||
const go = () => this.map?.flyTo({ ...back, duration: 800 });
|
||||
if (!pressed) return go();
|
||||
let done = false;
|
||||
const once = () => {
|
||||
if (done) return;
|
||||
done = true;
|
||||
window.removeEventListener('pointerup', once, true);
|
||||
window.removeEventListener('pointercancel', once, true);
|
||||
// After MapLibre has taken the release too.
|
||||
setTimeout(go, 0);
|
||||
};
|
||||
window.addEventListener('pointerup', once, true);
|
||||
window.addEventListener('pointercancel', once, true);
|
||||
setTimeout(once, 1500);
|
||||
}
|
||||
|
||||
/** The card gone at once (another one replaces it, or the map goes away). */
|
||||
private dropCard() {
|
||||
this.popup?.off();
|
||||
this.popup?.card.remove();
|
||||
this.popup = null;
|
||||
}
|
||||
|
||||
/** The people folded into the server, in the corner card. */
|
||||
private showMerged(place: string) {
|
||||
if (!this.merged.length) return;
|
||||
dom.content(this.card, [
|
||||
E('div', { class: 'dl-map-card-head' }, [E('b', {}, `Near ${place}`), ' · zoom in to see them']),
|
||||
...this.merged.map((m) => E('div', { class: 'dl-map-card-row' }, [E('span', {}, m.who), E('span', { class: 'dl-faint' }, m.where)])),
|
||||
]);
|
||||
this.card.classList.add('on');
|
||||
}
|
||||
|
||||
/** Close enough for everyone folded into the server to stand apart (never past zoom 12). */
|
||||
private zoomToMerged() {
|
||||
if (!this.map || !this.merged.length) return;
|
||||
const step = Math.log2(Math.max(...this.merged.map((m) => m.need))) + 0.3;
|
||||
const pts = [this.slots.find((m) => m.fixed)!.at, ...this.merged.map((m) => m.at)];
|
||||
const center: [number, number] = [pts.reduce((s, p) => s + p[0], 0) / pts.length, pts.reduce((s, p) => s + p[1], 0) / pts.length];
|
||||
this.map.flyTo({ center, zoom: Math.min(12, this.map.getZoom() + step), duration: 900 });
|
||||
}
|
||||
|
||||
/**
|
||||
* A place on a person's page: a rounded tile with the latest device's icon (and how many
|
||||
* devices, when several), blue while one is live, gray and fainter the longer ago it was
|
||||
* (down to 40% at 30 days); the city and when below.
|
||||
*/
|
||||
private placeMarker(g: Group, at: [number, number], person: Person | undefined): HTMLElement {
|
||||
const now = this.data!.now;
|
||||
const latest = [...g.points].sort((a, b) => Number(b.online) - Number(a.online) || b.ts - a.ts)[0];
|
||||
const kind = person?.devices.find((d) => d.id === latest.device)?.kind ?? 'other';
|
||||
const n = g.points.length;
|
||||
const tile = E('span', { class: 'dl-mk-tile' });
|
||||
tile.innerHTML = iconSvg(kind, 'dl-mk-tile-ic') + (n > 1 ? `<span class="dl-mk-tile-n">${n}</span>` : '');
|
||||
const when = g.online ? 'now' : ago(g.ts, now);
|
||||
const el = E(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
class: `dl-mk place${g.online ? ' online' : ''}`,
|
||||
style: g.online ? null : `--dl-mk-fade:${Math.max(0.4, 1 - (0.6 * (now - g.ts)) / (30 * 86400)).toFixed(2)}`,
|
||||
'aria-label': `${n} device${n === 1 ? '' : 's'} in ${g.city || 'an unknown city'}, ${when}`,
|
||||
},
|
||||
[tile, E('span', { class: 'dl-mk-label below' }, [g.city || g.cc || '?', E('span', { class: 'dl-mk-when' }, when)])],
|
||||
);
|
||||
el.addEventListener('click', (ev) => {
|
||||
ev.stopPropagation();
|
||||
this.openPopup(g, at, el);
|
||||
});
|
||||
return el;
|
||||
}
|
||||
|
||||
/**
|
||||
* A place in a device's window: the live one as a blue tile with the device's icon and
|
||||
* "now", the earlier ones as small gray tiles numbered by recency (1 = most recent).
|
||||
*/
|
||||
private stepMarker(g: Group, at: [number, number], person: Person | undefined, n: number): HTMLElement {
|
||||
if (g.online) return this.placeMarker(g, at, person);
|
||||
const when = ago(g.ts, this.data!.now);
|
||||
const el = E('button', { type: 'button', class: 'dl-mk place step', 'aria-label': `${n}: ${g.city || 'an unknown city'}, ${when}` }, [
|
||||
E('span', { class: 'dl-mk-tile sm' }, String(n)),
|
||||
E('span', { class: 'dl-mk-label below' }, [g.city || g.cc || '?', ` · ${when}`]),
|
||||
]);
|
||||
el.addEventListener('click', (ev) => {
|
||||
ev.stopPropagation();
|
||||
this.openPopup(g, at, el);
|
||||
});
|
||||
return el;
|
||||
}
|
||||
|
||||
/**
|
||||
* One person in focus (hovering any of their markers): all their places and arcs stay,
|
||||
* everyone else fades, and a card lists their devices with where and when.
|
||||
*/
|
||||
private focus(person: string | null) {
|
||||
this.focused = person;
|
||||
for (const x of this.people) {
|
||||
x.el.classList.toggle('dim', !!person && x.person !== person);
|
||||
x.el.classList.toggle('hl', x.person === person);
|
||||
}
|
||||
const opacity = person ? ['case', ['==', ['get', 'person'], person], 0.85, 0.15] : 0.85;
|
||||
for (const id of ['dl-arc-live', 'dl-arc-recent']) if (this.map?.getLayer(id)) this.map.setPaintProperty(id, 'line-opacity', opacity);
|
||||
this.card.classList.toggle('on', !!person);
|
||||
if (!person || !this.data) return;
|
||||
const data = this.data;
|
||||
const who = data.people.find((x) => x.id === person);
|
||||
const pts = visiblePoints(data, this.range)
|
||||
.filter((p) => p.person === person)
|
||||
.sort((a, b) => Number(b.online) - Number(a.online) || b.ts - a.ts);
|
||||
dom.content(this.card, [
|
||||
E('div', { class: 'dl-map-card-head' }, [E('b', {}, who?.name ?? person), ` · ${pts.length} device${pts.length === 1 ? '' : 's'}`]),
|
||||
...pts.map((p) =>
|
||||
E('div', { class: 'dl-map-card-row' }, [
|
||||
E('span', {}, who?.devices.find((d) => d.id === p.device)?.name ?? 'Device'),
|
||||
E('span', { class: 'dl-faint' }, `${p.city || p.cc || '?'} · ${p.online ? 'now' : ago(p.ts, data.now)}`),
|
||||
]),
|
||||
),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Zoom to what matters: the points fill the map, never closer than zoom 12 (11 on a person's page)
|
||||
* (one place, or a few in one city, shows the neighbourhood), and lone
|
||||
* outliers never shrink everything to a continent (the farthest 10% are
|
||||
* left out when the rest are clustered).
|
||||
*/
|
||||
private fit(coords: [number, number][], animate = false) {
|
||||
if (!coords.length) return;
|
||||
const km = (a: [number, number], b: [number, number]) => {
|
||||
const r = Math.PI / 180;
|
||||
@@ -362,25 +676,32 @@ export class ConnectionMap {
|
||||
const sorted = [...coords].sort((a, b) => km(center, a) - km(center, b));
|
||||
pts = sorted.slice(0, Math.ceil(sorted.length * 0.9));
|
||||
}
|
||||
const spread = Math.max(...pts.map((c) => km(center, c)));
|
||||
if (spread < 25) {
|
||||
// Everyone in one city: show the city, accuracy zones included.
|
||||
this.map.jumpTo({ center, zoom: 9.5 });
|
||||
return;
|
||||
}
|
||||
const b = new this.gl.LngLatBounds(pts[0], pts[0]);
|
||||
pts.forEach((c) => b.extend(c));
|
||||
const h = this.el.clientHeight || 380;
|
||||
this.map.fitBounds(b, {
|
||||
padding: { top: Math.min(90, h / 4), bottom: Math.min(70, h / 5), left: 60, right: 60 },
|
||||
maxZoom: 9,
|
||||
duration: 0,
|
||||
});
|
||||
const opts = {
|
||||
// Just enough room for the labels: the server's chip above its plate, a place's name above its dot.
|
||||
padding: { top: Math.min(60, h / 5), bottom: Math.min(40, h / 8), left: 48, right: 48 },
|
||||
// A person's page shows a little more around a single place.
|
||||
maxZoom: this.data?.person ? 11 : 12,
|
||||
};
|
||||
if (!animate) this.map.fitBounds(b, { ...opts, duration: 0 });
|
||||
else this.glide(this.map.cameraForBounds(b, opts)?.zoom ?? null, () => this.map.fitBounds(b, { ...opts, duration: 1200 }));
|
||||
}
|
||||
|
||||
private openPopup(g: Group, at: [number, number], shift: [number, number] = [0, 0]) {
|
||||
/** A programmatic move to `zoom`: markers are decluttered for where it ends, then follow it. */
|
||||
private glide(zoom: number | null, move: () => void) {
|
||||
this.targetZoom = zoom;
|
||||
this.declutter();
|
||||
this.map.once('moveend', () => {
|
||||
this.targetZoom = null;
|
||||
this.declutter();
|
||||
});
|
||||
move();
|
||||
}
|
||||
|
||||
private openPopup(g: Group, at: [number, number], el?: HTMLElement) {
|
||||
const data = this.data!;
|
||||
this.popup?.remove();
|
||||
const where = [g.city, g.cc || g.country].filter(Boolean).join(', ');
|
||||
const people = [...new Set(g.points.map((p) => p.person))];
|
||||
const rows = g.points
|
||||
@@ -413,25 +734,135 @@ export class ConnectionMap {
|
||||
])
|
||||
: '',
|
||||
]);
|
||||
// Make room above the marker so the popup is never cut by the map edge.
|
||||
const h = this.el.clientHeight || 380;
|
||||
this.map.easeTo({ center: at, offset: [0, Math.min(140, h * 0.32)], duration: 300 });
|
||||
this.popup = new this.gl.Popup({
|
||||
offset: [shift[0], shift[1] - 18],
|
||||
anchor: 'bottom',
|
||||
closeButton: false,
|
||||
focusAfterOpen: false,
|
||||
maxWidth: '300px',
|
||||
className: 'dl-popup',
|
||||
})
|
||||
.setLngLat(at)
|
||||
.setDOMContent(body)
|
||||
.addTo(this.map);
|
||||
// Closer to a marker clicked from afar (city level); the card itself never moves the map.
|
||||
const zoom = this.map.getZoom();
|
||||
if (zoom < CLICK_ZOOM) {
|
||||
if (!this.before) this.before = { center: this.map.getCenter().toArray(), zoom };
|
||||
this.map.flyTo({ center: at, zoom: CLICK_ZOOM, duration: 800 });
|
||||
}
|
||||
this.dropCard();
|
||||
const card = E('div', { class: 'dl-root dl-popcard', role: 'dialog' }, [E('span', { class: 'dl-popcard-tip' }), body]);
|
||||
document.body.appendChild(card);
|
||||
const mapEl = this.el;
|
||||
const marker = (el?.querySelector('.dl-mk-av, .dl-mk-tile') as HTMLElement | null) ?? el ?? null;
|
||||
// Above the marker when the window has room there, else below; inside the window sideways;
|
||||
// hidden while the marker is outside the map.
|
||||
const place = () => {
|
||||
if (!marker) return;
|
||||
const r = marker.getBoundingClientRect();
|
||||
const m = mapEl.getBoundingClientRect();
|
||||
const cx = r.left + r.width / 2;
|
||||
const cy = r.top + r.height / 2;
|
||||
card.classList.toggle('away', cx < m.left || cx > m.right || cy < m.top || cy > m.bottom);
|
||||
const w = card.offsetWidth;
|
||||
const h = card.offsetHeight;
|
||||
const above = r.top - h - 12 >= 8 || r.top > window.innerHeight - r.bottom;
|
||||
const left = Math.min(Math.max(8, cx - w / 2), window.innerWidth - w - 8);
|
||||
card.classList.toggle('above', above);
|
||||
card.classList.toggle('below', !above);
|
||||
card.style.left = `${left}px`;
|
||||
card.style.top = `${above ? r.top - h - 12 : r.bottom + 12}px`;
|
||||
card.style.setProperty('--tip-x', `${cx - left}px`);
|
||||
};
|
||||
// A press anywhere but the card or a marker (a marker opens its own) closes it, as do Esc,
|
||||
// scrolling the page (not the card's own list) and going to another page.
|
||||
const outside = (ev: Event) => {
|
||||
if (!(ev.target as HTMLElement | null)?.closest('.dl-popcard, .maplibregl-marker')) this.closePopup(true);
|
||||
};
|
||||
const esc = (ev: KeyboardEvent) => {
|
||||
if (ev.key === 'Escape') this.closePopup();
|
||||
};
|
||||
const scrolled = (ev: Event) => {
|
||||
if (!(ev.target instanceof Element && ev.target.closest('.dl-popcard'))) this.closePopup();
|
||||
};
|
||||
const close = () => this.closePopup();
|
||||
this.map.on('move', place);
|
||||
window.addEventListener('scroll', scrolled, { capture: true, passive: true });
|
||||
window.addEventListener('resize', place);
|
||||
document.addEventListener('pointerdown', outside, true);
|
||||
document.addEventListener('keydown', esc);
|
||||
const offNav = onNavigate(close);
|
||||
window.addEventListener('pagehide', close);
|
||||
this.popup = {
|
||||
card,
|
||||
off: () => {
|
||||
this.map?.off('move', place);
|
||||
window.removeEventListener('scroll', scrolled, true);
|
||||
window.removeEventListener('resize', place);
|
||||
document.removeEventListener('pointerdown', outside, true);
|
||||
document.removeEventListener('keydown', esc);
|
||||
offNav();
|
||||
window.removeEventListener('pagehide', close);
|
||||
},
|
||||
};
|
||||
// Hidden with its page section (another one shown): gone too.
|
||||
const watch = window.setInterval(() => {
|
||||
if (this.popup?.card !== card) return clearInterval(watch);
|
||||
if (!mapEl.isConnected || !mapEl.getClientRects().length) this.dropCard();
|
||||
}, 400);
|
||||
place();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* How far each circle has to move (screen px) so none overlap by more than nothing, with `gap`
|
||||
* between them: overlapping pairs are pushed apart by the overlap, half each, all of it on the
|
||||
* one that isn't `fixed`. A few rounds settle a crowd; the result follows the input smoothly.
|
||||
*/
|
||||
export function separate(items: { x: number; y: number; r: number; fixed?: boolean }[], gap = 6): [number, number][] {
|
||||
const p = items.map((i) => ({ x: i.x, y: i.y }));
|
||||
for (let round = 0; round < 16; round++) {
|
||||
let moved = false;
|
||||
for (let i = 0; i < items.length; i++)
|
||||
for (let j = i + 1; j < items.length; j++) {
|
||||
const a = items[i],
|
||||
b = items[j];
|
||||
if (a.fixed && b.fixed) continue;
|
||||
let dx = p[j].x - p[i].x,
|
||||
dy = p[j].y - p[i].y,
|
||||
d = Math.hypot(dx, dy);
|
||||
const push = a.r + b.r + gap - d;
|
||||
if (push <= 0) continue;
|
||||
if (d < 0.01) {
|
||||
// On the very same spot: a fixed direction per pair, so they part the same way every time.
|
||||
const t = (i + 1) * 2.399 + j;
|
||||
[dx, dy, d] = [Math.cos(t), Math.sin(t), 1];
|
||||
}
|
||||
const wa = a.fixed ? 0 : b.fixed ? 1 : 0.5;
|
||||
const wb = 1 - wa;
|
||||
p[i].x -= (dx / d) * push * wa;
|
||||
p[i].y -= (dy / d) * push * wa;
|
||||
p[j].x += (dx / d) * push * wb;
|
||||
p[j].y += (dy / d) * push * wb;
|
||||
moved = true;
|
||||
}
|
||||
if (!moved) break;
|
||||
}
|
||||
return p.map((q, i) => [q.x - items[i].x, q.y - items[i].y]);
|
||||
}
|
||||
|
||||
/** The line from a moved marker back to its real spot, with a dot there (hidden when in place). */
|
||||
function pointer(el: HTMLElement, dx: number, dy: number) {
|
||||
let ptr = el.querySelector(':scope > .dl-mk-ptr') as HTMLElement | null;
|
||||
const len = Math.hypot(dx, dy);
|
||||
if (len < 1) {
|
||||
ptr?.remove();
|
||||
return;
|
||||
}
|
||||
if (!ptr) {
|
||||
ptr = E('span', { class: 'dl-mk-ptr' }, [E('i', { class: 'line' }), E('i', { class: 'spot' })]);
|
||||
el.prepend(ptr);
|
||||
}
|
||||
const line = ptr.firstElementChild as HTMLElement;
|
||||
const spot = ptr.lastElementChild as HTMLElement;
|
||||
line.style.width = `${len}px`;
|
||||
line.style.transform = `rotate(${Math.atan2(-dy, -dx)}rad)`;
|
||||
spot.style.transform = `translate(${-dx}px, ${-dy}px)`;
|
||||
}
|
||||
|
||||
interface Group {
|
||||
key: string;
|
||||
person: string;
|
||||
lat: number;
|
||||
lon: number;
|
||||
city: string;
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
// A new server's UDP port and device addresses, checked as the router checks
|
||||
// them (rpc/servers.uc) and said in plain words for the setup wizard. The
|
||||
// addresses are three numbers ("10.77.0"): the tunnel is that /24.
|
||||
|
||||
/** A network on the router, by name: an interface ("lan") or a server ("Home"). */
|
||||
export interface Network {
|
||||
name: string;
|
||||
cidr: string;
|
||||
}
|
||||
|
||||
/** UDP ports someone holds: a single port has from == to. */
|
||||
export interface PortHold {
|
||||
from: number;
|
||||
to: number;
|
||||
who: string;
|
||||
}
|
||||
|
||||
/** A help line under a field: what it means, or what is wrong (`bad`). */
|
||||
export interface Help {
|
||||
text: string;
|
||||
bad: boolean;
|
||||
}
|
||||
|
||||
interface Cidr {
|
||||
net: number;
|
||||
size: number;
|
||||
}
|
||||
|
||||
/** "10.77.0.0/24" as its network and size, prefix 8-30 like util.uc's parse_cidr; null if not one. */
|
||||
export function parseCidr(s: string): Cidr | null {
|
||||
const m = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\/(\d{1,2})$/.exec(s.trim());
|
||||
if (!m) return null;
|
||||
const [a, b, c, d] = m.slice(1, 5).map(Number);
|
||||
const prefix = Number(m[5]);
|
||||
if ([a, b, c, d].some((x) => x > 255) || prefix < 8 || prefix > 30) return null;
|
||||
const ip = a * 2 ** 24 + b * 2 ** 16 + c * 2 ** 8 + d;
|
||||
const size = 2 ** (32 - prefix);
|
||||
return { net: ip - (ip % size), size };
|
||||
}
|
||||
|
||||
const overlaps = (x: Cidr, y: Cidr): boolean => x.net < y.net + y.size && y.net < x.net + x.size;
|
||||
|
||||
const PRIVATE = ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16'].map((c) => parseCidr(c) as Cidr);
|
||||
|
||||
/** The first three numbers of a subnet ("10.77.0.0/24" → "10.77.0"). */
|
||||
export function rangeOf(subnet: string): string {
|
||||
return subnet.split('/')[0].split('.').slice(0, 3).join('.');
|
||||
}
|
||||
|
||||
/** The tunnel subnet of a range ("10.77.0" → "10.77.0.0/24"). */
|
||||
export function subnetOf(range: string): string {
|
||||
return `${range.trim()}.0/24`;
|
||||
}
|
||||
|
||||
/** The device addresses: what they give, or why not (`suggest` is a free range to offer). */
|
||||
export function rangeHelp(range: string, nets: Network[], suggest: string): Help {
|
||||
const r = range.trim();
|
||||
const c = /^\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(r) ? parseCidr(subnetOf(r)) : null;
|
||||
if (!c) return { text: 'Three numbers, like 10.77.0.', bad: true };
|
||||
if (!PRIVATE.some((p) => c.net >= p.net && c.net + c.size <= p.net + p.size))
|
||||
return { text: 'Use a private range: 10.x.x, 172.16–31.x or 192.168.x.', bad: true };
|
||||
const hit = nets.find((n) => {
|
||||
const o = parseCidr(n.cidr);
|
||||
return o != null && overlaps(c, o);
|
||||
});
|
||||
if (hit) {
|
||||
const used = hit.cidr.endsWith('/24') ? `${rangeOf(hit.cidr)}.x` : hit.cidr;
|
||||
const other = suggest && suggest !== r ? ` Try ${suggest}.` : '';
|
||||
return { text: `${hit.name} already uses ${used}.${other}`, bad: true };
|
||||
}
|
||||
return { text: `Devices get ${r}.2 – ${r}.254, the router ${r}.1.`, bad: false };
|
||||
}
|
||||
|
||||
const holder = (port: number, taken: PortHold[]): string | null => taken.find((t) => t.from <= port && port <= t.to)?.who ?? null;
|
||||
|
||||
const validPort = (port: number): boolean => Number.isInteger(port) && port >= 1 && port <= 65535;
|
||||
|
||||
/** A port: `free` when nobody holds it, or who does. */
|
||||
export function portHelp(port: number, taken: PortHold[], free: string): Help {
|
||||
if (!validPort(port)) return { text: 'Use a port from 1 to 65535.', bad: true };
|
||||
const who = holder(port, taken);
|
||||
return who ? { text: `Used by ${who}. Choose another port.`, bad: true } : { text: free, bad: false };
|
||||
}
|
||||
|
||||
/** The portal's TCP port; links on IP addresses (`ipLinks`) use plain HTTP on the next one too. */
|
||||
export function portalPortHelp(port: number, taken: PortHold[], ipLinks: boolean): Help {
|
||||
const free = ipLinks ? `HTTPS here, plain HTTP for links on IP addresses on ${port + 1}.` : 'HTTPS on this port, opened on WAN.';
|
||||
const h = portHelp(port, taken, free);
|
||||
if (h.bad || !ipLinks) return h;
|
||||
if (port === 65535) return { text: 'Links on IP addresses also need the next port: choose a lower one.', bad: true };
|
||||
const who = holder(port + 1, taken);
|
||||
return who ? { text: `Links on IP addresses also need ${port + 1}, used by ${who}. Choose another port.`, bad: true } : h;
|
||||
}
|
||||
@@ -41,7 +41,6 @@ function attention(st: Status): Attention[] {
|
||||
tone: 'bad',
|
||||
text: [`Tunnel ${s.ifname} is down. `, link(L.url('admin/network/dawnline/diagnostics'), 'Open Diagnostics')],
|
||||
});
|
||||
if (st.settings.paused_all) out.push({ tone: 'warn', text: ['Everyone is paused.'] });
|
||||
for (const p of st.people) {
|
||||
if (p.state === 'quota') out.push({ tone: 'warn', text: [link(personUrl(p.id), p.name), ' reached the data limit.'] });
|
||||
else if (p.state === 'expired') out.push({ tone: 'warn', text: [link(personUrl(p.id), p.name), '’s access has ended.'] });
|
||||
@@ -166,9 +165,8 @@ export class ServerOverview {
|
||||
this.range,
|
||||
);
|
||||
const legend = E('div', { class: 'dl-map-legend' }, [
|
||||
E('span', {}, [E('i', { class: 'dot ok' }), 'Online']),
|
||||
E('span', {}, [E('i', { class: 'dot' }), 'Seen recently']),
|
||||
E('span', {}, [E('i', { class: 'line' }), 'Live tunnel']),
|
||||
E('span', {}, [E('i', { class: 'line live' }), 'Live tunnel']),
|
||||
E('span', {}, [E('i', { class: 'line' }), 'Seen recently']),
|
||||
]);
|
||||
const wrap = E('div', { class: 'dl-map-wrap' }, [this.map.el, legend]);
|
||||
requestAnimationFrame(() => this.map!.mount(this.mapData()));
|
||||
@@ -178,11 +176,10 @@ export class ServerOverview {
|
||||
paint(quiet = false) {
|
||||
const st = this.st;
|
||||
const srv = st.servers[0];
|
||||
const slots = st.people.reduce((a, p) => a + Math.max(0, p.device_limit - p.devices.length), 0);
|
||||
|
||||
repaint(
|
||||
this.parts.bento,
|
||||
E('div', { class: 'dl-bento' }, [this.onlineTile(), this.speedTile(), coreOf(srv).overviewTile(srv), this.monthTile(slots)]),
|
||||
E('div', { class: 'dl-bento' }, [this.onlineTile(), this.speedTile(), coreOf(srv).overviewTile(srv), this.monthTile()]),
|
||||
quiet,
|
||||
);
|
||||
|
||||
@@ -235,11 +232,14 @@ export class ServerOverview {
|
||||
*/
|
||||
onlineTile(): HTMLElement {
|
||||
const st = this.st;
|
||||
const off = st.servers[0] ? !st.servers[0].enabled : false;
|
||||
const CAP = 12;
|
||||
const today = (d: Device) => d.spark[d.spark.length - 1] ?? 0;
|
||||
const cityOf = (d: Device) => st.geo.points.find((g) => g.device === d.id && g.city)?.city;
|
||||
const home = (d: Device) => /^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/.test(d.endpoint ?? '');
|
||||
const where = (d: Device) => (home(d) ? 'home' : cityOf(d)) ?? '';
|
||||
// Where a device is: its city, or "LAN" when it connects from the home network (the hover
|
||||
// card adds its address there).
|
||||
const where = (d: Device, ip = false): string => (home(d) ? (ip && d.endpoint ? `LAN · ${d.endpoint}` : 'LAN') : (cityOf(d) ?? ''));
|
||||
const connectedAt = (d: Device) => [...st.events].reverse().find((e) => e.type === 'connect' && e.device === d.id)?.ts ?? 0;
|
||||
const on = st.people
|
||||
.map((p) => ({ p, devs: p.devices.filter((d) => d.online).sort((a, b) => today(b) - today(a)) }))
|
||||
@@ -298,7 +298,7 @@ export class ServerOverview {
|
||||
E(
|
||||
'div',
|
||||
{ class: 'dl-hc-devs' },
|
||||
devs.map((d) => E('span', { class: 'dl-hc-dev' }, [icon(d.kind), [d.name, where(d)].filter(Boolean).join(' · ')])),
|
||||
devs.map((d) => E('span', { class: 'dl-hc-dev' }, [icon(d.kind), d.name, where(d) ? [' · ', where(d, true)] : ''])),
|
||||
),
|
||||
E('div', { class: 'dl-hc-foot' }, [
|
||||
E(
|
||||
@@ -321,7 +321,7 @@ export class ServerOverview {
|
||||
? E('span', { class: 'dl-onl-meta' }, [
|
||||
...devs.slice(0, 3).map((d) => icon(d.kind)),
|
||||
devs.length > 3 ? `+${devs.length - 3}` : '',
|
||||
where(devs[0]) ? E('span', {}, ` · ${where(devs[0])}`) : '',
|
||||
where(devs[0]) ? E('span', {}, [' · ', where(devs[0])]) : '',
|
||||
])
|
||||
: '',
|
||||
]);
|
||||
@@ -362,10 +362,11 @@ export class ServerOverview {
|
||||
: '',
|
||||
])
|
||||
: E('div', { class: 'dl-onl-empty' }, [
|
||||
E('span', {}, 'Nobody is connected'),
|
||||
// A server that is off takes no connections: say so rather than "nobody".
|
||||
E('span', {}, off ? 'The server is turned off' : 'Nobody is connected'),
|
||||
last
|
||||
? E('span', { class: 'dl-sub' }, `Last: ${last.p.name}, ${ago(last.d.handshake, st.now)}`)
|
||||
: E('span', { class: 'dl-sub' }, 'No device has connected yet'),
|
||||
: E('span', { class: 'dl-sub' }, off ? 'Devices connect once it is on' : 'No device has connected yet'),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
@@ -375,16 +376,12 @@ export class ServerOverview {
|
||||
* upload side by side, the last 15 minutes as a small chart, today's total.
|
||||
*/
|
||||
speedTile(): HTMLElement {
|
||||
return speedTile(this.st.servers[0]?.rate ?? [], this.st.now, this.st.totals.today);
|
||||
const srv = this.st.servers[0];
|
||||
return speedTile(srv?.rate ?? [], this.st.now, this.st.totals.today, srv ? !srv.enabled : false);
|
||||
}
|
||||
|
||||
/** The last 30 days, today on the right, with the peak; plus the people summary. */
|
||||
monthTile(slots: number): HTMLElement {
|
||||
const t = this.st.totals;
|
||||
const paused = this.st.people.filter((p) => p.state !== 'active').length;
|
||||
return daysTile(
|
||||
this.st.series,
|
||||
`${t.people} ${t.people === 1 ? 'person' : 'people'}${paused ? ` · ${paused} paused` : ''} · ${slots} device slot${slots === 1 ? '' : 's'} free`,
|
||||
);
|
||||
/** The last 30 days, today on the right, with the peak. */
|
||||
monthTile(): HTMLElement {
|
||||
return daysTile(this.st.series, '');
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,7 @@ import { copyText } from '../ui/files';
|
||||
import { dropdown, type MenuItem } from '../ui/menu';
|
||||
import { attempt, notify } from '../ui/toast';
|
||||
import { attachTip } from '../ui/tooltip';
|
||||
import { accessBadge, stateBadge } from '../ui/badges';
|
||||
import { accessBadge } from '../ui/badges';
|
||||
import { addDevice, openDevice, type DeviceOpts } from '../device';
|
||||
import { copyPersonLink, inviteCard } from '../invite';
|
||||
import { personUrl } from '../urls';
|
||||
@@ -56,6 +56,14 @@ function slotBar(p: Person): HTMLElement {
|
||||
type Filter = 'all' | 'online' | 'attention' | 'paused';
|
||||
type SortBy = 'seen' | 'name' | 'usage';
|
||||
|
||||
/** Paused by someone or something about the person; not over a limit (Needs attention), and not their server being off (the admin's pause still counts then). */
|
||||
const paused = (p: Person): boolean => (p.state === 'server_off' ? p.paused : !['active', 'quota', 'expired'].includes(p.state));
|
||||
/** Can't connect for a reason of their own (not just their server being off). */
|
||||
const stopped = (p: Person): boolean => (p.state === 'server_off' ? p.paused : p.state !== 'active');
|
||||
/** Why they can't connect, their own reason (the admin's pause shows through a turned-off server), or null. */
|
||||
const stopReason = (p: Person): Exclude<Person['state'], 'active' | 'server_off'> | null =>
|
||||
!stopped(p) ? null : p.state === 'server_off' ? 'paused' : (p.state as Exclude<Person['state'], 'active' | 'server_off'>);
|
||||
|
||||
function needsAttention(p: Person, today: string): boolean {
|
||||
const left = daysLeft(p.expires, today);
|
||||
return (
|
||||
@@ -269,7 +277,7 @@ export class PeoplePage {
|
||||
all: people.length,
|
||||
online: people.filter((p) => p.online > 0).length,
|
||||
attention: people.filter(attn).length,
|
||||
paused: people.filter((p) => p.state !== 'active' && p.state !== 'quota' && p.state !== 'expired').length,
|
||||
paused: people.filter((p) => paused(p)).length,
|
||||
};
|
||||
const tabs = this.el?.querySelector<HTMLElement>('.dl-people-tabs');
|
||||
if (tabs && !(quiet && focusInside(tabs))) {
|
||||
@@ -296,23 +304,27 @@ export class PeoplePage {
|
||||
const match = (p: Person) => {
|
||||
if (this.filter === 'online' && !p.online) return false;
|
||||
if (this.filter === 'attention' && !attn(p)) return false;
|
||||
if (this.filter === 'paused' && !(p.state !== 'active' && p.state !== 'quota' && p.state !== 'expired')) return false;
|
||||
if (this.filter === 'paused' && !paused(p)) return false;
|
||||
return true;
|
||||
};
|
||||
const order = [...people].sort((a, b) =>
|
||||
this.sort === 'name'
|
||||
? a.name.localeCompare(b.name)
|
||||
: this.sort === 'usage'
|
||||
? b.month[0] + b.month[1] - (a.month[0] + a.month[1])
|
||||
: b.online - a.online || b.last_seen - a.last_seen,
|
||||
// Whatever the sort: people who can connect, then those held by a limit or an end
|
||||
// date (often something to fix), then the ones the admin paused, last.
|
||||
const rank = (p: Person) => (stopReason(p) === 'paused' ? 2 : stopped(p) ? 1 : 0);
|
||||
const order = [...people].sort(
|
||||
(a, b) =>
|
||||
rank(a) - rank(b) ||
|
||||
(this.sort === 'name'
|
||||
? a.name.localeCompare(b.name)
|
||||
: this.sort === 'usage'
|
||||
? b.month[0] + b.month[1] - (a.month[0] + a.month[1])
|
||||
: b.online - a.online || b.last_seen - a.last_seen),
|
||||
);
|
||||
let shown = 0;
|
||||
for (const p of order) {
|
||||
const card = this.card(p.id);
|
||||
if (!card) continue;
|
||||
this.list.appendChild(card);
|
||||
card.classList.toggle('dl-off', p.state !== 'active');
|
||||
card.classList.toggle('dl-attn-row', p.state === 'quota' || p.state === 'expired');
|
||||
card.classList.toggle('dl-off', stopped(p));
|
||||
const hit = match(p);
|
||||
card.classList.toggle('dl-filtered', !hit);
|
||||
if (hit) shown++;
|
||||
@@ -343,7 +355,8 @@ export class PeoplePage {
|
||||
|
||||
// Term and hours sit by the name; online/last seen lives in the strip below.
|
||||
const pills: Node[] = [];
|
||||
if (p.expires) {
|
||||
const why = stopReason(p);
|
||||
if (p.expires && why !== 'expired') {
|
||||
const soon = left != null && left >= 0 && left <= Math.max(p.expire_warn, 3);
|
||||
const over = left != null && left < 0;
|
||||
pills.push(
|
||||
@@ -353,7 +366,8 @@ export class PeoplePage {
|
||||
]),
|
||||
);
|
||||
}
|
||||
if (p.hours) pills.push(E('span', { class: 'dl-pill-ic', title: 'Allowed hours' }, [icon('clock'), p.hours.replace('-', '–')]));
|
||||
if (p.hours && why !== 'hours')
|
||||
pills.push(E('span', { class: 'dl-pill-ic', title: 'Allowed hours' }, [icon('clock'), p.hours.replace('-', '–')]));
|
||||
|
||||
const chips = byDeviceState(p.devices).map((d) => {
|
||||
return E(
|
||||
@@ -394,20 +408,9 @@ export class PeoplePage {
|
||||
),
|
||||
);
|
||||
|
||||
// Ending soon (the strip below handles an end that has passed).
|
||||
const fixes: Node[] = [];
|
||||
if (p.state === 'quota' && p.quota_period === 'month')
|
||||
fixes.push(
|
||||
E(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
class: 'dl-fix',
|
||||
click: () => this.quick(p, { bonus_gb: String((p.bonus_gb || 0) + 10) }, '+10 GB this month'),
|
||||
},
|
||||
'+10 GB this month',
|
||||
),
|
||||
);
|
||||
if (p.expires && left != null && left <= Math.max(p.expire_warn, 3))
|
||||
if (p.expires && left != null && left <= Math.max(p.expire_warn, 3) && why !== 'expired')
|
||||
fixes.push(
|
||||
E(
|
||||
'button',
|
||||
@@ -466,7 +469,6 @@ export class PeoplePage {
|
||||
E('div', { class: 'dl-pcard-who' }, [
|
||||
E('div', { class: 'dl-card-head' }, [
|
||||
E('a', { class: 'dl-card-name', href: personUrl(p.id) }, p.name),
|
||||
stateBadge(p),
|
||||
accessBadge(p),
|
||||
...pills,
|
||||
]),
|
||||
@@ -477,11 +479,48 @@ export class PeoplePage {
|
||||
fixes.length ? E('div', { class: 'dl-fixes' }, fixes) : '',
|
||||
]),
|
||||
this.usageSide(p, actions),
|
||||
why ? this.stopStrip(p, why) : '',
|
||||
]),
|
||||
);
|
||||
return node;
|
||||
}
|
||||
|
||||
/** Across the bottom of a stopped person's card: why, since when or until when, and the one action that lifts it. */
|
||||
stopStrip(p: Person, why: NonNullable<ReturnType<typeof stopReason>>): HTMLElement {
|
||||
const today = this.today;
|
||||
// The month's data resets on the 1st (router time).
|
||||
const reset = addMonthsClamped(`${today.slice(0, 8)}01`, 1);
|
||||
const extra = () => this.quick(p, { bonus_gb: String((p.bonus_gb || 0) + 10) }, '+10 GB this month');
|
||||
const what: Record<typeof why, [string, 'warn' | 'bad', string, string, [string, string, () => unknown] | null]> = {
|
||||
paused: ['pause', 'warn', 'Paused', 'Devices can’t connect until you resume', ['play', 'Resume', () => this.togglePause(p)]],
|
||||
quota:
|
||||
p.quota_period === 'month'
|
||||
? ['chart', 'bad', 'Data limit reached', `Paused until it resets on ${date(reset)}`, ['plus', '+10 GB this month', extra]]
|
||||
: [
|
||||
'chart',
|
||||
'bad',
|
||||
'Data limit reached',
|
||||
'Paused until the limit is raised',
|
||||
['edit', 'Change limit', () => (location.href = personUrl(p.id))],
|
||||
],
|
||||
expired: [
|
||||
'calendar',
|
||||
'bad',
|
||||
`Access ended ${date(p.expires)}`,
|
||||
'Devices can’t connect',
|
||||
['calendar', 'Extend 1 month', () => this.quick(p, { expires: addMonth(p.expires, today) }, 'Extended by 1 month')],
|
||||
],
|
||||
hours: ['clock', 'warn', 'Outside allowed hours', `Access ${p.hours.replace('-', '–')} (router time)`, null],
|
||||
no_server: ['alert', 'warn', 'No server', 'Choose a server on their page', null],
|
||||
};
|
||||
const [ic, tone, title, sub, act] = what[why];
|
||||
return E('div', { class: `dl-pstrip ${tone}` }, [
|
||||
E('span', { class: `dl-need-ic ${tone}` }, icon(ic)),
|
||||
E('span', { class: 'dl-pstrip-text' }, [E('b', {}, title), E('span', { class: 'dl-faint' }, sub)]),
|
||||
act ? button([icon(act[0]), ` ${act[1]}`], act[2]) : '',
|
||||
]);
|
||||
}
|
||||
|
||||
/** Status and actions, this month's usage, a bar split by device (or filled toward the limit), today or live speed. */
|
||||
usageSide(p: Person, actions: HTMLElement): HTMLElement {
|
||||
const used = p.quota_used || p.month[0] + p.month[1];
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
// Person page: the name block with its actions, and the traffic tiles.
|
||||
|
||||
import { E } from '../../e';
|
||||
import { iconButton } from '../../ui/button';
|
||||
import { button, iconButton } from '../../ui/button';
|
||||
import { dropdown, type MenuItem } from '../../ui/menu';
|
||||
import { stateBadge } from '../../ui/badges';
|
||||
import { statePill } from '../../ui/badges';
|
||||
import { icon } from '../../../shared/icons';
|
||||
import { ago, bytes, date, initials, isoDay } from '../../../shared/format';
|
||||
import { copyPersonLink } from '../../invite';
|
||||
@@ -29,12 +29,8 @@ export function headPart(page: PersonPage): HTMLElement {
|
||||
]
|
||||
: []),
|
||||
null,
|
||||
{
|
||||
label: p.paused ? 'Resume' : 'Pause',
|
||||
icon: icon(p.paused ? 'play' : 'pause'),
|
||||
warn: !p.paused,
|
||||
run: () => page.patch({ paused: !p.paused }, p.paused ? 'Resumed' : 'Paused'),
|
||||
},
|
||||
// While paused, Resume is the page's own button (as the server's Turn on).
|
||||
...(p.paused ? [] : [{ label: 'Pause', icon: icon('pause'), warn: true, run: () => page.patch({ paused: true }, 'Paused') }]),
|
||||
{ label: 'Delete', icon: icon('trash'), danger: true, run: () => remove(page) },
|
||||
];
|
||||
return E('div', { class: 'dl-person-head' }, [
|
||||
@@ -42,11 +38,13 @@ export function headPart(page: PersonPage): HTMLElement {
|
||||
E('div', { class: 'dl-person-id' }, [
|
||||
E('span', { class: `dl-avatar lg${p.online ? ' online' : ''}` }, initials(p.name)),
|
||||
E('div', { class: 'dl-stack' }, [
|
||||
E('div', { class: 'dl-title-row' }, [E('h2', { class: 'dl-h1' }, p.name), stateBadge(p)]),
|
||||
E('div', { class: 'dl-title-row' }, [E('h2', { class: 'dl-h1' }, p.name), statePill(p)]),
|
||||
E('span', { class: 'dl-faint', title: added }, `${p.devices.length} of ${p.device_limit} devices · ${lastSeen}`),
|
||||
]),
|
||||
]),
|
||||
E('div', { class: 'dl-pcard-actions' }, [
|
||||
// White, as the server's Turn on.
|
||||
p.paused ? button([icon('play'), ' Resume'], () => page.patch({ paused: false }, 'Resumed'), 'add') : '',
|
||||
portal ? iconButton('link', 'Copy link', () => copyPersonLink(p.id), 'neutral', 'dl-icon-only') : '',
|
||||
iconButton('more', 'More', (ev: MouseEvent) => dropdown(ev.currentTarget as HTMLElement, menu), 'neutral', 'dl-icon-only'),
|
||||
]),
|
||||
|
||||
@@ -12,7 +12,8 @@ import { cancelButton, closeModal, confirmDialog, modal } from '../ui/modal';
|
||||
import { copyText } from '../ui/files';
|
||||
import { attempt, errorText, notify } from '../ui/toast';
|
||||
import { input, seg, sw } from '../ui/controls';
|
||||
import { card, group, needRow, row } from '../ui/layout';
|
||||
import { card, group, liveRow, needRow, row } from '../ui/layout';
|
||||
import { portalPortHelp, portHelp, rangeHelp, rangeOf, subnetOf } from '../netcheck';
|
||||
import { icon } from '../../shared/icons';
|
||||
import { duration } from '../../shared/format';
|
||||
import { accessCards } from '../interfaces';
|
||||
@@ -158,7 +159,7 @@ export class ServerPage {
|
||||
this.paint();
|
||||
},
|
||||
},
|
||||
[E('i', { class: `dot ${x.up ? 'ok' : 'bad'}` }), E('b', {}, x.name)],
|
||||
[E('i', { class: `dot ${!x.enabled ? 'warn' : x.up ? 'ok' : 'bad'}` }), E('b', {}, x.name)],
|
||||
),
|
||||
),
|
||||
E('button', { type: 'button', class: 'dl-srvtab add', click: () => this.addServer() }, [icon('plus'), 'Add server']),
|
||||
@@ -264,22 +265,16 @@ export class ServerPage {
|
||||
|
||||
/** Name and state, the address bar, and the page actions. */
|
||||
head(srv: Server): HTMLElement {
|
||||
const st = this.st;
|
||||
const part = (ic: string, body: (Node | string)[]) => E('span', { class: 'dl-addrbar-seg' }, [icon(ic), ...body]);
|
||||
const addr = srv.endpoint || '—';
|
||||
// "Turn on" while the server is off (turning off lives in Connection; the same
|
||||
// button also lifts an old router-wide pause).
|
||||
const off = !srv.enabled || st.settings.paused_all;
|
||||
// "Turn on" while the server is off (turning off lives in Connection).
|
||||
const actions = E('div', { class: 'dl-actions' }, [
|
||||
off
|
||||
!srv.enabled
|
||||
? button(
|
||||
[icon('play'), ' Turn on'],
|
||||
async () => {
|
||||
if (st.settings.paused_all && !(await attempt(() => api.pauseAll(false)))) return;
|
||||
if (!srv.enabled) await this.save(srv, { enabled: '1' }, 'Server turned on');
|
||||
else await this.refresh();
|
||||
},
|
||||
'positive',
|
||||
() => this.save(srv, { enabled: '1' }, 'Server turned on'),
|
||||
// White, as the other main actions (Add person).
|
||||
'add',
|
||||
)
|
||||
: '',
|
||||
]);
|
||||
@@ -289,10 +284,10 @@ export class ServerPage {
|
||||
E('h2', { class: 'dl-h1' }, srv.name),
|
||||
E(
|
||||
'span',
|
||||
{ class: `dl-pill ${!srv.enabled ? 'off' : srv.up ? 'ok' : 'bad'}` },
|
||||
// Off on purpose is a warning (yellow), not a failure (red).
|
||||
{ class: `dl-pill ${!srv.enabled ? 'warn' : srv.up ? 'ok' : 'bad'}` },
|
||||
!srv.enabled ? 'Turned off' : srv.up ? 'Running' : srv.blocked ? 'Can’t start' : 'Not running',
|
||||
),
|
||||
st.settings.paused_all && srv.enabled ? E('span', { class: 'dl-pill warn' }, 'Off') : '',
|
||||
E('span', { class: 'dl-spacer' }),
|
||||
actions,
|
||||
]),
|
||||
@@ -478,7 +473,8 @@ export class ServerPage {
|
||||
name: d.name,
|
||||
endpoint: d.endpoint,
|
||||
port: d.port,
|
||||
subnet: d.subnet,
|
||||
// The tunnel's first three numbers ("10.77.0"): it is that /24.
|
||||
range: rangeOf(d.subnet),
|
||||
preset: 'standard' as Method,
|
||||
// Off by default: the portal opens a port on WAN, so it is a choice.
|
||||
portal: false,
|
||||
@@ -488,11 +484,20 @@ export class ServerPage {
|
||||
wan_zone: d.wan_zone,
|
||||
};
|
||||
let step = 0;
|
||||
// The portal takes the server's port number (TCP beside UDP) until it is changed by hand.
|
||||
let portalSame = !extra && state.portal_port === state.port;
|
||||
const ipLinks = () => /^\d{1,3}(\.\d{1,3}){3}$/.test(state.endpoint);
|
||||
const portHelpNow = () => portHelp(state.port, d.udp_taken ?? [], 'Opened on the WAN firewall automatically.');
|
||||
const rangeHelpNow = () => rangeHelp(state.range, d.networks ?? [], rangeOf(d.subnet));
|
||||
const portalHelpNow = () => portalPortHelp(state.portal_port, d.tcp_taken ?? [], ipLinks());
|
||||
const root = E('div', { class: 'dl-wizard' });
|
||||
const field = (key: 'id' | 'name' | 'endpoint' | 'port' | 'subnet' | 'portal_port', attrs: Record<string, unknown> = {}) => {
|
||||
const field = (key: 'id' | 'name' | 'endpoint' | 'port' | 'range' | 'portal_port', attrs: Record<string, unknown> = {}) => {
|
||||
const el = input(String(state[key]), attrs);
|
||||
el.addEventListener('input', () => {
|
||||
(state as any)[key] = key === 'port' || key === 'portal_port' ? Number(el.value) : el.value.trim();
|
||||
if (key === 'port' || key === 'portal_port') (state as any)[key] = el.value.trim() === '' ? 0 : Number(el.value);
|
||||
else (state as any)[key] = el.value.trim();
|
||||
if (key === 'port' && portalSame) state.portal_port = state.port;
|
||||
if (key === 'portal_port') portalSame = state.portal_port === state.port;
|
||||
});
|
||||
return el;
|
||||
};
|
||||
@@ -525,31 +530,39 @@ export class ServerPage {
|
||||
render: () =>
|
||||
E('div', { class: 'dl-wizard-groups' }, [
|
||||
group('globe', 'Listening', 'Where devices reach AmneziaWG from the internet', [
|
||||
row(
|
||||
'UDP port',
|
||||
field('port', { inputmode: 'numeric', class: 'cbi-input-text dl-w-port dl-mono' }),
|
||||
'Opened on the WAN firewall automatically. A random high port is fine.',
|
||||
),
|
||||
liveRow('UDP port', field('port', { inputmode: 'numeric', class: 'cbi-input-text dl-w-port dl-mono' }), portHelpNow),
|
||||
]),
|
||||
group('network', 'Tunnel network', 'Addresses devices get inside the tunnel', [
|
||||
row(
|
||||
'Tunnel subnet',
|
||||
field('subnet', { class: 'cbi-input-text dl-mono' }),
|
||||
`Must not overlap your networks (${d.taken.join(', ') || 'none found'}).`,
|
||||
),
|
||||
(() => {
|
||||
const el = field('range', {
|
||||
class: 'cbi-input-text dl-w-range dl-mono',
|
||||
'aria-label': 'First three numbers of the device addresses',
|
||||
});
|
||||
return liveRow(
|
||||
'Device addresses',
|
||||
el,
|
||||
rangeHelpNow,
|
||||
E('span', { class: 'dl-suffixed' }, [el, E('span', { class: 'dl-mono' }, '.x')]),
|
||||
);
|
||||
})(),
|
||||
]),
|
||||
group('shield', 'Disguise', 'So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard', [
|
||||
methodPicker(d.awg, state.preset, (m) => (state.preset = m), undefined, d.awg_state?.tools !== false),
|
||||
]),
|
||||
]),
|
||||
check: () => (!state.port || !state.subnet ? 'Fill in the UDP port and subnet.' : null),
|
||||
check: () => {
|
||||
const p = portHelpNow();
|
||||
if (p.bad) return `UDP port: ${p.text}`;
|
||||
const r = rangeHelpNow();
|
||||
return r.bad ? `Device addresses: ${r.text}` : null;
|
||||
},
|
||||
};
|
||||
const portalPage: Page = {
|
||||
id: 'portal',
|
||||
title: 'Portal',
|
||||
render: () => {
|
||||
const portalPort = field('portal_port', { inputmode: 'numeric', class: 'cbi-input-text dl-w-port dl-mono' });
|
||||
const portRow = row('Listening port', portalPort, 'TCP port on WAN for the portal; the whole port belongs to it.');
|
||||
const portRow = liveRow('Listening port', portalPort, portalHelpNow);
|
||||
portRow.hidden = !state.portal;
|
||||
// Off | On, Off first: the same segmented control as in Settings.
|
||||
const onOff = seg(
|
||||
@@ -580,6 +593,11 @@ export class ServerPage {
|
||||
]),
|
||||
]);
|
||||
},
|
||||
check: () => {
|
||||
if (!state.portal) return null;
|
||||
const h = portalHelpNow();
|
||||
return h.bad ? `Portal port: ${h.text}` : null;
|
||||
},
|
||||
};
|
||||
const pages = (): Page[] => [serverPage, awgPage, extra ? null : portalPage].filter((x): x is Page => x != null);
|
||||
const aw = d.awg_state;
|
||||
@@ -666,7 +684,7 @@ export class ServerPage {
|
||||
state.name,
|
||||
d.ifname,
|
||||
state.port,
|
||||
state.subnet,
|
||||
subnetOf(state.range),
|
||||
state.endpoint,
|
||||
d.mtu,
|
||||
state.preset,
|
||||
@@ -678,10 +696,15 @@ export class ServerPage {
|
||||
),
|
||||
'Server created',
|
||||
);
|
||||
if (r)
|
||||
setTimeout(() => {
|
||||
if (!r) return;
|
||||
// A network restart drops the connection to LuCI for a few seconds.
|
||||
if (r.network_restart) notify('Restarting the network so it knows AmneziaWG: back in a few seconds');
|
||||
setTimeout(
|
||||
() => {
|
||||
location.href = url(r.id);
|
||||
}, 1500);
|
||||
},
|
||||
r.network_restart ? 10000 : 1500,
|
||||
);
|
||||
},
|
||||
'positive',
|
||||
{ disabled: missing.length > 0, title: missing.length ? 'Install AmneziaWG first' : null },
|
||||
|
||||
@@ -6,7 +6,8 @@ import { E } from '../../e';
|
||||
import { button } from '../../ui/button';
|
||||
import { cancelButton, closeModal, modal } from '../../ui/modal';
|
||||
import { input, isOn, sw } from '../../ui/controls';
|
||||
import { group, needRow, row } from '../../ui/layout';
|
||||
import { group, liveRow, needRow, row } from '../../ui/layout';
|
||||
import { portalPortHelp } from '../../netcheck';
|
||||
import { icon } from '../../../shared/icons';
|
||||
import { fmtDay } from '../../../shared/format';
|
||||
import { installMissing } from '../../pkgs';
|
||||
@@ -147,7 +148,10 @@ export function portalCard(host: SettingsHost): HTMLElement {
|
||||
|
||||
// One row per link, as people will see it (example code).
|
||||
const links = E('div', { class: 'dl-links' });
|
||||
// The port's help depends on the links too (IP addresses use the next port); set below.
|
||||
let refreshPort = () => {};
|
||||
const paintLinks = () => {
|
||||
refreshPort();
|
||||
const lport = Number(port.value) || eff.portal_port;
|
||||
dom.content(
|
||||
links,
|
||||
@@ -263,13 +267,11 @@ export function portalCard(host: SettingsHost): HTMLElement {
|
||||
};
|
||||
|
||||
const until = c && !c.self_signed && c.expires ? fmtDay(c.expires) : '';
|
||||
const listenRow = row(
|
||||
'Listening port',
|
||||
port,
|
||||
host.d.port_owners.length
|
||||
? `Port ${eff.portal_port} is used by ${host.d.port_owners.join(', ')}.`
|
||||
: `Where the portal runs on the router: HTTPS here, plain HTTP for IP addresses on ${eff.portal_port + 1}.`,
|
||||
// Who holds the port (our own portal doesn't count), and the next one while links use an IP address.
|
||||
const listenRow = liveRow('Listening port', port, () =>
|
||||
portalPortHelp(port.value.trim() === '' ? eff.portal_port : Number(port.value), host.d.tcp_taken ?? [], picked.some(isIp)),
|
||||
);
|
||||
refreshPort = listenRow.refresh;
|
||||
const custom = !!(s.portal_cert && s.portal_key);
|
||||
const kind = !c ? 'Portal is off' : custom ? 'Your files' : c.self_signed ? 'Self-signed' : 'Let’s Encrypt';
|
||||
const certFiles = () => {
|
||||
|
||||
@@ -29,6 +29,10 @@
|
||||
--dl-radius: 16px;
|
||||
}
|
||||
|
||||
/* Text is read, not edited: the arrow over it, the I-beam only where you type. */
|
||||
.dl-root, .dl-modal { cursor: default; }
|
||||
:is(.dl-root, .dl-modal) :is(input:not([type=checkbox], [type=radio], [type=range], [type=button], [type=submit]), textarea, [contenteditable=true]) { cursor: text; }
|
||||
|
||||
.dl-icon-wrap { display: inline-flex; align-items: center; justify-content: center; line-height: 0; }
|
||||
.dl-icon { width: 16px; height: 16px; }
|
||||
.dl-icon-btn { display: inline-flex !important; align-items: center; gap: 6px; }
|
||||
|
||||
@@ -72,7 +72,7 @@
|
||||
font-size: 13px; color: var(--dl-fg-muted); text-decoration: none !important; white-space: nowrap; }
|
||||
.dl-srvtab b { font-weight: 500; }
|
||||
.dl-srvtab i.dot { width: 7px; height: 7px; border-radius: 50%; background: var(--dl-fg-faint); flex: 0 0 auto; }
|
||||
.dl-srvtab i.dot.ok { background: var(--dl-ok); animation: dl-srv-pulse 2s ease-out infinite; } .dl-srvtab i.dot.bad { background: var(--dl-bad); }
|
||||
.dl-srvtab i.dot.ok { background: var(--dl-ok); animation: dl-srv-pulse 2s ease-out infinite; } .dl-srvtab i.dot.bad { background: var(--dl-bad); } .dl-srvtab i.dot.warn { background: var(--dl-warn); }
|
||||
/* The one status dot left: a server that is running pulses. */
|
||||
@keyframes dl-srv-pulse { 0% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--dl-ok) 55%, transparent); } 70%, 100% { box-shadow: 0 0 0 6px transparent; } }
|
||||
@media (prefers-reduced-motion: reduce) { .dl-srvtab i.dot.ok { animation: none; } }
|
||||
|
||||
+110
-24
@@ -1,37 +1,124 @@
|
||||
/* Connection map and charts. */
|
||||
/* map */
|
||||
.dl-geomap { position: relative; border-top: 1px solid var(--dl-line); background: var(--dl-soft); }
|
||||
/* As mapcn: no backdrop of its own, the globe sits on the card. */
|
||||
.dl-geomap { position: relative; border-top: 1px solid var(--dl-line); background: transparent; }
|
||||
.dl-map-status { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; color: var(--dl-fg-muted); font-size: 13px; z-index: 1; pointer-events: none; }
|
||||
.dl-map-wrap { position: relative; }
|
||||
.dl-map-legend { position: absolute; left: 12px; bottom: 12px; display: flex; gap: 12px; align-items: center; padding: 6px 12px; border-radius: 999px; font-size: 12px;
|
||||
background: color-mix(in srgb, var(--dl-card) 88%, transparent); border: 1px solid var(--dl-line); backdrop-filter: blur(6px); z-index: 2; }
|
||||
.dl-map-legend span { display: inline-flex; align-items: center; gap: 6px; color: var(--dl-fg-muted); }
|
||||
.dl-map-legend i.dot { width: 8px; height: 8px; border-radius: 50%; background: var(--dl-fg-faint); }
|
||||
.dl-map-legend i.dot.ok { background: var(--dl-ok); }
|
||||
.dl-map-legend i.line { width: 14px; height: 2px; border-radius: 2px; background: var(--dl-ok); }
|
||||
.dl-map-legend i.line { width: 14px; height: 0; border-top: 2px dashed #8a8a8a; }
|
||||
.dl-map-legend i.line.live { border-top-color: #3b82f6; }
|
||||
.dl-map-off { padding: 32px 16px; text-align: center; color: var(--dl-fg-muted); border-top: 1px solid var(--dl-line); }
|
||||
.dl-mk { all: unset; cursor: pointer; width: 18px; height: 18px; display: inline-flex; align-items: center; justify-content: center; position: relative; }
|
||||
.dl-mk-dot { width: 12px; height: 12px; border-radius: 50%; background: #8f8f8f; box-shadow: 0 0 0 3px rgba(0,0,0,.55); }
|
||||
.dl-mk.online .dl-mk-dot { width: 14px; height: 14px; background: #40c977; }
|
||||
.dl-mk.online::before { content: ''; position: absolute; inset: -9px; border-radius: 50%; background: rgba(64, 201, 119, .28); animation: dl-pulse 2s ease-out infinite; }
|
||||
@keyframes dl-pulse { 0% { transform: scale(.5); opacity: 1; } 100% { transform: scale(1.4); opacity: 0; } }
|
||||
@media (prefers-reduced-motion: reduce) { .dl-mk.online::before { animation: none; } }
|
||||
.dl-mk-home { width: 22px; height: 22px; border-radius: 7px; background: #ededed; display: flex; align-items: center; justify-content: center;
|
||||
box-shadow: 0 0 0 4px rgba(237, 237, 237, .18), 0 2px 6px rgba(0,0,0,.5); color: #131313; }
|
||||
.dl-mk-home-ic { width: 13px; height: 13px; }
|
||||
.dl-popup { z-index: 4; }
|
||||
.dl-popup .maplibregl-popup-content { background: var(--dl-elevated); color: var(--dl-fg); border: 1px solid var(--dl-line); border-radius: 12px; padding: 12px;
|
||||
box-shadow: var(--shadow-xl, 0 8px 16px -4px rgba(0,0,0,.4)); font: inherit; }
|
||||
.dl-popup .maplibregl-popup-tip { border-top-color: var(--dl-elevated) !important; border-bottom-color: var(--dl-elevated) !important; }
|
||||
.dl-mk { all: unset; cursor: pointer; position: relative; display: flex; align-items: center; justify-content: center; transition: opacity .2s; }
|
||||
.dl-mk-hub { position: relative; display: flex; align-items: center; justify-content: center; }
|
||||
/* The server: an inverse tile (white on dark, black on light) on a frosted plate. */
|
||||
.dl-mk-host { box-sizing: border-box; width: 40px; height: 40px; border-radius: 11px; display: flex; align-items: center; justify-content: center;
|
||||
background: color-mix(in srgb, var(--dl-elevated) 60%, transparent); border: 1px solid var(--dl-line); backdrop-filter: blur(6px);
|
||||
box-shadow: 0 6px 16px rgba(0,0,0,.35); }
|
||||
.dl-mk-host-tile { width: 26px; height: 26px; border-radius: 7px; display: flex; align-items: center; justify-content: center;
|
||||
background: var(--dl-fg); color: var(--background, var(--dl-elevated)); }
|
||||
.dl-mk-host-ic { width: 14px; height: 14px; }
|
||||
/* People: initials (who) with a device badge (what), blue while live, gray when seen recently. */
|
||||
.dl-mk-av { position: relative; box-sizing: border-box; width: 28px; height: 28px; border-radius: 50%; display: flex; align-items: center; justify-content: center;
|
||||
font-size: 10px; font-weight: 500; line-height: 1; border: 2px solid #8a8a8a; background: var(--dl-elevated); color: var(--dl-fg-muted); transition: box-shadow .2s; }
|
||||
.dl-mk.online .dl-mk-av { border-color: #3b82f6; background: color-mix(in srgb, #3b82f6 22%, var(--dl-elevated)); color: var(--dl-fg); }
|
||||
.dl-mk-badge { position: absolute; left: 16px; bottom: -6px; height: 16px; min-width: 16px; padding: 0 3px; border-radius: 8px;
|
||||
border: 2px solid var(--dl-elevated); background: #6b6b6b; color: #fff; display: flex; align-items: center; justify-content: center; gap: 1px;
|
||||
font-size: 9px; font-weight: 600; white-space: nowrap; box-sizing: content-box; }
|
||||
.dl-mk.online .dl-mk-badge { background: #3b82f6; }
|
||||
.dl-mk-badge-ic { width: 10px; height: 10px; stroke-width: 2.2; }
|
||||
/* A person's places (their page): rounded tiles without outlines, the live one blue. */
|
||||
.dl-mk-tile { position: relative; width: 26px; height: 26px; border-radius: 7px; display: flex; align-items: center; justify-content: center;
|
||||
background: color-mix(in srgb, var(--dl-fg) 18%, var(--dl-elevated)); color: var(--dl-fg); }
|
||||
.dl-mk.place.online .dl-mk-tile { background: #3b82f6; color: #fff; box-shadow: 0 2px 8px rgba(59, 130, 246, .35); }
|
||||
.dl-mk-tile-ic { width: 14px; height: 14px; }
|
||||
.dl-mk-tile-n { position: absolute; right: -5px; top: -5px; min-width: 14px; height: 14px; padding: 0 3px; box-sizing: border-box; border-radius: 7px;
|
||||
background: var(--dl-fg); color: var(--dl-elevated); font-size: 9px; font-weight: 600; line-height: 14px; text-align: center; }
|
||||
.dl-mk-when { display: block; text-align: center; color: var(--dl-fg-faint); font-weight: 400; }
|
||||
.dl-mk.place.online .dl-mk-when { color: #3b82f6; }
|
||||
.dl-mk-tile.sm { width: 18px; height: 18px; border-radius: 5px; font-size: 9px; font-weight: 600; }
|
||||
/* A device's places under its map: the same numbers as the tiles, the live one blue. */
|
||||
.dl-dmap { border: 1px solid var(--dl-line); border-radius: 12px; overflow: hidden; }
|
||||
.dl-dmap .dl-geomap { border-top: 0; }
|
||||
.dl-dplaces { display: flex; flex-direction: column; margin-top: 4px; }
|
||||
.dl-dplace-row { display: flex; align-items: center; gap: 10px; padding: 9px 2px; border-top: 1px solid var(--dl-line); font-size: 13px; }
|
||||
.dl-dplace-row:first-child { border-top: 0; }
|
||||
.dl-dplace-n { flex: 0 0 auto; width: 20px; height: 20px; border-radius: 5px; display: flex; align-items: center; justify-content: center; font-size: 10px; font-weight: 600;
|
||||
background: color-mix(in srgb, var(--dl-fg) 18%, var(--dl-elevated)); color: var(--dl-fg); }
|
||||
.dl-dplace-n.live { background: #3b82f6; color: #fff; }
|
||||
.dl-dplace-n .dl-icon { width: 12px; height: 12px; }
|
||||
.dl-dplace-now { color: #3b82f6; }
|
||||
/* Someone on top of the server: folded into a count on its plate until there is room. */
|
||||
/* MapLibre writes the marker's own opacity (fading what is behind the globe): ours goes on its parts. */
|
||||
.dl-mk > * { transition: opacity .15s; opacity: var(--dl-mk-fade, 1); }
|
||||
.dl-mk.merged { pointer-events: none; }
|
||||
.dl-mk.dl-mk-new > * { transition: none; }
|
||||
.dl-mk.merged > * { opacity: 0; }
|
||||
.dl-mk-hub { cursor: default; }
|
||||
.dl-mk-host { position: relative; }
|
||||
.dl-mk-host-n { position: absolute; right: -7px; top: -7px; min-width: 18px; height: 18px; padding: 0 5px; box-sizing: border-box; border-radius: 9px;
|
||||
border: 2px solid var(--dl-elevated); background: #3b82f6; color: #fff; font-size: 10px; font-weight: 600; line-height: 14px; text-align: center;
|
||||
opacity: 0; transform: scale(.5); transition: opacity .15s, transform .15s; pointer-events: none; }
|
||||
.dl-mk-host-n.on { opacity: 1; transform: none; }
|
||||
.dl-mk-hub:has(.dl-mk-host-n.on) { cursor: zoom-in; }
|
||||
/* A marker moved clear of a crowd: a line back to its real spot, and a dot there. */
|
||||
.dl-mk-ptr { position: absolute; left: 50%; top: 50%; width: 0; height: 0; z-index: -1; pointer-events: none; }
|
||||
.dl-mk-ptr .line { position: absolute; left: 0; top: -0.5px; height: 1px; background: var(--dl-fg-faint); transform-origin: 0 50%; }
|
||||
.dl-mk-ptr .spot { position: absolute; left: -3.5px; top: -3.5px; width: 7px; height: 7px; border-radius: 50%; box-sizing: border-box; border: 1.5px solid #fff; background: #8a8a8a; }
|
||||
.dl-mk.online .dl-mk-ptr .spot, .dl-mk.place.online .dl-mk-ptr .spot { background: #3b82f6; }
|
||||
/* Hovering a person: their places stay, everyone else fades. */
|
||||
.dl-mk.dim > * { opacity: .18; }
|
||||
.dl-mk.hl .dl-mk-av { box-shadow: 0 0 0 4px rgba(59, 130, 246, .25); }
|
||||
/* MarkerLabel: absolute above the dot, text-[10px] font-medium text-foreground. */
|
||||
.dl-mk-label { position: absolute; left: 50%; bottom: 100%; margin-bottom: 4px; transform: translateX(-50%); white-space: nowrap; pointer-events: none;
|
||||
font-size: 10px; line-height: 14px; font-weight: 500; color: var(--dl-fg); }
|
||||
.dl-mk-label.below { bottom: auto; top: 100%; margin: 4px 0 0; }
|
||||
/* The hub's label: bg-background/80 rounded-sm px-1.5 py-0.5 text-[11px] font-semibold backdrop-blur. */
|
||||
.dl-mk-label.chip { padding: 2px 6px; border-radius: 4px; font-size: 11px; line-height: 16px; font-weight: 600;
|
||||
background: color-mix(in srgb, var(--background, var(--dl-card)) 80%, transparent); backdrop-filter: blur(8px); }
|
||||
/* The attribution as on mapcn's site: a quiet tile with a filled "i"; opened, the credits beside it. */
|
||||
.dl-geomap .maplibregl-ctrl-bottom-right .maplibregl-ctrl-attrib.maplibregl-compact { margin: 0 10px 10px 0; min-height: 28px; padding: 0; border-radius: 8px;
|
||||
background: var(--dl-elevated); border: 1px solid var(--dl-line); color: var(--dl-fg-muted); box-shadow: none; font-size: 11px; line-height: 26px; }
|
||||
.dl-geomap .maplibregl-ctrl-bottom-right .maplibregl-ctrl-attrib.maplibregl-compact:not(.maplibregl-compact-show) { width: 28px; height: 28px; box-sizing: border-box; }
|
||||
.dl-geomap .maplibregl-ctrl-bottom-right .maplibregl-ctrl-attrib.maplibregl-compact.maplibregl-compact-show { padding: 0 32px 0 10px; }
|
||||
.dl-geomap .maplibregl-ctrl-attrib a { color: var(--dl-fg-muted); }
|
||||
.dl-geomap .maplibregl-ctrl-attrib-button { top: 0; right: 0; width: 26px; height: 26px; margin: 0; border-radius: 8px; background: none; }
|
||||
.dl-geomap .maplibregl-ctrl-attrib-button::after { content: ''; position: absolute; inset: 5px; background: var(--dl-fg);
|
||||
-webkit-mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath fill-rule='evenodd' d='M12 2a10 10 0 1 1 0 20 10 10 0 0 1 0-20Zm-1.2 8.2h2.4V17h-2.4v-6.8ZM12 6a1.4 1.4 0 1 0 0 2.8A1.4 1.4 0 0 0 12 6Z'/%3E%3C/svg%3E") center / contain no-repeat;
|
||||
mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath fill-rule='evenodd' d='M12 2a10 10 0 1 1 0 20 10 10 0 0 1 0-20Zm-1.2 8.2h2.4V17h-2.4v-6.8ZM12 6a1.4 1.4 0 1 0 0 2.8A1.4 1.4 0 0 0 12 6Z'/%3E%3C/svg%3E") center / contain no-repeat; }
|
||||
.dl-geomap .maplibregl-ctrl-attrib-button:focus { outline: none; box-shadow: none; }
|
||||
.dl-geomap .maplibregl-ctrl-attrib-button:focus-visible { outline: 2px solid var(--dl-ring); }
|
||||
/* The hovered person's devices, in the map's corner. */
|
||||
.dl-map-card { position: absolute; right: 12px; top: 12px; z-index: 3; min-width: 200px; max-width: 260px; padding: 10px 12px; border-radius: 10px; font-size: 12px; line-height: 20px;
|
||||
background: var(--dl-elevated); color: var(--dl-fg); border: 1px solid var(--dl-line); box-shadow: var(--shadow-xl, 0 8px 16px -4px rgba(0,0,0,.4));
|
||||
opacity: 0; transition: opacity .2s; pointer-events: none; }
|
||||
.dl-map-card.on { opacity: 1; }
|
||||
.dl-map-card-head b { font-weight: 500; }
|
||||
.dl-map-card-row { display: flex; justify-content: space-between; gap: 12px; white-space: nowrap; }
|
||||
/* A marker's card: floats over the page (never clipped by the map), pinned above or below the marker. */
|
||||
.dl-popcard { position: fixed; z-index: 2100; width: max-content; max-width: 300px; padding: 12px; border-radius: 12px; box-sizing: border-box;
|
||||
background: var(--dl-elevated); color: var(--dl-fg); border: 1px solid var(--dl-line); box-shadow: var(--shadow-xl, 0 8px 16px -4px rgba(0,0,0,.4)); }
|
||||
.dl-popcard.away { visibility: hidden; }
|
||||
.dl-popcard.leaving { pointer-events: none; }
|
||||
.dl-popcard-tip { position: absolute; left: var(--tip-x, 50%); width: 10px; height: 10px; margin-left: -6px; box-sizing: border-box;
|
||||
background: var(--dl-elevated); border: solid var(--dl-line); transform: rotate(45deg); }
|
||||
.dl-popcard.above .dl-popcard-tip { bottom: -6px; border-width: 0 1px 1px 0; }
|
||||
.dl-popcard.below .dl-popcard-tip { top: -6px; border-width: 1px 0 0 1px; }
|
||||
.dl-popcard.above { transform-origin: var(--tip-x, 50%) 100%; }
|
||||
.dl-popcard.below { transform-origin: var(--tip-x, 50%) 0; }
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
.dl-popcard { animation: dl-pop-in .16s ease-out; }
|
||||
.dl-popcard.leaving { animation: dl-pop-out .14s ease-in forwards; }
|
||||
}
|
||||
@keyframes dl-pop-in { from { opacity: 0; transform: scale(.94); } to { opacity: 1; transform: none; } }
|
||||
@keyframes dl-pop-out { from { opacity: 1; transform: none; } to { opacity: 0; transform: scale(.94); } }
|
||||
.dl-pop { display: flex; flex-direction: column; gap: 4px; font-size: 12px; line-height: 18px; min-width: 210px; }
|
||||
.dl-pop-head { display: flex; align-items: center; gap: 8px; font-size: 13px; margin-bottom: 2px; }
|
||||
.dl-mk.multi { width: 26px; height: 26px; }
|
||||
.dl-mk-count { min-width: 22px; height: 22px; padding: 0 6px; border-radius: 999px; background: #8f8f8f; color: #0a0a0a; font: 600 11px/22px var(--dl-mono);
|
||||
text-align: center; box-shadow: 0 0 0 3px rgba(0,0,0,.55); box-sizing: border-box; }
|
||||
.dl-mk.online .dl-mk-count { background: #40c977; }
|
||||
.dl-pop-net { width: 30px; height: 30px; border-radius: 9px; background: var(--dl-soft); display: inline-flex; align-items: center; justify-content: center; flex: 0 0 auto; color: var(--dl-fg-muted); }
|
||||
.dl-pop-list { display: flex; flex-direction: column; margin: 6px -4px 0; }
|
||||
.dl-pop-row { all: unset; cursor: pointer; display: flex; align-items: center; gap: 8px; padding: 5px 4px; border-radius: 6px; }
|
||||
/* The row's highlight lines up with the head's icon above it. */
|
||||
.dl-pop-list { display: flex; flex-direction: column; margin: 6px 0 0; max-height: 116px; overflow-y: auto; }
|
||||
.dl-pop-row { all: unset; cursor: pointer; display: flex; align-items: center; gap: 8px; padding: 6px 8px; border-radius: 8px; }
|
||||
.dl-pop-row:hover { background: var(--dl-soft); }
|
||||
.dl-pop-row:focus { outline: none; }
|
||||
.dl-pop-row:focus-visible { outline: 2px solid var(--dl-ring); }
|
||||
@@ -41,7 +128,6 @@
|
||||
.dl-pop-dot.on { background: var(--dl-ok); box-shadow: 0 0 0 3px var(--dl-ok-wash); }
|
||||
.dl-pop-actions { display: flex; gap: 6px; margin-top: 8px; padding-top: 8px; border-top: 1px solid var(--dl-line); }
|
||||
.dl-pop-actions .cbi-button { flex: 1; height: 28px !important; font-size: 12px !important; justify-content: center; }
|
||||
.maplibregl-ctrl-attrib { font-size: 10px; }
|
||||
|
||||
/* charts */
|
||||
.dl-chartbox { position: relative; }
|
||||
|
||||
@@ -165,6 +165,7 @@
|
||||
.dl-speed-chart .line.up { stroke: var(--dl-ok); stroke-width: 1.2; opacity: .85; }
|
||||
.dl-speed-wait { height: 44px; display: flex; flex-direction: column; justify-content: flex-end; gap: 6px; font-size: 11px; color: var(--dl-fg-faint); }
|
||||
.dl-speed-wait i { display: block; height: 1px; background: var(--dl-line); order: 2; }
|
||||
.dl-speed-val.off { color: var(--dl-fg-faint); }
|
||||
.dl-fld { display: flex; flex-direction: column; gap: 8px; margin: 0 0 16px; }
|
||||
.dl-fld-label { font-size: 13px; font-weight: 500; color: var(--dl-fg); }
|
||||
.dl-fld .cbi-input-text { width: 100%; box-sizing: border-box; }
|
||||
|
||||
@@ -3,7 +3,19 @@
|
||||
.dl-plist > .dl-card { display: block; margin: 0 0 12px; padding: 16px; min-width: 0; background: var(--dl-card); border: 1px solid var(--dl-line);
|
||||
border-radius: var(--dl-radius); box-shadow: var(--dl-shadow); }
|
||||
.dl-plist > .dl-card.dl-filtered { display: none; }
|
||||
.dl-plist > .dl-card.dl-off .dl-card-name, .dl-plist > .dl-card.dl-off .dl-avatar { opacity: .6; }
|
||||
/* Stopped (paused, ended, over a limit): the card fades, its strip and actions stay bright. */
|
||||
.dl-plist > .dl-card.dl-off :is(.dl-card-name, .dl-avatar, .dl-access, .dl-slotbar, .dl-chips, .dl-pill-ic, .dl-use-num, .dl-pside-foot, .dl-pside-state) { opacity: .45; }
|
||||
.dl-plist > .dl-card.dl-off .dl-usebar i { background: var(--dl-fg-faint); }
|
||||
.dl-plist > .dl-card.dl-off .dl-chip-tag { background: var(--dl-soft); color: var(--dl-fg-muted); }
|
||||
/* Why, across the card's bottom edge, with the action that lifts it */
|
||||
.dl-pcard:has(> .dl-pstrip) { row-gap: 14px; }
|
||||
.dl-pstrip { grid-column: 1 / -1; display: flex; align-items: center; flex-wrap: wrap; gap: 8px 12px; margin: 0 -16px -16px; padding: 10px 16px;
|
||||
border-top: 1px solid var(--dl-line); border-radius: 0 0 var(--dl-radius) var(--dl-radius); font-size: 14px; line-height: 20px; }
|
||||
.dl-pstrip.warn { background: color-mix(in srgb, var(--dl-warn) 7%, transparent); }
|
||||
.dl-pstrip.bad { background: color-mix(in srgb, var(--dl-bad) 7%, transparent); }
|
||||
.dl-pstrip-text { flex: 1; min-width: 0; display: flex; flex-wrap: wrap; align-items: baseline; gap: 0 8px; }
|
||||
.dl-pstrip-text b { font-weight: 500; }
|
||||
.dl-pstrip > .cbi-button { flex: none; height: 32px !important; }
|
||||
.dl-plist-none { color: var(--dl-fg-muted); text-align: center; padding: 28px 16px; background: var(--dl-card); border: 1px solid var(--dl-line);
|
||||
border-radius: var(--dl-radius); }
|
||||
.dl-card-head { display: flex; align-items: center; flex-wrap: wrap; gap: 6px 8px; }
|
||||
|
||||
@@ -134,7 +134,6 @@
|
||||
.dl-fix { all: unset; cursor: pointer; height: 26px; padding: 0 10px; border-radius: 999px; background: var(--dl-info-wash); color: var(--dl-info); font-size: 12px; font-weight: 500;
|
||||
display: inline-flex; align-items: center; }
|
||||
.dl-fix:hover { filter: brightness(1.15); }
|
||||
.dl-plist > .dl-card.dl-attn-row { border-color: color-mix(in srgb, var(--dl-warn) 35%, transparent); }
|
||||
@media (max-width: 760px) { .dl-pcard { grid-template-columns: 1fr; } .dl-pside { padding: 12px 0 0; border-left: 0; border-top: 1px solid var(--dl-line); } .dl-fixes { margin-left: 0; } }
|
||||
.dl-select { height: 34px !important; border-radius: 999px !important; min-width: 136px !important; width: auto !important; padding: 0 34px 0 14px !important;
|
||||
appearance: none !important; -webkit-appearance: none !important; background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%238b8f98' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E") !important; background-repeat: no-repeat !important; background-position: right 12px center !important; background-size: 14px !important; }
|
||||
|
||||
@@ -33,6 +33,11 @@
|
||||
.dl-hostport { display: flex; align-items: center; gap: 8px; flex: 1; min-width: 0; justify-content: flex-end; }
|
||||
.dl-hostport input { flex: 1; min-width: 0; }
|
||||
.dl-root input.dl-w-port, .dl-hostport input.dl-w-port { flex: 0 0 90px; width: 90px; }
|
||||
.dl-root input.dl-w-range { flex: 0 0 130px; width: 130px; }
|
||||
.dl-setrow .dl-sub.bad { color: var(--dl-bad); }
|
||||
/* An input with a fixed ending ("10.77.0" .x). */
|
||||
.dl-suffixed { display: inline-flex; align-items: center; gap: 6px; }
|
||||
.dl-suffixed > span { color: var(--dl-fg-muted); }
|
||||
.dl-more summary { cursor: pointer; color: var(--dl-fg-muted); font-size: 13px; margin-bottom: 10px; }
|
||||
.dl-more .dl-setrow + .dl-setrow { margin-top: 10px; }
|
||||
@media (max-width: 760px) { .dl-setrow:not(.head) { grid-template-columns: minmax(0, 1fr); } .dl-setrow-ctl, .dl-setrow-ctl .dl-chips-row { justify-content: flex-start; } }
|
||||
|
||||
+14
-16
@@ -10,28 +10,26 @@ export function pill(tone: string, text: string, title?: string): HTMLElement {
|
||||
return E('span', { class: `dl-pill ${tone}`, title: title ?? null }, text);
|
||||
}
|
||||
|
||||
const STATE_ICON: Record<Person['state'], string> = {
|
||||
active: '',
|
||||
paused: 'pause',
|
||||
paused_all: 'pause',
|
||||
expired: 'calendar',
|
||||
quota: 'chart',
|
||||
hours: 'clock',
|
||||
no_server: 'alert',
|
||||
};
|
||||
|
||||
export function stateTone(p: Person): string {
|
||||
if (p.state === 'active') return 'ok';
|
||||
if (p.state === 'quota' || p.state === 'expired') return 'bad';
|
||||
return 'warn';
|
||||
}
|
||||
|
||||
/** Nothing while active; otherwise a small icon with the state as tooltip. */
|
||||
export function stateBadge(p: Person): HTMLElement | '' {
|
||||
if (p.state === 'active') return '';
|
||||
const el = E('span', { class: `dl-ibadge ${stateTone(p)}`, 'aria-label': STATE_LABEL[p.state] }, icon(STATE_ICON[p.state] || 'alert'));
|
||||
attachTip(el, () => [E('div', { class: 'dl-tip-title' }, STATE_LABEL[p.state])]);
|
||||
return el;
|
||||
/**
|
||||
* The person's own state: a turned-off server hides why they would be off
|
||||
* anyway, but the admin's pause still shows ('server_off' itself is the server
|
||||
* page's to say).
|
||||
*/
|
||||
function ownState(p: Person): Person['state'] {
|
||||
return p.state === 'server_off' && p.paused ? 'paused' : p.state;
|
||||
}
|
||||
|
||||
/** Nothing while active (or while only their server is off); otherwise the state as text, as the server page's "Turned off". */
|
||||
export function statePill(p: Person): HTMLElement | '' {
|
||||
const s = ownState(p);
|
||||
if (s === 'active' || s === 'server_off') return '';
|
||||
return pill(stateTone({ ...p, state: s }), STATE_LABEL[s]);
|
||||
}
|
||||
|
||||
/** What the person can reach, as icons: home network, internet, or both. */
|
||||
|
||||
@@ -13,6 +13,31 @@ export function row(label: string, control: Node, help?: string): HTMLElement {
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* A row whose help line follows its input: `help` says what the value gives,
|
||||
* or what is wrong (red, the input marked too). Callers that change what the
|
||||
* help depends on call `refresh()`.
|
||||
*/
|
||||
export function liveRow(
|
||||
label: string,
|
||||
el: HTMLInputElement,
|
||||
help: () => { text: string; bad: boolean },
|
||||
control: Node = el,
|
||||
): HTMLElement & { refresh: () => void } {
|
||||
const r = row(label, control, ' ') as HTMLElement & { refresh: () => void };
|
||||
const sub = r.querySelector('.dl-sub') as HTMLElement;
|
||||
const paint = () => {
|
||||
const h = help();
|
||||
sub.textContent = h.text;
|
||||
sub.classList.toggle('bad', h.bad);
|
||||
el.classList.toggle('cbi-input-invalid', h.bad);
|
||||
};
|
||||
el.addEventListener('input', paint);
|
||||
r.refresh = paint;
|
||||
paint();
|
||||
return r;
|
||||
}
|
||||
|
||||
/** A section card with its own footer (Save etc.). */
|
||||
export function card(title: string, body: (Node | string)[], foot: (Node | string)[], extra = ''): HTMLElement {
|
||||
return E('section', { class: `dl-setsec ${extra}` }, [
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
// One floating tooltip that follows the pointer (small charts, meters, round
|
||||
// buttons). It hides when its anchor leaves the page (a repaint replaced it)
|
||||
// or the page navigates away, so it never lingers on <body>.
|
||||
// buttons). It hides when its anchor leaves the page or is hidden (a repaint
|
||||
// replaced it, another section is shown), on scrolling, on a tap or click
|
||||
// elsewhere (touch screens have no mouseleave) and when the page navigates
|
||||
// away, so it never lingers on <body>.
|
||||
|
||||
import { E } from '../e';
|
||||
import { onNavigate } from './nav';
|
||||
@@ -24,9 +26,9 @@ export function attachTip(el: HTMLElement, content: () => (Node | string)[]) {
|
||||
floating.style.left = `${ev.clientX}px`;
|
||||
floating.style.top = `${ev.clientY - 10}px`;
|
||||
anchor = el;
|
||||
// No mouseleave comes from an element that was removed under the pointer.
|
||||
// No mouseleave comes from an element that was removed or hidden under the pointer.
|
||||
watch ||= window.setInterval(() => {
|
||||
if (!anchor?.isConnected) hideTip();
|
||||
if (!anchor?.isConnected || !anchor.getClientRects().length) hideTip();
|
||||
}, 400);
|
||||
};
|
||||
el.addEventListener('mouseenter', show);
|
||||
@@ -35,3 +37,11 @@ export function attachTip(el: HTMLElement, content: () => (Node | string)[]) {
|
||||
}
|
||||
|
||||
onNavigate(hideTip);
|
||||
window.addEventListener('scroll', () => anchor && hideTip(), { capture: true, passive: true });
|
||||
document.addEventListener(
|
||||
'pointerdown',
|
||||
(ev) => {
|
||||
if (anchor && !anchor.contains(ev.target as Node)) hideTip();
|
||||
},
|
||||
true,
|
||||
);
|
||||
@@ -9,8 +9,11 @@ import { svg } from '../ui/layout';
|
||||
|
||||
const dayLabel = (day: string) => parseDay(day).toLocaleDateString('en-GB', { day: 'numeric', month: 'short' });
|
||||
|
||||
/** Throughput over the last 15 minutes plus today's total. */
|
||||
export function speedTile(rate: [number, number, number][], now: number, today: [number, number]): HTMLElement {
|
||||
/**
|
||||
* Throughput over the last 15 minutes plus today's total. `off`: the server is
|
||||
* turned off, so there is no speed to show (dashes, not zeros) and no chart.
|
||||
*/
|
||||
export function speedTile(rate: [number, number, number][], now: number, today: [number, number], off = false): HTMLElement {
|
||||
const pts = rate.slice(-15);
|
||||
const last = pts[pts.length - 1];
|
||||
const fresh = last && now - last[0] < 180;
|
||||
@@ -24,19 +27,19 @@ export function speedTile(rate: [number, number, number][], now: number, today:
|
||||
const dl = line(2),
|
||||
ul = line(1);
|
||||
const chart =
|
||||
pts.length > 1
|
||||
pts.length > 1 && !off
|
||||
? svg(
|
||||
`<svg viewBox="0 0 ${W} ${H}" preserveAspectRatio="none" class="dl-speed-chart" aria-hidden="true">` +
|
||||
`<path d="M${dl.join(' L')} L${W},${H} L0,${H}Z" class="area"/><path d="M${dl.join(' L')}" class="line"/>` +
|
||||
`<path d="M${ul.join(' L')}" class="line up"/></svg>`,
|
||||
)
|
||||
: E('div', { class: 'dl-speed-wait' }, [E('i'), E('span', {}, 'Collecting… 1 point a minute')]);
|
||||
: E('div', { class: 'dl-speed-wait' }, [E('i'), off ? '' : E('span', {}, 'Collecting… 1 point a minute')]);
|
||||
const col = (label: string, ic: string, cls: string, v: number) =>
|
||||
E('div', { class: 'dl-speed-col' }, [
|
||||
E('span', { class: 'dl-sub' }, [E('span', { class: cls }, ic), ` ${label}`]),
|
||||
E('span', { class: 'dl-speed-val' }, bits(v)),
|
||||
off ? E('span', { class: 'dl-speed-val off' }, '—') : E('span', { class: 'dl-speed-val' }, bits(v)),
|
||||
]);
|
||||
if (pts.length > 1)
|
||||
if (pts.length > 1 && !off)
|
||||
attachTip(chart, () => {
|
||||
const p = pts[pts.length - 1];
|
||||
return [
|
||||
@@ -47,7 +50,7 @@ export function speedTile(rate: [number, number, number][], now: number, today:
|
||||
return E('div', { class: 'dl-bento-tile' }, [
|
||||
E('div', { class: 'dl-bento-head' }, [
|
||||
E('span', { class: 'dl-metric-label' }, 'Speed now'),
|
||||
E('span', { class: 'dl-sub' }, 'last 15 min'),
|
||||
off ? '' : E('span', { class: 'dl-sub' }, 'last 15 min'),
|
||||
]),
|
||||
E('div', { class: 'dl-speed-cols' }, [col('Download', '↓', 'dl-dn', down), col('Upload', '↑', 'dl-up', up)]),
|
||||
chart,
|
||||
|
||||
+80
-74
@@ -5,20 +5,7 @@
|
||||
// devices on the left, access on the right.
|
||||
|
||||
import type { ClientConfig, Device, Kind, Person } from '../shared/types';
|
||||
import {
|
||||
ACCESS_LABEL,
|
||||
KIND_LABEL,
|
||||
STATE_LABEL,
|
||||
addDays,
|
||||
ago,
|
||||
byDeviceState,
|
||||
bytes,
|
||||
date,
|
||||
daysLeft,
|
||||
initials,
|
||||
isoDay,
|
||||
parseDay,
|
||||
} from '../shared/format';
|
||||
import { ACCESS_LABEL, KIND_LABEL, addDays, ago, byDeviceState, bytes, date, daysLeft, initials, isoDay, parseDay } from '../shared/format';
|
||||
import { iconSvg } from '../shared/icons';
|
||||
import { qrSvg } from '../shared/qr';
|
||||
import { vpnKey } from '../shared/vpnkey';
|
||||
@@ -31,6 +18,8 @@ interface State {
|
||||
/** The device this page was opened from (through the tunnel), if any. */
|
||||
here?: string | null;
|
||||
can_add: boolean;
|
||||
/** The admin stopped the person (paused, access ended): the page only shows. */
|
||||
locked?: boolean;
|
||||
kinds: Kind[];
|
||||
version: string;
|
||||
/** The router's day (YYYY-MM-DD) when it sends one; the browser's otherwise. */
|
||||
@@ -331,6 +320,34 @@ function linkGone() {
|
||||
);
|
||||
}
|
||||
|
||||
/** Why the person's devices can't connect: icon, title and what happens next. */
|
||||
function stateNotice(p: Person): [string, string, string] {
|
||||
switch (p.state) {
|
||||
case 'server_off':
|
||||
return ['server', 'The server is turned off', 'Your devices can’t connect until the admin turns it on again.'];
|
||||
case 'no_server':
|
||||
return ['server', 'No server yet', 'Ask the admin to add you to a server.'];
|
||||
case 'quota':
|
||||
return ['chart', 'You have used all your data', 'Your devices are paused until it resets.'];
|
||||
case 'expired':
|
||||
return ['calendar', 'Your access has ended', 'Ask the admin to extend it.'];
|
||||
case 'hours':
|
||||
return ['clock', 'Outside your hours', `Access is available ${p.hours.replace('-', '–')} (router time).`];
|
||||
default:
|
||||
return ['pause', 'Your access is paused by the admin', 'Your devices can’t connect until the admin resumes it.'];
|
||||
}
|
||||
}
|
||||
|
||||
/** A notice in the admin's Overview style: a tinted icon tile, a title and a line under it. */
|
||||
function alertRow(tone: string, icon: string, title: string, sub: string): HTMLElement {
|
||||
return h(
|
||||
'div',
|
||||
{ class: 'alert' },
|
||||
h('span', { class: `alert-ic ${tone}` }, ic(icon)),
|
||||
h('div', { class: 'stack' }, h('span', { class: 'strong' }, title), h('span', { class: 'muted s' }, sub)),
|
||||
);
|
||||
}
|
||||
|
||||
function stateTone(p: Person) {
|
||||
return p.state === 'active' ? 'ok' : p.state === 'quota' || p.state === 'expired' ? 'bad' : 'warn';
|
||||
}
|
||||
@@ -527,6 +544,8 @@ function deviceCard(d: Device, st: State): HTMLElement {
|
||||
});
|
||||
const week = d.spark.reduce((a, b) => a + b, 0);
|
||||
const setUp = !d.handshake && !d.disabled;
|
||||
// Stopped by the admin: no actions, and a device never set up has nothing to show.
|
||||
const locked = !!st.locked;
|
||||
// The device this page was opened from (through the tunnel): blue, and says so.
|
||||
const here = st.here === d.id;
|
||||
return h(
|
||||
@@ -543,24 +562,26 @@ function deviceCard(d: Device, st: State): HTMLElement {
|
||||
// Opened through the tunnel, so it is connected: say which one it is instead.
|
||||
here ? h('span', { class: 'dstat here' }, 'This device') : deviceStatus(d),
|
||||
),
|
||||
more,
|
||||
locked ? null : more,
|
||||
),
|
||||
setUp
|
||||
? [
|
||||
h(
|
||||
'button',
|
||||
{ type: 'button', class: 'btn primary block', onclick: () => connect(d) },
|
||||
ic(isMobile() ? 'open' : 'qr'),
|
||||
h('span', {}, isMobile() ? 'Open in AmneziaVPN' : 'Connect this device'),
|
||||
setUp && locked
|
||||
? null
|
||||
: setUp
|
||||
? [
|
||||
h(
|
||||
'button',
|
||||
{ type: 'button', class: 'btn primary block', onclick: () => connect(d) },
|
||||
ic(isMobile() ? 'open' : 'qr'),
|
||||
h('span', {}, isMobile() ? 'Open in AmneziaVPN' : 'Connect this device'),
|
||||
),
|
||||
]
|
||||
: h(
|
||||
'div',
|
||||
{ class: 'duse' },
|
||||
h('div', { class: 'stack' }, h('span', { class: 'faint s' }, 'Last 7 days'), h('span', { class: 'mono' }, bytes(week))),
|
||||
spark(d.spark),
|
||||
),
|
||||
]
|
||||
: h(
|
||||
'div',
|
||||
{ class: 'duse' },
|
||||
h('div', { class: 'stack' }, h('span', { class: 'faint s' }, 'Last 7 days'), h('span', { class: 'mono' }, bytes(week))),
|
||||
spark(d.spark),
|
||||
),
|
||||
d.config_stale && !setUp
|
||||
d.config_stale && !setUp && !locked
|
||||
? h(
|
||||
'div',
|
||||
{ class: 'notice' },
|
||||
@@ -577,35 +598,20 @@ function main(st: State) {
|
||||
const left = daysLeft(p.expires, today());
|
||||
const notice =
|
||||
p.state !== 'active'
|
||||
? h(
|
||||
'div',
|
||||
{ class: 'notice bad' },
|
||||
ic('alert'),
|
||||
h(
|
||||
'span',
|
||||
{},
|
||||
p.state === 'quota'
|
||||
? 'You have used all your data for this period. Your devices are paused until it resets.'
|
||||
: p.state === 'expired'
|
||||
? 'Your access has ended. Ask the admin to extend it.'
|
||||
: p.state === 'hours'
|
||||
? `Access is available ${p.hours.replace('-', '–')} (router time).`
|
||||
: 'Your access is paused by the admin.',
|
||||
),
|
||||
)
|
||||
? alertRow(stateTone(p), ...stateNotice(p))
|
||||
: left != null && left >= 0 && left <= Math.max(p.expire_warn, 1)
|
||||
? h(
|
||||
'div',
|
||||
{ class: 'notice' },
|
||||
ic('alert'),
|
||||
h('span', {}, `Your access ends ${left === 0 ? 'today' : `in ${left} day${left === 1 ? '' : 's'}`} (${date(p.expires)}).`),
|
||||
? alertRow(
|
||||
'warn',
|
||||
'calendar',
|
||||
`Your access ends ${left === 0 ? 'today' : `in ${left} day${left === 1 ? '' : 's'}`}`,
|
||||
`On ${date(p.expires)}. Ask the admin to extend it.`,
|
||||
)
|
||||
: null;
|
||||
|
||||
// The device this page was opened from comes first.
|
||||
const order = byDeviceState(p.devices).sort((a, b) => Number(b.id === st.here) - Number(a.id === st.here));
|
||||
const cards: HTMLElement[] = order.map((d) => deviceCard(d, st));
|
||||
const free = Math.max(0, p.device_limit - p.devices.length);
|
||||
const free = st.locked ? 0 : Math.max(0, p.device_limit - p.devices.length);
|
||||
if (free)
|
||||
cards.push(
|
||||
h(
|
||||
@@ -631,36 +637,36 @@ function main(st: State) {
|
||||
),
|
||||
),
|
||||
h('div', { class: 'dgrid' }, cards),
|
||||
!st.can_add
|
||||
? h('span', { class: 'faint s' }, `You have reached your limit of ${p.device_limit} devices. Remove one or ask the admin for more.`)
|
||||
: null,
|
||||
h(
|
||||
'span',
|
||||
{ class: 'faint s' },
|
||||
'New device? Install ',
|
||||
h('a', { href: 'https://amnezia.org/downloads', target: '_blank', rel: 'noopener noreferrer' }, 'AmneziaVPN'),
|
||||
' on it first.',
|
||||
),
|
||||
st.locked
|
||||
? null
|
||||
: [
|
||||
!st.can_add
|
||||
? h(
|
||||
'span',
|
||||
{ class: 'faint s' },
|
||||
`You have reached your limit of ${p.device_limit} devices. Remove one or ask the admin for more.`,
|
||||
)
|
||||
: null,
|
||||
h(
|
||||
'span',
|
||||
{ class: 'faint s' },
|
||||
'New device? Install ',
|
||||
h('a', { href: 'https://amnezia.org/downloads', target: '_blank', rel: 'noopener noreferrer' }, 'AmneziaVPN'),
|
||||
' on it first.',
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
// What stops the devices comes before the greeting.
|
||||
shell(
|
||||
notice,
|
||||
h(
|
||||
'div',
|
||||
{ class: 'hello' },
|
||||
h('span', { class: `avatar${p.online ? ' online' : ''}` }, initials(p.name)),
|
||||
h(
|
||||
'div',
|
||||
{ class: 'stack' },
|
||||
// Only when something is wrong: an "Active" pill says nothing.
|
||||
h(
|
||||
'div',
|
||||
{ class: 'row' },
|
||||
h('h1', {}, `Hi, ${p.name}`),
|
||||
p.state === 'active' ? null : h('span', { class: `pill ${stateTone(p)}` }, STATE_LABEL[p.state]),
|
||||
),
|
||||
),
|
||||
// What is wrong is in the notice above, not a pill here.
|
||||
h('h1', {}, `Hi, ${p.name}`),
|
||||
),
|
||||
notice,
|
||||
h('div', { class: 'layout' }, accessCard(st), devices),
|
||||
);
|
||||
}
|
||||
|
||||
+32
-23
@@ -258,29 +258,6 @@ h2 {
|
||||
background: var(--ok);
|
||||
box-shadow: 0 0 0 3px var(--bg);
|
||||
}
|
||||
.pill {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
height: 22px;
|
||||
padding: 0 9px;
|
||||
border-radius: 999px;
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
background: var(--soft);
|
||||
color: var(--muted);
|
||||
}
|
||||
.pill.ok {
|
||||
background: var(--ok-wash);
|
||||
color: var(--ok);
|
||||
}
|
||||
.pill.warn {
|
||||
background: var(--warn-wash);
|
||||
color: var(--warn);
|
||||
}
|
||||
.pill.bad {
|
||||
background: var(--bad-wash);
|
||||
color: var(--bad);
|
||||
}
|
||||
.notice {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
@@ -300,6 +277,38 @@ h2 {
|
||||
color: var(--bad);
|
||||
}
|
||||
|
||||
/* The page's notice, as in the admin's Overview: a row in a bordered list. */
|
||||
.alert {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
align-items: center;
|
||||
padding: 12px 16px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 12px;
|
||||
background: var(--card);
|
||||
font-size: 14px;
|
||||
line-height: 20px;
|
||||
}
|
||||
.alert-ic {
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
border-radius: 9px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex: none;
|
||||
background: var(--warn-wash);
|
||||
color: var(--warn);
|
||||
}
|
||||
.alert-ic.bad {
|
||||
background: var(--bad-wash);
|
||||
color: var(--bad);
|
||||
}
|
||||
.alert-ic .ic-svg {
|
||||
width: 15px;
|
||||
height: 15px;
|
||||
}
|
||||
|
||||
/* layout: phone = access then devices; desktop = devices | access */
|
||||
.layout {
|
||||
display: grid;
|
||||
|
||||
@@ -159,11 +159,11 @@ export const KIND_LABEL: Record<Kind, string> = {
|
||||
export const STATE_LABEL: Record<PersonState, string> = {
|
||||
active: 'Active',
|
||||
paused: 'Paused',
|
||||
paused_all: 'Paused (everyone)',
|
||||
expired: 'Expired',
|
||||
quota: 'Data limit reached',
|
||||
hours: 'Outside allowed hours',
|
||||
no_server: 'No server',
|
||||
server_off: 'Server is turned off',
|
||||
};
|
||||
|
||||
export function initials(name: string): string {
|
||||
|
||||
@@ -5,6 +5,8 @@ const P: Record<string, string> = {
|
||||
computer: '<rect x="3" y="4.5" width="18" height="12" rx="1.8"/><path d="M2 19.5h20"/>',
|
||||
tablet: '<rect x="4.5" y="2.5" width="15" height="19" rx="2.2"/><path d="M11 18.5h2"/>',
|
||||
router: '<rect x="3" y="13" width="18" height="7" rx="1.8"/><path d="M7 16.5h.01M10.5 16.5h.01M8 13l-2-6M16 13l2-6"/>',
|
||||
server:
|
||||
'<rect x="3" y="4" width="18" height="7" rx="1.8"/><rect x="3" y="13" width="18" height="7" rx="1.8"/><path d="M7 7.5h.01M7 16.5h.01M11 7.5h6M11 16.5h6"/>',
|
||||
other: '<path d="M12 3 20 7.5v9L12 21l-8-4.5v-9L12 3Z"/><path d="M4 7.5 12 12l8-4.5M12 12v9"/>',
|
||||
ethernet:
|
||||
'<rect x="9" y="3" width="6" height="5" rx="1"/><rect x="3" y="16" width="6" height="5" rx="1"/><rect x="15" y="16" width="6" height="5" rx="1"/><path d="M12 8v4M6 16v-4h12v4"/>',
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
export type Access = 'lan' | 'internet' | 'both';
|
||||
export type Kind = 'computer' | 'phone' | 'tablet' | 'router' | 'other';
|
||||
export type PersonState = 'active' | 'paused' | 'paused_all' | 'expired' | 'quota' | 'hours' | 'no_server';
|
||||
export type PersonState = 'active' | 'paused' | 'expired' | 'quota' | 'hours' | 'no_server' | 'server_off';
|
||||
export type Pair = [number, number]; // [rx, tx] from the router's point of view
|
||||
|
||||
export interface Device {
|
||||
@@ -99,7 +99,10 @@ export interface Server {
|
||||
/** Home networks by interface, for the per-person picker. */
|
||||
home: { dev: string; nets: string[] }[];
|
||||
preset: string;
|
||||
/** The MTU set; 0 = automatic, by device type and disguise. */
|
||||
mtu: number;
|
||||
/** The MTU devices get now: computers and routers, phones and tablets. */
|
||||
mtus: { computer: number; phone: number };
|
||||
keepalive: number;
|
||||
/** DNS servers given to devices; empty = this router. */
|
||||
dns: string[];
|
||||
@@ -191,7 +194,6 @@ export interface Status {
|
||||
/** The port in personal links (the portal's own). */
|
||||
portal_public_port?: number;
|
||||
portal_host: string;
|
||||
paused_all: boolean;
|
||||
default_device_limit: number;
|
||||
domain: string;
|
||||
hostnames: boolean;
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { arc, devicePlaces, separate, type MapData } from '../src/admin/map';
|
||||
|
||||
describe('arc (mapcn buildArcCoordinates)', () => {
|
||||
it('runs from one point to the other in 64 steps', () => {
|
||||
const pts = arc([-0.1276, 51.5074], [-74.006, 40.7128]);
|
||||
expect(pts).toHaveLength(65);
|
||||
expect(pts[0]).toEqual([-0.1276, 51.5074]);
|
||||
expect(pts[64][0]).toBeCloseTo(-74.006);
|
||||
expect(pts[64][1]).toBeCloseTo(40.7128);
|
||||
});
|
||||
|
||||
it('bends to the left of travel by a fifth of the distance', () => {
|
||||
// Due east 10°: the control point sits 2° north of the middle, the curve's peak half of that.
|
||||
const mid = arc([0, 0], [10, 0])[32];
|
||||
expect(mid[0]).toBeCloseTo(5);
|
||||
expect(mid[1]).toBeCloseTo(1);
|
||||
});
|
||||
|
||||
it('takes the short way across the antimeridian', () => {
|
||||
const pts = arc([139.69, 35.69], [-122.42, 37.77]);
|
||||
expect(pts[pts.length - 1][0]).toBeCloseTo(237.58);
|
||||
expect(Math.max(...pts.map((p) => Math.abs(p[0] - 139.69)))).toBeLessThan(100);
|
||||
});
|
||||
|
||||
it('is a single point pair when both ends meet', () => {
|
||||
expect(arc([10, 10], [10, 10])).toEqual([
|
||||
[10, 10],
|
||||
[10, 10],
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('devicePlaces', () => {
|
||||
const pt = (city: string, ts: number, online = false, device = 'lap') => ({
|
||||
person: 'my',
|
||||
device,
|
||||
ip: `ip-${city}-${ts}`,
|
||||
ts,
|
||||
online,
|
||||
lat: 0,
|
||||
lon: 0,
|
||||
city,
|
||||
country: '',
|
||||
cc: 'RU',
|
||||
asn: 0,
|
||||
org: '',
|
||||
});
|
||||
const now = 100 * 86400;
|
||||
const data = (points: ReturnType<typeof pt>[]): MapData => ({
|
||||
geo: { enabled: true, home: null, points } as unknown as MapData['geo'],
|
||||
people: [],
|
||||
now,
|
||||
person: 'my',
|
||||
device: 'lap',
|
||||
});
|
||||
|
||||
it('puts the live place first and numbers the rest newest first, one per city', () => {
|
||||
const list = devicePlaces(
|
||||
data([
|
||||
pt('Kazan', now - 25 * 86400),
|
||||
pt('Moscow', now - 7 * 86400),
|
||||
pt('Moscow', now - 9 * 86400),
|
||||
pt('Sochi', now - 86400),
|
||||
pt('Krasnodar', now, true),
|
||||
pt('Berlin', now - 86400, false, 'phone'),
|
||||
]),
|
||||
'30d',
|
||||
);
|
||||
expect(list.map((x) => [x.city, x.n])).toEqual([
|
||||
['Krasnodar', 0],
|
||||
['Sochi', 1],
|
||||
['Moscow', 2],
|
||||
['Kazan', 3],
|
||||
]);
|
||||
});
|
||||
|
||||
it('keeps to the period', () => {
|
||||
expect(devicePlaces(data([pt('Kazan', now - 25 * 86400), pt('Sochi', now - 86400)]), '7d').map((x) => x.city)).toEqual(['Sochi']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('separate', () => {
|
||||
it('leaves markers that do not touch alone', () => {
|
||||
expect(
|
||||
separate([
|
||||
{ x: 0, y: 0, r: 10 },
|
||||
{ x: 100, y: 0, r: 10 },
|
||||
]),
|
||||
).toEqual([
|
||||
[0, 0],
|
||||
[0, 0],
|
||||
]);
|
||||
});
|
||||
it('moves only the free one away from a fixed one, just clear', () => {
|
||||
const [s, p] = separate([
|
||||
{ x: 0, y: 0, r: 20, fixed: true },
|
||||
{ x: 30, y: 0, r: 14 },
|
||||
]);
|
||||
expect(s).toEqual([0, 0]);
|
||||
expect(p[0]).toBeCloseTo(20 + 14 + 6 - 30);
|
||||
expect(p[1]).toBeCloseTo(0);
|
||||
});
|
||||
it('fades to nothing as markers part (no jump)', () => {
|
||||
const at = (x: number) =>
|
||||
separate([
|
||||
{ x: 0, y: 0, r: 20, fixed: true },
|
||||
{ x, y: 0, r: 14 },
|
||||
])[1][0];
|
||||
expect(at(39)).toBeCloseTo(1);
|
||||
expect(at(39.9)).toBeCloseTo(0.1);
|
||||
expect(at(40)).toBe(0);
|
||||
});
|
||||
it('splits two free markers half each and parts ones on the same spot', () => {
|
||||
const [a, b] = separate(
|
||||
[
|
||||
{ x: 0, y: 0, r: 10 },
|
||||
{ x: 10, y: 0, r: 10 },
|
||||
],
|
||||
0,
|
||||
);
|
||||
expect(a[0]).toBeCloseTo(-5);
|
||||
expect(b[0]).toBeCloseTo(5);
|
||||
const same = separate(
|
||||
[
|
||||
{ x: 0, y: 0, r: 10 },
|
||||
{ x: 0, y: 0, r: 10 },
|
||||
{ x: 0, y: 0, r: 10 },
|
||||
],
|
||||
0,
|
||||
);
|
||||
for (let i = 0; i < 3; i++)
|
||||
for (let j = i + 1; j < 3; j++) expect(Math.hypot(same[i][0] - same[j][0], same[i][1] - same[j][1])).toBeGreaterThan(19);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { parseCidr, portalPortHelp, portHelp, rangeHelp, rangeOf, subnetOf } from '../src/admin/netcheck';
|
||||
|
||||
const nets = [
|
||||
{ name: 'lan', cidr: '10.0.1.0/24' },
|
||||
{ name: 'loopback', cidr: '127.0.0.0/8' },
|
||||
{ name: 'wan', cidr: '109.173.124.0/23' },
|
||||
{ name: 'guest', cidr: '192.168.0.0/16' },
|
||||
];
|
||||
|
||||
describe('netcheck', () => {
|
||||
it('parses subnets like the router', () => {
|
||||
expect(parseCidr('10.10.10.5/24')).toEqual({ net: 0x0a0a0a00, size: 256 });
|
||||
expect(parseCidr('10.10.10.0/31')).toBeNull();
|
||||
expect(parseCidr('10.10.300.0/24')).toBeNull();
|
||||
expect(parseCidr('10.10.10.0')).toBeNull();
|
||||
});
|
||||
|
||||
it('converts between a range and its subnet', () => {
|
||||
expect(rangeOf('10.77.0.0/24')).toBe('10.77.0');
|
||||
expect(subnetOf(' 10.77.0 ')).toBe('10.77.0.0/24');
|
||||
});
|
||||
|
||||
it('explains the device addresses', () => {
|
||||
expect(rangeHelp('10.10.10', nets, '10.77.0')).toEqual({
|
||||
text: 'Devices get 10.10.10.2 – 10.10.10.254, the router 10.10.10.1.',
|
||||
bad: false,
|
||||
});
|
||||
expect(rangeHelp('10.0.1', nets, '10.77.0')).toEqual({ text: 'lan already uses 10.0.1.x. Try 10.77.0.', bad: true });
|
||||
expect(rangeHelp('192.168.5', nets, '10.77.0').text).toBe('guest already uses 192.168.0.0/16. Try 10.77.0.');
|
||||
expect(rangeHelp('10.77.0', [{ name: 'Home', cidr: '10.77.0.0/24' }], '10.77.0').text).toBe('Home already uses 10.77.0.x.');
|
||||
});
|
||||
|
||||
it('wants a private range of three numbers', () => {
|
||||
expect(rangeHelp('8.8.8', nets, '').text).toBe('Use a private range: 10.x.x, 172.16–31.x or 192.168.x.');
|
||||
expect(rangeHelp('172.32.0', nets, '').bad).toBe(true);
|
||||
expect(rangeHelp('172.31.0', nets, '').bad).toBe(false);
|
||||
expect(rangeHelp('10.10', nets, '').text).toBe('Three numbers, like 10.77.0.');
|
||||
expect(rangeHelp('10.10.10.0', nets, '').bad).toBe(true);
|
||||
expect(rangeHelp('10.10.256', nets, '').bad).toBe(true);
|
||||
});
|
||||
|
||||
it('says who holds a port', () => {
|
||||
const taken = [
|
||||
{ from: 53, to: 53, who: 'dnsmasq on this router' },
|
||||
{ from: 4000, to: 4100, who: 'port forward “Game”' },
|
||||
];
|
||||
expect(portHelp(4500, taken, 'Free.')).toEqual({ text: 'Free.', bad: false });
|
||||
expect(portHelp(53, taken, '').text).toBe('Used by dnsmasq on this router. Choose another port.');
|
||||
expect(portHelp(4050, taken, '').text).toBe('Used by port forward “Game”. Choose another port.');
|
||||
expect(portHelp(0, taken, '').text).toBe('Use a port from 1 to 65535.');
|
||||
expect(portHelp(Number.NaN, taken, '').bad).toBe(true);
|
||||
});
|
||||
|
||||
it('checks the portal port and the next one for IP links', () => {
|
||||
const taken = [{ from: 8444, to: 8444, who: 'nginx on this router' }];
|
||||
expect(portalPortHelp(8443, taken, false)).toEqual({ text: 'HTTPS on this port, opened on WAN.', bad: false });
|
||||
expect(portalPortHelp(8443, taken, true).text).toBe(
|
||||
'Links on IP addresses also need 8444, used by nginx on this router. Choose another port.',
|
||||
);
|
||||
expect(portalPortHelp(9443, taken, true)).toEqual({ text: 'HTTPS here, plain HTTP for links on IP addresses on 9444.', bad: false });
|
||||
expect(portalPortHelp(8444, taken, false).bad).toBe(true);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user