Dawnline 0.20.0
Build packages / CI (push) Blocked by required conditions
Build packages / Version (push) Waiting to run
CI / Web (format, types, tests, bundles) (push) Blocked by required conditions
CI / ShellCheck (push) Blocked by required conditions
CI / Backend (Go: vet, tests, a real ubusd and uhttpd) (push) Blocked by required conditions
CI / Package files (push) Blocked by required conditions
Build packages / CI (push) Blocked by required conditions
Build packages / Version (push) Waiting to run
CI / Web (format, types, tests, bundles) (push) Blocked by required conditions
CI / ShellCheck (push) Blocked by required conditions
CI / Backend (Go: vet, tests, a real ubusd and uhttpd) (push) Blocked by required conditions
CI / Package files (push) Blocked by required conditions
- **Backend rewritten in Go.** One daemon, `dawnlined`, replaces the whole ucode backend: the rpcd plugin, the agent, the CLI and the updater. The package no longer depends on ucode. - **Per-architecture builds.** The release carries the backend for arm64, ARMv7, mips, mipsle and amd64; the router fetches its own after the package is installed and checks its sha256. Dawnline does not run on other architectures (older ARM, 32-bit x86, RISC-V). - **Faster on the router.** A firewall sync takes 0.06 s instead of 0.9 s; a full apply takes about 300 ms. The portal is served by the daemon itself, without a CGI process per request. - **Live pages.** The admin and the portal follow a live stream from the router instead of re-fetching the whole state every 30 seconds. - **Admin redesigned in the portal's style.** Three sections (Overview · Log · Settings); a server is a page of its own with People, Places and Settings; a device opens as a dialog over its person. - **Changes wait for «Apply».** Every setting, and a person's access, is staged in one dock before it reaches the router. - **Configuration rollout.** After a change that makes devices fetch their configuration again, the admin shows how many have fetched it and who has not. Every setting shows beforehand (⟳N) how many devices it will touch. - **Waiting for a decision.** Overview and People put first the people who need one (access ended, limit reached, a device that does not connect), each with its one action a tap away. - **Bulk actions on people.** «Select» (or a long press on a card) picks several people to extend by a month, pause or resume at once. - **Undo.** An action done from a card or a request is undone from its toast. - **Update dialogs redesigned.** An update is one view from its question to its result; Dawnline's own update runs in it like every other, and the page reloads itself once the new version answers. Other versions are a list, each with its notes and Install on a page of its own. - **Site to site: networks behind a router.** A router connected as a device can have networks behind it (up to eight, /16 to /30): the server routes them and applies the router's access to them. A network that shares addresses with a tunnel, the router's own networks or another site is refused by name. - **Routers from the portal.** People can add a router and name its networks on their own page; the admin accepts or declines with a reason, or lets them through without asking. - **Check access and Health know the networks behind routers.** - **Usage limits reworked.** A monthly limit no longer follows the calendar. A person's month starts with their first traffic and ends a month later; the next one starts only when they connect again, so time away uses up none of it. Before, everyone's limit reset on the 1st. - Extra data lasts until that person's month ends; «Reset usage» starts the month anew. - A limit is for a month or for the whole term; the admin and the portal show when it resets. - Charts that said «this month» show the last 30 days. - After the update nobody loses what was counted: the month that was running becomes the person's first and ends on the 1st. - **Access by time of day removed.** The Hours limit is gone from the admin, the portal and the backend; saved hours are dropped. - **Expiry simplified.** An end date always stops access, with a heads-up three days before; the per-person choice is gone. - **No false disconnects from sleeping phones.** A phone or a tablet stays online through ten minutes of silence. - **Mobile Safari fixes.** Pressing a control no longer sends the page to its top; tab tracks that do not fit scroll; switches animate after a press.
This commit is contained in:
1 parent
f8130e39a8
commit
ac90575b0b
788 files changed
+139244
-41720
No files matched your search
@@ -1,530 +0,0 @@
|
||||
// Server → Access pieces: home services (picked from devices at home), circles,
|
||||
// "Who reaches what" and "Check access".
|
||||
|
||||
import type { Circle, Person, Server, Status } from '../shared/types';
|
||||
import { E } from './e';
|
||||
import { api, type HomeHost } from './api';
|
||||
import { button } from './ui/button';
|
||||
import { cancelButton, closeModal, confirmDialog, modal } from './ui/modal';
|
||||
import { attempt, notify } from './ui/toast';
|
||||
import { chipToggle, input } from './ui/controls';
|
||||
import { firstBad, liveField } from './ui/layout';
|
||||
import { circleNameHelp, ipv4Help, nameHelp, portsHelp } from './netcheck';
|
||||
import { icon } from '../shared/icons';
|
||||
import { fmt, plural } from '../shared/i18n';
|
||||
|
||||
type Service = Status['services'][number];
|
||||
|
||||
/** Circle colours; the circle stores an index. */
|
||||
const CIRCLE_COLORS = ['#3a83f7', '#a78bfa', '#f472b6', '#f59e0b', '#10b981', '#22d3ee', '#ef4444', '#84cc16'];
|
||||
|
||||
export const circleDot = (c: Circle | undefined) =>
|
||||
E('i', { class: 'dl-circle-dot', style: `background:${CIRCLE_COLORS[c?.color ?? 0] ?? CIRCLE_COLORS[0]}` });
|
||||
|
||||
/** People whose devices can be reached at home (the mesh and home devices). */
|
||||
export const homeAccess = (p: Person) => p.access === 'both' || (p.access === 'lan' && !p.services?.length);
|
||||
|
||||
/* ---------- Home services ---------- */
|
||||
|
||||
function serviceDialog(sv: Service | null, prefill: Partial<Service>, onSaved: () => unknown) {
|
||||
const name = input(sv?.name ?? prefill.name ?? '', { placeholder: _('NAS') });
|
||||
const addr = input(sv?.address ?? prefill.address ?? '', { placeholder: '192.168.1.10', class: 'cbi-input-text dl-mono' });
|
||||
const ports = input((sv?.ports ?? prefill.ports ?? []).join(', '), {
|
||||
placeholder: _('All ports, or e.g. 445, 5000'),
|
||||
class: 'cbi-input-text dl-mono',
|
||||
});
|
||||
const nameRow = liveField(_('Name', 'circle or service'), name, () => nameHelp(name.value, [], _('Shown to people who may reach it.')));
|
||||
const addrRow = liveField(_('Address'), addr, () => ipv4Help(addr.value));
|
||||
const portsRow = liveField(_('Ports'), ports, () => portsHelp(ports.value));
|
||||
modal(
|
||||
sv ? fmt(_('Edit %s'), sv.name) : _('Add service'),
|
||||
[nameRow, addrRow, portsRow],
|
||||
[
|
||||
cancelButton(),
|
||||
' ',
|
||||
button(
|
||||
_('Save'),
|
||||
async () => {
|
||||
const bad = firstBad([nameRow, addrRow, portsRow]);
|
||||
if (bad) {
|
||||
notify(bad, 'warning');
|
||||
return;
|
||||
}
|
||||
const list = ports.value.split(/[ ,]+/).filter(Boolean);
|
||||
if (await attempt(() => api.serviceSet(sv?.id ?? '', name.value, addr.value, list), _('Saved'))) {
|
||||
closeModal();
|
||||
onSaved();
|
||||
}
|
||||
},
|
||||
'positive',
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/** The port group a Bonjour service type belongs to, by its name. */
|
||||
function mdnsLabels(): Record<string, string> {
|
||||
const web = _('Web');
|
||||
const printer = _('Printer');
|
||||
return {
|
||||
_smb: 'SMB',
|
||||
_afpovertcp: 'AFP',
|
||||
_http: web,
|
||||
_https: web,
|
||||
_ssh: 'SSH',
|
||||
_sftp: 'SFTP',
|
||||
'_sftp-ssh': 'SFTP',
|
||||
_ipp: printer,
|
||||
_ipps: printer,
|
||||
_printer: printer,
|
||||
'_pdl-datastream': printer,
|
||||
_airplay: 'AirPlay',
|
||||
_raop: 'AirPlay',
|
||||
_rfb: _('Screen sharing'),
|
||||
_googlecast: 'Cast',
|
||||
_hap: 'HomeKit',
|
||||
_rdp: _('Remote desktop'),
|
||||
_ftp: 'FTP',
|
||||
};
|
||||
}
|
||||
|
||||
/** Port groups a device at home offers: what it announces over Bonjour, or the usual ones. */
|
||||
function portGroups(h: HomeHost): [string, string[]][] {
|
||||
const labels = mdnsLabels();
|
||||
const by = new Map<string, Set<string>>();
|
||||
for (const s of h.services) {
|
||||
const label = labels[s.type.split('.')[0]];
|
||||
if (!label || !s.port) continue;
|
||||
(by.get(label) ?? by.set(label, new Set()).get(label)!).add(String(s.port));
|
||||
}
|
||||
return by.size
|
||||
? [...by].map(([l, p]) => [l, [...p].sort((a, b) => +a - +b)])
|
||||
: [
|
||||
[_('Web'), ['80', '443']],
|
||||
['SMB', ['445']],
|
||||
['SSH', ['22']],
|
||||
];
|
||||
}
|
||||
|
||||
/** Home services as a live part of Server → Access: `update` repaints it from a new status. */
|
||||
export interface HomeServices {
|
||||
el: HTMLElement;
|
||||
update(st: Status): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Services shared by all servers, and the devices at home to add them from.
|
||||
* The devices are read once; `reload` refreshes the status after a change
|
||||
* (the rest of the Access section, and what is typed there, stays).
|
||||
*/
|
||||
export function homeServices(initial: Status, serverId: string, reload: () => Promise<unknown>): HomeServices {
|
||||
let st = initial;
|
||||
let hosts: { hosts: HomeHost[]; mdns: boolean } | null = null;
|
||||
let failed = false;
|
||||
/** The "Add from devices at home" fold, once opened or closed by hand. */
|
||||
let open: boolean | null = null;
|
||||
/** Devices with a change on its way: a second click would add the service twice. */
|
||||
const busy = new Set<string>();
|
||||
const list = E('div', { class: 'dl-list' });
|
||||
const picker = E('div', { class: 'dl-stack gap8' }, E('span', { class: 'dl-sub' }, _('Looking for devices at home…')));
|
||||
|
||||
const paintRows = () => {
|
||||
const services = st.services;
|
||||
dom.content(
|
||||
list,
|
||||
services.length
|
||||
? services.map((sv) =>
|
||||
E('div', { class: 'dl-row' }, [
|
||||
icon('home'),
|
||||
E('span', { class: 'dl-row-main dl-stack' }, [
|
||||
E('b', {}, sv.name),
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-mono dl-faint' },
|
||||
`${sv.address} · ${sv.ports.length ? fmt(_('ports %s'), sv.ports.join(', ')) : _('all ports')}`,
|
||||
),
|
||||
]),
|
||||
button(_('Edit'), () => serviceDialog(sv, {}, reload)),
|
||||
button(
|
||||
[icon('trash')],
|
||||
async () => {
|
||||
if (
|
||||
(await confirmDialog(
|
||||
fmt(_('Remove %s?'), sv.name),
|
||||
_('People limited to this service lose access to it.'),
|
||||
_('Remove'),
|
||||
true,
|
||||
)) &&
|
||||
(await attempt(() => api.serviceDelete(sv.id), _('Removed')))
|
||||
)
|
||||
await reload();
|
||||
},
|
||||
'neutral',
|
||||
{ title: _('Remove'), 'aria-label': fmt(_('Remove %s'), sv.name) },
|
||||
),
|
||||
]),
|
||||
)
|
||||
: [E('div', { class: 'dl-row dl-muted' }, _('No services yet: pick ports of a device below.'))],
|
||||
);
|
||||
};
|
||||
|
||||
/** Ports chosen for a device: add, change or remove its service at once. */
|
||||
async function choose(h: HomeHost, ports: string[] | null) {
|
||||
if (busy.has(h.address)) return;
|
||||
busy.add(h.address);
|
||||
paintPicker();
|
||||
try {
|
||||
const sv = st.services.find((s) => s.address === h.address);
|
||||
const ok =
|
||||
ports === null
|
||||
? sv && (await attempt(() => api.serviceDelete(sv.id), fmt(_('%s removed'), sv.name)))
|
||||
: await attempt(
|
||||
() => api.serviceSet(sv?.id ?? '', sv?.name ?? (h.name || h.address), h.address, ports),
|
||||
sv ? fmt(_('%s updated'), sv.name) : fmt(_('%s added'), h.name || h.address),
|
||||
);
|
||||
if (ok) await reload();
|
||||
} finally {
|
||||
busy.delete(h.address);
|
||||
paintPicker();
|
||||
}
|
||||
}
|
||||
|
||||
function hostRow(h: HomeHost): HTMLElement {
|
||||
const sv = st.services.find((s) => s.address === h.address);
|
||||
const all = !!sv && !sv.ports.length;
|
||||
const chosen = new Set(sv?.ports ?? []);
|
||||
const wait = busy.has(h.address);
|
||||
const chip = (label: string, on: boolean, click: () => void) =>
|
||||
chipToggle(label, on, click, { disabled: wait ? 'disabled' : null, 'aria-busy': wait ? 'true' : null });
|
||||
// The name and the ports share a wrapping line: the ports go under the name before it is squeezed.
|
||||
return E('div', { class: 'dl-row dl-host' }, [
|
||||
icon(h.services.some((s) => s.type.startsWith('_ipp') || s.type.startsWith('_printer')) ? 'file' : 'computer'),
|
||||
E('div', { class: 'dl-host-body' }, [
|
||||
E('span', { class: 'dl-row-main dl-stack' }, [
|
||||
E('b', {}, h.name || h.address),
|
||||
E('span', { class: 'dl-mono dl-faint' }, h.address),
|
||||
]),
|
||||
E('div', { class: 'dl-chips-row' }, [
|
||||
chip(_('All ports'), all, () => choose(h, all ? null : [])),
|
||||
...portGroups(h).map(([label, ports]) => {
|
||||
const on = !all && ports.every((p) => chosen.has(p));
|
||||
return chip(`${label} ${ports.join(', ')}`, on, () => {
|
||||
const next = new Set(all ? [] : chosen);
|
||||
for (const p of ports) {
|
||||
if (on) next.delete(p);
|
||||
else next.add(p);
|
||||
}
|
||||
choose(h, next.size ? [...next] : null);
|
||||
});
|
||||
}),
|
||||
]),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
|
||||
function paintPicker() {
|
||||
if (failed) return dom.content(picker, E('span', { class: 'dl-sub' }, _("Couldn't read the devices at home.")));
|
||||
if (!hosts) return;
|
||||
const r = hosts;
|
||||
if (!r.hosts.length) return dom.content(picker, E('span', { class: 'dl-sub' }, _('No devices found in the home network right now.')));
|
||||
// Open while there are no services yet (that is where they come from), then as left.
|
||||
const fold = E('details', { class: 'dl-params', open: (open ?? !st.services.length) ? '' : null }, [
|
||||
E('summary', {}, [
|
||||
icon('chevron'),
|
||||
E('span', {}, _('Add from devices at home')),
|
||||
E('span', { class: 'dl-pcount' }, String(r.hosts.length)),
|
||||
]),
|
||||
E('div', { class: 'dl-params-body' }, [
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-sub' },
|
||||
r.mdns
|
||||
? _('Ports they announce over Bonjour. Pick what to open, or all ports.')
|
||||
: _('Devices that got an address from this router. Pick the ports to open, or all ports.'),
|
||||
),
|
||||
E('div', { class: 'dl-list' }, r.hosts.map(hostRow)),
|
||||
]),
|
||||
]);
|
||||
fold.addEventListener('toggle', () => (open = (fold as HTMLDetailsElement).open));
|
||||
dom.content(picker, fold);
|
||||
}
|
||||
|
||||
api
|
||||
.homeHosts(serverId)
|
||||
.then((r) => {
|
||||
hosts = r;
|
||||
paintPicker();
|
||||
})
|
||||
.catch(() => {
|
||||
failed = true;
|
||||
paintPicker();
|
||||
});
|
||||
paintRows();
|
||||
|
||||
const el = E('div', { class: 'dl-stack gap8' }, [
|
||||
E('div', { class: 'dl-iflead' }, [
|
||||
E('div', { class: 'dl-iflead-row' }, [
|
||||
E('b', {}, _('Home services')),
|
||||
button([icon('plus'), ' ', _('Add service')], () => serviceDialog(null, {}, reload)),
|
||||
]),
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-sub' },
|
||||
_('Home-only people can be limited to these instead of whole networks (chosen on their page). Shared by all servers.'),
|
||||
),
|
||||
]),
|
||||
list,
|
||||
picker,
|
||||
]);
|
||||
return {
|
||||
el,
|
||||
update(n: Status) {
|
||||
st = n;
|
||||
paintRows();
|
||||
paintPicker();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/* ---------- Circles ---------- */
|
||||
|
||||
export function circleDialog(st: Status, serverId: string, ci: Circle | null, onDone: () => unknown) {
|
||||
const used = new Set(st.circles.filter((c) => c.server === serverId).map((c) => c.color));
|
||||
let color = ci?.color ?? CIRCLE_COLORS.findIndex((_c, i) => !used.has(i));
|
||||
if (color < 0) color = 0;
|
||||
const name = input(ci?.name ?? '', { placeholder: _('Family') });
|
||||
const people = st.people.filter((p) => p.server === serverId).sort((a, b) => a.name.localeCompare(b.name));
|
||||
const members = new Set(people.filter((p) => ci && p.circle === ci.id).map((p) => p.id));
|
||||
|
||||
const swatches = E('div', { class: 'dl-swatches', role: 'radiogroup', 'aria-label': _('Colour') });
|
||||
const paintSwatches = () =>
|
||||
dom.content(
|
||||
swatches,
|
||||
CIRCLE_COLORS.map((c, i) =>
|
||||
E('button', {
|
||||
type: 'button',
|
||||
role: 'radio',
|
||||
class: `dl-swatch${i === color ? ' on' : ''}`,
|
||||
style: `--sw:${c}`,
|
||||
'aria-checked': i === color ? 'true' : 'false',
|
||||
'aria-label': fmt(_('Colour %s'), i + 1),
|
||||
click: () => {
|
||||
color = i;
|
||||
paintSwatches();
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
paintSwatches();
|
||||
|
||||
const chips = E(
|
||||
'div',
|
||||
{ class: 'dl-chips-row' },
|
||||
people.map((p) => {
|
||||
const other = p.circle && p.circle !== ci?.id ? st.circles.find((c) => c.id === p.circle) : undefined;
|
||||
return E(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
class: `dl-chipbtn${members.has(p.id) ? ' on' : ''}`,
|
||||
title: !homeAccess(p)
|
||||
? fmt(_("%s has no home access: their devices aren't reachable anyway"), p.name)
|
||||
: other
|
||||
? fmt(_('Now in %s'), other.name)
|
||||
: '',
|
||||
click: (ev: Event) => {
|
||||
if (!members.delete(p.id)) members.add(p.id);
|
||||
(ev.currentTarget as HTMLElement).classList.toggle('on', members.has(p.id));
|
||||
},
|
||||
},
|
||||
[p.name, !homeAccess(p) ? E('b', {}, _('internet')) : other ? E('b', {}, other.name) : ''],
|
||||
);
|
||||
}),
|
||||
);
|
||||
const field = (label: string, el: Node) =>
|
||||
E('div', { class: 'cbi-value' }, [E('label', { class: 'cbi-value-title' }, label), E('div', { class: 'cbi-value-field' }, el)]);
|
||||
const others = st.circles.filter((c) => c.server === serverId && c.id !== ci?.id).map((c) => c.name);
|
||||
const nameRow = liveField(_('Name', 'circle or service'), name, () => circleNameHelp(name.value, others));
|
||||
|
||||
modal(
|
||||
ci ? fmt(_('Edit %s'), ci.name) : _('New circle'),
|
||||
[
|
||||
nameRow,
|
||||
field(_('Colour'), swatches),
|
||||
field(_('People'), chips),
|
||||
E('p', { class: 'dl-sub' }, _('Devices of people in one circle reach each other. A person is in one circle at a time.')),
|
||||
],
|
||||
[
|
||||
ci
|
||||
? button(
|
||||
_('Delete'),
|
||||
async () => {
|
||||
if (await attempt(() => api.circleDelete(ci.id), fmt(_('%s deleted'), ci.name))) {
|
||||
closeModal();
|
||||
onDone();
|
||||
}
|
||||
},
|
||||
'negative',
|
||||
)
|
||||
: '',
|
||||
E('span', { class: 'dl-spacer' }),
|
||||
cancelButton(),
|
||||
' ',
|
||||
button(
|
||||
_('Save'),
|
||||
async () => {
|
||||
const h = nameRow.help();
|
||||
if (h.bad) {
|
||||
notify(h.text, 'warning');
|
||||
return;
|
||||
}
|
||||
if (await attempt(() => api.circleSet(ci?.id ?? '', serverId, name.value, color, [...members]), _('Saved'))) {
|
||||
closeModal();
|
||||
onDone();
|
||||
}
|
||||
},
|
||||
'positive',
|
||||
),
|
||||
],
|
||||
'dl-circle-modal',
|
||||
);
|
||||
}
|
||||
|
||||
/** The server's circles as chips (click to edit) and a round "+" to add one. */
|
||||
export function circleChips(st: Status, serverId: string, onDone: () => unknown): HTMLElement {
|
||||
const list = st.circles.filter((c) => c.server === serverId);
|
||||
return E('div', { class: 'dl-chips-row dl-circles' }, [
|
||||
...list.map((c) => {
|
||||
const who = st.people.filter((p) => p.circle === c.id).map((p) => p.name);
|
||||
return E(
|
||||
'button',
|
||||
{ type: 'button', class: 'dl-chip', title: fmt(_('Edit %s'), c.name), click: () => circleDialog(st, serverId, c, onDone) },
|
||||
[circleDot(c), E('b', {}, c.name), E('span', { class: 'dl-faint' }, who.length ? who.join(', ') : _('nobody yet'))],
|
||||
);
|
||||
}),
|
||||
E(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
class: 'dl-chip add',
|
||||
title: _('New circle'),
|
||||
'aria-label': _('New circle'),
|
||||
click: () => circleDialog(st, serverId, null, onDone),
|
||||
},
|
||||
icon('plus'),
|
||||
),
|
||||
]);
|
||||
}
|
||||
|
||||
/* ---------- Who reaches what ---------- */
|
||||
|
||||
export function whoReaches(st: Status, srv: Server): HTMLElement {
|
||||
const people = st.people.filter((p) => p.server === srv.id);
|
||||
const yes = (t = '') => E('span', { class: 'dl-yes' }, [icon('check'), t]);
|
||||
const no = () => E('span', { class: 'dl-faint' }, '—');
|
||||
const home = (list: Person[]) => {
|
||||
const kinds = new Set(list.map((p) => (p.access === 'lan' && p.services?.length ? 'services' : p.home_nets?.length ? 'some' : 'all')));
|
||||
if (!kinds.size) kinds.add('all');
|
||||
const label = { all: _('all networks'), some: _('their networks'), services: _('services') };
|
||||
return yes([...kinds].map((k) => label[k]).join(' / '));
|
||||
};
|
||||
const each = () => (srv.mesh === 'off' ? no() : srv.mesh === 'circles' ? yes(_('circle')) : yes());
|
||||
const net = srv.lan_like ? _('like home') : _('direct');
|
||||
const row = (label: string, list: Person[], cells: Node[]) =>
|
||||
E('tr', {}, [
|
||||
E('td', {}, [E('b', {}, label), E('div', { class: 'dl-sub' }, plural(list.length, '%s person', '%s people'))]),
|
||||
...cells.map((c) => E('td', {}, c)),
|
||||
]);
|
||||
const by = (a: string) => people.filter((p) => p.access === a);
|
||||
return E('section', { class: 'dl-setsec' }, [
|
||||
E('div', { class: 'dl-setsec-body' }, [
|
||||
E('div', { class: 'dl-panel-head' }, [
|
||||
E('h3', {}, _('Who reaches what')),
|
||||
E('span', { class: 'dl-spacer' }),
|
||||
E('span', { class: 'dl-sub' }, _('From the rules on this server')),
|
||||
]),
|
||||
E(
|
||||
'div',
|
||||
{ class: 'dl-reach-wrap' },
|
||||
E('table', { class: 'dl-table dl-reach' }, [
|
||||
E(
|
||||
'tr',
|
||||
{},
|
||||
['', _('Internet'), _('Home'), _('This router'), _('Each other')].map((t) => E('th', {}, t)),
|
||||
),
|
||||
row(_('Internet'), by('internet'), [yes(net), no(), E('span', { class: 'dl-faint' }, 'DNS'), no()]),
|
||||
row(_('Home'), by('lan'), [E('span', { class: 'dl-faint' }, _('their own')), home(by('lan')), yes(), each()]),
|
||||
row(_('Both'), by('both'), [yes(net), home(by('both')), yes(), each()]),
|
||||
]),
|
||||
),
|
||||
E(
|
||||
'p',
|
||||
{ class: 'dl-sub' },
|
||||
_(
|
||||
'Home devices reach the devices of people with home access, on the networks those people reach. Paused, ended and over-the-limit people reach nothing.',
|
||||
),
|
||||
),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
|
||||
/* ---------- Check access ---------- */
|
||||
|
||||
export function checkAccess(st: Status, srv: Server): HTMLElement {
|
||||
const devs = st.people
|
||||
.filter((p) => p.server === srv.id)
|
||||
.flatMap((p) => p.devices.map((d) => ({ id: d.id, label: `${p.name} · ${d.name}` })))
|
||||
.sort((a, b) => a.label.localeCompare(b.label));
|
||||
const ADDR = '@addr';
|
||||
/** A device, or an address typed in. */
|
||||
const end = (placeholder: string, initial: string) => {
|
||||
const sel = E('select', { class: 'cbi-input-select', 'aria-label': placeholder }, [
|
||||
...devs.map((d) => E('option', { value: d.id, selected: d.id === initial ? 'selected' : null }, d.label)),
|
||||
E('option', { value: ADDR, selected: initial === ADDR ? 'selected' : null }, _('Address')),
|
||||
]) as HTMLSelectElement;
|
||||
const addr = input('', { placeholder, class: 'cbi-input-text dl-mono' });
|
||||
const wrap = E('div', { class: 'dl-check-end' }, [sel, addr]);
|
||||
const sync = () => (addr.hidden = sel.value !== ADDR);
|
||||
sel.addEventListener('change', sync);
|
||||
sync();
|
||||
return { el: wrap, value: () => (sel.value === ADDR ? addr.value.trim() : sel.value) };
|
||||
};
|
||||
const from = end('10.0.1.11', devs[0]?.id ?? ADDR);
|
||||
const to = end('10.0.1.20:445', ADDR);
|
||||
const out = E('div', { class: 'dl-stack gap8' });
|
||||
const run = async () => {
|
||||
const r = await attempt(() => api.accessCheck(from.value(), to.value()));
|
||||
if (!r) return;
|
||||
const stop = r.steps.findIndex((s) => !s.ok);
|
||||
dom.content(out, [
|
||||
E('div', { class: `dl-verdict ${r.ok ? 'ok' : 'bad'}` }, [
|
||||
E('b', {}, r.ok ? _('Allowed') : _('Blocked')),
|
||||
E('span', { class: 'dl-sub' }, r.ok ? _('Every step lets it through') : fmt(_('Stops at step %s of %s'), stop + 1, r.steps.length)),
|
||||
]),
|
||||
E(
|
||||
'ul',
|
||||
{ class: 'dl-checks' },
|
||||
r.steps.map((s) =>
|
||||
E('li', {}, [
|
||||
E('span', { class: `dl-check-icon ${s.ok ? 'ok' : 'error'}` }, icon(s.ok ? 'check' : 'x')),
|
||||
E('div', { class: 'dl-check-body' }, [
|
||||
E('div', { class: 'dl-check-title' }, s.title),
|
||||
s.detail ? E('div', { class: 'dl-check-detail' }, s.detail) : '',
|
||||
]),
|
||||
]),
|
||||
),
|
||||
),
|
||||
]);
|
||||
};
|
||||
return E('section', { class: 'dl-setsec' }, [
|
||||
E('div', { class: 'dl-setsec-body' }, [
|
||||
E('div', { class: 'dl-panel-head' }, [
|
||||
E('h3', {}, _('Check access')),
|
||||
E('span', { class: 'dl-spacer' }),
|
||||
E('span', { class: 'dl-sub' }, _('Why something does or does not connect')),
|
||||
]),
|
||||
E('div', { class: 'dl-check-form' }, [from.el, E('span', { class: 'dl-faint' }, '→'), to.el, button(_('Check'), run)]),
|
||||
out,
|
||||
]),
|
||||
]);
|
||||
}
|
||||
+73
-52
@@ -1,4 +1,4 @@
|
||||
// luci.dawnline RPC bindings. The backend reports failures as { error }, and
|
||||
// The backend's RPC bindings (ubus object `dawnline`, the Go backend). The backend reports failures as { error }, and
|
||||
// a change the router saved but could not fully put into effect (access rules
|
||||
// that did not load, a server that refused its devices) as { warning }.
|
||||
|
||||
@@ -18,6 +18,7 @@ import type {
|
||||
} from '../shared/types';
|
||||
import { notify } from './ui/toast';
|
||||
import { lang } from '../shared/i18n';
|
||||
import { markWritten, streamMeter, streamStatus } from './state/stream';
|
||||
|
||||
/** Throw a backend failure; show a warning the answer carries. */
|
||||
function settle<T>(r: any): T {
|
||||
@@ -29,14 +30,26 @@ function settle<T>(r: any): T {
|
||||
}
|
||||
|
||||
/**
|
||||
* A method of luci.dawnline. The page's language goes last, after the
|
||||
* A method of the backend (`dawnline`). The page's language goes last, after the
|
||||
* method's own arguments: the router writes its messages in it.
|
||||
*/
|
||||
function call<T>(method: string, params: string[] = []) {
|
||||
const fn = rpc.declare<any>({ object: 'luci.dawnline', method, params: [...params, 'lang'] });
|
||||
return async (...args: unknown[]): Promise<T> => settle<T>(await fn(...params.map((_p, i) => args[i]), lang()));
|
||||
const declare = (object: string) => rpc.declare<any>({ object, method, params: [...params, 'lang'] });
|
||||
const here = declare('dawnline');
|
||||
return async (...args: unknown[]): Promise<T> => {
|
||||
try {
|
||||
return settle<T>(await here(...params.map((_p, i) => args[i]), lang()));
|
||||
} finally {
|
||||
// anything but a question may have changed what the stream shows: the next status is read after it
|
||||
if (!ASKS.test(method)) markWritten();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/** The methods that only ask. */
|
||||
const ASKS =
|
||||
/^(status|meter|rev|events|health|service_log|settings_get|portal_info|(server_)?interfaces|access_check|home_hosts|setup_defaults|endpoint_probe|person_(links|usage)|device_config|backup_(list|read)|export|updates_(status|releases|notes|changes))$/;
|
||||
|
||||
export interface SetupDefaults {
|
||||
id: string;
|
||||
name: string;
|
||||
@@ -111,11 +124,12 @@ export interface Meter {
|
||||
|
||||
/**
|
||||
* A device's own link values for device_update; left out = kept. Numbers go as text: '' = the server's, keep-alive
|
||||
* '0' = off. LAN Bypass stays as chosen when the device was added (the RPC takes it, the admin UI never changes it).
|
||||
* '0' = off. LAN Bypass: its own local network outside the tunnel (the device fetches its configuration again).
|
||||
*/
|
||||
export interface DeviceLinkPatch {
|
||||
mtu?: string;
|
||||
keepalive?: string;
|
||||
lan_bypass?: boolean;
|
||||
}
|
||||
|
||||
export interface Backup {
|
||||
@@ -310,7 +324,7 @@ interface LikeHome {
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export type IfaceCategory = 'wan' | 'ethernet' | 'wifi' | 'vpn' | 'other';
|
||||
type IfaceCategory = 'wan' | 'ethernet' | 'wifi' | 'vpn' | 'other';
|
||||
|
||||
export interface NetDevice {
|
||||
name: string;
|
||||
@@ -390,26 +404,11 @@ const logsClear = (f: LogFilter = {}) => logsClearRaw(f.person ?? '', f.device ?
|
||||
|
||||
/** Fields for person_update; send strings ('' clears an optional value). */
|
||||
export type PersonPatch = Partial<
|
||||
Record<
|
||||
| 'name'
|
||||
| 'access'
|
||||
| 'device_limit'
|
||||
| 'expires'
|
||||
| 'expire_action'
|
||||
| 'expire_warn'
|
||||
| 'quota_gb'
|
||||
| 'quota_period'
|
||||
| 'bonus_gb'
|
||||
| 'hours'
|
||||
| 'note'
|
||||
| 'dns_mode'
|
||||
| 'server',
|
||||
string
|
||||
>
|
||||
Record<'name' | 'access' | 'device_limit' | 'expires' | 'quota_gb' | 'quota_period' | 'bonus_gb' | 'note' | 'dns_mode' | 'server', string>
|
||||
> & { paused?: boolean; services?: string[]; circle?: string; home_nets?: string[] };
|
||||
|
||||
const personUpdateRaw = rpc.declare<any>({
|
||||
object: 'luci.dawnline',
|
||||
object: 'dawnline',
|
||||
method: 'person_update',
|
||||
params: [
|
||||
'id',
|
||||
@@ -417,12 +416,9 @@ const personUpdateRaw = rpc.declare<any>({
|
||||
'access',
|
||||
'device_limit',
|
||||
'expires',
|
||||
'expire_action',
|
||||
'expire_warn',
|
||||
'quota_gb',
|
||||
'quota_period',
|
||||
'bonus_gb',
|
||||
'hours',
|
||||
'note',
|
||||
'dns_mode',
|
||||
'paused',
|
||||
@@ -434,30 +430,42 @@ const personUpdateRaw = rpc.declare<any>({
|
||||
});
|
||||
|
||||
async function personUpdate(id: string, patch: PersonPatch): Promise<{ person: Person }> {
|
||||
const keys = [
|
||||
'name',
|
||||
'access',
|
||||
'device_limit',
|
||||
'expires',
|
||||
'expire_action',
|
||||
'expire_warn',
|
||||
'quota_gb',
|
||||
'quota_period',
|
||||
'bonus_gb',
|
||||
'hours',
|
||||
'note',
|
||||
'dns_mode',
|
||||
] as const;
|
||||
const keys = ['name', 'access', 'device_limit', 'expires', 'quota_gb', 'quota_period', 'bonus_gb', 'note', 'dns_mode'] as const;
|
||||
const args: unknown[] = [id, ...keys.map((k) => patch[k]), patch.paused, patch.services, patch.circle, patch.home_nets, patch.server];
|
||||
return settle(await personUpdateRaw(...args));
|
||||
try {
|
||||
return settle(await personUpdateRaw(...args));
|
||||
} finally {
|
||||
markWritten();
|
||||
}
|
||||
}
|
||||
|
||||
const status = call<Status>('status', ['days']);
|
||||
/** One person's changes in a people_update list. */
|
||||
export interface PeopleChange {
|
||||
id: string;
|
||||
patch: Pick<PersonPatch, 'expires' | 'bonus_gb' | 'quota_gb' | 'device_limit'> & {
|
||||
paused?: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
const deviceUpdateRaw = call<unknown>('device_update', ['id', 'name', 'disabled', 'mtu', 'keepalive']);
|
||||
/**
|
||||
* From the backend's stream (state/stream.ts: the backend reads the router once for every open tab, when
|
||||
* something changed). The stream's status holds the longest history a page asks for; one that asked for
|
||||
* fewer days gets more. A backend that does not answer yet (it is starting, or was just restarted) is waited
|
||||
* for a quarter of a minute; then the page says so, and fills in when it does.
|
||||
*/
|
||||
const status = async (_days: number): Promise<Status> => {
|
||||
for (let i = 0; i < 6; i++) {
|
||||
const st = await streamStatus();
|
||||
if (st) return st;
|
||||
await new Promise((done) => setTimeout(done, 2500));
|
||||
}
|
||||
throw new Error(_('Dawnline is starting on the router: this page fills in when it answers.'));
|
||||
};
|
||||
|
||||
const deviceUpdateRaw = call<unknown>('device_update', ['id', 'name', 'disabled', 'mtu', 'keepalive', 'lan_bypass']);
|
||||
/** Rename, turn off or on, or change how a device connects; what is undefined stays as it is. */
|
||||
const deviceUpdate = (id: string, name?: string, disabled?: boolean, link: DeviceLinkPatch = {}) =>
|
||||
deviceUpdateRaw(id, name, disabled, link.mtu, link.keepalive);
|
||||
deviceUpdateRaw(id, name, disabled, link.mtu, link.keepalive, link.lan_bypass);
|
||||
|
||||
/** One line of the service log: tunnel and service starts, stops, watchdog repairs, errors. */
|
||||
export interface ServiceLogEntry {
|
||||
@@ -472,6 +480,8 @@ export interface ServiceLogEntry {
|
||||
by?: 'admin';
|
||||
kind?: string;
|
||||
note?: string;
|
||||
/** The server an admin's change was made on (older entries have only its name, in `who`). */
|
||||
sid?: string;
|
||||
}
|
||||
|
||||
export interface ServiceLog {
|
||||
@@ -491,9 +501,9 @@ export interface ServiceLog {
|
||||
export type Health = { checks: HealthCheck[] } & ServiceLog;
|
||||
|
||||
export const api = {
|
||||
rev: call<{ rev: number; version?: string }>('rev'),
|
||||
/** The live meter's points newer than `since` (0: all); polled while the Overview shows it. */
|
||||
meter: call<Meter>('meter', ['since']),
|
||||
meter: async (since: number): Promise<Meter> =>
|
||||
(await streamMeter(since)) ?? { now: Date.now() / 1000, want: 10, keep: 120, ts: since, points: [] },
|
||||
personUpdate,
|
||||
settingsGet: call<SettingsData>('settings_get'),
|
||||
portalInfo: call<PortalInfo>('portal_info'),
|
||||
@@ -501,8 +511,8 @@ export const api = {
|
||||
serviceSet: call<{ id: string }>('service_set', ['id', 'name', 'address', 'ports']),
|
||||
serviceDelete: call<unknown>('service_delete', ['id']),
|
||||
geoClear: call<unknown>('geo_clear'),
|
||||
/** The newest `limit` events; a person's only, or only those after `since` (a ts), when given. */
|
||||
events: call<{ events: LogEvent[]; total: number; policy: LogsInfo['policy'] }>('events', ['limit', 'person', 'since']),
|
||||
/** The newest `limit` events; a person's or a device's only, or only those after `since` (a ts), when given. */
|
||||
events: call<{ events: LogEvent[]; total: number; policy: LogsInfo['policy'] }>('events', ['limit', 'person', 'since', 'device']),
|
||||
logsClear,
|
||||
interfaces: call<InterfacesData>('interfaces', ['id']),
|
||||
serverInterfaces: call<InterfacesData>('server_interfaces', [
|
||||
@@ -558,17 +568,28 @@ export const api = {
|
||||
'quota_period',
|
||||
]),
|
||||
personPause: call<unknown>('person_pause', ['id', 'paused']),
|
||||
/** Several people at once, all or nothing (one transaction, one apply): People's picks and their undo. */
|
||||
peopleUpdate: call<{ changed: number }>('people_update', ['list']) as (list: PeopleChange[]) => Promise<{ changed: number }>,
|
||||
/** A new link; `remove` lists devices (ids) to take away with the old one. */
|
||||
personRegen: call<{ link: string | null; removed: number }>('person_regen', ['id', 'remove']),
|
||||
personDelete: call<unknown>('person_delete', ['id']),
|
||||
personUsage: call<{ person: DayUsage[]; devices: Record<string, DayUsage[]> }>('person_usage', ['id', 'days']),
|
||||
/** A new device; `lan_bypass` (true) keeps its own local network outside the tunnel. */
|
||||
deviceCreate: call<{ id: string; config: ClientConfig }>('device_create', ['person', 'name', 'kind', 'lan_bypass']),
|
||||
/** A device's configuration; `issue` (true) when it goes to the device as a code, a file or a key: only that clears "Update config". */
|
||||
deviceConfig: call<ClientConfig>('device_config', ['id', 'issue']),
|
||||
/** `networks`: what stands behind a new router, its own from the start. */
|
||||
deviceCreate: call<{ id: string; config: ClientConfig }>('device_create', ['person', 'name', 'kind', 'lan_bypass', 'networks']),
|
||||
/** The networks behind a router, all of them at once; the router applies everything (its routes move). */
|
||||
deviceNetworks: call<{ networks: string[] }>('device_networks', ['id', 'networks']),
|
||||
/**
|
||||
* The answer to what a router's owner asked for on their own page: `accept` or `decline` (with a reason they
|
||||
* read), for the networks named or for all that is asked; `reopen` puts the question back (the undo of either).
|
||||
*/
|
||||
deviceAnswer: call<unknown>('device_answer', ['id', 'answer', 'reason', 'router', 'networks']),
|
||||
/** A device's configuration, to show it; showing marks nothing as given out (that is the portal's fetch, a new device, new keys). */
|
||||
deviceConfig: call<ClientConfig>('device_config', ['id']),
|
||||
deviceUpdate,
|
||||
deviceDelete: call<unknown>('device_delete', ['id']),
|
||||
deviceRotate: call<ClientConfig>('device_rotate', ['id']),
|
||||
/** New keys: the device is set up again; `kind` and `lan_bypass` (asked again) change with them when given. */
|
||||
deviceRotate: call<ClientConfig>('device_rotate', ['id', 'kind', 'lan_bypass']),
|
||||
apply: call<unknown>('apply'),
|
||||
health: call<Health>('health'),
|
||||
healthFix: call<Health>('health_fix', ['id']),
|
||||
|
||||
@@ -1,564 +0,0 @@
|
||||
// The AmneziaWG core in the admin: how a device connects (.conf, AmneziaVPN
|
||||
// key, QR, V2RayTun's link), the disguise and its parameters, and the core's own settings on
|
||||
// Server → AmneziaWG. Plain WireGuard is AmneziaWG with the disguise off.
|
||||
|
||||
import type { AwgConfig, Kind, Server, Status } from '../../shared/types';
|
||||
import { E } from '../e';
|
||||
import { api } from '../api';
|
||||
import { button } from '../ui/button';
|
||||
import { confirmDialog } from '../ui/modal';
|
||||
import { copyText, downloadFile } from '../ui/files';
|
||||
import { attempt, notify } from '../ui/toast';
|
||||
import { input } from '../ui/controls';
|
||||
import { callout, card, firstBad, group, liveRow, row } from '../ui/layout';
|
||||
import { qrCode } from '../ui/qr';
|
||||
import { keepaliveHelp, mtuHelp, portHelp, type PortHold } from '../netcheck';
|
||||
import { vpnKey } from '../../shared/vpnkey';
|
||||
import { awgLink, v2rFits } from '../../shared/awglink';
|
||||
import { V2R_WINDOWS } from '../../shared/flags';
|
||||
import { icon } from '../../shared/icons';
|
||||
import { methodInfo, methodPicker, type Method, defaultMethod, legacyTitle } from '../disguise';
|
||||
import { fmt, fill, num, plural } from '../../shared/i18n';
|
||||
import { coreHead, type ConnectView, type Core, type CoreCtx } from './common';
|
||||
|
||||
/** `.conf` names of the disguise parameters, in file order. */
|
||||
const CONF: [string, string][] = [
|
||||
['jc', 'Jc'],
|
||||
['jmin', 'Jmin'],
|
||||
['jmax', 'Jmax'],
|
||||
['s1', 'S1'],
|
||||
['s2', 'S2'],
|
||||
['s3', 'S3'],
|
||||
['s4', 'S4'],
|
||||
['h1', 'H1'],
|
||||
['h2', 'H2'],
|
||||
['h3', 'H3'],
|
||||
['h4', 'H4'],
|
||||
['i1', 'I1'],
|
||||
['i2', 'I2'],
|
||||
['i3', 'I3'],
|
||||
['i4', 'I4'],
|
||||
['i5', 'I5'],
|
||||
['header_protection_key', 'HeaderProtectionKey'],
|
||||
['content_padding_addition', 'ContentPaddingAddition'],
|
||||
['rekey_after_time', 'RekeyAfterTime'],
|
||||
['rekey_timeout', 'RekeyTimeout'],
|
||||
['reject_after_time', 'RejectAfterTime'],
|
||||
['keepalive_timeout', 'KeepaliveTimeout'],
|
||||
['max_handshake_attempts', 'MaxHandshakeAttempts'],
|
||||
['random_trailers', 'RandomTrailers'],
|
||||
['disable_cookies', 'DisableCookies'],
|
||||
];
|
||||
|
||||
/**
|
||||
* The applied parameters, grouped by what they do, with a plain-language
|
||||
* line per group. Collapsed by default; copyable as config lines. The header
|
||||
* protection key stays out of the status (read-only users can read it): the
|
||||
* view says there is one, and each device's file has it.
|
||||
*/
|
||||
function paramsView(o: Record<string, string>, hpk: boolean): HTMLElement | null {
|
||||
const has = (k: string) => (k === 'header_protection_key' ? hpk : o[k] != null && o[k] !== '');
|
||||
const keys = CONF.filter(([k]) => has(k));
|
||||
if (!keys.length) return null;
|
||||
const val = (k: string, name: string) =>
|
||||
E('span', { class: 'dl-pv' }, [E('i', {}, name), E('b', {}, k === 'header_protection_key' ? _('set', 'key') : o[k])]);
|
||||
const group = (title: string, ic: string, text: string, ks: string[]) => {
|
||||
const present = CONF.filter(([k]) => ks.includes(k) && has(k));
|
||||
return present.length
|
||||
? E('div', { class: 'dl-pgroup' }, [
|
||||
E('div', { class: 'dl-pgroup-head' }, [icon(ic), E('b', {}, title)]),
|
||||
E('p', {}, text),
|
||||
E(
|
||||
'div',
|
||||
{ class: 'dl-pvals' },
|
||||
present.map(([k, n]) => val(k, n)),
|
||||
),
|
||||
])
|
||||
: '';
|
||||
};
|
||||
const jc = Number(o.jc || 0);
|
||||
const signature = (o.i1 ?? '').includes('0x8580')
|
||||
? _('A first packet shaped like a DNS answer.')
|
||||
: _('Extra packets sent before the handshake.');
|
||||
const conf = keys
|
||||
.filter(([k]) => k !== 'header_protection_key')
|
||||
.map(([k, n]) => `${n} = ${o[k]}`)
|
||||
.join('\n');
|
||||
const body = E('div', { class: 'dl-pgrid' }, [
|
||||
group(
|
||||
_('Junk packets'),
|
||||
'zap',
|
||||
jc
|
||||
? fmt(
|
||||
N_(jc, '%s random packet of %s–%s bytes before each handshake.', '%s random packets of %s–%s bytes before each handshake.'),
|
||||
num(jc),
|
||||
o.jmin,
|
||||
o.jmax,
|
||||
)
|
||||
: _('No junk packets.'),
|
||||
['jc', 'jmin', 'jmax'],
|
||||
),
|
||||
group(
|
||||
_('Padding'),
|
||||
'archive',
|
||||
_('Random bytes in front of handshake, cookie and data packets, so their sizes do not match WireGuard.'),
|
||||
['s1', 's2', 's3', 's4'],
|
||||
),
|
||||
group(_('Packet types'), 'key', _('The values that replace WireGuard’s recognisable message types.'), ['h1', 'h2', 'h3', 'h4']),
|
||||
group(_('Signatures'), 'globe', signature, ['i1', 'i2', 'i3', 'i4', 'i5']),
|
||||
group(_('Protection'), 'lock', _('AmneziaWG 3.1: encrypted headers, random tails and extra padding on data packets.'), [
|
||||
'header_protection_key',
|
||||
'content_padding_addition',
|
||||
'random_trailers',
|
||||
'disable_cookies',
|
||||
]),
|
||||
group(_('Timing'), 'clock', _('Handshake and key timers vary within these ranges instead of WireGuard’s fixed values.'), [
|
||||
'rekey_after_time',
|
||||
'rekey_timeout',
|
||||
'reject_after_time',
|
||||
'keepalive_timeout',
|
||||
'max_handshake_attempts',
|
||||
]),
|
||||
]);
|
||||
return E('details', { class: 'dl-params' }, [
|
||||
E('summary', {}, [
|
||||
icon('chevron'),
|
||||
E('span', {}, _('Current parameters')),
|
||||
E('span', { class: 'dl-pcount' }, String(keys.length)),
|
||||
E('span', { class: 'dl-spacer' }),
|
||||
E(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
class: 'dl-linkbtn',
|
||||
click: (ev: Event) => {
|
||||
ev.preventDefault();
|
||||
copyText(conf, hpk ? _('Parameters copied. The header protection key is in each device’s file.') : _('Parameters copied'));
|
||||
},
|
||||
},
|
||||
_('Copy as config'),
|
||||
),
|
||||
]),
|
||||
body,
|
||||
]);
|
||||
}
|
||||
|
||||
/** One configuration line, highlighted; private and preshared keys masked unless shown. */
|
||||
function confLine(line: string, reveal: boolean): Node {
|
||||
if (/^\s*\[.+\]\s*$/.test(line)) return E('span', { class: 'dl-conf-sec' }, line);
|
||||
const m = /^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(line);
|
||||
if (!m) return document.createTextNode(line);
|
||||
const secret = /^(\s*)(PrivateKey|PresharedKey)\b/.test(line);
|
||||
return E('span', {}, [
|
||||
E('span', { class: 'dl-conf-k' }, m[1]),
|
||||
' ',
|
||||
secret && !reveal ? E('span', { class: 'dl-conf-mask' }, '••••••••••••••••') : m[2],
|
||||
]);
|
||||
}
|
||||
|
||||
/** The .conf as a file card (download) and a folded, highlighted view with copy and a hidden key. */
|
||||
function fileCard(cfg: AwgConfig): HTMLElement {
|
||||
let reveal = false;
|
||||
const pre = E('pre', { class: 'dl-conf' });
|
||||
const paint = () =>
|
||||
dom.content(
|
||||
pre,
|
||||
cfg.conf.split('\n').flatMap((l, i) => (i ? ['\n', confLine(l, reveal)] : [confLine(l, reveal)])),
|
||||
);
|
||||
const eye = E(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
class: 'dl-chipbtn',
|
||||
click: (ev: Event) => {
|
||||
ev.preventDefault();
|
||||
reveal = !reveal;
|
||||
dom.content(eye, [icon(reveal ? 'x' : 'key'), reveal ? _('Hide key') : _('Show key')]);
|
||||
paint();
|
||||
},
|
||||
},
|
||||
[icon('key'), _('Show key')],
|
||||
);
|
||||
paint();
|
||||
const size = new Blob([cfg.conf]).size;
|
||||
return E('div', { class: 'dl-stack gap8' }, [
|
||||
E('div', { class: 'dl-filecard' }, [
|
||||
E('span', { class: 'dl-filecard-ic' }, '.conf'),
|
||||
E('span', { class: 'dl-stack' }, [
|
||||
E('span', { class: 'dl-mono dl-ellipsis' }, cfg.filename),
|
||||
E('span', { class: 'dl-sub' }, `AmneziaWG · ${plural(size, '%s byte', '%s bytes')}`),
|
||||
]),
|
||||
button([icon('download'), ' ', _('Download')], () => downloadFile(cfg.filename, cfg.conf, 'application/octet-stream'), 'positive'),
|
||||
]),
|
||||
E('details', { class: 'dl-params' }, [
|
||||
E('summary', {}, [
|
||||
icon('chevron'),
|
||||
E('span', {}, _('Configuration')),
|
||||
E('span', { class: 'dl-spacer' }),
|
||||
eye,
|
||||
E(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
class: 'dl-chipbtn',
|
||||
click: (ev: Event) => {
|
||||
ev.preventDefault();
|
||||
copyText(cfg.conf, _('Configuration copied'));
|
||||
},
|
||||
},
|
||||
[icon('copy'), _('Copy')],
|
||||
),
|
||||
]),
|
||||
pre,
|
||||
]),
|
||||
]);
|
||||
}
|
||||
|
||||
/** The configuration carries no disguise values: plain WireGuard, any WireGuard app takes it. */
|
||||
export function plainWg(cfg: AwgConfig): boolean {
|
||||
const o = (cfg.amnezia.obfuscation ?? {}) as Record<string, string | undefined>;
|
||||
const neutral: Record<string, string> = { h1: '1', h2: '2', h3: '3', h4: '4' };
|
||||
return Object.entries(o).every(([k, v]) => v == null || v === '' || v === (neutral[k] ?? '0'));
|
||||
}
|
||||
|
||||
/**
|
||||
* V2RayTun's way in: the connection as its awg:// link (shared/awglink.ts;
|
||||
* the app's own words are in portal/setup.ts, with where they come from). A
|
||||
* computer runs it on Windows, whose core looks the server's name up itself:
|
||||
* the link keeps the name. That one is off for now (shared/flags.ts
|
||||
* V2R_WINDOWS: its core leaves the server's DNS unused). Anything else is
|
||||
* taken for Android, whose core takes no name: the link has the server's IP
|
||||
* (amnezia.host_ip, from device_config).
|
||||
*/
|
||||
function v2rPane(cfg: AwgConfig, kind: Kind): HTMLElement {
|
||||
const win = kind === 'computer';
|
||||
const host = cfg.amnezia.host.replace(/^\[(.*)\]$/, '$1');
|
||||
const ip = win ? null : (cfg.amnezia.host_ip ?? null);
|
||||
const link = awgLink(cfg.conf, cfg.server, ip);
|
||||
const box = E('div', { class: 'dl-linkbox' }, [
|
||||
E('span', { class: 'dl-mono', title: link }, link),
|
||||
button(_('Copy'), () => copyText(link, _('Link copied'))),
|
||||
]);
|
||||
if (win)
|
||||
return E('div', { class: 'dl-stack gap8' }, [
|
||||
box,
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-sub' },
|
||||
fmt(
|
||||
_(
|
||||
'V2RayTun on Windows: %s, then set its mode to %s and connect. That mode needs administrator rights: the app offers to restart with them.',
|
||||
),
|
||||
['+', _('Import from clipboard', 'V2RayTun app')].join(' → '),
|
||||
_('Tunnel', 'V2RayTun app'),
|
||||
),
|
||||
),
|
||||
]);
|
||||
return E('div', { class: 'dl-qr-pane' }, [
|
||||
qrCode(link),
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-sub' },
|
||||
fmt(
|
||||
_('V2RayTun on Android: %s, or copy the link and %s.'),
|
||||
['+', _('Import config from QRcode', 'V2RayTun app')].join(' → '),
|
||||
['+', _('Import config from Clipboard', 'V2RayTun app')].join(' → '),
|
||||
),
|
||||
),
|
||||
box,
|
||||
// Honest about what the IP costs, and about a name that gives none.
|
||||
ip && ip !== host
|
||||
? E(
|
||||
'div',
|
||||
{ class: 'dl-hint' },
|
||||
_('The link has the server’s IP address, not its name: if the address changes, set the device up again.'),
|
||||
)
|
||||
: !ip
|
||||
? callout('warn', fmt(_('%s does not resolve right now, and V2RayTun on Android connects by IP address only.'), host))
|
||||
: '',
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* File / key / QR / V2RayTun switcher for a client configuration of a device
|
||||
* of this kind; opens on the file unless asked otherwise. V2RayTun is left out
|
||||
* for a router, for a computer while V2R_WINDOWS is off (shared/flags.ts) and
|
||||
* for AmneziaWG 3.1 (the Maximum disguise), which it lacks.
|
||||
*/
|
||||
async function connectBlock(cfg: AwgConfig, kind: Kind, initial: ConnectView = 'file'): Promise<HTMLElement> {
|
||||
if (!cfg.has_private_key)
|
||||
return E(
|
||||
'div',
|
||||
{ class: 'dl-hint' },
|
||||
_('This device generated its own keys in the browser, so its full configuration only exists on that device.'),
|
||||
);
|
||||
const key = await vpnKey(cfg, cfg.server);
|
||||
const panes: Partial<Record<ConnectView, () => Node>> = {
|
||||
qr: () =>
|
||||
E('div', { class: 'dl-qr-pane' }, [
|
||||
qrCode(cfg.conf),
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-sub' },
|
||||
plainWg(cfg)
|
||||
? _('Scan with AmneziaVPN or any WireGuard app on the device.')
|
||||
: _('Scan with AmneziaVPN or AmneziaWG on the device.'),
|
||||
),
|
||||
]),
|
||||
key: () =>
|
||||
E('div', { class: 'dl-stack gap8' }, [
|
||||
E('div', { class: 'dl-linkbox' }, [E('span', { class: 'dl-mono' }, key), button(_('Copy'), () => copyText(key, _('Key copied')))]),
|
||||
// The app's own labels (portal/setup.ts has where they come from): + in its bottom bar, Insert, Continue.
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-sub' },
|
||||
fmt(_('AmneziaVPN → %s. Keep it private.'), ['+', _('Insert', 'AmneziaVPN app'), _('Continue', 'AmneziaVPN app')].join(' → ')),
|
||||
),
|
||||
]),
|
||||
file: () => fileCard(cfg),
|
||||
};
|
||||
if (kind !== 'router' && (kind !== 'computer' || V2R_WINDOWS) && v2rFits(cfg.conf)) panes.v2r = () => v2rPane(cfg, kind);
|
||||
const labels: [ConnectView, string][] = [
|
||||
['file', _('File')],
|
||||
['key', _('Key')],
|
||||
['qr', _('QR code')],
|
||||
['v2r', 'V2RayTun'],
|
||||
];
|
||||
const body = E('div', { class: 'dl-connect-body' });
|
||||
const seg = E('div', { class: 'dl-seg' });
|
||||
const show = (id: ConnectView) => {
|
||||
seg.querySelectorAll('button').forEach((b) => b.classList.toggle('on', b.dataset.id === id));
|
||||
dom.content(body, panes[id]!());
|
||||
};
|
||||
for (const [id, label] of labels)
|
||||
if (panes[id]) seg.appendChild(E('button', { type: 'button', 'data-id': id, click: () => show(id) }, label));
|
||||
show(panes[initial] ? initial : 'file');
|
||||
return E('div', { class: 'dl-stack gap12' }, [seg, body]);
|
||||
}
|
||||
|
||||
/** Switch the disguise (every device imports its configuration again). */
|
||||
async function applyDisguise(ctx: CoreCtx, srv: Server, m: Method, same: boolean) {
|
||||
const info = methodInfo(m)!;
|
||||
const people = ctx.st.people.filter((p) => p.server === srv.id);
|
||||
const devices = people.reduce((n, p) => n + p.devices.length, 0);
|
||||
const ok = await confirmDialog(
|
||||
same ? _('Generate new disguise values?') : fmt(_('Switch to %s?'), info.title),
|
||||
[
|
||||
plural(
|
||||
devices,
|
||||
'%s AmneziaWG device stops connecting until it imports its configuration again (from their personal link or from you).',
|
||||
'%s AmneziaWG devices stop connecting until they import their configuration again (from their personal link or from you).',
|
||||
),
|
||||
m === 'max' ? _('They need an app with AmneziaWG 3.1.') : m === 'balanced' ? _('They need an app with AmneziaWG 2.0 or newer.') : '',
|
||||
ctx.st.servers.length === 1 && devices ? _('To keep the old disguise for some people, add a second server and move them there.') : '',
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' '),
|
||||
same ? _('Generate and apply') : _('Switch and apply'),
|
||||
true,
|
||||
);
|
||||
if (!ok) return;
|
||||
if (await attempt(() => api.serverObfuscation(srv.id, m), same ? _('New values applied') : fmt(_('%s applied'), info.title))) {
|
||||
notify(_('Devices are marked “Update config” until they import again.'), 'info', 6000);
|
||||
await ctx.refresh();
|
||||
}
|
||||
}
|
||||
|
||||
/** Server → AmneziaWG: listening port, what goes into every configuration, disguise, tunnel. */
|
||||
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(srv.mtu ? String(srv.mtu) : '', {
|
||||
placeholder: _('Auto'),
|
||||
inputmode: 'numeric',
|
||||
class: 'cbi-input-text dl-w-port dl-mono',
|
||||
});
|
||||
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 ?? defaultMethod(st.awg);
|
||||
const apply = button('', () => applyDisguise(ctx, srv, selected, selected === current), 'neutral');
|
||||
const label = () =>
|
||||
dom.content(
|
||||
apply,
|
||||
selected === current ? [icon('reset'), ' ', _('Generate new values')] : [fmt(_('Switch to %s'), methodInfo(selected)!.title)],
|
||||
);
|
||||
label();
|
||||
const tools = st.awg_state?.tools !== false;
|
||||
// Who holds which port arrives once the card is built (netstat on the
|
||||
// router); until then the port is only checked for its range.
|
||||
let holds: PortHold[] = [];
|
||||
const portRow = liveRow(_('UDP port'), port, () =>
|
||||
portHelp(
|
||||
Number(port.value),
|
||||
holds,
|
||||
[
|
||||
_('Opened on the WAN firewall automatically.'),
|
||||
Number(port.value) === 4500 ? _('4500 is IPsec’s port: most networks let it through.') : '',
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' '),
|
||||
),
|
||||
);
|
||||
api
|
||||
.serverPorts(srv.id)
|
||||
.then((r) => {
|
||||
holds = r.udp_taken ?? [];
|
||||
portRow.refresh();
|
||||
})
|
||||
.catch(() => {});
|
||||
const mtuRow = liveRow('MTU', mtu, () => mtuHelp(mtu.value, srv.mtus));
|
||||
const kaRow = liveRow(_('Keep-alive'), ka, () => keepaliveHelp(ka.value));
|
||||
return card(
|
||||
'',
|
||||
[
|
||||
coreHead('AmneziaWG', srv.ifname),
|
||||
group('globe', _('Listening'), _('Where devices reach this core from the internet'), [portRow]),
|
||||
group('file', _('In every device configuration'), _('Changing these marks devices “Update config” until they import again'), [
|
||||
mtuRow,
|
||||
kaRow,
|
||||
]),
|
||||
group('shield', _('Disguise'), _('So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard'), [
|
||||
// A server from before 0.8 on the old junk-only disguise: it runs, but is no longer offered.
|
||||
legacyTitle(srv.preset)
|
||||
? callout(
|
||||
'warn',
|
||||
fill(
|
||||
_(
|
||||
'%s is AmneziaWG 1.0 junk only, which networks learned to spot; it is not offered any more. Switch to %s or %s: devices import their configuration again.',
|
||||
),
|
||||
E('b', {}, legacyTitle(srv.preset)!),
|
||||
E('b', {}, _('Balanced')),
|
||||
E('b', {}, _('Maximum')),
|
||||
),
|
||||
)
|
||||
: '',
|
||||
methodPicker(
|
||||
st.awg,
|
||||
selected,
|
||||
(m) => {
|
||||
selected = m;
|
||||
label();
|
||||
},
|
||||
current,
|
||||
tools,
|
||||
),
|
||||
// Only about an installed AmneziaWG: without one the server page says what to install.
|
||||
tools && !st.awg.v3
|
||||
? callout(
|
||||
'info',
|
||||
fill(
|
||||
_('This router runs an older AmneziaWG. %s becomes available with kmod-amneziawg and amneziawg-tools 3.1.'),
|
||||
E('b', {}, _('Maximum')),
|
||||
),
|
||||
)
|
||||
: '',
|
||||
paramsView(srv.obf ?? {}, srv.hpk) ?? '',
|
||||
E('div', { class: 'dl-row-end' }, [
|
||||
E('span', { class: 'dl-sub' }, _('Applies at once: every AmneziaWG device imports its configuration again.')),
|
||||
apply,
|
||||
]),
|
||||
]),
|
||||
E('details', { class: 'dl-params' }, [
|
||||
E('summary', {}, [icon('chevron'), E('span', {}, _('Tunnel')), E('span', { class: 'dl-pcount' }, '3')]),
|
||||
E('div', { class: 'dl-params-body' }, [
|
||||
row(_('Interface'), E('span', { class: 'dl-mono' }, `${srv.ifname} · ${fmt(_('router %s'), srv.address)}`)),
|
||||
row(_('Tunnel subnet'), E('span', { class: 'dl-mono' }, srv.subnet), _('Device addresses come from it.')),
|
||||
row(
|
||||
_('Server public key'),
|
||||
E('span', { class: 'dl-keyrow' }, [
|
||||
E('code', { class: 'dl-mono' }, srv.public_key),
|
||||
button([icon('copy')], () => copyText(srv.public_key, _('Public key copied')), 'neutral', {
|
||||
title: _('Copy'),
|
||||
class: 'cbi-button cbi-button-neutral dl-icon-only sm',
|
||||
}),
|
||||
]),
|
||||
),
|
||||
]),
|
||||
]),
|
||||
],
|
||||
[
|
||||
E('span', { class: 'dl-sub' }, _('Port, MTU and keep-alive apply at once.')),
|
||||
button(
|
||||
_('Save'),
|
||||
() => {
|
||||
// The help lines already say what is wrong: do not send it anyway.
|
||||
const bad = firstBad([portRow, mtuRow, kaRow]);
|
||||
if (bad) {
|
||||
notify(bad, 'warning');
|
||||
return;
|
||||
}
|
||||
return ctx.save({ port: port.value, mtu: mtu.value, keepalive: ka.value }, _('AmneziaWG saved'));
|
||||
},
|
||||
'positive',
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/** Overview: the disguise in use, its stealth and speed, and the values devices carry in words. */
|
||||
function overviewTile(srv: Server): HTMLElement {
|
||||
const m = methodInfo(srv.preset);
|
||||
const o = srv.obf ?? {};
|
||||
const segs = (n: number, cls: string) =>
|
||||
E(
|
||||
'span',
|
||||
{ class: `dl-segs ${cls}` },
|
||||
[0, 1, 2, 3].map((i) => E('i', { class: i < n ? 'on' : '' })),
|
||||
);
|
||||
const chips: string[] = [];
|
||||
if (+o.jc) chips.push(`${plural(+o.jc, '%s junk', '%s junk')} · ${o.jmin}–${o.jmax} ${_('B')}`);
|
||||
const pad = ['s1', 's2', 's3', 's4'].filter((k) => +o[k]).map((k) => `${k.toUpperCase()} ${o[k]}`);
|
||||
if (pad.length) chips.push(pad.slice(0, 2).join(' · ') + (pad.length > 2 ? ` +${pad.length - 2}` : ''));
|
||||
if (['h1', 'h2', 'h3', 'h4'].some((k) => o[k] && o[k] !== String(['h1', 'h2', 'h3', 'h4'].indexOf(k) + 1))) chips.push(_('H1–H4 random'));
|
||||
if (o.i1) chips.push(/0x(8580|0100)0001/.test(o.i1) ? _('DNS-like first packets') : _('Signature packets'));
|
||||
if (srv.hpk) chips.push(_('Encrypted headers'));
|
||||
if (!chips.length) chips.push(m?.id === 'off' ? _('Plain WireGuard') : _('No values yet'));
|
||||
return E('div', { class: 'dl-bento-tile dl-disg' }, [
|
||||
E('div', { class: 'dl-bento-head' }, [
|
||||
E('span', { class: 'dl-metric-label' }, _('Disguise')),
|
||||
E('a', { href: `${L.url('admin/services/dawnline/server')}?server=${encodeURIComponent(srv.id)}§ion=awg` }, _('Change')),
|
||||
]),
|
||||
E('div', { class: 'dl-disg-id' }, [
|
||||
E('span', { class: `dl-disg-ic${m?.id === 'off' ? ' off' : ''}` }, icon(m?.ic ?? 'shield')),
|
||||
E('span', { class: 'dl-stack' }, [
|
||||
E('b', {}, m ? m.title : (legacyTitle(srv.preset) ?? _('Custom', 'disguise'))),
|
||||
E('span', { class: 'dl-sub' }, m ? m.short : legacyTitle(srv.preset) ? _('Switch to Balanced or Maximum') : _('Set by hand')),
|
||||
]),
|
||||
]),
|
||||
m
|
||||
? E('div', { class: 'dl-disg-meters' }, [
|
||||
E('span', {}, _('Stealth')),
|
||||
segs(m.stealth, 'acc'),
|
||||
E('span', {}, _('Speed')),
|
||||
segs(m.speed, 'ok'),
|
||||
])
|
||||
: '',
|
||||
E(
|
||||
'div',
|
||||
{ class: 'dl-disg-chips' },
|
||||
chips.map((c) => E('span', {}, c)),
|
||||
),
|
||||
]);
|
||||
}
|
||||
|
||||
export const awg: Core = {
|
||||
id: 'awg',
|
||||
label: 'AmneziaWG',
|
||||
settingsCard,
|
||||
overviewTile,
|
||||
connectBlock,
|
||||
qrText: (cfg) => cfg.conf,
|
||||
// Labels are getters: the text is made when a menu is drawn.
|
||||
appKey: {
|
||||
get label() {
|
||||
return _('Copy AmneziaVPN config');
|
||||
},
|
||||
make: (cfg) => vpnKey(cfg, cfg.server),
|
||||
},
|
||||
file: {
|
||||
get label() {
|
||||
return _('Download AmneziaWG config');
|
||||
},
|
||||
make: (cfg) => ({ name: cfg.filename, text: cfg.conf }),
|
||||
},
|
||||
};
|
||||
@@ -1,40 +0,0 @@
|
||||
// What every tunnel core gives the admin (cores/index.ts holds the registry),
|
||||
// what a core's settings card gets from the Server page, and that card's head.
|
||||
|
||||
import type { ClientConfig, Kind, Server, Status } from '../../shared/types';
|
||||
import { E } from '../e';
|
||||
|
||||
/** The ways a device takes its configuration, as the set-up switcher names them. */
|
||||
export type ConnectView = 'file' | 'key' | 'qr' | 'v2r';
|
||||
|
||||
/** What the Server page hands a core's settings card. */
|
||||
export interface CoreCtx {
|
||||
st: Status;
|
||||
/** server_update with these values, then refresh. */
|
||||
save: (values: Record<string, unknown>, ok?: string) => Promise<void>;
|
||||
refresh: () => Promise<void>;
|
||||
}
|
||||
|
||||
/** A tunnel core (AmneziaWG today): its name and the pieces of the admin that differ per core. */
|
||||
export interface Core {
|
||||
id: string;
|
||||
/** "AmneziaWG": the server section, the address bar, the settings card. */
|
||||
label: string;
|
||||
/** Server → <label>: the core's own settings. */
|
||||
settingsCard(ctx: CoreCtx, srv: Server): HTMLElement;
|
||||
/** Overview: how the tunnel looks on the wire (the disguise tile). */
|
||||
overviewTile(srv: Server): HTMLElement;
|
||||
/** How a device of this kind connects: file / key / QR / V2RayTun's link, opening on `initial`. */
|
||||
connectBlock(cfg: ClientConfig, kind: Kind, initial?: ConnectView): Promise<HTMLElement>;
|
||||
/** What a QR code for the device carries. */
|
||||
qrText(cfg: ClientConfig): string;
|
||||
/** The key the device's app imports (⋯ → Copy key), with the menu label. */
|
||||
appKey?: { label: string; make(cfg: ClientConfig): Promise<string> };
|
||||
/** The config file the device imports, with the menu label. */
|
||||
file: { label: string; make(cfg: ClientConfig): { name: string; text: string } };
|
||||
}
|
||||
|
||||
/** 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) : '']);
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
// Tunnel cores by id. A server names its core (`core`, AmneziaWG when absent);
|
||||
// the Server, device and person pages ask the registry instead of importing a
|
||||
// core directly, so another core (VLESS/Xray) plugs in here.
|
||||
|
||||
import type { Server } from '../../shared/types';
|
||||
import type { Core } from './common';
|
||||
import { awg } from './awg';
|
||||
|
||||
export type { Core } from './common';
|
||||
|
||||
const CORES: Record<string, Core> = { awg };
|
||||
|
||||
/** The core of a server (or of the server a person is on). */
|
||||
export function coreOf(srv?: Pick<Server, 'core'> | null): Core {
|
||||
return CORES[srv?.core || 'awg'] ?? awg;
|
||||
}
|
||||
|
||||
/** The core of a person's server. */
|
||||
export function coreFor(servers: Server[], serverId: string): Core {
|
||||
return coreOf(servers.find((s) => s.id === serverId));
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
// Who the admin's demo shows (past.ts, status.ts and router.ts make the router's answers of them): a server with
|
||||
// eight people and fifteen devices on it and a second one turned off, in the states the README's pictures are about
|
||||
// (a limit reached, a device that does not connect, a term about to end, people online, someone offline, someone
|
||||
// paused). Everyone is made up, in English and in Russian: the Russian cast lives around Krasnodar, the English one
|
||||
// in Portugal and Spain. Data only: no router's or person's real name, address or key belongs here, and public
|
||||
// addresses are the documentation ranges' (past.ts).
|
||||
|
||||
import type { Access, Kind, LinkState } from '../../shared/types';
|
||||
|
||||
export type Lang = 'en' | 'ru';
|
||||
/** A name as it is said in each language, or the same in both. */
|
||||
export type Said = string | readonly [en: string, ru: string];
|
||||
export const say = (s: Said, lang: Lang): string => (typeof s === 'string' ? s : s[lang === 'ru' ? 1 : 0]);
|
||||
|
||||
/** Where the cast connects from: home is the router's own city. */
|
||||
export type PlaceId = 'home' | 'north' | 'south' | 'inland' | 'far';
|
||||
|
||||
interface Place {
|
||||
city: string;
|
||||
country: string;
|
||||
cc: string;
|
||||
lat: number;
|
||||
lon: number;
|
||||
/** The network operator there. */
|
||||
org: string;
|
||||
}
|
||||
|
||||
export const PLACES: Record<Lang, Record<PlaceId, Place>> = {
|
||||
en: {
|
||||
home: { city: 'Lisbon', country: 'Portugal', cc: 'PT', lat: 38.7223, lon: -9.1393, org: 'MEO' },
|
||||
north: { city: 'Porto', country: 'Portugal', cc: 'PT', lat: 41.1579, lon: -8.6291, org: 'MEO' },
|
||||
south: { city: 'Faro', country: 'Portugal', cc: 'PT', lat: 37.0194, lon: -7.9304, org: 'NOS' },
|
||||
inland: { city: 'Coimbra', country: 'Portugal', cc: 'PT', lat: 40.2033, lon: -8.4103, org: 'Vodafone' },
|
||||
far: { city: 'Seville', country: 'Spain', cc: 'ES', lat: 37.3891, lon: -5.9845, org: 'Orange' },
|
||||
},
|
||||
ru: {
|
||||
home: { city: 'Краснодар', country: 'Россия', cc: 'RU', lat: 45.035, lon: 38.975, org: 'Ростелеком' },
|
||||
north: { city: 'Новороссийск', country: 'Россия', cc: 'RU', lat: 44.723, lon: 37.769, org: 'Ростелеком' },
|
||||
south: { city: 'Сочи', country: 'Россия', cc: 'RU', lat: 43.585, lon: 39.723, org: 'МТС' },
|
||||
inland: { city: 'Ростов-на-Дону', country: 'Россия', cc: 'RU', lat: 47.2357, lon: 39.7015, org: 'МегаФон' },
|
||||
far: { city: 'Ставрополь', country: 'Россия', cc: 'RU', lat: 45.0428, lon: 41.9734, org: 'Билайн' },
|
||||
},
|
||||
};
|
||||
|
||||
export interface CastDevice {
|
||||
id: string;
|
||||
name: Said;
|
||||
kind: Kind;
|
||||
/** Days since it was added. */
|
||||
added: number;
|
||||
/** GB it moved in the last 30 days. */
|
||||
gb: number;
|
||||
/** Hours it has been online for; absent: it is not. */
|
||||
on?: number;
|
||||
/** Seconds since it was last seen (an online one: its last handshake). */
|
||||
seen: number;
|
||||
/** Where it was last seen (home when absent), and where it was on the days before: [place, days ago]. */
|
||||
at?: PlaceId;
|
||||
was?: readonly (readonly [PlaceId, number])[];
|
||||
/** Its configuration changed since it last fetched it. */
|
||||
stale?: boolean;
|
||||
disabled?: boolean;
|
||||
/** Its link failing in a named way. */
|
||||
link?: LinkState;
|
||||
/** Its own keep-alive, seconds. */
|
||||
keepalive?: number;
|
||||
/** The networks behind a router. */
|
||||
behind?: string[];
|
||||
/** Added by its person on their own page. */
|
||||
portal?: boolean;
|
||||
}
|
||||
|
||||
export interface CastPerson {
|
||||
id: string;
|
||||
name: Said;
|
||||
access: Access;
|
||||
/** Days since they were added. */
|
||||
joined: number;
|
||||
limit: number;
|
||||
devices: CastDevice[];
|
||||
/** Days until their term ends (negative: since it ended); absent: no end date. */
|
||||
ends?: number;
|
||||
/** A traffic limit in GB and its period. */
|
||||
quota?: readonly [gb: number, period: 'month' | 'total'];
|
||||
/** Days since they were paused. */
|
||||
paused?: number;
|
||||
note?: Said;
|
||||
circle?: string;
|
||||
}
|
||||
|
||||
export const SERVER = {
|
||||
id: 's_home',
|
||||
name: 'Ames Gateway',
|
||||
ifname: 'awg0',
|
||||
port: 4500,
|
||||
subnet: '10.8.0.0/24',
|
||||
address: '10.8.0.1',
|
||||
endpoint: 'vpn.ames.example',
|
||||
/** "dawnline-demo-key-not-a-real-one", not a key of anything. */
|
||||
public_key: 'ZGF3bmxpbmUtZGVtby1rZXktbm90LWEtcmVhbC1vbmU=',
|
||||
home: '192.168.1.0/24',
|
||||
/** Seconds its tunnel has been up. */
|
||||
uptime: 16 * 86400 + 3 * 3600,
|
||||
} as const;
|
||||
|
||||
/** A second server, set up and turned off: nobody is on it. */
|
||||
export const SPARE = {
|
||||
id: 's_cottage',
|
||||
name: ['Cottage', 'Дача'],
|
||||
ifname: 'awg1',
|
||||
port: 4501,
|
||||
subnet: '10.9.0.0/24',
|
||||
address: '10.9.0.1',
|
||||
} as const;
|
||||
|
||||
export const CIRCLES: readonly { id: string; name: Said; color: number }[] = [
|
||||
{ id: 'c1', name: ['Family', 'Семья'], color: 0 },
|
||||
{ id: 'c2', name: ['Guests', 'Гости'], color: 3 },
|
||||
];
|
||||
|
||||
/** What is shared at home (Access). */
|
||||
export const SERVICES: readonly { id: string; name: string; address: string; ports: string[] }[] = [
|
||||
{ id: 'sv1', name: 'NAS', address: '192.168.1.10', ports: ['445'] },
|
||||
{ id: 'sv2', name: 'Home Assistant', address: '192.168.1.20', ports: ['8123'] },
|
||||
];
|
||||
|
||||
const laptop: Said = ['Laptop', 'Ноутбук'];
|
||||
|
||||
export const PEOPLE: readonly CastPerson[] = [
|
||||
{
|
||||
id: 'p_dima',
|
||||
name: ['Dima', 'Дима'],
|
||||
access: 'both',
|
||||
joined: 50,
|
||||
limit: 3,
|
||||
quota: [300, 'total'],
|
||||
devices: [
|
||||
{
|
||||
id: 'd_d1',
|
||||
name: 'ThinkPad',
|
||||
kind: 'computer',
|
||||
added: 50,
|
||||
gb: 14.7,
|
||||
seen: 4 * 86400,
|
||||
at: 'south',
|
||||
was: [['home', 7]],
|
||||
link: 'trying',
|
||||
},
|
||||
{ id: 'd_d2', name: 'Xiaomi 14', kind: 'phone', added: 45, gb: 8.2, on: 0.7, seen: 15, link: 'shared', portal: true },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'p_lena',
|
||||
name: ['Lena Ortiz', 'Лена Орлова'],
|
||||
access: 'both',
|
||||
joined: 70,
|
||||
limit: 4,
|
||||
ends: 2,
|
||||
note: ['Sister', 'Сестра'],
|
||||
circle: 'c1',
|
||||
devices: [
|
||||
{
|
||||
id: 'd_l1',
|
||||
name: 'iPhone 16 Pro',
|
||||
kind: 'phone',
|
||||
added: 70,
|
||||
gb: 16.4,
|
||||
on: 1.5,
|
||||
seen: 40,
|
||||
was: [
|
||||
['south', 6],
|
||||
['north', 5],
|
||||
],
|
||||
},
|
||||
{ id: 'd_l2', name: 'MacBook Air', kind: 'computer', added: 64, gb: 25.5, seen: 7600 },
|
||||
{ id: 'd_l3', name: 'iPad', kind: 'tablet', added: 30, gb: 5.3, seen: 3 * 86400, at: 'south', stale: true },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'p_misha',
|
||||
name: ['Misha', 'Миша'],
|
||||
access: 'internet',
|
||||
joined: 60,
|
||||
limit: 3,
|
||||
quota: [50, 'month'],
|
||||
circle: 'c1',
|
||||
devices: [
|
||||
{ id: 'd_m1', name: 'Galaxy S24', kind: 'phone', added: 60, gb: 22.1, on: 2.2, seen: 25, at: 'inland' },
|
||||
{ id: 'd_m2', name: laptop, kind: 'computer', added: 58, gb: 28.2, seen: 5 * 3600, at: 'inland' },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'p_artem',
|
||||
name: ['Artem', 'Артём'],
|
||||
access: 'both',
|
||||
joined: 40,
|
||||
limit: 3,
|
||||
ends: 3,
|
||||
devices: [
|
||||
{ id: 'd_a1', name: 'Pixel 9', kind: 'phone', added: 40, gb: 11.5, on: 1.85, seen: 70, was: [['north', 2]] },
|
||||
{ id: 'd_a2', name: ['Keenetic cottage', 'Keenetic дача'], kind: 'router', added: 38, gb: 17, seen: 9 * 3600, at: 'north' },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'p_office',
|
||||
name: ['Office', 'Офис'],
|
||||
access: 'lan',
|
||||
joined: 66,
|
||||
limit: 2,
|
||||
devices: [
|
||||
{ id: 'd_o1', name: 'Mikrotik hAP', kind: 'router', added: 66, gb: 47.1, on: 5, seen: 60, keepalive: 25, behind: ['192.168.2.0/24'] },
|
||||
{ id: 'd_o2', name: ['Print server', 'Принтер-сервер'], kind: 'other', added: 66, gb: 0, seen: 32 * 86400, disabled: true },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'p_katya',
|
||||
name: ['Katya', 'Катя'],
|
||||
access: 'internet',
|
||||
joined: 46,
|
||||
limit: 3,
|
||||
devices: [{ id: 'd_t1', name: laptop, kind: 'computer', added: 44, gb: 6.3, on: 4, seen: 75, stale: true }],
|
||||
},
|
||||
{
|
||||
id: 'p_boris',
|
||||
name: ['Boris', 'Борис'],
|
||||
access: 'internet',
|
||||
joined: 14,
|
||||
limit: 3,
|
||||
devices: [
|
||||
{ id: 'd_b1', name: laptop, kind: 'computer', added: 12, gb: 13.1, seen: 7800, stale: true },
|
||||
{ id: 'd_b2', name: 'iPad', kind: 'tablet', added: 12, gb: 2.8, seen: 15000 },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'p_kirill',
|
||||
name: ['Kirill (guest)', 'Кирилл (гость)'],
|
||||
access: 'internet',
|
||||
joined: 20,
|
||||
limit: 1,
|
||||
ends: -7,
|
||||
paused: 7,
|
||||
circle: 'c2',
|
||||
devices: [{ id: 'd_g1', name: 'iPhone', kind: 'phone', added: 20, gb: 1.4, seen: 10 * 86400, at: 'far' }],
|
||||
},
|
||||
];
|
||||
|
||||
/** The router's own words (its checks), which it sends in the page's language. */
|
||||
export const CHECKS: readonly { id: string; title: Said; detail?: Said; warn?: boolean }[] = [
|
||||
{ id: 'awg', title: ['AmneziaWG installed', 'AmneziaWG установлен'] },
|
||||
{ id: 'nft', title: ['Access rules loaded', 'Правила доступа загружены'] },
|
||||
{ id: `up_${SERVER.id}`, title: ['Tunnel running', 'Туннель работает'] },
|
||||
{ id: `ep_${SERVER.id}`, title: ['Public address', 'Публичный адрес'] },
|
||||
{
|
||||
id: `homenet_${SERVER.id}`,
|
||||
title: ['A home network is outside the firewall', 'Домашняя сеть вне межсетевого экрана'],
|
||||
detail: [
|
||||
'guest (192.168.3.0/24) is not in a firewall zone: the firewall rejects this traffic.',
|
||||
'guest (192.168.3.0/24) не входит в зону: межсетевой экран отбрасывает этот трафик.',
|
||||
],
|
||||
warn: true,
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,51 @@
|
||||
<!doctype html>
|
||||
<!-- The admin's demo page (src/admin/demo/main.ts): the skeleton the Outline theme's header template gives a LuCI
|
||||
page (luci-theme-outline, ucode/template/themes/outline/header.ut and footer.ut), with LuCI's own #view in it.
|
||||
The theme's files are not part of this build: whoever serves the page serves a build of the theme at
|
||||
/luci-static/outline and this folder at /dawnline-demo, the page itself at any LuCI address of Dawnline's
|
||||
(/cgi-bin/luci/admin/services/dawnline/<view>), with <html lang> set to the language, as LuCI's server does. -->
|
||||
<html lang="en" data-outline-media="/luci-static/outline" data-default-theme="device" data-nav="navbar" data-sidebar-collapsed="false">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="color-scheme" content="light dark" />
|
||||
<title>Outline | Dawnline</title>
|
||||
<script>
|
||||
// As the theme's header does before the first paint: dark or light by the system's choice.
|
||||
document.documentElement.setAttribute('data-darkmode', String(window.matchMedia('(prefers-color-scheme: dark)').matches));
|
||||
</script>
|
||||
<link rel="stylesheet" href="/luci-static/outline/main.css" data-luci-shell />
|
||||
</head>
|
||||
<body class="lang_en" data-page="admin-services-dawnline">
|
||||
<div id="sidebar" data-media="/luci-static/outline" data-hostname="Outline"></div>
|
||||
<div id="sidebar-overlay"></div>
|
||||
<div id="main-wrapper">
|
||||
<div class="content-card">
|
||||
<header class="card-header">
|
||||
<div class="card-header-left">
|
||||
<button id="sidebar-hamburger" class="topbar-hamburger" type="button">
|
||||
<img src="/luci-static/outline/icons/menu.svg" width="18" height="18" alt="" />
|
||||
</button>
|
||||
<nav class="topbar-breadcrumb" id="topbar-breadcrumb"></nav>
|
||||
<a class="topbar-brand" href="/">
|
||||
<img src="/luci-static/outline/images/logo.png" width="20" height="20" alt="" />
|
||||
<span>Outline</span>
|
||||
</a>
|
||||
</div>
|
||||
<div class="card-header-right">
|
||||
<div id="indicators" class="topbar-indicators"></div>
|
||||
<button id="theme-toggle-btn" class="topbar-icon-btn" type="button">
|
||||
<img class="theme-icon-light" src="/luci-static/outline/icons/sun.svg" width="16" height="16" alt="" />
|
||||
<img class="theme-icon-dark" src="/luci-static/outline/icons/moon.svg" width="16" height="16" alt="" />
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
<div id="maincontent" tabindex="-1">
|
||||
<div id="tabmenu" style="display: none"></div>
|
||||
<div id="view"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<script src="/dawnline-demo/admin.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,104 @@
|
||||
// LuCI's side of the admin, for the demo, where there is no LuCI: the globals the admin's modules take from its
|
||||
// loader (luci.d.ts: E, L, rpc, poll, ui) and the translation globals _() and N_(), which look a string up in the
|
||||
// admin's own catalog as LuCI does on a router with luci-i18n-dawnline-<lang> installed. Only what the admin uses,
|
||||
// each behaving as LuCI's does. It knows nothing of the router: a call goes to LuCI's ubus door as JSON-RPC, and who
|
||||
// answers there is serve.ts. Imported first, before anything of the admin's (main.ts).
|
||||
|
||||
import ru from '../../../../package/luci-app-dawnline/po/ru/dawnline.po';
|
||||
import type { Catalog } from '../../../i18n/po';
|
||||
|
||||
/** Where LuCI sends its calls, and the session it sends them with (nobody's: there is no login here). */
|
||||
export const DOOR = '/ubus';
|
||||
const SESSION = '00000000000000000000000000000000';
|
||||
|
||||
const CATALOGS: Record<string, Catalog> = { ru };
|
||||
/** Which plural form a number takes, by each language's gettext rule. */
|
||||
const FORMS: Record<string, (n: number) => number> = {
|
||||
ru: (n) => (n % 10 === 1 && n % 100 !== 11 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2),
|
||||
};
|
||||
|
||||
/** The page's language is its <html lang>, which LuCI's server sets (here: whoever serves the page). */
|
||||
const catalog = (): Catalog | undefined => CATALOGS[document.documentElement.lang];
|
||||
const key = (s: string, ctx?: string) => (ctx ? `${ctx}\u0004${s}` : s);
|
||||
const tr = (s: string, ctx?: string): string => catalog()?.s[key(s, ctx)] ?? s;
|
||||
const ntr = (n: number, one: string, many: string, ctx?: string): string =>
|
||||
catalog()?.p[key(one, ctx)]?.[FORMS[document.documentElement.lang]?.(n) ?? 0] ?? (n === 1 ? one : many);
|
||||
|
||||
type Attrs = Record<string, unknown>;
|
||||
type Kid = Node | string | number;
|
||||
|
||||
/** LuCI's E() as the admin calls it (e.ts): a function is a listener, an object its JSON, null is left out. */
|
||||
function element(tag: string, attrs: Attrs = {}, kids: Kid | Kid[] = []): HTMLElement {
|
||||
const el = document.createElement(tag);
|
||||
for (const [k, v] of Object.entries(attrs)) {
|
||||
if (v == null) continue;
|
||||
if (typeof v === 'function') el.addEventListener(k, v as EventListener);
|
||||
else el.setAttribute(k, typeof v === 'object' ? JSON.stringify(v) : String(v));
|
||||
}
|
||||
for (const kid of Array.isArray(kids) ? kids : [kids]) el.append(kid instanceof Node ? kid : String(kid));
|
||||
return el;
|
||||
}
|
||||
|
||||
let ids = 0;
|
||||
|
||||
/** rpc.declare: the arguments by their names to the ubus door, the answer's data back; a refusal is thrown in LuCI's words. */
|
||||
const declare: (typeof rpc)['declare'] = <T>({ object, method, params = [] }: { object: string; method: string; params?: string[] }) => {
|
||||
return async (...args: unknown[]): Promise<T> => {
|
||||
const named = Object.fromEntries(params.map((p, i) => [p, args[i]] as const).filter(([, v]) => v !== undefined));
|
||||
const res = await fetch(DOOR, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ jsonrpc: '2.0', id: ++ids, method: 'call', params: [SESSION, object, method, named] }),
|
||||
});
|
||||
if (!res.ok) throw new Error(`RPC call to ${object}/${method} failed with HTTP error ${res.status}`);
|
||||
const r = (await res.json()) as { result?: [number, unknown?]; error?: { code: number } };
|
||||
if (r.error) throw new Error(`RPC call to ${object}/${method} failed with error ${r.error.code}`);
|
||||
if (r.result?.[0] !== 0) throw new Error(`RPC call to ${object}/${method} failed with ubus code ${r.result?.[0] ?? -1}`);
|
||||
return (r.result[1] ?? {}) as T;
|
||||
};
|
||||
};
|
||||
|
||||
const timers = new Map<() => unknown, number>();
|
||||
const polls: Pick<typeof poll, 'add' | 'remove' | 'start' | 'stop' | 'active'> = {
|
||||
add(fn, seconds = 5) {
|
||||
if (timers.has(fn)) return false;
|
||||
timers.set(fn, window.setInterval(fn, seconds * 1000));
|
||||
return true;
|
||||
},
|
||||
remove(fn) {
|
||||
clearInterval(timers.get(fn));
|
||||
return timers.delete(fn);
|
||||
},
|
||||
start() {},
|
||||
stop() {
|
||||
for (const t of timers.values()) clearInterval(t);
|
||||
timers.clear();
|
||||
},
|
||||
active: () => timers.size > 0,
|
||||
};
|
||||
|
||||
const modules = new Map<string, unknown>();
|
||||
|
||||
/** A module as LuCI's loader would hand it out (L.require): the admin's own, built into this page. */
|
||||
export function provide(name: string, module: unknown): void {
|
||||
modules.set(name, module);
|
||||
}
|
||||
|
||||
const luci: Pick<typeof L, 'env' | 'url' | 'hasViewPermission' | 'resolveDefault' | 'require'> = {
|
||||
// no ubuspath: nothing here holds an event stream, so the page follows by held calls
|
||||
env: { sessionid: SESSION },
|
||||
url: (...parts) => `/cgi-bin/luci/${parts.join('/')}`,
|
||||
hasViewPermission: () => true,
|
||||
resolveDefault: (p, def) => p.catch(() => def),
|
||||
require: (name) => (modules.has(name) ? Promise.resolve(modules.get(name)) : Promise.reject(new Error(`No module ${name}`))),
|
||||
};
|
||||
|
||||
Object.assign(globalThis, {
|
||||
_: tr,
|
||||
N_: ntr,
|
||||
E: element,
|
||||
L: luci,
|
||||
rpc: { declare, getBaseURL: () => DOOR, getSessionID: () => SESSION },
|
||||
poll: polls,
|
||||
ui: { menu: { flushCache() {} } },
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
// The admin's demo (npm run build:demo → dist/admin-demo): the admin's real pages outside LuCI, over a router that
|
||||
// lives in the page and is all made up (cast.ts, past.ts, status.ts, router.ts, serve.ts), inside the Outline
|
||||
// theme's shell (index.html, shell.ts; the theme's own files are not here: whoever serves the page serves them at
|
||||
// /luci-static/outline). It is what the README's pictures of the admin are taken from
|
||||
// (scripts/capture-screenshots.mjs), so nobody's router, people or addresses are ever in them. It answers what
|
||||
// those pages ask and refuses the rest: not a demo for visitors, as the portal's is (portal/demo).
|
||||
//
|
||||
// This file is LuCI's part: it hands the admin its modules and runs the view the address names, as LuCI runs a
|
||||
// view (load, then render into #view). The order of the imports is the boot order: LuCI's globals, then the
|
||||
// router at its door, then the admin.
|
||||
|
||||
import { provide } from './luci';
|
||||
import './serve';
|
||||
import * as app from '../main';
|
||||
import * as style from '../style-module';
|
||||
import * as map from '../map-module';
|
||||
import * as qr from '../qr-module';
|
||||
import { here } from '../shell/routes';
|
||||
import { drawShell } from './shell';
|
||||
|
||||
// On a router these are LuCI modules of their own, fetched when asked for (shell/style.ts, maps.ts, qr.ts).
|
||||
provide('dawnline.style', style);
|
||||
provide('dawnline.map', map);
|
||||
provide('dawnline.qr', qr);
|
||||
|
||||
interface View {
|
||||
load(): Promise<unknown>;
|
||||
render(data: never): Node;
|
||||
}
|
||||
|
||||
async function open(): Promise<void> {
|
||||
drawShell();
|
||||
const make = (app as Record<string, (() => View) | undefined>)[here().view] ?? app.overview;
|
||||
const view = make();
|
||||
const data = await view.load();
|
||||
document.getElementById('view')?.replaceChildren(view.render(data as never));
|
||||
}
|
||||
|
||||
void open();
|
||||
@@ -0,0 +1,144 @@
|
||||
// What the demo's cast did before its moment (cast.ts says who they are): the clock every answer is given on, each
|
||||
// device's traffic a day at a time, when it was on and where, and from those the log and the places. Made by rule
|
||||
// from the cast, the same every time, so every capture of a page shows the same day.
|
||||
//
|
||||
// Pure: no DOM and no LuCI. Every public address is from the ranges kept for documentation (203.0.113.0/24,
|
||||
// 198.51.100.0/24): nobody's.
|
||||
|
||||
import type { Device, GeoPoint, LogEvent, Pair } from '../../shared/types';
|
||||
import { PEOPLE, PLACES, SERVER, type CastDevice, type Lang, type PlaceId } from './cast';
|
||||
|
||||
/** The moment every answer is given at: Sunday 8 November 2026, 12:40 on the router's clock. */
|
||||
export const NOW = Date.UTC(2026, 10, 8, 9, 40) / 1000;
|
||||
/** The router's offset from UTC, minutes. */
|
||||
export const TZ = 180;
|
||||
|
||||
export const MIN = 60;
|
||||
export const HOUR = 3600;
|
||||
export const DAY = 86400;
|
||||
/** The admin counts in binary units: "50 GB" is 50 GiB. */
|
||||
export const GB = 2 ** 30;
|
||||
/** Days of traffic the status holds: the longest history a page asks for. */
|
||||
export const DAYS = 60;
|
||||
/** What a device sends is about a tenth of what it moves. */
|
||||
export const UP = 0.1;
|
||||
/** How busy each day of the week is, Sunday first. */
|
||||
const WEEK = [1.1, 0.9, 1.15, 0.8, 1.05, 1.3, 0.75];
|
||||
/** When a device of each kind is usually on, on the router's clock: [from, for] in hours. */
|
||||
const HABITS: Record<Device['kind'], readonly (readonly [number, number])[]> = {
|
||||
phone: [
|
||||
[7.2, 1.75],
|
||||
[17.6, 5.4],
|
||||
],
|
||||
computer: [[19, 3]],
|
||||
tablet: [[20.5, 1.5]],
|
||||
router: [[16, 11.6]],
|
||||
other: [[10, 6]],
|
||||
};
|
||||
|
||||
/** The same number from 0 to 1 for the same words: what makes one made-up day unlike the next, every time alike. */
|
||||
export function chance(...words: (string | number)[]): number {
|
||||
let h = 2166136261;
|
||||
for (const c of words.join('|')) h = Math.imul(h ^ c.charCodeAt(0), 16777619);
|
||||
return (h >>> 0) / 2 ** 32;
|
||||
}
|
||||
|
||||
/** The router's midnight `ago` days back, and the router's day a moment falls on ("YYYY-MM-DD"). */
|
||||
export const midnight = (ago: number): number => Math.floor((NOW + TZ * MIN) / DAY) * DAY - TZ * MIN - ago * DAY;
|
||||
export const dayOf = (t: number): string => new Date((t + TZ * MIN) * 1000).toISOString().slice(0, 10);
|
||||
|
||||
export const DEVICES = PEOPLE.flatMap((p) => p.devices);
|
||||
const pair = (bytes: number): Pair => [Math.round(bytes * UP), Math.round(bytes * (1 - UP))];
|
||||
export const sum = (pairs: Pair[]): Pair => pairs.reduce<Pair>((s, p) => [s[0] + p[0], s[1] + p[1]], [0, 0]);
|
||||
export const add = (lists: Pair[][]): Pair[] => Array.from({ length: DAYS }, (_x, i) => sum(lists.map((l) => l[i])));
|
||||
|
||||
/** A device's address at a place: the same one every time, from a documentation range (home: 203.0.113.x). */
|
||||
export function addressAt(d: CastDevice, at: PlaceId): string {
|
||||
const n = 10 + DEVICES.indexOf(d);
|
||||
return at === 'home' ? `203.0.113.${n}` : `198.51.100.${n + 40 * (Object.keys(PLACES.en).indexOf(at) - 1)}`;
|
||||
}
|
||||
|
||||
/** Each of the last DAYS days' [rx, tx] of a device, oldest first: nothing before it was added or after it was last seen. */
|
||||
export function daily(d: CastDevice): Pair[] {
|
||||
const last = Math.floor(d.seen / DAY);
|
||||
const weights = Array.from({ length: DAYS }, (_x, i) => {
|
||||
const ago = DAYS - 1 - i;
|
||||
if (ago > d.added || ago < last) return 0;
|
||||
const weekday = new Date((midnight(ago) + TZ * MIN + DAY / 2) * 1000).getUTCDay();
|
||||
// today is only partly gone
|
||||
return WEEK[weekday] * (0.5 + chance(d.id, ago)) * (ago ? 1 : (NOW - midnight(0)) / DAY);
|
||||
});
|
||||
const month = weights.slice(-30).reduce((s, w) => s + w, 0) || 1;
|
||||
return weights.map((w) => pair((w / month) * d.gb * GB));
|
||||
}
|
||||
|
||||
interface Session {
|
||||
from: number;
|
||||
/** 0: it is still on. */
|
||||
to: number;
|
||||
at: PlaceId;
|
||||
}
|
||||
|
||||
/** When a device was on in the last 30 days, oldest first, by the habits of its kind; the last one is how it stands now. */
|
||||
function sessions(d: CastDevice): Session[] {
|
||||
const at = d.at ?? 'home';
|
||||
const seen = NOW - d.seen;
|
||||
const last: Session = d.on ? { from: NOW - d.on * HOUR, to: 0, at } : { from: seen - HABITS[d.kind][0][1] * HOUR, to: seen, at };
|
||||
const out: Session[] = [];
|
||||
for (let ago = Math.min(30, d.added); ago >= 0; ago--)
|
||||
for (const [start, hours] of HABITS[d.kind]) {
|
||||
const from = midnight(ago) + (start + chance(d.id, ago, start) - 0.5) * HOUR;
|
||||
const to = from + (hours + chance(d.id, ago, hours) - 0.5) * HOUR;
|
||||
// a computer stays shut some evenings; nothing overlaps how the device stands now
|
||||
if (to > last.from - HOUR / 2 || (d.kind !== 'phone' && chance(d.id, 'shut', ago) < 0.15)) continue;
|
||||
out.push({ from: Math.round(from), to: Math.round(to), at: d.was?.find(([, days]) => days === ago)?.[0] ?? at });
|
||||
}
|
||||
return [...out, last];
|
||||
}
|
||||
|
||||
/** The log of the last 30 days, oldest first: every device coming and going, and what the router noticed. */
|
||||
export function log(lang: Lang): LogEvent[] {
|
||||
const out: LogEvent[] = [];
|
||||
for (const p of PEOPLE) {
|
||||
for (const d of p.devices) {
|
||||
const who = { person: p.id, device: d.id, server: SERVER.id };
|
||||
for (const s of sessions(d)) {
|
||||
const place = PLACES[lang][s.at];
|
||||
out.push({ ...who, ts: s.from, type: 'connect', detail: addressAt(d, s.at), where: `${place.city} · ${place.org}` });
|
||||
if (s.to) out.push({ ...who, ts: s.to, type: 'disconnect' });
|
||||
}
|
||||
if (d.link) out.push({ ...who, ts: NOW - (d.on ? 10 * MIN : 4 * HOUR), type: 'device_failing', detail: d.link });
|
||||
}
|
||||
if (p.paused !== undefined) out.push({ person: p.id, server: SERVER.id, ts: NOW - p.paused * DAY, type: 'paused', by: 'admin' });
|
||||
}
|
||||
return out.filter((e) => e.ts > NOW - 30 * DAY).sort((a, b) => a.ts - b.ts);
|
||||
}
|
||||
|
||||
/** Where every device was seen in the last 30 days: the newest moment at each place. */
|
||||
export function places(lang: Lang): GeoPoint[] {
|
||||
const out: GeoPoint[] = [];
|
||||
for (const p of PEOPLE)
|
||||
for (const d of p.devices) {
|
||||
const newest = new Map<PlaceId, Session>();
|
||||
for (const s of sessions(d)) newest.set(s.at, s);
|
||||
for (const [at, s] of newest) {
|
||||
if ((s.to || NOW) < NOW - 30 * DAY) continue;
|
||||
const { city, country, cc, lat, lon, org } = PLACES[lang][at];
|
||||
out.push({
|
||||
person: p.id,
|
||||
device: d.id,
|
||||
ip: addressAt(d, at),
|
||||
ts: s.to || NOW,
|
||||
online: !s.to,
|
||||
lat,
|
||||
lon,
|
||||
city,
|
||||
country,
|
||||
cc,
|
||||
asn: 0,
|
||||
org,
|
||||
});
|
||||
}
|
||||
}
|
||||
return out.sort((a, b) => b.ts - a.ts);
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
// The router the admin's demo asks (serve.ts hands its questions here): what the backend answers besides the status
|
||||
// (status.ts), made of the same cast at the same fixed moment: the log, the checks, the service log, a server's
|
||||
// interfaces, a device's configuration, the live meter. It only answers questions: what changes something is not
|
||||
// here, and serve.ts refuses it.
|
||||
//
|
||||
// Pure: no DOM and no LuCI. Its addresses are private or from the documentation ranges, its keys are not keys.
|
||||
|
||||
import type { ClientConfig, HealthCheck, Pair } from '../../shared/types';
|
||||
import type { Health, InterfacesData, LogsInfo, MeterPoint, NetDevice, ServiceLog } from '../api';
|
||||
import { CHECKS, PEOPLE, SERVER, SPARE, say, type Lang } from './cast';
|
||||
import { DEVICES, HOUR, NOW, UP, chance, log, sum } from './past';
|
||||
import { status } from './status';
|
||||
|
||||
const POLICY: LogsInfo['policy'] = {
|
||||
keep_days: 30,
|
||||
max: 20000,
|
||||
categories: ['connections', 'people', 'problems'],
|
||||
persist: '10min',
|
||||
usage_days: 60,
|
||||
usage_months: 12,
|
||||
};
|
||||
|
||||
/** The newest `limit` events; a person's or a device's only, or only those after `since`, when given. */
|
||||
export function events(lang: Lang, limit: number, who?: string, since?: number, dev?: string) {
|
||||
const all = log(lang).filter((e) => (!who || e.person === who) && (!dev || e.device === dev) && (!since || e.ts > since));
|
||||
return { events: all.slice(-(limit || 300)), total: all.length, policy: POLICY };
|
||||
}
|
||||
|
||||
/** The service log: the watchdog at rest, and the one change the admin made to the server (the day before). */
|
||||
export function serviceLog(): ServiceLog {
|
||||
const targets = [
|
||||
{ id: 'awg', name: 'AmneziaWG' },
|
||||
{ id: `up_${SERVER.id}`, name: SERVER.name },
|
||||
{ id: 'nft', name: 'nftables' },
|
||||
];
|
||||
return {
|
||||
watchdog: {
|
||||
enabled: true,
|
||||
last: NOW - 40,
|
||||
beat: NOW - 20,
|
||||
now: NOW,
|
||||
targets: targets.map((t) => ({ ...t, ok: true, tries: 0 })),
|
||||
repairs: [],
|
||||
},
|
||||
log: [
|
||||
{
|
||||
ts: NOW - 22 * HOUR,
|
||||
src: 'dawnline',
|
||||
level: 'info',
|
||||
msg: 'changed',
|
||||
by: 'admin',
|
||||
kind: 'server',
|
||||
who: SERVER.name,
|
||||
sid: SERVER.id,
|
||||
note: 'MTU',
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
/** The checks: every one passes but the cast's one finding, so a page shows where a fix stands. */
|
||||
export function health(lang: Lang): Health {
|
||||
const checks: HealthCheck[] = CHECKS.map((c) => ({
|
||||
id: c.id,
|
||||
title: say(c.title, lang),
|
||||
status: c.warn ? 'warn' : 'ok',
|
||||
detail: c.detail ? say(c.detail, lang) : '',
|
||||
fix: null,
|
||||
problem: c.warn ? say(c.title, lang) : null,
|
||||
}));
|
||||
return { checks, ...serviceLog() };
|
||||
}
|
||||
|
||||
/** What the router's interfaces are to the server: its WAN, its home network, and a guest network no firewall zone holds. */
|
||||
export function interfaces(id: string): InterfacesData | null {
|
||||
if (id !== SERVER.id && id !== SPARE.id) return null;
|
||||
const ifname = id === SERVER.id ? SERVER.ifname : SPARE.ifname;
|
||||
const dev = (name: string, o: Partial<NetDevice>): NetDevice => ({
|
||||
name,
|
||||
category: 'ethernet',
|
||||
kind: 'ethernet',
|
||||
up: true,
|
||||
master: null,
|
||||
members: [],
|
||||
nets: [],
|
||||
addrs: [],
|
||||
logical: null,
|
||||
proto: 'static',
|
||||
zone: null,
|
||||
...o,
|
||||
});
|
||||
return {
|
||||
server: id,
|
||||
ifname,
|
||||
detected: { wan: 'eth0', lan: 'br-lan' },
|
||||
saved: { wan: '', lan: '' },
|
||||
config: {
|
||||
auto_wan: true,
|
||||
wan_device: '',
|
||||
auto_lan: true,
|
||||
lan_devices: [],
|
||||
lan_like: false,
|
||||
device_mesh: true,
|
||||
mesh: id === SERVER.id ? 'circles' : 'off',
|
||||
},
|
||||
like_home: { active: false },
|
||||
effective: {
|
||||
wan: { dev: 'eth0', zone: 'wan', auto: true, missing: false },
|
||||
home: [{ dev: 'br-lan', auto: true, nets: [SERVER.home], zone: 'lan', missing: false }],
|
||||
nets: [SERVER.home],
|
||||
zones: ['lan'],
|
||||
},
|
||||
zones: ['lan', 'wan'],
|
||||
devices: [
|
||||
dev('eth0', { category: 'wan', kind: 'wan', addrs: ['203.0.113.1/24'], logical: 'wan', proto: 'dhcp', zone: 'wan' }),
|
||||
dev('br-lan', {
|
||||
kind: 'bridge',
|
||||
members: ['lan1', 'lan2', 'lan3'],
|
||||
nets: [SERVER.home],
|
||||
addrs: ['192.168.1.1/24'],
|
||||
logical: 'lan',
|
||||
zone: 'lan',
|
||||
home: true,
|
||||
auto: true,
|
||||
}),
|
||||
dev('br-guest', {
|
||||
category: 'wifi',
|
||||
kind: 'bridge',
|
||||
members: ['phy0-ap1'],
|
||||
nets: ['192.168.3.0/24'],
|
||||
addrs: ['192.168.3.1/24'],
|
||||
logical: 'guest',
|
||||
}),
|
||||
dev(ifname, { category: 'vpn', kind: 'vpn', up: id === SERVER.id, proto: 'amneziawg', zone: 'lan', own: true }),
|
||||
],
|
||||
lan_only: PEOPLE.filter((p) => p.access === 'lan').length,
|
||||
};
|
||||
}
|
||||
|
||||
/** Keys that open nothing: "demo-device-key--not-a-real-one!" and "demo-shared-key--not-a-real-one!". */
|
||||
const NO_KEY = 'ZGVtby1kZXZpY2Uta2V5LS1ub3QtYS1yZWFsLW9uZSE=';
|
||||
const NO_PSK = 'ZGVtby1zaGFyZWQta2V5LS1ub3QtYS1yZWFsLW9uZSE=';
|
||||
|
||||
/** A device's configuration as its set-up shows it. It connects nowhere: the server's name does not exist. */
|
||||
export function config(id: string, lang: Lang): ClientConfig | null {
|
||||
const p = status(lang).people.find((x) => x.devices.some((d) => d.id === id));
|
||||
const d = p?.devices.find((x) => x.id === id);
|
||||
if (!p || !d) return null;
|
||||
const allowed = p.access === 'lan' ? [SERVER.home] : ['0.0.0.0/0'];
|
||||
const conf = [
|
||||
'[Interface]',
|
||||
`PrivateKey = ${NO_KEY}`,
|
||||
`Address = ${d.address}/32`,
|
||||
`DNS = ${SERVER.address}`,
|
||||
`MTU = ${d.mtu_used}`,
|
||||
'',
|
||||
'[Peer]',
|
||||
`PublicKey = ${SERVER.public_key}`,
|
||||
`PresharedKey = ${NO_PSK}`,
|
||||
`Endpoint = ${SERVER.endpoint}:${SERVER.port}`,
|
||||
`AllowedIPs = ${allowed.join(', ')}`,
|
||||
'',
|
||||
].join('\n');
|
||||
return {
|
||||
name: d.name,
|
||||
person: p.name,
|
||||
server: SERVER.name,
|
||||
filename: `${d.hostname.split('.')[0]}.conf`,
|
||||
conf,
|
||||
has_private_key: true,
|
||||
amnezia: {
|
||||
host: SERVER.endpoint,
|
||||
port: SERVER.port,
|
||||
mtu: String(d.mtu_used),
|
||||
dns: [SERVER.address],
|
||||
allowed_ips: allowed,
|
||||
client_ip: d.address,
|
||||
client_priv_key: NO_KEY,
|
||||
client_pub_key: NO_KEY,
|
||||
psk_key: NO_PSK,
|
||||
server_pub_key: SERVER.public_key,
|
||||
persistent_keep_alive: String(d.keepalive_used ?? 0),
|
||||
obfuscation: {},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** The live meter's last two minutes: each online device streaming a little unevenly, the server their sum. */
|
||||
export function meter(): MeterPoint[] {
|
||||
const live = DEVICES.filter((d) => d.on);
|
||||
return Array.from({ length: 120 }, (_x, i) => {
|
||||
const ts = NOW - 119 + i;
|
||||
const dev: Record<string, Pair> = {};
|
||||
for (const d of live) {
|
||||
const down = (3e5 + chance(d.id, 'speed') * 1.4e6) * (1 + 0.4 * Math.sin(ts / (7 + d.id.length)) + 0.2 * Math.sin(ts / 3));
|
||||
dev[d.id] = [Math.round(down * UP), Math.round(down)];
|
||||
}
|
||||
return { ts, servers: { [SERVER.id]: sum(Object.values(dev)) }, dev };
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
// The demo's router at LuCI's ubus door: it owns fetch for that one address and answers the JSON-RPC the page sends
|
||||
// there as the backend's object `dawnline` does, from status.ts and router.ts. Two kinds of question come: the stream's (hello,
|
||||
// sync, wait, watch, refresh: state/transport.ts), answered with the whole state as one snapshot that never moves,
|
||||
// and the pages' own (the log, a person's usage, the checks, the service log, a server's interfaces, a device's
|
||||
// configuration).
|
||||
//
|
||||
// It answers questions only. Anything else (a change, or a question no page of the demo's asks yet) is refused as
|
||||
// ubus refuses an unknown method, and named on the console, so whoever opens a page it cannot draw sees why.
|
||||
// Imported before the admin (main.ts): the door is taken before a page asks.
|
||||
|
||||
import { DOOR } from './luci';
|
||||
import { NOW } from './past';
|
||||
import { config, events, health, interfaces, meter, serviceLog } from './router';
|
||||
import { status, usage } from './status';
|
||||
import type { Lang } from './cast';
|
||||
|
||||
/** ubus's own status codes. */
|
||||
const OK = 0;
|
||||
const METHOD_NOT_FOUND = 3;
|
||||
const NOT_FOUND = 4;
|
||||
|
||||
const EPOCH = 'demo';
|
||||
const started = Date.now();
|
||||
/** The router's clock: the demo's moment, moving on with the page (so what the page holds stays fresh). */
|
||||
const clock = (): number => NOW + (Date.now() - started) / 1000;
|
||||
/** The router says its own words in the page's language. */
|
||||
const lang = (): Lang => (document.documentElement.lang === 'ru' ? 'ru' : 'en');
|
||||
|
||||
type Args = Record<string, unknown>;
|
||||
const text = (v: unknown): string | undefined => (typeof v === 'string' && v ? v : undefined);
|
||||
const count = (v: unknown): number | undefined => (typeof v === 'number' && Number.isFinite(v) ? v : undefined);
|
||||
|
||||
/** The status cut into the stream's topics (state/join.ts puts them together again), with the meter and the backend's own. */
|
||||
function topics(): Record<string, unknown> {
|
||||
const { now, tz, servers, people, circles, services, geo, events: recent, totals, series, hours, ...router } = status(lang());
|
||||
return {
|
||||
backend: { ok: true, at: clock() },
|
||||
router,
|
||||
clock: { now, tz },
|
||||
traffic: { totals, series, hours },
|
||||
servers,
|
||||
people,
|
||||
circles,
|
||||
services,
|
||||
places: geo,
|
||||
recent,
|
||||
meter: meter(),
|
||||
};
|
||||
}
|
||||
|
||||
const sleep = (seconds: number) => new Promise((done) => setTimeout(done, seconds * 1000));
|
||||
|
||||
const ANSWERS: Record<string, (a: Args) => unknown> = {
|
||||
hello: () => ({ version: 'demo', stream: 'poll', epoch: EPOCH, seq: 1, lease: 30, now: clock() }),
|
||||
sync: () => ({ epoch: EPOCH, seq: 1, docs: topics() }),
|
||||
// nothing ever happens here: a held call is let go empty when its time is up
|
||||
wait: (a) => sleep(count(a.timeout) ?? 15).then(() => ({ epoch: EPOCH, seq: 1, events: [] })),
|
||||
watch: () => ({}),
|
||||
refresh: () => ({}),
|
||||
events: (a) => events(lang(), count(a.limit) ?? 0, text(a.person), count(a.since), text(a.device)),
|
||||
person_usage: (a) => usage(text(a.id) ?? '', count(a.days) ?? 31),
|
||||
health: () => health(lang()),
|
||||
interfaces: (a) => interfaces(text(a.id) ?? ''),
|
||||
device_config: (a) => config(text(a.id) ?? '', lang()),
|
||||
service_log: () => serviceLog(),
|
||||
};
|
||||
|
||||
interface Call {
|
||||
id?: unknown;
|
||||
params?: unknown;
|
||||
}
|
||||
|
||||
async function answer(call: Call): Promise<object> {
|
||||
const [, object, method, args] = Array.isArray(call.params) ? (call.params as unknown[]) : [];
|
||||
const reply = (code: number, data?: unknown) => ({
|
||||
jsonrpc: '2.0',
|
||||
id: call.id ?? null,
|
||||
result: data === undefined ? [code] : [code, data],
|
||||
});
|
||||
if (object !== 'dawnline' || typeof method !== 'string') return reply(NOT_FOUND);
|
||||
const made = Object.prototype.hasOwnProperty.call(ANSWERS, method)
|
||||
? await ANSWERS[method](args && typeof args === 'object' ? (args as Args) : {})
|
||||
: undefined;
|
||||
if (made == null) {
|
||||
console.warn(`Dawnline demo: the router does not answer "${method}"`);
|
||||
return reply(METHOD_NOT_FOUND);
|
||||
}
|
||||
return reply(OK, made);
|
||||
}
|
||||
|
||||
/** One request to the door: a call or a batch of them; given up when the page lets it go (a held call it no longer waits for). */
|
||||
async function door(init: RequestInit = {}): Promise<Response> {
|
||||
const gone = new Promise<never>((_ok, fail) =>
|
||||
init.signal?.addEventListener('abort', () => fail(new DOMException('Aborted', 'AbortError'))),
|
||||
);
|
||||
let asked: Call | Call[];
|
||||
try {
|
||||
asked = JSON.parse(String(init.body)) as Call | Call[];
|
||||
} catch {
|
||||
return new Response('', { status: 400 });
|
||||
}
|
||||
const made = Array.isArray(asked) ? Promise.all(asked.map(answer)) : answer(asked);
|
||||
return new Response(JSON.stringify(await Promise.race([made, gone])), { headers: { 'Content-Type': 'application/json' } });
|
||||
}
|
||||
|
||||
const real = window.fetch.bind(window);
|
||||
window.fetch = (input, init) => {
|
||||
const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
|
||||
return new URL(url, location.href).pathname === DOOR ? door(init) : real(input, init);
|
||||
};
|
||||
@@ -0,0 +1,86 @@
|
||||
// The Outline theme's chrome around the demo's page: what the theme's own scripts draw into the skeleton its
|
||||
// header template gives (index.html) once LuCI hands them its menu. They need LuCI itself, so the same markup is
|
||||
// made here by hand, for a made-up menu: the brand, the five sections a router with statistics has, search and log
|
||||
// out, LuCI's poll indicator. Laid out by the theme's stylesheet as its navbar or its sidebar (html[data-nav]).
|
||||
// Follows luci-theme-outline 1.3 (menu-outline.js renderSidebarChrome and render): when the theme changes that
|
||||
// markup, this changes with it. A picture's frame only: nothing here is pressed.
|
||||
|
||||
const MEDIA = '/luci-static/outline';
|
||||
|
||||
/** LuCI's top-level sections: its menu node, the theme's icon for it, its title in LuCI's own catalog. */
|
||||
const SECTIONS = [
|
||||
['status', 'activity', 'Status', 'Состояние'],
|
||||
['system', 'settings', 'System', 'Система'],
|
||||
['services', 'layers', 'Services', 'Службы'],
|
||||
['network', 'network', 'Network', 'Сеть'],
|
||||
['statistics', 'chart-bar', 'Statistics', 'Статистика'],
|
||||
] as const;
|
||||
/** The section Dawnline's pages are in. */
|
||||
const HERE = 'services';
|
||||
|
||||
type Kid = Node | string;
|
||||
|
||||
function el(tag: string, attrs: Record<string, string>, kids: Kid[] = []): HTMLElement {
|
||||
const e = document.createElement(tag);
|
||||
for (const [k, v] of Object.entries(attrs)) e.setAttribute(k, v);
|
||||
e.append(...kids);
|
||||
return e;
|
||||
}
|
||||
|
||||
const icon = (name: string, size = 20) =>
|
||||
el('img', { src: `${MEDIA}/icons/${name}.svg`, width: String(size), height: String(size), alt: '', class: 'outline-icon' });
|
||||
|
||||
/** Draw the chrome into the page's skeleton, in the page's language. */
|
||||
export function drawShell(): void {
|
||||
const sidebar = document.getElementById('sidebar');
|
||||
if (!sidebar) return;
|
||||
const ru = document.documentElement.lang === 'ru';
|
||||
const host = sidebar.dataset.hostname ?? 'Outline';
|
||||
const out = ru ? 'Выйти' : 'Log out';
|
||||
sidebar.replaceChildren(
|
||||
el('div', { class: 'sidebar-rail' }, [
|
||||
el('a', { class: 'sidebar-rail-home', href: '/', 'aria-label': host }, [
|
||||
el('img', { class: 'sidebar-logo', src: `${MEDIA}/images/logo.png`, alt: '', width: '20', height: '20' }),
|
||||
el('span', { class: 'sidebar-rail-expand', 'aria-hidden': 'true' }, [icon('panel-left-open')]),
|
||||
el('span', { class: 'sidebar-rail-label' }, [host]),
|
||||
]),
|
||||
el('div', { class: 'sidebar-rail-sep', role: 'presentation' }),
|
||||
el(
|
||||
'nav',
|
||||
{ class: 'sidebar-rail-nav', id: 'sidebar-rail-nav' },
|
||||
SECTIONS.map(([name, glyph, en, inRu]) => {
|
||||
const title = ru ? inRu : en;
|
||||
const cls = name === HERE ? 'sidebar-rail-item active is-shown' : 'sidebar-rail-item';
|
||||
return el('a', { class: cls, href: `/cgi-bin/luci/admin/${name}`, 'data-section': name, 'aria-label': title }, [
|
||||
icon(glyph),
|
||||
el('span', { class: 'sidebar-rail-label' }, [title]),
|
||||
]);
|
||||
}),
|
||||
),
|
||||
el('div', { class: 'sidebar-footer', id: 'sidebar-footer' }, [
|
||||
el('a', { class: 'sidebar-logout', href: '/cgi-bin/luci/admin/logout', 'aria-label': out }, [
|
||||
el('span', { class: 'sidebar-icon', 'aria-hidden': 'true' }, [icon('log-out')]),
|
||||
el('span', { class: 'sidebar-label' }, [out]),
|
||||
]),
|
||||
]),
|
||||
]),
|
||||
el('div', { class: 'sidebar-panel' }, [
|
||||
el('div', { class: 'sidebar-header' }, [
|
||||
el('a', { class: 'sidebar-brand', href: '/' }, [el('span', { class: 'sidebar-brand-text' }, [host])]),
|
||||
el('button', { id: 'cmdk-trigger', class: 'cmdk-trigger sidebar-icon-btn', type: 'button' }, [icon('search')]),
|
||||
el('button', { id: 'sidebar-toggle-btn', class: 'sidebar-toggle sidebar-icon-btn', type: 'button' }, [
|
||||
el('span', { class: 'icon-collapse' }, [icon('panel-left-close')]),
|
||||
el('span', { class: 'icon-expand' }, [icon('panel-left-open')]),
|
||||
]),
|
||||
]),
|
||||
el('nav', { class: 'sidebar-nav', id: 'sidebar-nav' }),
|
||||
]),
|
||||
);
|
||||
sidebar.dataset.outlineBuilt = '1';
|
||||
// LuCI's own indicator of its poll, which the theme draws among the top bar's
|
||||
document
|
||||
.getElementById('indicators')
|
||||
?.replaceChildren(
|
||||
el('span', { 'data-indicator': 'poll-status', 'data-clickable': 'true', 'data-style': 'active' }, [ru ? 'Обновление' : 'Refreshing']),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
// The demo router's status (router.ts gives the other answers): the cast (cast.ts) and what it did (past.ts) in the
|
||||
// shape the backend sends, in the language the page asks in. Each person's state follows from their own numbers
|
||||
// (a limit reached, a term ended, paused), as on a router.
|
||||
//
|
||||
// Pure: no DOM and no LuCI.
|
||||
|
||||
import type { DayUsage, Device, Pair, Person, Server, Status } from '../../shared/types';
|
||||
import { CIRCLES, PEOPLE, PLACES, SERVER, SERVICES, SPARE, say, type CastDevice, type CastPerson, type Lang } from './cast';
|
||||
import { DAY, DAYS, DEVICES, GB, HOUR, MIN, NOW, TZ, UP, add, addressAt, chance, daily, dayOf, log, midnight, places, sum } from './past';
|
||||
|
||||
function device(p: CastPerson, d: CastDevice, lang: Lang, n: number): Device {
|
||||
const days = daily(d);
|
||||
const small = d.kind === 'phone' || d.kind === 'tablet';
|
||||
const slug = (s: string) =>
|
||||
s
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-|-$/g, '');
|
||||
return {
|
||||
id: d.id,
|
||||
name: say(d.name, lang),
|
||||
kind: d.kind,
|
||||
address: `10.8.0.${10 + n}`,
|
||||
disabled: !!d.disabled,
|
||||
created: NOW - d.added * DAY,
|
||||
created_by: d.portal ? 'portal' : 'admin',
|
||||
online: !!d.on,
|
||||
handshake: NOW - d.seen,
|
||||
endpoint: `${addressAt(d, d.at ?? 'home')}:${40000 + n}`,
|
||||
active: !!d.on,
|
||||
month: sum(days.slice(-30)),
|
||||
// what it moved before these two months, by how long it has been here
|
||||
total: sum(days).map((b) => Math.round(b * Math.max(1, d.added / 20))) as Pair,
|
||||
spark: days.slice(-7),
|
||||
hostname: `${slug(say(d.name, 'en'))}.${slug(say(p.name, 'en').split(' ')[0])}.lan`,
|
||||
browser_key: !!d.portal,
|
||||
config_stale: !!d.stale,
|
||||
config_issued: NOW - d.seen - HOUR,
|
||||
lan_bypass: d.kind !== 'router',
|
||||
mtu: 0,
|
||||
keepalive: d.keepalive ?? null,
|
||||
mtu_used: small ? 1280 : 1380,
|
||||
keepalive_used: d.keepalive ?? 0,
|
||||
link: d.link ? { state: d.link, since: NOW - (d.on ? 10 * MIN : 4 * HOUR) } : null,
|
||||
setup: null,
|
||||
...(d.behind ? { behind: d.behind } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/** Throughput a minute apart for the last quarter of an hour, [ts, rx, tx] in bytes/s: a few hundred KB/s down. */
|
||||
function rate(id: string, live: boolean): [number, number, number][] {
|
||||
if (!live) return [];
|
||||
const down = 3e5 + chance(id, 'speed') * 1.4e6;
|
||||
return Array.from({ length: 15 }, (_x, i) => {
|
||||
const tx = Math.round(down * (0.6 + 0.8 * chance(id, 'minute', i)));
|
||||
return [NOW - (14 - i) * MIN, Math.round(tx * UP), tx];
|
||||
});
|
||||
}
|
||||
|
||||
function person(p: CastPerson, lang: Lang, first: number): Person {
|
||||
const devices = p.devices.map((d, j) => device(p, d, lang, first + j));
|
||||
const month = sum(devices.map((d) => d.month));
|
||||
const total = sum(devices.map((d) => d.total));
|
||||
const [quota, period] = p.quota ?? [0, 'month' as const];
|
||||
const used = period === 'total' ? total : month;
|
||||
const expires = p.ends === undefined ? '' : dayOf(NOW + p.ends * DAY);
|
||||
const over = quota > 0 && used[0] + used[1] >= quota * GB;
|
||||
// their limit month began with their first traffic and ends a month later, twelve days from now
|
||||
const resets = NOW + 12 * DAY + 5 * HOUR;
|
||||
return {
|
||||
id: p.id,
|
||||
name: say(p.name, lang),
|
||||
server: SERVER.id,
|
||||
access: p.access,
|
||||
device_limit: p.limit,
|
||||
expires,
|
||||
quota_gb: quota,
|
||||
quota_period: period,
|
||||
quota_used: used[0] + used[1],
|
||||
quota_limit: quota * GB,
|
||||
quota_month: month,
|
||||
quota_resets: resets,
|
||||
quota_reset_day: dayOf(resets),
|
||||
bonus_gb: 0,
|
||||
dns_mode: 'device',
|
||||
paused: p.paused !== undefined,
|
||||
state: p.paused !== undefined ? 'paused' : over ? 'quota' : expires && expires < dayOf(NOW) ? 'expired' : 'active',
|
||||
month,
|
||||
total,
|
||||
online: devices.filter((d) => d.online).length,
|
||||
last_seen: Math.max(...devices.map((d) => d.handshake)),
|
||||
devices,
|
||||
rate: rate(
|
||||
p.id,
|
||||
devices.some((d) => d.online),
|
||||
),
|
||||
has_link: true,
|
||||
note: p.note ? say(p.note, lang) : '',
|
||||
services: [],
|
||||
home_nets: [],
|
||||
...(p.circle ? { circle: p.circle } : {}),
|
||||
created: NOW - p.joined * DAY,
|
||||
code_set: NOW - p.joined * DAY,
|
||||
};
|
||||
}
|
||||
|
||||
/** The server everyone is on, and the one that is turned off. */
|
||||
function servers(series: DayUsage[], people: Person[], lang: Lang): Server[] {
|
||||
const online = people.reduce((n, p) => n + p.online, 0);
|
||||
const home: Server = {
|
||||
id: SERVER.id,
|
||||
name: SERVER.name,
|
||||
ifname: SERVER.ifname,
|
||||
port: SERVER.port,
|
||||
subnet: SERVER.subnet,
|
||||
endpoint: SERVER.endpoint,
|
||||
public_key: SERVER.public_key,
|
||||
enabled: true,
|
||||
lan_like: false,
|
||||
device_mesh: true,
|
||||
mesh: 'circles',
|
||||
portal_routers: 'ask',
|
||||
portal_nets: 'ask',
|
||||
home: [{ dev: 'br-lan', nets: [SERVER.home] }],
|
||||
preset: 'balanced',
|
||||
mtu: 0,
|
||||
mtus: { computer: 1380, phone: 1280 },
|
||||
keepalive: 0,
|
||||
dns: [],
|
||||
series,
|
||||
rate: rate(SERVER.id, true).map(([ts, rx, tx]) => [ts, rx * online, tx * online]),
|
||||
address: SERVER.address,
|
||||
up: true,
|
||||
uptime: SERVER.uptime,
|
||||
peers: DEVICES.length,
|
||||
reached: NOW - 15,
|
||||
online,
|
||||
obf: {},
|
||||
hpk: false,
|
||||
};
|
||||
const spare: Server = {
|
||||
...home,
|
||||
id: SPARE.id,
|
||||
name: say(SPARE.name, lang),
|
||||
ifname: SPARE.ifname,
|
||||
port: SPARE.port,
|
||||
subnet: SPARE.subnet,
|
||||
address: SPARE.address,
|
||||
endpoint: '',
|
||||
enabled: false,
|
||||
mesh: 'off',
|
||||
preset: 'off',
|
||||
series: series.map((d) => ({ day: d.day, rx: 0, tx: 0 })),
|
||||
rate: [],
|
||||
up: false,
|
||||
uptime: 0,
|
||||
peers: 0,
|
||||
reached: 0,
|
||||
online: 0,
|
||||
};
|
||||
return [home, spare];
|
||||
}
|
||||
|
||||
const made = new Map<Lang, Status>();
|
||||
|
||||
/** The status, in the language the page asks in (the cast's names and places are said in it). */
|
||||
export function status(lang: Lang): Status {
|
||||
const kept = made.get(lang);
|
||||
if (kept) return kept;
|
||||
let n = 0;
|
||||
const people = PEOPLE.map((p) => person(p, lang, (n += p.devices.length) - p.devices.length));
|
||||
const days = add(DEVICES.map(daily));
|
||||
const series = days.map(([rx, tx], i) => ({ day: dayOf(midnight(DAYS - 1 - i)), rx, tx }));
|
||||
const today = days[DAYS - 1];
|
||||
// today by the router's hour, midnight to now: quiet at night, busier towards noon
|
||||
const hours = Array.from({ length: Math.floor((NOW - midnight(0)) / HOUR) + 1 }, (_x, h) => 0.3 + h / 6 + chance('hour', h));
|
||||
const all = hours.reduce((s, w) => s + w, 0);
|
||||
const home = PLACES[lang].home;
|
||||
const st: Status = {
|
||||
version: 'demo',
|
||||
now: NOW,
|
||||
tz: TZ,
|
||||
hostname: 'OpenWrt',
|
||||
settings: {
|
||||
portal_enabled: true,
|
||||
portal_port: 8443,
|
||||
portal_host: SERVER.endpoint,
|
||||
default_device_limit: 3,
|
||||
domain: 'lan',
|
||||
hostnames: true,
|
||||
geo_enabled: true,
|
||||
home_dns_fallback: '',
|
||||
},
|
||||
servers: servers(series, people, lang),
|
||||
people,
|
||||
services: [...SERVICES],
|
||||
circles: CIRCLES.map((c) => ({ id: c.id, server: SERVER.id, name: say(c.name, lang), color: c.color })),
|
||||
totals: {
|
||||
people: people.length,
|
||||
devices: DEVICES.length,
|
||||
online: people.filter((p) => p.online).length,
|
||||
active: people.filter((p) => p.state === 'active').length,
|
||||
today,
|
||||
month: sum(days.slice(-30)),
|
||||
},
|
||||
series,
|
||||
hours: hours.map((w) => [Math.round((today[0] * w) / all), Math.round((today[1] * w) / all)]),
|
||||
events: log(lang).slice(-60),
|
||||
awg: { v2: true, v3: true },
|
||||
awg_state: { tools: true, kmod: true, loaded: true, handler: true, missing: [], ok: true },
|
||||
wan: '203.0.113.1',
|
||||
like_home: { active: false },
|
||||
geo: {
|
||||
enabled: true,
|
||||
home: { lat: home.lat, lon: home.lon, city: home.city, country: home.country, cc: home.cc, asn: 0, org: home.org },
|
||||
points: places(lang),
|
||||
},
|
||||
};
|
||||
made.set(lang, st);
|
||||
return st;
|
||||
}
|
||||
|
||||
/** A person's traffic and each of their devices', a day at a time, for the last `days` days. */
|
||||
export function usage(id: string, days: number): { person: DayUsage[]; devices: Record<string, DayUsage[]> } | null {
|
||||
const p = PEOPLE.find((x) => x.id === id);
|
||||
if (!p) return null;
|
||||
const take = Math.min(DAYS, Math.max(1, days));
|
||||
const named = (pairs: Pair[]): DayUsage[] => pairs.slice(-take).map(([rx, tx], i) => ({ day: dayOf(midnight(take - 1 - i)), rx, tx }));
|
||||
const each = p.devices.map(daily);
|
||||
return { person: named(add(each)), devices: Object.fromEntries(p.devices.map((d, i) => [d.id, named(each[i])])) };
|
||||
}
|
||||
@@ -1,147 +0,0 @@
|
||||
// A device's own link in its drawer (./device): what goes wrong with its
|
||||
// connection (the agent's link state, in words about the device), its MTU and
|
||||
// keep-alive with a dialog each, and LAN Bypass as it was chosen when the
|
||||
// device was added. The router checks the values again
|
||||
// (core.set_device_link); the help lines are ./netcheck's, the state's words
|
||||
// ./events/model's.
|
||||
|
||||
import type { Device, DeviceLink, Person, Server } from '../shared/types';
|
||||
import { E } from './e';
|
||||
import { api, type DeviceLinkPatch } from './api';
|
||||
import { button } from './ui/button';
|
||||
import { cancelButton, closeModal, modal } from './ui/modal';
|
||||
import { attempt, notify } from './ui/toast';
|
||||
import { liveField } from './ui/layout';
|
||||
import { deviceKeepaliveHelp, deviceMtuHelp, type Help } from './netcheck';
|
||||
import { linkStateText } from './events/model';
|
||||
import { fmt } from '../shared/i18n';
|
||||
import { homeOf, netsLabel } from '../shared/format';
|
||||
|
||||
/** Status while the link fails in a named way: the state (warn) and a line on what it means; null for an unknown one. */
|
||||
export function linkStatus(link: DeviceLink): HTMLElement[] | null {
|
||||
const t = linkStateText(link.state);
|
||||
return t ? [E('span', { class: 'dl-dstat warn' }, t.title), E('span', { class: 'dl-sub' }, t.line)] : null;
|
||||
}
|
||||
|
||||
/** The MTU a device gets with none of its own: its server's for its kind (null when that is not known). */
|
||||
function autoMtu(d: Device, srv?: Server): number | null {
|
||||
if (srv) return d.kind === 'phone' || d.kind === 'tablet' ? srv.mtus.phone : srv.mtus.computer;
|
||||
return d.mtu ? null : (d.mtu_used ?? null);
|
||||
}
|
||||
|
||||
/** One value in a dialog of its own: the field with its help as it is typed, Save through device_update. */
|
||||
function linkDialog(
|
||||
title: string,
|
||||
label: string,
|
||||
input: HTMLInputElement,
|
||||
help: () => Help,
|
||||
patch: () => DeviceLinkPatch,
|
||||
id: string,
|
||||
saved: () => unknown,
|
||||
) {
|
||||
const field = liveField(label, input, help);
|
||||
modal(
|
||||
title,
|
||||
[field],
|
||||
[
|
||||
cancelButton(),
|
||||
' ',
|
||||
button(
|
||||
_('Save'),
|
||||
async () => {
|
||||
const h = field.help();
|
||||
if (h.bad) {
|
||||
notify(h.text, 'warning');
|
||||
return;
|
||||
}
|
||||
if (await attempt(() => api.deviceUpdate(id, undefined, undefined, patch()), _('Saved'))) {
|
||||
closeModal();
|
||||
await saved();
|
||||
}
|
||||
},
|
||||
'positive',
|
||||
),
|
||||
],
|
||||
);
|
||||
setTimeout(() => input.select(), 50);
|
||||
}
|
||||
|
||||
/** A number field for a link value: the device's own, or empty for what it gets without one (`placeholder`). */
|
||||
function numberInput(value: number | null | undefined, placeholder: string | null): HTMLInputElement {
|
||||
return E('input', {
|
||||
type: 'text',
|
||||
class: 'cbi-input-text',
|
||||
inputmode: 'numeric',
|
||||
maxlength: 4,
|
||||
value: value == null ? '' : String(value),
|
||||
placeholder,
|
||||
}) as HTMLInputElement;
|
||||
}
|
||||
|
||||
function mtuDialog(d: Device, srv: Server | undefined, saved: () => unknown) {
|
||||
const auto = autoMtu(d, srv);
|
||||
const input = numberInput(d.mtu || null, auto ? fmt(_('Automatic: %s'), auto) : null);
|
||||
linkDialog(
|
||||
fmt(_('MTU of %s'), d.name),
|
||||
'MTU',
|
||||
input,
|
||||
() => deviceMtuHelp(input.value),
|
||||
() => ({ mtu: input.value.trim() }),
|
||||
d.id,
|
||||
saved,
|
||||
);
|
||||
}
|
||||
|
||||
function keepaliveDialog(d: Device, srv: Server | undefined, saved: () => unknown) {
|
||||
const input = numberInput(d.keepalive, srv ? fmt(_('As the server: %s'), srv.keepalive) : null);
|
||||
linkDialog(
|
||||
fmt(_('Keep-alive of %s'), d.name),
|
||||
_('Keep-alive'),
|
||||
input,
|
||||
() => deviceKeepaliveHelp(input.value),
|
||||
() => ({ keepalive: input.value.trim() }),
|
||||
d.id,
|
||||
saved,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Details rows as [label, value]: the MTU and keep-alive its configuration
|
||||
* carries, each with Change (its own dialog, then `saved`), and LAN Bypass as
|
||||
* it was chosen when the device was added.
|
||||
*/
|
||||
export function linkRows(d: Device, p: Person, srv: Server | undefined, saved: () => unknown): [string, Node][] {
|
||||
const home = homeOf(p, srv);
|
||||
// Two buttons say "Change": each is named after its row for a screen reader.
|
||||
const value = (v: string, from: string, name: string, change: () => void) =>
|
||||
E('span', { class: 'dl-kv-act' }, [
|
||||
E('span', {}, [v, from ? [' ', E('span', { class: 'dl-faint' }, from)] : '']),
|
||||
E('button', { type: 'button', class: 'dl-linkbtn', 'aria-label': name, click: change }, _('Change')),
|
||||
]);
|
||||
const ka = d.keepalive_used;
|
||||
return [
|
||||
[
|
||||
'MTU',
|
||||
value(d.mtu_used == null ? '—' : String(d.mtu_used), d.mtu ? '' : _('automatic'), _('Change the MTU'), () =>
|
||||
mtuDialog(d, srv, saved),
|
||||
),
|
||||
],
|
||||
[
|
||||
_('Keep-alive'),
|
||||
value(
|
||||
ka == null ? '—' : ka ? fmt(_('%s s'), ka) : _('Off'),
|
||||
d.keepalive != null ? '' : _('as the server'),
|
||||
_('Change the keep-alive'),
|
||||
() => keepaliveDialog(d, srv, saved),
|
||||
),
|
||||
],
|
||||
[
|
||||
_('LAN Bypass'),
|
||||
E('span', {}, [
|
||||
!d.lan_bypass ? _('Off') : home.length ? fmt(_('On, except %s (home)'), netsLabel(home)) : _('On'),
|
||||
' ',
|
||||
E('span', { class: 'dl-faint' }, _('set when it was added')),
|
||||
]),
|
||||
],
|
||||
];
|
||||
}
|
||||
@@ -1,734 +0,0 @@
|
||||
// Device drawer: a right-hand panel with the device's status, connection
|
||||
// (QR / key / file, from its server's core), details and actions; the ⋯ menu
|
||||
// on a device card; and the admin's Add device dialog. Its own link (link
|
||||
// state, MTU, keep-alive, LAN Bypass) is ./device-link.
|
||||
|
||||
import type { ClientConfig, Device, Geo, Kind, LogEvent, Person, Server } from '../shared/types';
|
||||
import { E } from './e';
|
||||
import { api } from './api';
|
||||
import { button } from './ui/button';
|
||||
import { cancelButton, closeModal, confirmDialog, modal } from './ui/modal';
|
||||
import { copyText, downloadFile } from './ui/files';
|
||||
import { dropdown, type MenuItem } from './ui/menu';
|
||||
import { drawer } from './ui/drawer';
|
||||
import { attempt, notify } from './ui/toast';
|
||||
import { liveField, warnNote } from './ui/layout';
|
||||
import { isOn, sw } from './ui/controls';
|
||||
import { qrCode } from './ui/qr';
|
||||
import { deviceNameHelp, type Help } from './netcheck';
|
||||
import { deviceStatus } from './ui/badges';
|
||||
import {
|
||||
ago,
|
||||
bytes,
|
||||
defaultName,
|
||||
fitName,
|
||||
homeOf,
|
||||
isoDay,
|
||||
kindLabel,
|
||||
netsLabel,
|
||||
pickLabel,
|
||||
PICKS,
|
||||
todayOf,
|
||||
type KindPick,
|
||||
} from '../shared/format';
|
||||
import { guardDeviceName } from '../shared/name-guard';
|
||||
import { fill, fmt, locale, num } from '../shared/i18n';
|
||||
import { icon } from '../shared/icons';
|
||||
import { eventBy } from './events/model';
|
||||
import { spark } from './widgets/spark';
|
||||
import { clearLogDialog, exportEvents, resetUsageDialog } from './logs';
|
||||
import { coreFor, coreOf, type Core } from './cores';
|
||||
import { plainWg } from './cores/awg';
|
||||
import { onLiveChange } from './state/live';
|
||||
import { ConnectionMap, rangeControl, type Range } from './map';
|
||||
import { PlacesView } from './places/render';
|
||||
import { personUrl } from './urls';
|
||||
import { linkRows, linkStatus } from './device-link';
|
||||
|
||||
/** What the page that opens a device hands over. */
|
||||
export interface DeviceOpts {
|
||||
/** Reload the page after a change made here. */
|
||||
refresh: () => unknown;
|
||||
geo?: Geo;
|
||||
/** The router's clock (seconds) and day, for "5 min ago" and the chart labels. */
|
||||
now?: number;
|
||||
today?: string;
|
||||
/** The device's server's core (AmneziaWG when not given). */
|
||||
core?: Core;
|
||||
/** The device's server: what an empty MTU or keep-alive of its own gives. */
|
||||
server?: Server;
|
||||
/** The page's activity log, when it keeps one: the drawer reads it instead of fetching its own. */
|
||||
events?: () => LogEvent[] | null;
|
||||
}
|
||||
|
||||
function when(ts: number): string {
|
||||
return ts
|
||||
? new Date(ts * 1000).toLocaleString(locale(), { day: 'numeric', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' })
|
||||
: '—';
|
||||
}
|
||||
|
||||
function copyRow(label: string, value: string, mono = false): HTMLElement {
|
||||
return E('div', { class: 'dl-kvrow' }, [
|
||||
E('span', { class: 'dl-kvrow-k' }, label),
|
||||
E(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
class: `dl-kvrow-v copy${mono ? ' dl-mono' : ''}`,
|
||||
title: _('Copy'),
|
||||
click: () => copyText(value, fmt(_('%s copied'), label)),
|
||||
},
|
||||
[E('span', {}, value), icon('copy')],
|
||||
),
|
||||
]);
|
||||
}
|
||||
|
||||
function row(label: string, value: Node | string): HTMLElement {
|
||||
return E('div', { class: 'dl-kvrow' }, [E('span', { class: 'dl-kvrow-k' }, label), E('span', { class: 'dl-kvrow-v' }, value)]);
|
||||
}
|
||||
|
||||
/** The device's own events: tone and icon (what they say is in eventText). */
|
||||
const DEV_EVENT: Record<string, [string, string]> = {
|
||||
connect: ['ok', 'plug'],
|
||||
disconnect: ['', 'plug'],
|
||||
roam: ['', 'network'],
|
||||
device_added: ['ok', 'plus'],
|
||||
device_removed: ['', 'trash'],
|
||||
device_keys: ['', 'reset'],
|
||||
};
|
||||
|
||||
/** What happened in the text colour, the details muted (as in the main log). */
|
||||
function eventText(e: LogEvent): (string | HTMLElement)[] {
|
||||
const m = (t: string) => E('span', { class: 'dl-muted' }, t);
|
||||
const by = eventBy(e) === 'portal' ? _('on the portal') : eventBy(e) === 'admin' ? _('by you') : '';
|
||||
switch (e.type) {
|
||||
case 'connect':
|
||||
return [...(e.detail ? fill(_('Connected from %s'), m(e.detail)) : [_('Connected')]), e.where ? m(` · ${e.where}`) : ''];
|
||||
case 'disconnect':
|
||||
return [_('Went offline')];
|
||||
case 'roam':
|
||||
return [_('Changed network'), m(` · ${e.detail ?? ''}`)];
|
||||
case 'device_added':
|
||||
return by ? fill(_('Added %s'), m(by)) : [_('Added')];
|
||||
case 'device_removed':
|
||||
return by ? fill(_('Removed %s'), m(by)) : [_('Removed')];
|
||||
default: // device_keys
|
||||
return by ? fill(_('New keys %s'), m(by)) : [_('New keys')];
|
||||
}
|
||||
}
|
||||
|
||||
/** Activity of one device, newest first. */
|
||||
function deviceEvents(events: LogEvent[], id: string, now?: number): HTMLElement {
|
||||
const mine = events
|
||||
.filter((e) => e.device === id && DEV_EVENT[e.type])
|
||||
.reverse()
|
||||
.slice(0, 12);
|
||||
if (!mine.length) return E('div', { class: 'dl-sub' }, _('No activity yet.'));
|
||||
return E(
|
||||
'div',
|
||||
{ class: 'dl-dev-log' },
|
||||
mine.map((e) => {
|
||||
const [tone, ic] = DEV_EVENT[e.type];
|
||||
const t = new Date(e.ts * 1000);
|
||||
return E('div', { class: `dl-dev-log-row${eventBy(e) === 'admin' ? ' dl-ev-by-admin' : ''}` }, [
|
||||
eventBy(e) === 'admin'
|
||||
? E('span', { class: 'dl-ev-tile', title: _('Done by you in LuCI') }, icon('admin'))
|
||||
: E('span', { class: `dl-ev-tile ev ${tone}` }, icon(ic)),
|
||||
E('span', { class: 'dl-row-main' }, eventText(e)),
|
||||
E('span', { class: 'dl-faint dl-nowrap', title: t.toLocaleString(locale()) }, ago(e.ts, now)),
|
||||
]);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/** Open the drawer of a device that was just made or changed, with fresh status. */
|
||||
async function reopen(personId: string, deviceId: string, o: DeviceOpts) {
|
||||
const st = await api.status(1).catch(() => null);
|
||||
const p2 = st?.people.find((x) => x.id === personId);
|
||||
const d2 = p2?.devices.find((x) => x.id === deviceId);
|
||||
if (st && p2 && d2)
|
||||
void openDevice(p2, d2, {
|
||||
...o,
|
||||
geo: st.geo,
|
||||
now: st.now,
|
||||
today: todayOf(st.series),
|
||||
core: coreFor(st.servers, p2.server),
|
||||
server: st.servers.find((s) => s.id === p2.server),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The connection of a device that holds an older configuration, behind a button: showing the new one is what
|
||||
* counts as giving it out (it clears "Update config"), never opening the drawer. `shown` runs once it is out.
|
||||
*/
|
||||
function newConfigGate(id: string, show: (cfg: ClientConfig) => Promise<HTMLElement>, shown: () => unknown): HTMLElement {
|
||||
const box = E('div', { class: 'dl-row-actions' });
|
||||
dom.content(
|
||||
box,
|
||||
button([icon('qr'), ' ', _('Show the new configuration')], async () => {
|
||||
const cfg = await attempt(() => api.deviceConfig(id, true));
|
||||
if (!cfg) return;
|
||||
box.className = '';
|
||||
dom.content(box, await show(cfg));
|
||||
void shown();
|
||||
}),
|
||||
);
|
||||
return box;
|
||||
}
|
||||
|
||||
/** Device drawer. */
|
||||
export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
|
||||
// A look: only a delivery (a code, a file, a key handed to the device) clears "Update config".
|
||||
const cfg = await attempt(() => api.deviceConfig(dev.id));
|
||||
if (!cfg) return;
|
||||
const core = o.core ?? coreOf(null);
|
||||
let d = dev;
|
||||
let p = person;
|
||||
let geo = o.geo;
|
||||
let now = o.now;
|
||||
let today = o.today ?? isoDay(new Date());
|
||||
let srv = o.server;
|
||||
// Phones and tablets are set up by scanning; computers and routers by a file.
|
||||
const block = (c: ClientConfig) => core.connectBlock(c, dev.kind, dev.kind === 'phone' || dev.kind === 'tablet' ? 'qr' : 'file');
|
||||
// An older configuration on the device: the new one waits for a click (the inline QR code is itself a delivery).
|
||||
// `relinked`: its MTU or keep-alive was just changed here, which outdates the configuration on screen even where
|
||||
// the router keeps no record of what the device got (never "stale" then, e.g. after a JSON import).
|
||||
let gated = dev.config_stale;
|
||||
let relinked = false;
|
||||
const gate = () =>
|
||||
newConfigGate(dev.id, block, () => {
|
||||
gated = false;
|
||||
return changed();
|
||||
});
|
||||
const connect = gated ? gate() : await block(cfg);
|
||||
const titleEl = E('div', { class: 'dl-drawer-title' });
|
||||
const stats = E('div', {});
|
||||
const details = E('div', {});
|
||||
const log = E('div', {}, E('div', { class: 'dl-sub' }, _('Loading…')));
|
||||
let logEvents: LogEvent[] = [];
|
||||
const showLog = (events: LogEvent[]) => {
|
||||
logEvents = events.filter((e) => e.device === d.id);
|
||||
dom.content(log, deviceEvents(events, d.id, now));
|
||||
view?.update({ events });
|
||||
};
|
||||
/** The page's events when it has them; otherwise a fetch (`force` after clearing). */
|
||||
const loadLog = async (force = false) => {
|
||||
const own = o.events?.();
|
||||
if (own && !force) return showLog(own);
|
||||
const ev = await api.events(2000, person.id).catch(() => null);
|
||||
if (ev) showLog(ev.events);
|
||||
};
|
||||
|
||||
// Where this device connected from: the map, a row per place with a strip of when it was
|
||||
// there (from the log's connections), and a replay of the period on the map.
|
||||
let range: Range = '30d';
|
||||
let map: ConnectionMap | null = null;
|
||||
let view: PlacesView | null = null;
|
||||
const paint = () => {
|
||||
dom.content(titleEl, [
|
||||
E('span', { class: `dl-dcard-ic${d.online ? ' on' : ''}` }, icon(d.kind)),
|
||||
E('div', { class: 'dl-stack' }, [
|
||||
E('div', { class: 'dl-title-row' }, [
|
||||
E('h3', {}, d.name),
|
||||
button([icon('edit')], () => rename(), 'neutral', { title: _('Rename'), class: 'cbi-button cbi-button-neutral dl-icon-only sm' }),
|
||||
]),
|
||||
E('span', { class: 'dl-sub' }, `${p.name} · ${kindLabel(d.kind)}`),
|
||||
]),
|
||||
]);
|
||||
const week = d.spark.reduce((a, [rx, tx]) => a + rx + tx, 0);
|
||||
dom.content(
|
||||
stats,
|
||||
E('div', { class: 'dl-dstats' }, [
|
||||
E('div', { class: 'dl-dstats-cell wide' }, [
|
||||
E('span', { class: 'dl-metric-label' }, _('Status')),
|
||||
// Its link failing in a named way says so, with what it means; otherwise its usual status.
|
||||
(d.link && !d.disabled && linkStatus(d.link)) || deviceStatus(d, now, _('Waiting for the first connection'), p),
|
||||
]),
|
||||
E('div', { class: 'dl-dstats-cell' }, [
|
||||
E('span', { class: 'dl-metric-label' }, _('This month')),
|
||||
E('b', {}, bytes(d.month[0] + d.month[1])),
|
||||
E('span', { class: 'dl-sub dl-mono' }, `↓ ${bytes(d.month[1])} ↑ ${bytes(d.month[0])}`),
|
||||
]),
|
||||
E('div', { class: 'dl-dstats-cell' }, [
|
||||
E('span', { class: 'dl-metric-label' }, _('Last 7 days')),
|
||||
E('b', {}, bytes(week)),
|
||||
spark(d.spark, 120, 22, today),
|
||||
]),
|
||||
]),
|
||||
);
|
||||
dom.content(
|
||||
details,
|
||||
E('div', { class: 'dl-kv2' }, [
|
||||
copyRow(_('Tunnel address'), d.address),
|
||||
...linkRows(d, p, srv, () => {
|
||||
relinked = true;
|
||||
return changed();
|
||||
}).map(([k, v]) => row(k, v)),
|
||||
d.hostname && p.access !== 'internet' ? copyRow(_('Local address'), d.hostname) : '',
|
||||
// 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' }, [
|
||||
`↓ ${bytes(d.total[1])} · ↑ ${bytes(d.total[0])}`,
|
||||
E(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
class: 'dl-linkbtn danger',
|
||||
click: () => resetUsageDialog('device', d.id, d.name, () => setTimeout(changed, 300)),
|
||||
},
|
||||
_('Reset'),
|
||||
),
|
||||
]),
|
||||
),
|
||||
row(_('Added'), `${when(d.created)} · ${d.created_by === 'portal' ? _('from the portal') : _('by you')}`),
|
||||
// The whole key, copyable: it is what another WireGuard server needs to add this device by hand.
|
||||
cfg.amnezia.client_pub_key ? copyRow(_('Public key'), cfg.amnezia.client_pub_key) : row(_('Public key'), '—'),
|
||||
]),
|
||||
);
|
||||
dom.content(foot, [
|
||||
button(
|
||||
[icon(d.disabled ? 'play' : 'pause'), ' ', d.disabled ? _('Enable') : _('Disable')],
|
||||
async () => {
|
||||
if (await attempt(() => api.deviceUpdate(d.id, undefined, !d.disabled), d.disabled ? _('Device enabled') : _('Device disabled')))
|
||||
await changed();
|
||||
},
|
||||
'neutral',
|
||||
d.disabled ? {} : { class: 'cbi-button cbi-button-neutral dl-btn-warn' },
|
||||
),
|
||||
button([icon('key'), ' ', _('New keys')], async () => {
|
||||
if (
|
||||
!(await confirmDialog(
|
||||
_('Generate new keys?'),
|
||||
_('The current configuration on this device stops working until it is imported again.'),
|
||||
_('Generate'),
|
||||
true,
|
||||
))
|
||||
)
|
||||
return;
|
||||
const c = await attempt(() => api.deviceRotate(d.id), _('New keys generated'));
|
||||
if (c) {
|
||||
o.refresh();
|
||||
handle.close();
|
||||
await reopen(p.id, d.id, o);
|
||||
}
|
||||
}),
|
||||
E('span', { class: 'dl-spacer' }),
|
||||
button(
|
||||
[icon('trash'), ' ', _('Remove')],
|
||||
async () => {
|
||||
if (
|
||||
!(await confirmDialog(
|
||||
fmt(_('Remove %s?'), d.name),
|
||||
_('The device is disconnected immediately and its configuration stops working.'),
|
||||
_('Remove'),
|
||||
true,
|
||||
))
|
||||
)
|
||||
return;
|
||||
if (await attempt(() => api.deviceDelete(d.id), _('Device removed'))) {
|
||||
handle.close();
|
||||
o.refresh();
|
||||
}
|
||||
},
|
||||
'negative',
|
||||
),
|
||||
]);
|
||||
};
|
||||
|
||||
/** The device's own state, fresh from the router; the page underneath is left alone. */
|
||||
const reload = async () => {
|
||||
const st = await api.status(1).catch(() => null);
|
||||
const p2 = st?.people.find((x) => x.id === p.id);
|
||||
const d2 = p2?.devices.find((x) => x.id === d.id);
|
||||
if (!st || !p2 || !d2) return;
|
||||
p = p2;
|
||||
d = d2;
|
||||
geo = st.geo;
|
||||
now = st.now;
|
||||
today = todayOf(st.series);
|
||||
srv = st.servers.find((s) => s.id === p2.server);
|
||||
paint();
|
||||
// A change made here (its MTU or keep-alive) or elsewhere left the configuration on screen behind: the new one
|
||||
// waits behind the button.
|
||||
if ((d.config_stale || relinked) && !gated) {
|
||||
gated = true;
|
||||
dom.content(connectSec, connectBody(gate()));
|
||||
}
|
||||
relinked = false;
|
||||
view?.update({ geo: st.geo, now: st.now, person: p, device: d });
|
||||
};
|
||||
/** After a change made here: this drawer and the page. */
|
||||
const changed = async () => {
|
||||
await reload();
|
||||
o.refresh();
|
||||
};
|
||||
|
||||
const rename = () => {
|
||||
const input = E('input', { type: 'text', class: 'cbi-input-text', value: d.name }) as HTMLInputElement;
|
||||
const said = nameGuard(input, () => nameRow.refresh());
|
||||
const taken = p.devices.filter((x) => x.id !== d.id).map((x) => x.name);
|
||||
const nameRow = liveField(_('Name'), input, () => said(deviceNameHelp(input.value, taken, _('Shown in the portal and in the app.'))));
|
||||
modal(
|
||||
fmt(_('Rename %s'), d.name),
|
||||
[nameRow],
|
||||
[
|
||||
cancelButton(),
|
||||
' ',
|
||||
button(
|
||||
_('Save'),
|
||||
async () => {
|
||||
const h = nameRow.help();
|
||||
if (h.bad) {
|
||||
notify(h.text, 'warning');
|
||||
return;
|
||||
}
|
||||
if (await attempt(() => api.deviceUpdate(d.id, input.value, undefined), _('Renamed'))) {
|
||||
closeModal();
|
||||
await changed();
|
||||
}
|
||||
},
|
||||
'positive',
|
||||
),
|
||||
],
|
||||
);
|
||||
setTimeout(() => input.select(), 50);
|
||||
};
|
||||
|
||||
const foot = E('div', { class: 'dl-drawer-actions' });
|
||||
const connectBody = (c: HTMLElement) => [
|
||||
// Whether it is connected (or still waiting) is in Status above.
|
||||
E('div', { class: 'dl-dsec-head' }, [E('h4', {}, _('Connect', 'section'))]),
|
||||
d.config_stale
|
||||
? warnNote(
|
||||
_(
|
||||
'This device has an older configuration: networks or DNS changed since it was set up. Import it again with the QR code, key or file below.',
|
||||
),
|
||||
)
|
||||
: '',
|
||||
c,
|
||||
];
|
||||
const connectSec = E('section', { class: 'dl-dsec' }, connectBody(connect));
|
||||
const activitySec = E('section', { class: 'dl-dsec' }, [
|
||||
E('div', { class: 'dl-dsec-head' }, [
|
||||
E('h4', {}, _('Activity')),
|
||||
E('div', { class: 'dl-dsec-actions' }, [
|
||||
E(
|
||||
'button',
|
||||
{ type: 'button', class: 'dl-linkbtn', click: () => exportEvents({ people: [p] }, logEvents, 'csv', d.id) },
|
||||
_('Export'),
|
||||
),
|
||||
E(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
class: 'dl-linkbtn danger',
|
||||
click: () =>
|
||||
clearLogDialog(fmt(_("Clear %s's activity"), d.name), fmt(_('Removes events about %s.'), d.name), { device: d.id }, () => {
|
||||
void loadLog(true);
|
||||
o.refresh();
|
||||
}),
|
||||
},
|
||||
_('Clear'),
|
||||
),
|
||||
E('a', { href: `${L.url('admin/services/dawnline/diagnostics')}?tab=log` }, _('All activity')),
|
||||
]),
|
||||
]),
|
||||
log,
|
||||
]);
|
||||
const detailsSec = E('section', { class: 'dl-dsec' }, [
|
||||
E('div', { class: 'dl-dsec-head' }, E('h4', {}, _('Details', 'section'))),
|
||||
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,
|
||||
);
|
||||
const v = (view = new PlacesView(map, range, {
|
||||
geo,
|
||||
now: now ?? Date.now() / 1000,
|
||||
person: p,
|
||||
device: d,
|
||||
events: o.events?.() ?? null,
|
||||
}));
|
||||
locationsSec = E('section', { class: 'dl-dsec' }, [
|
||||
E('div', { class: 'dl-dsec-head' }, [
|
||||
E('h4', {}, _('Locations')),
|
||||
rangeControl(
|
||||
range,
|
||||
(r) => {
|
||||
range = r;
|
||||
v.setRange(r);
|
||||
},
|
||||
false,
|
||||
),
|
||||
]),
|
||||
E('div', { class: 'dl-dmap' }, [map.el, v.controls]),
|
||||
v.el,
|
||||
]);
|
||||
}
|
||||
// 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, 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.
|
||||
const live = () => {
|
||||
void reload();
|
||||
void loadLog();
|
||||
};
|
||||
const off = onLiveChange(live);
|
||||
const watch = window.setInterval(live, 30000);
|
||||
const handle = drawer(titleEl, body, foot, () => {
|
||||
clearInterval(watch);
|
||||
off();
|
||||
view?.destroy();
|
||||
map?.destroy();
|
||||
});
|
||||
paint();
|
||||
if (map && view) requestAnimationFrame(() => view && map?.mount(view.mapData()));
|
||||
}
|
||||
|
||||
/** ⋯ on a device card: quick actions (everything else is in the panel; click the card). */
|
||||
export function quickMenu(anchor: HTMLElement, p: Person, d: Device, o: DeviceOpts) {
|
||||
const core = o.core ?? coreOf(null);
|
||||
// Each of these gives the configuration out.
|
||||
const cfg = () => attempt(() => api.deviceConfig(d.id, true));
|
||||
const items: (MenuItem | null)[] = [
|
||||
{
|
||||
label: _('Show QR code'),
|
||||
icon: icon('qr'),
|
||||
run: async () => {
|
||||
const c = await cfg();
|
||||
if (!c) return;
|
||||
modal(
|
||||
`${d.name} · ${_('QR code')}`,
|
||||
E('div', { class: 'dl-qr-pane' }, [
|
||||
qrCode(core.qrText(c)),
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-sub' },
|
||||
plainWg(c)
|
||||
? _('Scan with AmneziaVPN or any WireGuard app on the device.')
|
||||
: _('Scan with AmneziaVPN or AmneziaWG on the device.'),
|
||||
),
|
||||
]),
|
||||
cancelButton(_('Close')),
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
label: core.file.label,
|
||||
icon: icon('download'),
|
||||
run: async () => {
|
||||
const c = await cfg();
|
||||
if (!c) return;
|
||||
const f = core.file.make(c);
|
||||
downloadFile(f.name, f.text, 'application/octet-stream');
|
||||
},
|
||||
},
|
||||
core.appKey
|
||||
? {
|
||||
label: core.appKey.label,
|
||||
icon: icon('copy'),
|
||||
run: async () => {
|
||||
const c = await cfg();
|
||||
if (c) copyText(await core.appKey!.make(c), _('Key copied'));
|
||||
},
|
||||
}
|
||||
: null,
|
||||
null,
|
||||
{ label: _('Rename'), icon: icon('edit'), run: () => openDevice(p, d, o) },
|
||||
{
|
||||
label: _('New keys'),
|
||||
icon: icon('key'),
|
||||
run: async () => {
|
||||
if (
|
||||
await confirmDialog(
|
||||
_('Generate new keys?'),
|
||||
_('The current configuration on this device stops working until it is imported again.'),
|
||||
_('Generate'),
|
||||
true,
|
||||
)
|
||||
)
|
||||
if (await attempt(() => api.deviceRotate(d.id), _('New keys generated'))) o.refresh();
|
||||
},
|
||||
},
|
||||
{
|
||||
label: d.disabled ? _('Enable') : _('Disable'),
|
||||
icon: icon(d.disabled ? 'play' : 'pause'),
|
||||
warn: !d.disabled,
|
||||
run: async () => {
|
||||
if (await attempt(() => api.deviceUpdate(d.id, undefined, !d.disabled), d.disabled ? _('Device enabled') : _('Device disabled')))
|
||||
o.refresh();
|
||||
},
|
||||
},
|
||||
{
|
||||
label: _('Delete'),
|
||||
icon: icon('trash'),
|
||||
danger: true,
|
||||
run: async () => {
|
||||
if (
|
||||
await confirmDialog(
|
||||
fmt(_('Remove %s?'), d.name),
|
||||
_('The device is disconnected immediately and its configuration stops working.'),
|
||||
_('Remove'),
|
||||
true,
|
||||
)
|
||||
)
|
||||
if (await attempt(() => api.deviceDelete(d.id), _('Device removed'))) o.refresh();
|
||||
},
|
||||
},
|
||||
];
|
||||
dropdown(anchor, items);
|
||||
}
|
||||
|
||||
/**
|
||||
* A device's name field guarded as the portal's are (shared/name-guard.ts): a refused character shakes the input,
|
||||
* and the row's help says why until a change gets in or the field is left (Save never reads a stale reason).
|
||||
* Returns what the row's help passes its own through.
|
||||
*/
|
||||
function nameGuard(input: HTMLInputElement, refresh: () => void): (help: Help) => Help {
|
||||
let why: string | null = null;
|
||||
guardDeviceName(input, input, (w) => {
|
||||
why = w;
|
||||
refresh();
|
||||
});
|
||||
input.addEventListener('blur', () => {
|
||||
if (!why) return;
|
||||
why = null;
|
||||
refresh();
|
||||
});
|
||||
return (help) => (why ? { text: why, bad: true } : help);
|
||||
}
|
||||
|
||||
/** Admin "Add device" dialog for a person; opens the new device's drawer. */
|
||||
export function addDevice(person: Person, o: DeviceOpts) {
|
||||
const taken = person.devices.map((x) => x.name);
|
||||
// The name a type gives when none is typed: "Phone", then "Phone 2" (as the portal does).
|
||||
const suggest = (k: Kind) => {
|
||||
const base = defaultName(k);
|
||||
let n = 1;
|
||||
let name = fitName(base);
|
||||
while (taken.some((t) => t.toLowerCase() === name.toLowerCase())) name = fitName(base, ` ${++n}`);
|
||||
return name;
|
||||
};
|
||||
// Mobile from here is a phone: the admin is never on the device itself (see KindPick).
|
||||
const kindOf = (p: KindPick): Kind => (p === 'mobile' ? 'phone' : p);
|
||||
let pick: KindPick = 'mobile';
|
||||
const nameInput = E('input', {
|
||||
type: 'text',
|
||||
class: 'cbi-input-text',
|
||||
placeholder: suggest(kindOf(pick)),
|
||||
}) as HTMLInputElement;
|
||||
const said = nameGuard(nameInput, () => nameRow.refresh());
|
||||
const nameRow = liveField(_('Name'), nameInput, () =>
|
||||
said(
|
||||
nameInput.value.trim()
|
||||
? deviceNameHelp(nameInput.value, taken, _('Shown in the portal and in the app.'))
|
||||
: { text: fmt(_('Named after its type: %s.'), suggest(kindOf(pick))), bad: false },
|
||||
),
|
||||
);
|
||||
const kinds = E(
|
||||
'div',
|
||||
{ class: 'dl-kinds', role: 'radiogroup', 'aria-label': _('Type') },
|
||||
PICKS.map((k) =>
|
||||
E(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
role: 'radio',
|
||||
class: k === pick ? 'on' : '',
|
||||
'aria-checked': k === pick ? 'true' : 'false',
|
||||
'data-kind': k,
|
||||
click: () => {
|
||||
pick = k;
|
||||
kinds.querySelectorAll('button').forEach((c) => {
|
||||
const on = (c as HTMLElement).dataset.kind === k;
|
||||
c.classList.toggle('on', on);
|
||||
c.setAttribute('aria-checked', on ? 'true' : 'false');
|
||||
});
|
||||
nameInput.placeholder = suggest(kindOf(k));
|
||||
nameRow.refresh();
|
||||
},
|
||||
},
|
||||
[icon(k), E('span', {}, pickLabel(k))],
|
||||
),
|
||||
),
|
||||
);
|
||||
// LAN Bypass: on unless turned off (the person chooses it on the portal, the admin here).
|
||||
const bypass = sw(true, _('LAN Bypass'));
|
||||
const over = person.devices.length >= person.device_limit;
|
||||
modal(
|
||||
fmt(_('Add a device for %s'), person.name),
|
||||
[
|
||||
over
|
||||
? E(
|
||||
'p',
|
||||
{ class: 'dl-hint' },
|
||||
fmt(
|
||||
N_(
|
||||
person.device_limit,
|
||||
'%s already has %s of %s device. As admin you can still add one.',
|
||||
'%s already has %s of %s devices. As admin you can still add one.',
|
||||
),
|
||||
person.name,
|
||||
num(person.devices.length),
|
||||
num(person.device_limit),
|
||||
),
|
||||
)
|
||||
: '',
|
||||
E('div', { class: 'dl-fld' }, [E('span', { class: 'dl-fld-label' }, _('Type')), kinds]),
|
||||
// As the portal's Add a device: between the type and the name.
|
||||
E('div', { class: 'cbi-value dl-live' }, [
|
||||
E('div', { class: 'cbi-value-title' }, [
|
||||
E('label', {}, _('LAN Bypass')),
|
||||
E(
|
||||
'div',
|
||||
{ class: 'dl-sub' },
|
||||
homeOf(person, o.server).length
|
||||
? fmt(
|
||||
_('The device’s local network stays reachable while connected, except %s: your home network.'),
|
||||
netsLabel(homeOf(person, o.server)),
|
||||
)
|
||||
: _('The device’s local network stays reachable while connected.'),
|
||||
),
|
||||
]),
|
||||
E('div', { class: 'cbi-value-field' }, bypass),
|
||||
]),
|
||||
nameRow,
|
||||
],
|
||||
[
|
||||
cancelButton(),
|
||||
' ',
|
||||
button(
|
||||
_('Add device'),
|
||||
async () => {
|
||||
const h = nameRow.help();
|
||||
if (h.bad) {
|
||||
notify(h.text, 'warning');
|
||||
return;
|
||||
}
|
||||
const name = nameInput.value.trim() || suggest(kindOf(pick));
|
||||
const r = await attempt(() => api.deviceCreate(person.id, name, kindOf(pick), isOn(bypass)));
|
||||
if (!r) return;
|
||||
closeModal();
|
||||
notify(fmt(_('%s added'), name), 'success', 3000);
|
||||
o.refresh();
|
||||
await reopen(person.id, r.id, o);
|
||||
},
|
||||
'positive',
|
||||
),
|
||||
],
|
||||
);
|
||||
setTimeout(() => nameInput.focus(), 50);
|
||||
}
|
||||
+25
-102
@@ -1,9 +1,8 @@
|
||||
// Disguise methods: one picker for the Server page and the setup wizard.
|
||||
// The disguise methods in words: what each does to the traffic, which apps
|
||||
// take it, what the router needs for it, and how a switch to it is said (the
|
||||
// Server page's presets and the new server's sheet draw them). No DOM.
|
||||
|
||||
import type { AwgCaps } from '../shared/types';
|
||||
import { E } from './e';
|
||||
import { icon } from '../shared/icons';
|
||||
import { fmt } from '../shared/i18n';
|
||||
|
||||
export type Method = 'balanced' | 'max' | 'off';
|
||||
/** The router features a method may need (the boolean ones of AwgCaps). */
|
||||
@@ -12,55 +11,41 @@ type AwgNeed = 'v2' | 'v3';
|
||||
export interface MethodInfo {
|
||||
id: Method;
|
||||
title: string;
|
||||
ic: string;
|
||||
/** What it does, and what it costs. */
|
||||
text: string;
|
||||
/** 0-4, shown as dots. */
|
||||
stealth: number;
|
||||
speed: number;
|
||||
/** Which apps can connect. */
|
||||
/** Which apps connect with it. */
|
||||
apps: string;
|
||||
/** The same, short (server header). */
|
||||
short: string;
|
||||
/** Router capability it needs. */
|
||||
needs?: AwgNeed;
|
||||
/** The question before switching to it. */
|
||||
ask: string;
|
||||
}
|
||||
|
||||
/** The methods in picker order, in the page's language. */
|
||||
function methods(): MethodInfo[] {
|
||||
/** The methods in the presets' order, in the page's language. */
|
||||
export function methods(): MethodInfo[] {
|
||||
return [
|
||||
{
|
||||
id: 'off',
|
||||
title: _('Off'),
|
||||
ic: 'zap',
|
||||
stealth: 0,
|
||||
speed: 4,
|
||||
text: _('Plain WireGuard-compatible traffic. Fastest, but easy to recognise and block.'),
|
||||
text: _('Plain WireGuard. Fast, but easy to recognise and block.'),
|
||||
apps: _('Any WireGuard app'),
|
||||
short: _('Any WireGuard app'),
|
||||
ask: _('Turn the disguise off?'),
|
||||
},
|
||||
{
|
||||
id: 'balanced',
|
||||
title: _('Balanced'),
|
||||
ic: 'shield',
|
||||
stealth: 3,
|
||||
speed: 4,
|
||||
text: _('Traffic does not look like a VPN. About the same speed.'),
|
||||
apps: _('AmneziaWG 2.0+, AmneziaVPN 4.8.12+'),
|
||||
needs: 'v2',
|
||||
text: _(
|
||||
'AmneziaWG 2.0: junk packets, padded packets and a first packet that looks like DNS. For networks that learned to spot 1.0-style junk.',
|
||||
),
|
||||
apps: _('AmneziaVPN 4.8.12 or newer, AmneziaWG 2.0+ apps'),
|
||||
short: _('AmneziaWG 2.0+ apps'),
|
||||
ask: _('Switch the disguise to Balanced?'),
|
||||
},
|
||||
{
|
||||
id: 'max',
|
||||
title: _('Maximum'),
|
||||
ic: 'lock',
|
||||
stealth: 4,
|
||||
speed: 3,
|
||||
text: _('For networks that block everything. Slower.'),
|
||||
apps: _('AmneziaWG 3.1+, not V2RayTun'),
|
||||
needs: 'v3',
|
||||
text: _('AmneziaWG 3.1: encrypted packet headers, random tails and sizes, jittered timing, and a first packet that looks like DNS.'),
|
||||
apps: _('Apps with AmneziaWG 3.1 (current AmneziaVPN)'),
|
||||
short: _('AmneziaWG 3.1 apps'),
|
||||
ask: _('Switch the disguise to Maximum?'),
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -70,89 +55,27 @@ export const methodInfo = (id: string): MethodInfo | undefined => methods().find
|
||||
/** The disguise a new server gets: the strongest this router can run. */
|
||||
export const defaultMethod = (caps: AwgCaps): Method => (caps.v3 ? 'max' : caps.v2 ? 'balanced' : 'off');
|
||||
|
||||
/** A method this router can run. */
|
||||
export const runs = (m: MethodInfo, caps: AwgCaps): boolean => !m.needs || !!caps[m.needs];
|
||||
|
||||
/**
|
||||
* Servers made before 0.8 may carry the old Standard or Strong disguise
|
||||
* (1.0-style junk only, which networks learned to spot). They keep running;
|
||||
* the picker offers Balanced or Maximum instead. The title for such a server, or null.
|
||||
* the presets offer Balanced or Maximum instead. The title for such a server, or null.
|
||||
*/
|
||||
export const legacyTitle = (preset: string): string | null =>
|
||||
preset === 'standard' ? _('Standard (old)') : preset === 'strong' ? _('Strong (old)') : null;
|
||||
|
||||
/** The disguise's name as a server has it: a method, an old one, or set by hand. */
|
||||
export const presetName = (preset: string): string => methodInfo(preset)?.title ?? legacyTitle(preset) ?? _('Custom', 'disguise');
|
||||
|
||||
/**
|
||||
* Why a method is not available. `installed` is false while no AmneziaWG is
|
||||
* installed at all ("newer" would be misleading then).
|
||||
*/
|
||||
function needsText(need: AwgNeed, installed: boolean): string {
|
||||
export function needsText(need: AwgNeed, installed: boolean): string {
|
||||
if (!installed) return need === 'v2' ? _('Needs AmneziaWG on the router.') : _('Needs AmneziaWG 3.1 on the router: install it first.');
|
||||
return need === 'v2'
|
||||
? _('Needs AmneziaWG 2.0 or newer on the router (kmod-amneziawg and amneziawg-tools from July 2025 on).')
|
||||
: _('Needs AmneziaWG 3.1 on the router (kmod-amneziawg and amneziawg-tools 3.1).');
|
||||
}
|
||||
|
||||
function dots(n: number, label: string): HTMLElement {
|
||||
return E('span', { class: 'dl-dots', title: fmt(_('%s: %s of 4'), label, n) }, [
|
||||
E('span', { class: 'dl-dots-label' }, label),
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-dots-row' },
|
||||
[0, 1, 2, 3].map((i) => E('i', { class: i < n ? 'on' : '' })),
|
||||
),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Method cards. `current` gets a badge; unavailable methods stay visible but
|
||||
* disabled with the reason, so it is clear what an upgrade would bring.
|
||||
* `installed` is false while the router has no AmneziaWG tools at all.
|
||||
*/
|
||||
export function methodPicker(
|
||||
caps: AwgCaps,
|
||||
selected: Method,
|
||||
onSelect: (m: Method) => void,
|
||||
current?: string,
|
||||
installed = true,
|
||||
): HTMLElement {
|
||||
const el = E('div', { class: 'dl-methods', role: 'radiogroup', 'aria-label': _('Disguise method') });
|
||||
const paint = () =>
|
||||
dom.content(
|
||||
el,
|
||||
methods().map((m) => {
|
||||
const ok = !m.needs || caps[m.needs];
|
||||
const on = m.id === selected;
|
||||
return E(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
role: 'radio',
|
||||
'aria-checked': on ? 'true' : 'false',
|
||||
'aria-disabled': ok ? null : 'true',
|
||||
class: `dl-method${on ? ' on' : ''}${ok ? '' : ' off'}`,
|
||||
click: () => {
|
||||
if (!ok || on) return;
|
||||
selected = m.id;
|
||||
paint();
|
||||
onSelect(m.id);
|
||||
},
|
||||
},
|
||||
[
|
||||
E('div', { class: 'dl-method-head' }, [
|
||||
E('span', { class: 'dl-method-ic' }, icon(m.ic)),
|
||||
E('b', {}, m.title),
|
||||
m.id === current ? E('span', { class: 'dl-pill ok' }, _('Current')) : '',
|
||||
]),
|
||||
E('p', {}, m.text),
|
||||
E('div', { class: 'dl-method-meters' }, [dots(m.stealth, _('Stealth')), dots(m.speed, _('Speed'))]),
|
||||
E(
|
||||
'div',
|
||||
{ class: 'dl-method-foot' },
|
||||
ok
|
||||
? [icon(m.id === 'off' ? 'wireguard' : 'amneziawg'), E('span', {}, m.apps)]
|
||||
: [icon('alert'), E('span', {}, needsText(m.needs!, installed))],
|
||||
),
|
||||
],
|
||||
);
|
||||
}),
|
||||
);
|
||||
paint();
|
||||
return el;
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
// The router's clock for the log: days and times in the router's time zone
|
||||
// (status.tz, minutes east of UTC), not the browser's (code-standards: time
|
||||
// and dates come from the router). A router too old to send its offset reads
|
||||
// in the browser's. Pure: no DOM.
|
||||
|
||||
import { ago, fmtDay, parseDay } from '../../shared/format';
|
||||
import { fmt, locale } from '../../shared/i18n';
|
||||
|
||||
/** The offset to use at `ts` (minutes): the router's, else the browser's at that moment. */
|
||||
const offsetAt = (ts: number, tz?: number): number => tz ?? -new Date(ts * 1000).getTimezoneOffset();
|
||||
|
||||
/** The router's day of `ts`: YYYY-MM-DD. */
|
||||
export const routerDay = (ts: number, tz?: number): string => new Date((ts + offsetAt(ts, tz) * 60) * 1000).toISOString().slice(0, 10);
|
||||
|
||||
/** The router's time of day of `ts`: HH:MM (24 h: the log's column lines up in every language). */
|
||||
export const routerTime = (ts: number, tz?: number): string => new Date((ts + offsetAt(ts, tz) * 60) * 1000).toISOString().slice(11, 16);
|
||||
|
||||
/** The day before a YYYY-MM-DD. */
|
||||
export const dayBefore = (day: string): string => new Date(Date.parse(`${day}T12:00:00Z`) - 86400_000).toISOString().slice(0, 10);
|
||||
|
||||
/** A day's heading: Today, Yesterday, else "6 Nov" ("6 Nov 2025" in another year). */
|
||||
export function dayTitle(day: string, today: string): string {
|
||||
if (day === today) return _('Today');
|
||||
if (day === dayBefore(today)) return _('Yesterday');
|
||||
if (day.slice(0, 4) !== today.slice(0, 4)) return fmtDay(day);
|
||||
return parseDay(day).toLocaleDateString(locale(), { day: 'numeric', month: 'short' });
|
||||
}
|
||||
|
||||
/** The router's day and time of `ts`: "8 Nov, 12:40" (the year too when it is another). */
|
||||
export function routerDate(ts: number, tz: number | undefined, now = ts): string {
|
||||
const day = routerDay(ts, tz);
|
||||
const d = parseDay(day).toLocaleDateString(locale(), {
|
||||
day: 'numeric',
|
||||
month: 'short',
|
||||
year: day.slice(0, 4) === routerDay(now, tz).slice(0, 4) ? undefined : 'numeric',
|
||||
});
|
||||
return fmt(_('%s, %s'), d, routerTime(ts, tz));
|
||||
}
|
||||
|
||||
/** When `ts` was, near: "today at 17:40", "yesterday at 17:40", "6 Nov at 17:40" (within 30 days), else "2 months ago". */
|
||||
export function whenAt(ts: number, now: number, tz?: number): string {
|
||||
const today = routerDay(now, tz);
|
||||
const day = routerDay(ts, tz);
|
||||
const at = routerTime(ts, tz);
|
||||
if (day === today) return fmt(_('today at %s'), at);
|
||||
if (day === dayBefore(today)) return fmt(_('yesterday at %s'), at);
|
||||
if (now - ts < 30 * 86400) return fmt(_('%s at %s'), parseDay(day).toLocaleDateString(locale(), { day: 'numeric', month: 'short' }), at);
|
||||
return ago(ts, now);
|
||||
}
|
||||
|
||||
/** The router's offset as a zone: "UTC+3", "UTC+5:30", "UTC−4", "UTC". */
|
||||
export function zoneLabel(tz: number): string {
|
||||
if (!tz) return 'UTC';
|
||||
const a = Math.abs(tz);
|
||||
return `UTC${tz > 0 ? '+' : '−'}${Math.floor(a / 60)}${a % 60 ? `:${String(a % 60).padStart(2, '0')}` : ''}`;
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
// Which rows of the log's feed show: by kind (the track: all, connections,
|
||||
// people, system, problems) and by the words typed into its search (names,
|
||||
// addresses, places, what a line says). Pure: no DOM.
|
||||
|
||||
import type { Status } from '../../shared/types';
|
||||
import type { FeedItem } from './sessions';
|
||||
import { categoryOf, isProblem } from './model';
|
||||
|
||||
export type LogKind = 'all' | 'connections' | 'people' | 'system' | 'problems';
|
||||
export const KINDS: LogKind[] = ['all', 'connections', 'people', 'system', 'problems'];
|
||||
|
||||
export function matchesKind(x: FeedItem, k: LogKind): boolean {
|
||||
if (k === 'all') return true;
|
||||
if (k === 'problems') return isProblem(x);
|
||||
if (k === 'system') return !!x.sys;
|
||||
return !!x.ev && categoryOf(x.ev.type) === k;
|
||||
}
|
||||
|
||||
/** How many rows of each kind. */
|
||||
export function kindCounts(items: FeedItem[]): Record<LogKind, number> {
|
||||
const n = { all: 0, connections: 0, people: 0, system: 0, problems: 0 };
|
||||
for (const x of items) for (const k of KINDS) if (matchesKind(x, k)) n[k]++;
|
||||
return n;
|
||||
}
|
||||
|
||||
/**
|
||||
* What a row can be found by, lower case: the names of its person and device
|
||||
* (as they are now, and as the log kept them), its address, place and details;
|
||||
* for a service line its subject, message and details. `said`: the sentence as
|
||||
* the page draws it, so what is read can be typed.
|
||||
*/
|
||||
export function haystack(x: FeedItem, names: Pick<Status, 'people'>, said = ''): string {
|
||||
const parts = [said];
|
||||
if (x.ev) {
|
||||
const e = x.ev;
|
||||
const p = names.people.find((q) => q.id === e.person);
|
||||
parts.push(
|
||||
p?.name ?? '',
|
||||
e.pname ?? '',
|
||||
p?.devices.find((d) => d.id === e.device)?.name ?? '',
|
||||
e.dname ?? '',
|
||||
e.detail ?? '',
|
||||
e.where ?? '',
|
||||
);
|
||||
parts.push(...Object.entries(e.hosts ?? {}).flat());
|
||||
}
|
||||
if (x.sys) parts.push(x.sys.who ?? '', x.sys.msg, x.sys.detail ?? '', x.sys.kind ?? '', x.sys.note ?? '');
|
||||
return parts.join('\n').toLocaleLowerCase();
|
||||
}
|
||||
|
||||
/** Every word of `query` is somewhere in the row's haystack (an empty query matches all). */
|
||||
export function matchesQuery(hay: string, query: string): boolean {
|
||||
const words = query.toLocaleLowerCase().split(/\s+/).filter(Boolean);
|
||||
return words.every((w) => hay.includes(w));
|
||||
}
|
||||
@@ -25,7 +25,7 @@ export const LOG_TEMPLATES: string[] = [
|
||||
'Backup',
|
||||
'Browsers will refuse the portal after that. Renew it with ACME, or choose another certificate in Settings.',
|
||||
'Changed: %s.',
|
||||
'Choose a disguise on the Server page: it replaces the values set by hand.',
|
||||
'Choose a disguise in Settings → Disguise: it replaces the values set by hand.',
|
||||
'Choose another interface name in the server settings.',
|
||||
'Components',
|
||||
'Connections',
|
||||
@@ -33,7 +33,7 @@ export const LOG_TEMPLATES: string[] = [
|
||||
"Dawnline didn't stop it: the router's network restarted, someone stopped it by hand, or it failed.",
|
||||
'Firewall',
|
||||
'Install it in Dawnline → Components.',
|
||||
'Install that AmneziaWG build in Dawnline → Components, or switch the disguise on the Server page.',
|
||||
'Install that AmneziaWG build in Settings → Updates, or switch the disguise in Settings → Disguise.',
|
||||
'Internet like a home device',
|
||||
'MTU is now automatic',
|
||||
'Missing: %s.',
|
||||
@@ -45,6 +45,7 @@ export const LOG_TEMPLATES: string[] = [
|
||||
'Personal links',
|
||||
'Personal portal',
|
||||
'Router',
|
||||
'Routes',
|
||||
'Servers',
|
||||
'Speed',
|
||||
'System packages',
|
||||
@@ -67,6 +68,7 @@ export const LOG_TEMPLATES: string[] = [
|
||||
"couldn't be updated - the previous rules stay, and changes to access wait until they load",
|
||||
"couldn't load - no device is loaded into the tunnels until they do",
|
||||
"couldn't load devices into the tunnel",
|
||||
"couldn't set a route to a network behind a router",
|
||||
"couldn't start",
|
||||
"couldn't start · %d failed attempts in %d min",
|
||||
'failed - internet goes out directly for now',
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// The activity log's vocabulary: categories, who did what, problems, retention.
|
||||
// No DOM and no RPC here (see ./render for rows).
|
||||
|
||||
import type { Kind, LogEvent } from '../../shared/types';
|
||||
import { kindLabel } from '../../shared/format';
|
||||
import type { Declined, Kind, LogEvent, Server } from '../../shared/types';
|
||||
import { declinedWords, kindLabel } from '../../shared/format';
|
||||
import type { LogCategory, LogsInfo, ServiceLogEntry } from '../api';
|
||||
import { fmt, known, plural } from '../../shared/i18n';
|
||||
import { LOG_TEMPLATES } from './log-templates';
|
||||
@@ -14,7 +14,6 @@ const CATEGORY: Record<string, LogCategory> = {
|
||||
roam: 'connections',
|
||||
device_added: 'people',
|
||||
device_removed: 'people',
|
||||
devices_removed: 'people',
|
||||
device_changed: 'people',
|
||||
device_keys: 'people',
|
||||
link_changed: 'people',
|
||||
@@ -24,7 +23,8 @@ const CATEGORY: Record<string, LogCategory> = {
|
||||
paused: 'people',
|
||||
resumed: 'people',
|
||||
expiring: 'people',
|
||||
expired_kept: 'people',
|
||||
quota_reached: 'people',
|
||||
quota_restored: 'people',
|
||||
portal_blocked: 'problems',
|
||||
device_failing: 'problems',
|
||||
device_recovered: 'problems',
|
||||
@@ -95,7 +95,6 @@ export function reasonText(detail: string): string {
|
||||
'paused by admin': _('paused by admin'),
|
||||
'end date reached': _('end date reached'),
|
||||
'data limit reached': _('data limit reached'),
|
||||
'outside allowed hours': _('outside allowed hours'),
|
||||
'no server': _('no server'),
|
||||
'server turned off': _('server turned off'),
|
||||
};
|
||||
@@ -115,12 +114,9 @@ export function changedText(detail: string): string {
|
||||
access: _('access'),
|
||||
device_limit: _('device limit'),
|
||||
expires: _('end date'),
|
||||
expire_action: _('what happens at the end'),
|
||||
expire_warn: _('warning before the end'),
|
||||
quota_gb: _('data limit'),
|
||||
quota_period: _('data limit period'),
|
||||
bonus_gb: _('extra data'),
|
||||
hours: _('allowed hours'),
|
||||
dns_mode: _('DNS'),
|
||||
paused: _('pause'),
|
||||
services: _('home services'),
|
||||
@@ -150,6 +146,28 @@ export function deviceChangedText(detail: string): string {
|
||||
if (at < 0) return f[part] ?? part;
|
||||
const k = part.slice(0, at);
|
||||
const v = part.slice(at + 1);
|
||||
// a router's networks, and what its owner asked for about them with the admin's answers (a list is written
|
||||
// with spaces; "router": the router itself)
|
||||
const nets = v.split(' ').join(', ');
|
||||
const router = v === 'router';
|
||||
switch (k) {
|
||||
case 'networks':
|
||||
return v === 'none' ? _('no networks behind it') : fmt(_('networks behind it: %s'), nets);
|
||||
case 'asked':
|
||||
return router ? _('the router is asked for') : fmt(_('asked for: %s'), nets);
|
||||
case 'withdrew':
|
||||
return fmt(_('no longer asked for: %s'), nets);
|
||||
case 'accepted':
|
||||
return router ? _('the router accepted') : fmt(_('accepted: %s'), nets);
|
||||
case 'declined':
|
||||
return router ? _('the router declined') : fmt(_('declined: %s'), nets);
|
||||
case 'reopened':
|
||||
return router ? _('the router is asked for again') : fmt(_('asked for again: %s'), nets);
|
||||
case 'reason':
|
||||
return (['overlap', 'unneeded', 'talk'] as const).some((x) => x === v)
|
||||
? fmt(_('reason: %s'), declinedWords(v as Declined))
|
||||
: _('no reason given');
|
||||
}
|
||||
if (k === 'lan_bypass') return v === 'on' ? _('LAN Bypass on') : _('LAN Bypass off');
|
||||
if (k === 'kind') return fmt(_('type: %s'), ['computer', 'phone', 'tablet', 'router', 'other'].includes(v) ? kindLabel(v as Kind) : v);
|
||||
if (v === 'auto') return fmt(_('%s: automatic'), f[k] ?? k);
|
||||
@@ -225,6 +243,13 @@ export function adminSentence(msg: string, kind?: string | null, who?: string |
|
||||
return forWho ? { text: _('You reset traffic history for %s'), named: true } : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The admin changed this server (its settings, turned it on or off): by its id where the line has one, else by
|
||||
* the name it had (lines from before the id was written).
|
||||
*/
|
||||
export const changedServer = (e: ServiceLogEntry, srv: Pick<Server, 'id' | 'name'>): boolean =>
|
||||
e.by === 'admin' && e.kind === 'server' && (e.sid ? e.sid === srv.id : e.who === srv.name);
|
||||
|
||||
/** The name in a sentence adminSentence() made with %s (its "for …" taken off). */
|
||||
export const adminName = (msg: string, who: string) => (msg === 'reset traffic history' ? who.replace(/^for /, '') : who);
|
||||
|
||||
|
||||
+70
-187
@@ -1,13 +1,12 @@
|
||||
// Log rows: an activity event as a sentence ("You added device Phone for
|
||||
// Myata", one translated sentence per event with the names in it), its tile
|
||||
// and time, and a service log line (its text comes from the router).
|
||||
// and a service log line's (its text comes from the router); the Log's feed
|
||||
// draws the rows (pages/log/feed.ts).
|
||||
|
||||
import type { LogEvent, Status } from '../../shared/types';
|
||||
import type { ServiceLogEntry } from '../api';
|
||||
import { E } from '../e';
|
||||
import { icon } from '../../shared/icons';
|
||||
import { ago, fmtDay } from '../../shared/format';
|
||||
import { fill, fmt, locale, num } from '../../shared/i18n';
|
||||
import { fill, fmt, num } from '../../shared/i18n';
|
||||
import {
|
||||
adminName,
|
||||
adminSentence,
|
||||
@@ -23,58 +22,22 @@ import {
|
||||
sourceName,
|
||||
} from './model';
|
||||
|
||||
/** What the people and servers in the log are called now. */
|
||||
export type Names = Pick<Status, 'people' | 'servers'>;
|
||||
|
||||
const EVENT_TONE: Record<string, string> = {
|
||||
connect: 'ok',
|
||||
disconnect: '',
|
||||
roam: '',
|
||||
device_added: 'ok',
|
||||
device_removed: '',
|
||||
person_added: '',
|
||||
person_removed: '',
|
||||
paused: 'warn',
|
||||
resumed: 'ok',
|
||||
expiring: 'warn',
|
||||
expired_kept: '',
|
||||
portal_blocked: 'bad',
|
||||
person_changed: '',
|
||||
devices_removed: 'warn',
|
||||
device_failing: 'warn',
|
||||
device_recovered: 'ok',
|
||||
};
|
||||
|
||||
/** The icon in an event's tile: the device's kind for device events, else what happened. */
|
||||
const EVENT_ICON: Record<string, string> = {
|
||||
devices_removed: 'trash',
|
||||
link_changed: 'link',
|
||||
person_added: 'plus',
|
||||
person_removed: 'trash',
|
||||
person_changed: 'edit',
|
||||
paused: 'pause',
|
||||
resumed: 'play',
|
||||
expiring: 'calendar',
|
||||
expired_kept: 'calendar',
|
||||
};
|
||||
|
||||
function eventIcon(st: Names, e: LogEvent): string {
|
||||
if (e.device) {
|
||||
const d = st.people.flatMap((p) => p.devices).find((x) => x.id === e.device);
|
||||
return d?.kind ?? e.dkind ?? 'other';
|
||||
}
|
||||
return EVENT_ICON[e.type] ?? 'activity';
|
||||
/** Where a name in a sentence leads (the pages make people and devices links); none: names in bold. */
|
||||
export interface NameLinks {
|
||||
person(id: string): string;
|
||||
device(person: string, device: string): string;
|
||||
}
|
||||
|
||||
/** A router day (YYYY-MM-DD) in the page's language; anything else as it came. */
|
||||
const routerDay = (s: string) => (/^\d{4}-\d{2}-\d{2}$/.test(s) ? fmtDay(s) : s);
|
||||
|
||||
export function eventText(st: Pick<Status, 'people'>, e: LogEvent, personId?: string): Node[] {
|
||||
export function eventText(st: Pick<Status, 'people'>, e: LogEvent, personId?: string, links?: NameLinks): Node[] {
|
||||
const scoped = personId !== undefined && e.person === personId;
|
||||
const person = st.people.find((p) => p.id === e.person);
|
||||
const who = person?.name ?? e.pname ?? e.person ?? '';
|
||||
const dev = person?.devices.find((d) => d.id === e.device)?.name ?? e.dname ?? '';
|
||||
const known = person?.devices.find((d) => d.id === e.device);
|
||||
const dev = known?.name ?? e.dname ?? '';
|
||||
const b = (t: string) => E('b', {}, t);
|
||||
// A person or device the router still has is a link where links are given; one removed since, its name as it was.
|
||||
const pn = (t = who) => (links && person ? E('a', { href: links.person(person.id) }, t) : b(t));
|
||||
const dn = (t: string) => (links && person && known ? E('a', { href: links.device(person.id, known.id) }, t) : b(t));
|
||||
const m = (t: string) => E('span', { class: 'dl-muted' }, t);
|
||||
const mono = (t: string) => E('span', { class: 'dl-mono' }, t);
|
||||
/** An address; at home, the name of the device that has it, with the address in brackets. */
|
||||
@@ -89,34 +52,40 @@ export function eventText(st: Pick<Status, 'people'>, e: LogEvent, personId?: st
|
||||
const w = _('You');
|
||||
return s.startsWith(`${w} `) ? [E('span', { class: 'dl-you' }, w), ...say(s.slice(w.length), ...args)] : say(s, ...args);
|
||||
};
|
||||
const wd = b(scoped ? dev || _('a device') : dev ? `${who} · ${dev}` : who);
|
||||
// The device with whose it is: "Person · Device", or, with links, the device first, as its own rows say it.
|
||||
const wd = scoped
|
||||
? dn(dev || _('a device'))
|
||||
: !dev
|
||||
? pn()
|
||||
: links
|
||||
? E('span', {}, [dn(dev), E('span', { class: 'ev-sep' }, ' · '), pn()])
|
||||
: b(`${who} · ${dev}`);
|
||||
const detail = plainDetail(e);
|
||||
const devName = b(detail || dev || _('a device'));
|
||||
const devName = dn(detail || dev || _('a device'));
|
||||
const by = eventBy(e);
|
||||
if (by === 'admin')
|
||||
switch (e.type) {
|
||||
case 'device_added':
|
||||
return scoped ? you(_('You added device %s'), devName) : you(_('You added device %s for %s'), devName, b(who));
|
||||
return scoped ? you(_('You added device %s'), devName) : you(_('You added device %s for %s'), devName, pn());
|
||||
case 'device_removed':
|
||||
return scoped ? you(_('You removed device %s'), devName) : you(_('You removed device %s from %s'), devName, b(who));
|
||||
return scoped ? you(_('You removed device %s'), devName) : you(_('You removed device %s from %s'), devName, pn());
|
||||
case 'paused':
|
||||
return scoped ? you(_('You paused access')) : you(_('You paused person %s'), b(who));
|
||||
return scoped ? you(_('You paused access')) : you(_('You paused person %s'), pn());
|
||||
case 'resumed':
|
||||
return scoped ? you(_('You resumed access')) : you(_('You resumed person %s'), b(who));
|
||||
return scoped ? you(_('You resumed access')) : you(_('You resumed person %s'), pn());
|
||||
case 'device_changed': {
|
||||
const d = b(dev || _('a device'));
|
||||
const d = dn(dev || _('a device'));
|
||||
if (detail.startsWith('renamed from '))
|
||||
return [
|
||||
...(scoped ? you(_('You renamed device %s'), d) : you(_('You renamed device %s of %s'), d, b(who))),
|
||||
...(scoped ? you(_('You renamed device %s'), d) : you(_('You renamed device %s of %s'), d, pn())),
|
||||
m(` · ${fmt(_('was %s'), detail.slice(13))}`),
|
||||
];
|
||||
if (detail === 'turned off')
|
||||
return scoped ? you(_('You turned off device %s'), d) : you(_('You turned off device %s of %s'), d, b(who));
|
||||
if (detail === 'turned on')
|
||||
return scoped ? you(_('You turned on device %s'), d) : you(_('You turned on device %s of %s'), d, b(who));
|
||||
return scoped ? you(_('You turned off device %s'), d) : you(_('You turned off device %s of %s'), d, pn());
|
||||
if (detail === 'turned on') return scoped ? you(_('You turned on device %s'), d) : you(_('You turned on device %s of %s'), d, pn());
|
||||
// Its own link options by name ("mtu, keepalive"), as person_changed lists a person's.
|
||||
return [
|
||||
...(scoped ? you(_('You changed device %s'), d) : you(_('You changed device %s of %s'), d, b(who))),
|
||||
...(scoped ? you(_('You changed device %s'), d) : you(_('You changed device %s of %s'), d, pn())),
|
||||
...(detail ? [m(` · ${deviceChangedText(detail)}`)] : []),
|
||||
];
|
||||
}
|
||||
@@ -124,12 +93,12 @@ export function eventText(st: Pick<Status, 'people'>, e: LogEvent, personId?: st
|
||||
return [
|
||||
...(scoped
|
||||
? you(_('You issued new keys for device %s'), devName)
|
||||
: you(_('You issued new keys for device %s of %s'), devName, b(who))),
|
||||
: you(_('You issued new keys for device %s of %s'), devName, pn())),
|
||||
m(` · ${_('it needs its new configuration')}`),
|
||||
];
|
||||
case 'link_changed':
|
||||
return [
|
||||
...(scoped ? you(_('You issued a new personal link')) : you(_('You issued a new link for person %s'), b(who))),
|
||||
...(scoped ? you(_('You issued a new personal link')) : you(_('You issued a new link for person %s'), pn())),
|
||||
m(` · ${_('the old link stopped working')}`),
|
||||
];
|
||||
}
|
||||
@@ -155,25 +124,25 @@ export function eventText(st: Pick<Status, 'people'>, e: LogEvent, personId?: st
|
||||
return by === 'portal'
|
||||
? scoped
|
||||
? say(_('Device %s added on the portal'), devName)
|
||||
: say(_('Person %s added device %s on their portal'), b(who), devName)
|
||||
: say(_('Person %s added device %s on their portal'), pn(), devName)
|
||||
: scoped
|
||||
? say(_('Device %s added'), devName)
|
||||
: say(_('Person %s added device %s'), b(who), devName);
|
||||
: say(_('Person %s added device %s'), pn(), devName);
|
||||
case 'device_removed':
|
||||
return by === 'portal'
|
||||
? scoped
|
||||
? say(_('Device %s removed on the portal'), devName)
|
||||
: say(_('Person %s removed device %s on their portal'), b(who), devName)
|
||||
: say(_('Person %s removed device %s on their portal'), pn(), devName)
|
||||
: scoped
|
||||
? say(_('Device %s removed'), devName)
|
||||
: say(_('Person %s removed device %s'), b(who), devName);
|
||||
: say(_('Person %s removed device %s'), pn(), devName);
|
||||
case 'device_changed':
|
||||
if (detail.startsWith('renamed from '))
|
||||
return [
|
||||
...(by === 'portal'
|
||||
? scoped
|
||||
? say(_('Device %s renamed on the portal'), b(dev || _('a device')))
|
||||
: say(_('Person %s renamed device %s on their portal'), b(who), b(dev || _('a device')))
|
||||
? say(_('Device %s renamed on the portal'), dn(dev || _('a device')))
|
||||
: say(_('Person %s renamed device %s on their portal'), pn(), dn(dev || _('a device')))
|
||||
: say(_('Device %s renamed'), wd)),
|
||||
m(` · ${fmt(_('was %s'), detail.slice(13))}`),
|
||||
];
|
||||
@@ -183,23 +152,23 @@ export function eventText(st: Pick<Status, 'people'>, e: LogEvent, personId?: st
|
||||
if (by === 'portal')
|
||||
return [
|
||||
...(scoped
|
||||
? say(_('Device %s changed on the portal'), b(dev || _('a device')))
|
||||
: say(_('Person %s changed device %s on their portal'), b(who), b(dev || _('a device')))),
|
||||
? say(_('Device %s changed on the portal'), dn(dev || _('a device')))
|
||||
: say(_('Person %s changed device %s on their portal'), pn(), dn(dev || _('a device')))),
|
||||
...(detail ? [m(` · ${deviceChangedText(detail)}`)] : []),
|
||||
];
|
||||
return [...say(_('Device %s changed'), wd), ...(detail ? [m(` · ${deviceChangedText(detail)}`)] : [])];
|
||||
case 'device_keys':
|
||||
return scoped
|
||||
? say(_('New keys issued for device %s on the portal'), devName)
|
||||
: say(_('Person %s issued new keys for device %s on their portal'), b(who), devName);
|
||||
: say(_('Person %s issued new keys for device %s on their portal'), pn(), devName);
|
||||
case 'person_added':
|
||||
return scoped ? you(_('You added this person')) : you(_('You added person %s'), b(e.detail ?? who));
|
||||
return scoped ? you(_('You added this person')) : you(_('You added person %s'), pn(e.detail ?? who));
|
||||
case 'person_removed':
|
||||
return scoped ? you(_('You removed this person')) : you(_('You removed person %s'), b(e.detail ?? who));
|
||||
return scoped ? you(_('You removed this person')) : you(_('You removed person %s'), pn(e.detail ?? who));
|
||||
case 'person_changed':
|
||||
// The detail lists changed fields by their option names (device_limit, expire_action).
|
||||
// The detail lists changed fields by their option names (device_limit, quota_gb).
|
||||
return [
|
||||
...(scoped ? you(_('You changed settings')) : you(_('You changed person %s'), b(who))),
|
||||
...(scoped ? you(_('You changed settings')) : you(_('You changed person %s'), pn())),
|
||||
...(detail ? [m(` · ${changedText(detail)}`)] : []),
|
||||
];
|
||||
case 'expiring': {
|
||||
@@ -207,39 +176,37 @@ export function eventText(st: Pick<Status, 'people'>, e: LogEvent, personId?: st
|
||||
return n != null
|
||||
? scoped
|
||||
? say(N_(n, 'Access ends in %s day', 'Access ends in %s days'), m(num(n)))
|
||||
: say(N_(n, 'Person %s’s access ends in %s day', 'Person %s’s access ends in %s days'), b(who), m(num(n)))
|
||||
: say(N_(n, 'Person %s’s access ends in %s day', 'Person %s’s access ends in %s days'), pn(), m(num(n)))
|
||||
: scoped
|
||||
? say(_('Access ends in a few days'))
|
||||
: say(_('Person %s’s access ends in a few days'), b(who));
|
||||
: say(_('Person %s’s access ends in a few days'), pn());
|
||||
}
|
||||
case 'expired_kept':
|
||||
return scoped
|
||||
? say(_('End date passed (%s) · access kept'), m(routerDay(e.detail ?? '')))
|
||||
: say(_('Person %s’s end date passed (%s) · access kept'), b(who), m(routerDay(e.detail ?? '')));
|
||||
case 'paused':
|
||||
return e.detail
|
||||
? scoped
|
||||
? say(_('Access paused - %s'), m(reasonText(e.detail)))
|
||||
: say(_('Person %s paused - %s'), b(who), m(reasonText(e.detail)))
|
||||
: say(_('Person %s paused - %s'), pn(), m(reasonText(e.detail)))
|
||||
: scoped
|
||||
? say(_('Access paused'))
|
||||
: say(_('Person %s paused'), b(who));
|
||||
: say(_('Person %s paused'), pn());
|
||||
case 'resumed':
|
||||
return e.detail && e.detail !== 'active'
|
||||
? scoped
|
||||
? say(_('Access resumed - %s'), m(reasonText(e.detail)))
|
||||
: say(_('Person %s resumed - %s'), b(who), m(reasonText(e.detail)))
|
||||
: say(_('Person %s resumed - %s'), pn(), m(reasonText(e.detail)))
|
||||
: scoped
|
||||
? say(_('Access resumed'))
|
||||
: say(_('Person %s resumed'), b(who));
|
||||
: say(_('Person %s resumed'), pn());
|
||||
case 'quota_reached':
|
||||
return scoped ? say(_('Data limit reached')) : say(_('Person %s reached the data limit'), pn());
|
||||
case 'quota_restored':
|
||||
return scoped ? say(_('Data is back after the limit')) : say(_('Person %s has data again after the limit'), pn());
|
||||
case 'portal_blocked':
|
||||
return say(
|
||||
_('%s blocked %s for 15 min after too many wrong codes'),
|
||||
E('b', { class: 'dl-sys-src' }, _('Personal portal')),
|
||||
e.detail === 'all Cloudflare visitors' ? m(_('all Cloudflare visitors')) : mono(e.detail ?? ''),
|
||||
);
|
||||
case 'devices_removed':
|
||||
return scoped ? say(_('All devices removed, end date reached')) : say(_('Person %s - all devices removed, end date reached'), b(who));
|
||||
case 'device_failing':
|
||||
return [...say(_('Device %s has a connection problem'), wd), ...(e.detail ? [m(` · ${linkStatesText(e.detail)}`)] : [])];
|
||||
case 'device_recovered':
|
||||
@@ -249,46 +216,8 @@ export function eventText(st: Pick<Status, 'people'>, e: LogEvent, personId?: st
|
||||
}
|
||||
}
|
||||
|
||||
/** Events about the router rather than people look like service log lines: icon tile, colour by outcome. */
|
||||
const SYSTEM_EVENT: Record<string, [string, string]> = {
|
||||
portal_blocked: ['globe', 'bad'],
|
||||
};
|
||||
|
||||
/** With several servers, which one a person's event happened on (left out where that is clear). */
|
||||
function serverPill(st: Names, e: LogEvent): HTMLElement | '' {
|
||||
if (st.servers.length < 2 || !e.person) return '';
|
||||
const p = st.people.find((x) => x.id === e.person);
|
||||
const srv = p && st.servers.find((s) => s.id === p.server);
|
||||
return srv ? E('span', { class: 'dl-ev-srv', title: _('Server') }, srv.name) : '';
|
||||
}
|
||||
|
||||
/** An activity event as a row; `time` replaces the "5 min ago" (`now` is the router's clock). */
|
||||
export function eventRow(
|
||||
st: Names & { now?: number },
|
||||
e: LogEvent,
|
||||
opts: { server?: boolean; time?: string; person?: string } = {},
|
||||
): HTMLElement {
|
||||
const sys = SYSTEM_EVENT[e.type];
|
||||
const by = eventBy(e);
|
||||
return E('div', { class: `dl-row${by === 'admin' ? ' dl-ev-by-admin' : sys ? ` dl-ev-by-system ${sys[1]}` : ''}` }, [
|
||||
by === 'admin'
|
||||
? E('span', { class: 'dl-ev-tile', title: _('Done by you in LuCI') }, icon('admin'))
|
||||
: sys
|
||||
? E('span', { class: 'dl-ev-tile sys' }, icon(sys[0]))
|
||||
: E('span', { class: `dl-ev-tile ev ${EVENT_TONE[e.type] ?? ''}` }, icon(eventIcon(st, e))),
|
||||
E('span', { class: 'dl-row-main' }, eventText(st, e, opts.person)),
|
||||
opts.server === false ? '' : serverPill(st, e),
|
||||
E('span', { class: 'dl-faint dl-nowrap', title: new Date(e.ts * 1000).toLocaleString(locale()) }, opts.time ?? ago(e.ts, st.now)),
|
||||
]);
|
||||
}
|
||||
|
||||
/** Colour per service log level (tile, source and row): neutral unless something came up, was repaired or failed. */
|
||||
// "down" is a tunnel that stopped without Dawnline asking (its own stops are "info").
|
||||
const SYS_TONE: Record<ServiceLogEntry['level'], string> = { info: '', up: 'ok', down: 'warn', repair: 'warn', error: 'bad' };
|
||||
const SYS_ICON: Record<ServiceLogEntry['src'], string> = { awg: 'tunnel', dawnline: 'sunrise', portal: 'globe' };
|
||||
|
||||
/** A service log level as its tile's tooltip says it. */
|
||||
function levelLabel(l: ServiceLogEntry['level']): string {
|
||||
export function levelLabel(l: ServiceLogEntry['level']): string {
|
||||
return { info: _('info'), up: _('up'), down: _('down'), repair: _('repair'), error: _('error') }[l] ?? l;
|
||||
}
|
||||
|
||||
@@ -318,69 +247,23 @@ function adminLine(e: ServiceLogEntry): (Node | string)[] {
|
||||
}
|
||||
|
||||
/** A log line's details: its sentences in the page's language, command output as it is. */
|
||||
const detailText = (d: string) =>
|
||||
export const detailText = (d: string) =>
|
||||
d
|
||||
.split('\n')
|
||||
.map((l) => logText(l))
|
||||
.join('\n');
|
||||
|
||||
/** A service log line: source, message, folded details; click to unfold. */
|
||||
export function systemRow(e: ServiceLogEntry, open: boolean, toggle: () => void, time: string): HTMLElement {
|
||||
const admin = e.by === 'admin';
|
||||
/** A service log line's sentence: the admin's own change, or the source and what it says (no details). */
|
||||
export function systemText(e: ServiceLogEntry): (Node | string)[] {
|
||||
if (e.by === 'admin') return [...adminLine(e), e.note ? E('span', { class: 'dl-muted' }, ` · ${noteText(e.note)}`) : ''];
|
||||
const msg = logText(e.msg);
|
||||
const row = E(
|
||||
'div',
|
||||
{
|
||||
class: `dl-row dl-slog-row ${admin ? 'dl-ev-by-admin' : `dl-ev-by-system ${SYS_TONE[e.level] ?? ''}`}${e.detail ? ' has-detail' : ''}`,
|
||||
},
|
||||
[
|
||||
admin
|
||||
? E('span', { class: 'dl-ev-tile', title: _('Done by you in LuCI') }, icon('admin'))
|
||||
: E('span', { class: 'dl-ev-tile sys', title: levelLabel(e.level) }, icon(SYS_ICON[e.src] ?? 'zap')),
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-row-main' },
|
||||
admin
|
||||
? [
|
||||
...adminLine(e),
|
||||
e.note ? E('span', { class: 'dl-muted' }, ` · ${noteText(e.note)}`) : '',
|
||||
e.detail ? E('span', { class: `dl-slog-more${open ? ' open' : ''}` }, icon('chevron')) : '',
|
||||
e.detail && open ? E('pre', { class: 'dl-slog-detail' }, detailText(e.detail)) : '',
|
||||
]
|
||||
: [
|
||||
// Servers have names people chose: say it is a server. Services name themselves.
|
||||
e.src === 'awg' && e.who && e.who !== 'AmneziaWG' ? E('span', { class: 'dl-ev-kind' }, `${_('Server')} `) : '',
|
||||
// A server's name as it is; Dawnline's own subjects ("Access rules") in the page's language.
|
||||
E(
|
||||
'b',
|
||||
{ class: 'dl-sys-src', title: sourceName(e.src) },
|
||||
e.who ? (e.src === 'awg' ? e.who : logText(e.who)) : sourceName(e.src),
|
||||
),
|
||||
// A translation may go on from the subject with a colon ("Home: AmneziaWG isn't running").
|
||||
/^[:,]/.test(msg) ? '' : ' ',
|
||||
E('span', { class: 'dl-muted' }, msg),
|
||||
e.detail ? E('span', { class: `dl-slog-more${open ? ' open' : ''}` }, icon('chevron')) : '',
|
||||
e.detail && open ? E('pre', { class: 'dl-slog-detail' }, detailText(e.detail)) : '',
|
||||
],
|
||||
),
|
||||
E('span', { class: 'dl-faint dl-nowrap', title: new Date(e.ts * 1000).toLocaleString(locale()) }, time),
|
||||
],
|
||||
);
|
||||
if (e.detail)
|
||||
row.addEventListener('click', (ev) => {
|
||||
if (!(ev.target as HTMLElement).closest('pre')) toggle();
|
||||
});
|
||||
return row;
|
||||
}
|
||||
|
||||
/** "Today", "Yesterday" or "Monday 12 October" (capitalised: Russian names weekdays in lower case). */
|
||||
export function dayTitle(ts: number): string {
|
||||
const d = new Date(ts * 1000);
|
||||
const today = new Date();
|
||||
const y = new Date();
|
||||
y.setDate(today.getDate() - 1);
|
||||
if (d.toDateString() === today.toDateString()) return _('Today');
|
||||
if (d.toDateString() === y.toDateString()) return _('Yesterday');
|
||||
const t = d.toLocaleDateString(locale(), { weekday: 'long', day: 'numeric', month: 'long' });
|
||||
return t.charAt(0).toLocaleUpperCase(locale()) + t.slice(1);
|
||||
return [
|
||||
// Servers have names people chose: say it is a server. Services name themselves.
|
||||
e.src === 'awg' && e.who && e.who !== 'AmneziaWG' ? E('span', { class: 'dl-ev-kind' }, `${_('Server')} `) : '',
|
||||
// A server's name as it is; Dawnline's own subjects ("Access rules") in the page's language.
|
||||
E('b', { class: 'dl-sys-src', title: sourceName(e.src) }, e.who ? (e.src === 'awg' ? e.who : logText(e.who)) : sourceName(e.src)),
|
||||
// A translation may go on from the subject with a colon ("Home: AmneziaWG isn't running").
|
||||
/^[:,]/.test(msg) ? '' : ' ',
|
||||
E('span', { class: 'dl-muted' }, msg),
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
// What the Log is asked for, as its address says it: the kind of entries and
|
||||
// the words searched (events/find.ts matches those), and the scope: one
|
||||
// person's, one device's or one server's rows, one day (today, yesterday, the
|
||||
// last 7 days). Here: the address read and written, which rows a scope keeps,
|
||||
// and how many rows each choice of a filter would leave (the lists under the
|
||||
// «Person», «Device» and «Server» chips). Pure: no DOM (pages/log draws it).
|
||||
|
||||
import type { Status } from '../../shared/types';
|
||||
import type { FeedItem } from './sessions';
|
||||
import { dayBefore, routerDay } from './clock';
|
||||
import { KINDS, type LogKind } from './find';
|
||||
|
||||
/** A day filter: the router's today, its yesterday, or the last 7 × 24 hours. */
|
||||
export type LogDay = 'today' | 'yesterday' | '7d';
|
||||
export const DAYS: LogDay[] = ['today', 'yesterday', '7d'];
|
||||
|
||||
export interface LogQuery {
|
||||
kind: LogKind;
|
||||
day: LogDay | '';
|
||||
person: string;
|
||||
device: string;
|
||||
server: string;
|
||||
/** The words typed into the search. */
|
||||
q: string;
|
||||
}
|
||||
|
||||
/** Nothing asked: the whole log. */
|
||||
export const WHOLE: LogQuery = { kind: 'all', day: '', person: '', device: '', server: '', q: '' };
|
||||
|
||||
/** Who the scope is read against: the people with their devices, the servers. */
|
||||
export type Who = Pick<Status, 'people' | 'servers'>;
|
||||
|
||||
/** The router's clock: now (s) and its UTC offset (minutes). */
|
||||
export interface Clock {
|
||||
now: number;
|
||||
tz?: number;
|
||||
}
|
||||
|
||||
/** What an address' query asks for; anything it does not know is left out (`day=week` is the 7 days' older name). */
|
||||
export function parseLogQuery(query: string): LogQuery {
|
||||
const p = new URLSearchParams(query);
|
||||
const kind = p.get('kind') as LogKind | null;
|
||||
const day = p.get('day') === 'week' ? '7d' : (p.get('day') as LogDay | null);
|
||||
return {
|
||||
kind: kind && KINDS.includes(kind) ? kind : 'all',
|
||||
day: day && DAYS.includes(day) ? day : '',
|
||||
person: p.get('person') ?? '',
|
||||
device: p.get('device') ?? '',
|
||||
server: p.get('server') ?? '',
|
||||
q: (p.get('q') ?? '').trim(),
|
||||
};
|
||||
}
|
||||
|
||||
/** A query as the address' parameters (shell/routes.ts logUrl takes them): only what narrows the log. */
|
||||
export function logQueryParams(q: LogQuery): {
|
||||
kind?: string;
|
||||
day?: string;
|
||||
person?: string;
|
||||
device?: string;
|
||||
server?: string;
|
||||
q?: string;
|
||||
} {
|
||||
return {
|
||||
kind: q.kind === 'all' ? undefined : q.kind,
|
||||
day: q.day || undefined,
|
||||
person: q.person || undefined,
|
||||
device: q.device || undefined,
|
||||
server: q.server || undefined,
|
||||
q: q.q || undefined,
|
||||
};
|
||||
}
|
||||
|
||||
/** Something narrows the log (its way off, «Reset», is offered). */
|
||||
export const narrowed = (q: LogQuery): boolean => !!(q.kind !== 'all' || q.day || q.person || q.device || q.server || q.q);
|
||||
|
||||
/**
|
||||
* A query with filters changed. A device is someone's: picking one drops a person it is not of, and picking a
|
||||
* person drops a device that is not theirs (the two together would leave nothing).
|
||||
*/
|
||||
export function withFilters(q: LogQuery, patch: Partial<LogQuery>, people: Who['people']): LogQuery {
|
||||
const next = { ...q, ...patch };
|
||||
const has = (person: string, device: string) => !!people.find((p) => p.id === person)?.devices.some((d) => d.id === device);
|
||||
if (patch.device && next.person && !has(next.person, patch.device)) next.person = '';
|
||||
else if (patch.person && next.device && !has(patch.person, next.device)) next.device = '';
|
||||
return next;
|
||||
}
|
||||
|
||||
/**
|
||||
* The server a row happened on: a person's event on their server (as the row says it), another event on the one
|
||||
* the router wrote into it; a service line on the server it names (older lines have only its name).
|
||||
*/
|
||||
function serverOf(x: FeedItem, who: Who, ofPerson: Map<string, string>): string | undefined {
|
||||
if (x.ev) return (x.ev.person ? ofPerson.get(x.ev.person) : undefined) ?? x.ev.server;
|
||||
return x.sys?.sid ?? (x.sys?.who ? who.servers.find((s) => s.name === x.sys!.who)?.id : undefined);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a row is in the query's scope: who, where and when (not its kind and not the search). A person's or a
|
||||
* device's log has no service lines: those are no one's.
|
||||
*/
|
||||
export function inScope(q: LogQuery, who: Who, clock: Clock): (x: FeedItem) => boolean {
|
||||
const ofPerson = new Map(who.people.map((p) => [p.id, p.server]));
|
||||
const today = routerDay(clock.now, clock.tz);
|
||||
const yesterday = dayBefore(today);
|
||||
const weekAgo = clock.now - 7 * 86400;
|
||||
return (x) => {
|
||||
if (q.person && x.ev?.person !== q.person) return false;
|
||||
if (q.device && x.ev?.device !== q.device) return false;
|
||||
if (q.server && serverOf(x, who, ofPerson) !== q.server) return false;
|
||||
if (q.day === 'today') return routerDay(x.ts, clock.tz) === today;
|
||||
if (q.day === 'yesterday') return routerDay(x.ts, clock.tz) === yesterday;
|
||||
if (q.day === '7d') return x.ts >= weekAgo;
|
||||
return true;
|
||||
};
|
||||
}
|
||||
|
||||
/** One choice of a filter and how many rows it would leave. */
|
||||
interface Choice {
|
||||
id: string;
|
||||
n: number;
|
||||
}
|
||||
|
||||
export interface Choices {
|
||||
people: Choice[];
|
||||
devices: Choice[];
|
||||
servers: Choice[];
|
||||
}
|
||||
|
||||
const tally = (items: FeedItem[], key: (x: FeedItem) => string | undefined): Map<string, number> => {
|
||||
const n = new Map<string, number>();
|
||||
for (const x of items) {
|
||||
const k = key(x);
|
||||
if (k) n.set(k, (n.get(k) ?? 0) + 1);
|
||||
}
|
||||
return n;
|
||||
};
|
||||
|
||||
/** Those with rows, the most first (equal ones in the order given), and the picked one whatever it has. */
|
||||
const ranked = (ids: string[], n: Map<string, number>, picked: string): Choice[] =>
|
||||
[...new Set(picked ? [...ids, picked] : ids)]
|
||||
.map((id) => ({ id, n: n.get(id) ?? 0 }))
|
||||
.filter((c) => c.n > 0 || c.id === picked)
|
||||
.sort((a, b) => b.n - a.n);
|
||||
|
||||
/**
|
||||
* What each filter's list offers, with the rows each choice would leave under the other filters of the scope:
|
||||
* people (whatever device is picked: another person takes it off), the devices of the picked person (of
|
||||
* everyone, with none picked), every server in the router's order. A picked one that is gone from the router
|
||||
* (removed since) is still listed, so it can be seen checked.
|
||||
*/
|
||||
export function choices(items: FeedItem[], q: LogQuery, who: Who, clock: Clock): Choices {
|
||||
const ofPerson = new Map(who.people.map((p) => [p.id, p.server]));
|
||||
const left = (lift: Partial<LogQuery>) => items.filter(inScope({ ...q, ...lift }, who, clock));
|
||||
const devices = who.people.filter((p) => !q.person || p.id === q.person).flatMap((p) => p.devices.map((d) => d.id));
|
||||
const perServer = tally(left({ server: '' }), (x) => serverOf(x, who, ofPerson));
|
||||
return {
|
||||
people: ranked(
|
||||
who.people.map((p) => p.id),
|
||||
tally(left({ person: '', device: '' }), (x) => x.ev?.person),
|
||||
q.person,
|
||||
),
|
||||
devices: ranked(
|
||||
devices,
|
||||
tally(left({ device: '' }), (x) => x.ev?.device),
|
||||
q.device,
|
||||
),
|
||||
servers: who.servers.map((s) => ({ id: s.id, n: perServer.get(s.id) ?? 0 })),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
// The log's feed as rows: a device's connect and its next disconnect are one
|
||||
// row, its session ("online 09:20 until 11:40", or still online), which stands
|
||||
// under the day it began; the other events and the service log's lines are a
|
||||
// row each. Newest first. Pure: no DOM (pages/log draws the rows).
|
||||
// A device that drops and comes back within a few minutes from the same place
|
||||
// (a phone switching networks, a tunnel re-keying) stays one session that
|
||||
// counts its reconnects: on a real router such a phone logs dozens a day.
|
||||
|
||||
import type { LogEvent } from '../../shared/types';
|
||||
import type { ServiceLogEntry } from '../api';
|
||||
import { routerDay } from './clock';
|
||||
|
||||
/** A row of the feed. */
|
||||
export interface FeedItem {
|
||||
ts: number;
|
||||
ev?: LogEvent;
|
||||
sys?: ServiceLogEntry;
|
||||
/**
|
||||
* A session (a connect): when it ended (its disconnect), or null while it
|
||||
* lasts. Absent from other rows, and from a connect whose end is not known
|
||||
* (a newer connect of the same device came first, or the device is not
|
||||
* online now although no disconnect was logged).
|
||||
*/
|
||||
until?: number | null;
|
||||
/** A session's disconnect itself (exported with it). */
|
||||
end?: LogEvent;
|
||||
/** A session: how many times the device came back within REJOIN of dropping, folded into it. */
|
||||
rejoins?: number;
|
||||
}
|
||||
|
||||
/** A device back within this long from the same place: the same session (seconds). */
|
||||
const REJOIN = 15 * 60;
|
||||
|
||||
/** Where a connect came from, to tell a reconnect from a move. */
|
||||
const placeKey = (e: LogEvent): string => e.where ?? e.detail ?? '';
|
||||
|
||||
/**
|
||||
* The feed: `events` (any order) folded into sessions, `system` beside them.
|
||||
* `online(device)`: whether a device is online now, so a session with no end
|
||||
* logged says "online now" only when it is true.
|
||||
*/
|
||||
export function sessions(events: LogEvent[], system: ServiceLogEntry[] = [], online: (device: string) => boolean = () => true): FeedItem[] {
|
||||
const out: FeedItem[] = [];
|
||||
const open = new Map<string, FeedItem>();
|
||||
// Each device's last ended session, to fold a quick return into it.
|
||||
const ended = new Map<string, FeedItem>();
|
||||
for (const e of [...events].sort((a, b) => a.ts - b.ts)) {
|
||||
if (e.type === 'connect' && e.device) {
|
||||
// A connect while the last one is open: that one's end was never logged.
|
||||
const was = open.get(e.device);
|
||||
if (was) delete was.until;
|
||||
const last = ended.get(e.device);
|
||||
if (!was && last && last.until && e.ts - last.until <= REJOIN && placeKey(last.ev!) === placeKey(e)) {
|
||||
last.until = null;
|
||||
delete last.end;
|
||||
last.rejoins = (last.rejoins ?? 0) + 1;
|
||||
open.set(e.device, last);
|
||||
ended.delete(e.device);
|
||||
continue;
|
||||
}
|
||||
const it: FeedItem = { ts: e.ts, ev: e, until: null };
|
||||
open.set(e.device, it);
|
||||
out.push(it);
|
||||
} else if (e.type === 'disconnect' && e.device && open.has(e.device)) {
|
||||
const it = open.get(e.device)!;
|
||||
it.until = e.ts;
|
||||
it.end = e;
|
||||
open.delete(e.device);
|
||||
ended.set(e.device, it);
|
||||
} else out.push({ ts: e.ts, ev: e });
|
||||
}
|
||||
for (const [device, it] of open) if (!online(device)) delete it.until;
|
||||
for (const sys of system) out.push({ ts: sys.ts, sys });
|
||||
return out.sort((a, b) => b.ts - a.ts);
|
||||
}
|
||||
|
||||
/** Rows grouped by the router's day they began on, newest day first (rows keep their order). */
|
||||
export function byDay(items: FeedItem[], tz?: number): { day: string; items: FeedItem[] }[] {
|
||||
const days: { day: string; items: FeedItem[] }[] = [];
|
||||
for (const it of items) {
|
||||
const day = routerDay(it.ts, tz);
|
||||
const last = days[days.length - 1];
|
||||
if (last?.day === day) last.items.push(it);
|
||||
else days.push({ day, items: [it] });
|
||||
}
|
||||
return days;
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
// A device's link over its last 30 days, from the log: whether it worked,
|
||||
// hour by hour, as runs in a state (in the network; failing in a named way,
|
||||
// the agent's device_failing until device_recovered; let in only to the portal
|
||||
// and the router's DNS, between the person's quota_reached and
|
||||
// quota_restored), and ticks where something changed what it gets (its
|
||||
// own settings or keys, the person's, its server's). Also the line that says
|
||||
// at rest since when it is the way it is. Days and times are the router's
|
||||
// (status.tz). Pure: no DOM (widgets/timeline.ts draws it).
|
||||
|
||||
import type { Device, LogEvent, Person, Server } from '../../shared/types';
|
||||
import type { ServiceLogEntry } from '../api';
|
||||
import { ago, duration } from '../../shared/format';
|
||||
import { fmt, plural } from '../../shared/i18n';
|
||||
import { plainWhere } from '../../shared/org';
|
||||
import { routerDay, routerTime } from './clock';
|
||||
import { changedServer, linkStateText } from './model';
|
||||
|
||||
export type RunState = 'ok' | 'warn' | 'bad';
|
||||
|
||||
/** A stretch of time in one state, where the device connected from (City · Operator, '' unknown). */
|
||||
export interface Run {
|
||||
a: number;
|
||||
b: number;
|
||||
s: RunState;
|
||||
where: string;
|
||||
}
|
||||
|
||||
/** A change that rewrote what the device gets: the event (or the service log's line) that says so. */
|
||||
export interface Tick {
|
||||
t: number;
|
||||
ev?: LogEvent;
|
||||
sys?: ServiceLogEntry;
|
||||
}
|
||||
|
||||
export type Span = '24h' | '7d' | '30d';
|
||||
export const SPAN: Record<Span, number> = { '24h': 86400, '7d': 7 * 86400, '30d': 30 * 86400 };
|
||||
const H = 3600;
|
||||
|
||||
export interface LinkTimeline {
|
||||
runs: Run[];
|
||||
ticks: Tick[];
|
||||
}
|
||||
|
||||
export interface TimelineInput {
|
||||
device: Device;
|
||||
person: Person;
|
||||
server?: Server;
|
||||
/** The device's and its person's events (any order). */
|
||||
events: LogEvent[];
|
||||
/** The service log (its server's changes). */
|
||||
system?: ServiceLogEntry[];
|
||||
now: number;
|
||||
tz?: number;
|
||||
}
|
||||
|
||||
type Interval = [number, number];
|
||||
|
||||
/** The device's sessions: connect (and roam) to the next disconnect, the last one open to now while it is online. */
|
||||
function sessions(ev: LogEvent[], d: Device, now: number): Run[] {
|
||||
const out: Run[] = [];
|
||||
let cur: Run | null = null;
|
||||
const close = (t: number) => {
|
||||
if (cur && t > cur.a) out.push({ ...cur, b: t });
|
||||
cur = null;
|
||||
};
|
||||
for (const e of ev) {
|
||||
if (e.type === 'connect') {
|
||||
close(e.ts);
|
||||
cur = { a: e.ts, b: e.ts, s: 'ok', where: e.where ? plainWhere(e.where) : '' };
|
||||
} else if (e.type === 'roam') {
|
||||
const where: string = (cur as Run | null)?.where ?? '';
|
||||
close(e.ts);
|
||||
cur = { a: e.ts, b: e.ts, s: 'ok', where: e.where ? plainWhere(e.where) : where };
|
||||
} else if (e.type === 'disconnect') close(e.ts);
|
||||
}
|
||||
if (cur) close(d.online ? now : Math.min(now, Math.max(d.handshake, (cur as Run).a)));
|
||||
return out;
|
||||
}
|
||||
|
||||
/** From each `start` event to its `stop` (or, the last one, to now while `still`). */
|
||||
function intervals(ev: LogEvent[], start: string, stop: string, still: boolean, now: number): Interval[] {
|
||||
const out: Interval[] = [];
|
||||
let from: number | null = null;
|
||||
for (const e of ev) {
|
||||
if (e.type === start && from == null) from = e.ts;
|
||||
else if (e.type === stop && from != null) {
|
||||
out.push([from, e.ts]);
|
||||
from = null;
|
||||
}
|
||||
}
|
||||
if (from != null && still) out.push([from, now]);
|
||||
return out;
|
||||
}
|
||||
|
||||
const inAny = (t: number, list: Interval[]) => list.some(([a, b]) => t >= a && t < b);
|
||||
|
||||
/**
|
||||
* The device's runs and ticks over the last 30 days. A failing link counts
|
||||
* whether or not it was connected (trying: it knocks without a session); the
|
||||
* limit only colours the time it was connected.
|
||||
*/
|
||||
export function linkTimeline(o: TimelineInput): LinkTimeline {
|
||||
const { device: d, person: p, now } = o;
|
||||
const from = now - SPAN['30d'];
|
||||
const sorted = [...o.events].sort((a, b) => a.ts - b.ts);
|
||||
const mine = sorted.filter((e) => e.device === d.id);
|
||||
const own = sorted.filter((e) => e.person === p.id && !e.device);
|
||||
const sess = sessions(mine, d, now).filter((r) => r.b > from);
|
||||
const failing = intervals(mine, 'device_failing', 'device_recovered', !!d.link && !d.disabled, now);
|
||||
const quota = intervals(own, 'quota_reached', 'quota_restored', p.state === 'quota', now);
|
||||
// Every moment the state may change; between two of them it holds.
|
||||
const cuts = new Set<number>([from, now]);
|
||||
for (const r of sess) cuts.add(r.a).add(r.b);
|
||||
for (const [a, b] of [...failing, ...quota]) cuts.add(a).add(b);
|
||||
const points = [...cuts].filter((t) => t >= from && t <= now).sort((a, b) => a - b);
|
||||
const runs: Run[] = [];
|
||||
for (let i = 0; i + 1 < points.length; i++) {
|
||||
const [a, b] = [points[i], points[i + 1]];
|
||||
if (b <= a) continue;
|
||||
const mid = (a + b) / 2;
|
||||
const s = sess.find((r) => mid >= r.a && mid < r.b);
|
||||
let state: RunState | null = s ? 'ok' : null;
|
||||
if (inAny(mid, failing)) state = 'warn';
|
||||
else if (state === 'ok' && inAny(mid, quota)) state = 'bad';
|
||||
if (!state) continue;
|
||||
const where = s?.where ?? '';
|
||||
const last = runs[runs.length - 1];
|
||||
if (last && last.b === a && last.s === state && last.where === where) last.b = b;
|
||||
else runs.push({ a, b, s: state, where });
|
||||
}
|
||||
const ticks: Tick[] = [
|
||||
...mine.filter((e) => e.type === 'device_changed' || e.type === 'device_keys').map((e) => ({ t: e.ts, ev: e })),
|
||||
...own.filter((e) => e.type === 'person_changed').map((e) => ({ t: e.ts, ev: e })),
|
||||
...(o.system ?? []).filter((x) => x.msg === 'changed' && !!o.server && changedServer(x, o.server)).map((x) => ({ t: x.ts, sys: x })),
|
||||
].filter((k) => k.t > from && k.t <= now);
|
||||
return { runs, ticks: ticks.sort((a, b) => a.t - b.t) };
|
||||
}
|
||||
|
||||
/** Seconds in state `s` within the last `span`. */
|
||||
export function timeIn(runs: Run[], span: Span, now: number, s: RunState = 'ok'): number {
|
||||
const from = now - SPAN[span];
|
||||
return runs.filter((r) => r.s === s).reduce((n, r) => n + Math.max(0, Math.min(r.b, now) - Math.max(r.a, from)), 0);
|
||||
}
|
||||
|
||||
/** Times its link failed within the last `span` (runs of warn that began in it). */
|
||||
const failures = (runs: Run[], span: Span, now: number) => runs.filter((r) => r.s === 'warn' && r.a >= now - SPAN[span]).length;
|
||||
|
||||
/** "the last 7 days", for the line's label. */
|
||||
export const spanWords = (s: Span): string => ({ '24h': _('last 24 hours'), '7d': _('last 7 days'), '30d': _('last 30 days') })[s];
|
||||
|
||||
/** "08:40" today, else "4 Nov 08:40" (router time). */
|
||||
function since(t: number, now: number, tz?: number, day?: (d: string) => string): string {
|
||||
const time = routerTime(t, tz);
|
||||
return routerDay(t, tz) === routerDay(now, tz) || !day ? time : `${day(routerDay(t, tz))} ${time}`;
|
||||
}
|
||||
|
||||
export interface Summary {
|
||||
value: string;
|
||||
tone: 'ok' | 'warn' | 'bad' | '';
|
||||
sub: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* What the line says at rest for a period: since when the device is the way it
|
||||
* is, and under it how the period went. `day` writes a router day ("4 Nov").
|
||||
*/
|
||||
export function summary(t: LinkTimeline, o: TimelineInput, span: Span, day: (d: string) => string): Summary {
|
||||
const { device: d, person: p, now, tz } = o;
|
||||
const on = timeIn(t.runs, span, now);
|
||||
const fails = failures(t.runs, span, now);
|
||||
const hours = on ? fmt(_('online %s in the %s'), plural(Math.round(on / H), '%s hour', '%s hours'), spanWords(span)) : '';
|
||||
const how = [hours, fails ? plural(fails, '%s failure', '%s failures') : on ? _('no failures') : ''].filter(Boolean).join(' · ');
|
||||
const lastSeen = d.handshake ? fmt(_('Last online %s'), ago(d.handshake, now)) : _('It has not connected yet');
|
||||
if (d.disabled) return { value: _('Disabled by you'), tone: '', sub: lastSeen };
|
||||
const cur = t.runs[t.runs.length - 1];
|
||||
const live = cur && cur.b >= now - 60 ? cur : null;
|
||||
if (d.link) {
|
||||
const w = linkStateText(d.link.state)?.title ?? '';
|
||||
return { value: fmt(_('%s since %s'), w, since(d.link.since, now, tz, day)), tone: 'warn', sub: d.online ? how || lastSeen : lastSeen };
|
||||
}
|
||||
if (d.online && p.state === 'quota') {
|
||||
const q = live?.s === 'bad' ? live.a : null;
|
||||
return {
|
||||
value: q ? fmt(_('Data limit reached %s'), since(q, now, tz, day)) : _('Data limit reached'),
|
||||
tone: 'bad',
|
||||
sub: _('Online, but only the portal and the router’s DNS open.'),
|
||||
};
|
||||
}
|
||||
if (d.online && !live) return { value: _('Online'), tone: 'ok', sub: how };
|
||||
if (d.online) {
|
||||
// Since the session in the network began: runs back to back of any state but a failure count as one.
|
||||
let a = live?.a ?? now;
|
||||
for (let i = t.runs.length - 1; i > 0 && t.runs[i - 1].b >= t.runs[i].a && t.runs[i - 1].s !== 'warn'; i--) a = t.runs[i - 1].a;
|
||||
return { value: fmt(_('Online since %s'), since(a, now, tz, day)), tone: 'ok', sub: how };
|
||||
}
|
||||
// a router its owner asked for has been given nothing yet: it waits for the admin's answer
|
||||
if (!d.handshake && d.waiting && !d.declined)
|
||||
return {
|
||||
value: _('Waits for your answer'),
|
||||
tone: 'warn',
|
||||
sub: _('Asked for on its owner’s page. It can connect once you accept it.'),
|
||||
};
|
||||
if (!d.handshake)
|
||||
return {
|
||||
value: _('It has not connected yet'),
|
||||
tone: '',
|
||||
sub: _('Its configuration was given out, but the device has never connected.'),
|
||||
};
|
||||
return {
|
||||
value: fmt(_('Offline for %s'), duration(now - d.handshake)),
|
||||
tone: '',
|
||||
sub: how || fmt(_('No connections in the %s'), spanWords(span)),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
// What a failure says to a person, wherever the admin shows one (a toast, a sheet's line, a field's refusal, What's
|
||||
// new, the wait): one place, so a programmer's text never reaches the page (the owner, 2026-11-12: «полный текст
|
||||
// ошибки может появиться не только тут… нужно как-то правильно показывать их по всей админке»).
|
||||
//
|
||||
// A failure is shown as it came only when it is a sentence for a person: the backend's refusals (its own words,
|
||||
// in the page's language) and the page's own (`new Error(_('…'))`). Those begin with a capital letter; what a
|
||||
// program wrote does not (Go's errors by its own convention, our internal ones), or it is LuCI's report of the bus
|
||||
// or the network, which is told by its code in plain words instead. What is not shown goes to the console, whole.
|
||||
//
|
||||
// Pure: no DOM, no state of the pages'.
|
||||
|
||||
/** LuCI's report of a failed call (rpc.js): the object and method, then how it failed. */
|
||||
const RPC = /^RPC call to \S+ (?:failed with (HTTP error|error|ubus code) (-?\d+)|returned invalid message frame)/;
|
||||
|
||||
/** What kind of failure it is, as a person needs to know it. */
|
||||
export type FailureKind = 'said' | 'away' | 'slow' | 'session' | 'denied' | 'mismatch' | 'offline' | 'server' | 'bug';
|
||||
|
||||
/** The kind of `e`. */
|
||||
export function failureKind(e: unknown): FailureKind {
|
||||
const err = e instanceof Error ? e : null;
|
||||
const msg = (err ? err.message : typeof e === 'string' ? e : '').trim();
|
||||
// the engine's own (a TypeError, a SyntaxError): a fault of the page
|
||||
if (err && err.name !== 'Error' && err.name !== 'AbortError')
|
||||
return err.name === 'TypeError' && /fetch|network|load failed/i.test(msg) ? 'offline' : 'bug';
|
||||
const rpc = RPC.exec(msg);
|
||||
if (rpc) {
|
||||
const [, how, code] = rpc;
|
||||
const n = Number(code);
|
||||
if (!how) return 'mismatch';
|
||||
if (how === 'HTTP error') return n === 0 ? 'offline' : n === 403 ? 'session' : 'server';
|
||||
if (how === 'error') return n === -32002 ? 'session' : n === -32601 || n === -32602 || n === -32600 ? 'mismatch' : 'away';
|
||||
// ubus: 4 not found, 5 no data, 10 connection lost — the backend is not on the bus (restarting)
|
||||
if (n === 4 || n === 5 || n === 10) return 'away';
|
||||
if (n === 7) return 'slow';
|
||||
if (n === 6) return 'denied';
|
||||
if (n === 1 || n === 2 || n === 3 || n === 8) return 'mismatch';
|
||||
return 'bug';
|
||||
}
|
||||
if (msg.startsWith('XHR request timed out')) return 'slow';
|
||||
if (msg.startsWith('XHR request aborted') || /^(Failed to fetch|NetworkError|Load failed)/.test(msg)) return 'offline';
|
||||
if (msg.startsWith('Session expired')) return 'session';
|
||||
// a sentence: it begins with a capital letter (in any script) and is not a page of something
|
||||
return /^\p{Lu}/u.test(msg) && msg.length <= 600 ? 'said' : 'bug';
|
||||
}
|
||||
|
||||
/** The words for each kind that is not said as it came. */
|
||||
function wordsFor(kind: Exclude<FailureKind, 'said'>): string {
|
||||
switch (kind) {
|
||||
case 'away':
|
||||
return _('Dawnline is not answering on the router right now: it may be restarting. Try again in a moment.');
|
||||
case 'slow':
|
||||
return _('The router took too long to answer. Try again.');
|
||||
case 'session':
|
||||
return _('Your session has ended. Reload the page to sign in again.');
|
||||
case 'denied':
|
||||
return _('This login may not do that.');
|
||||
case 'mismatch':
|
||||
return _('The page and the router do not agree on this request. Reload the page; if it goes on, update Dawnline.');
|
||||
case 'offline':
|
||||
return _('The router could not be reached. Check the connection and try again.');
|
||||
case 'server':
|
||||
return _('The router’s web server could not answer. Try again in a moment.');
|
||||
case 'bug':
|
||||
return _('Something went wrong on this page. Try again; if it goes on, reload the page.');
|
||||
}
|
||||
}
|
||||
|
||||
const told = new WeakSet<object>();
|
||||
|
||||
/** A failure as a person reads it; what it was is put in the console (once), for whoever looks into it. */
|
||||
export function failureText(e: unknown): string {
|
||||
const kind = failureKind(e);
|
||||
if (kind === 'said') return (e instanceof Error ? e.message : String(e)).trim();
|
||||
if (e && typeof e === 'object') {
|
||||
if (!told.has(e)) {
|
||||
told.add(e);
|
||||
console.warn('dawnline:', e);
|
||||
}
|
||||
} else console.warn('dawnline:', e);
|
||||
return wordsFor(kind);
|
||||
}
|
||||
|
||||
/** The backend's words for a failure that has none of its own (backend/methods/words.go Unworded). */
|
||||
const unworded = (): string => _('Something went wrong on the router. Try again; if it goes on, look at the Log.');
|
||||
|
||||
/**
|
||||
* A failure the router keeps in its state (a component's check, an update job, the history of updates) as a person
|
||||
* reads it: its sentence, or, for a program's text, the plain one; null when it says nothing.
|
||||
*/
|
||||
export function routerSaid(text: string | null | undefined): string | null {
|
||||
const t = (text ?? '').trim();
|
||||
if (!t) return null;
|
||||
if (/^\p{Lu}/u.test(t) && t.length <= 600) return t;
|
||||
console.warn('dawnline: the router said', t);
|
||||
return unworded();
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
// Adding a device for a person (the portal's add, in the admin's sheet): what
|
||||
// it is, LAN Bypass, its name (one suggested by its kind, refused characters
|
||||
// shaking the field, a taken name said in red), then its set-up with the wait
|
||||
// for its first connection at the top (flows/setup.ts). Past the person's
|
||||
// device limit the admin may still add one: the line under the title says so.
|
||||
|
||||
import type { Person, Server } from '../../shared/types';
|
||||
import { api } from '../api';
|
||||
import { h } from '../../portal/dom';
|
||||
import { glide, go, head, openSheet, sub, type View } from '../../portal/ui/sheet';
|
||||
import { once } from '../../portal/ui/feedback';
|
||||
import { badLine } from '../../portal/ui/bad-line';
|
||||
import { kindOf, kindTiles } from '../../portal/flows/device-form';
|
||||
import { defaultName, fitName, PICKS, type KindPick } from '../../shared/format';
|
||||
import { guardDeviceName } from '../../shared/name-guard';
|
||||
import { shake } from '../../shared/shake';
|
||||
import { fmt, num } from '../../shared/i18n';
|
||||
import { errorText } from '../ui/toast';
|
||||
import { ic } from '../ui/icons';
|
||||
import { adminLan } from './device-form';
|
||||
import { setupView, type SetupCtx } from './setup';
|
||||
import { loadQr } from '../shell/qr';
|
||||
import { behindRefetch, takenFor } from '../servers/behind';
|
||||
import { reMark } from '../ui/edit-rows';
|
||||
import { fold } from '../../portal/ui/fold';
|
||||
import { glass } from '../ui/glass';
|
||||
import { netValues } from '../widgets/net-values';
|
||||
import { putChildren } from '../../portal/ui/put';
|
||||
|
||||
export interface AddCtx {
|
||||
person: Person;
|
||||
server?: Server;
|
||||
now: () => number;
|
||||
/** Once the device exists (the page reads the status again). */
|
||||
added?: (id: string) => void;
|
||||
setup?: Pick<SetupCtx, 'fresh' | 'done'>;
|
||||
/** Everyone on the router: what a new router's networks are held against, and who fetches again for them. */
|
||||
people?: Person[];
|
||||
/** Every server (their tunnels' networks are nobody's to have behind a router). */
|
||||
servers?: Server[];
|
||||
}
|
||||
|
||||
function vAdd(c: AddCtx): View {
|
||||
const p = c.person;
|
||||
let pick: KindPick = 'mobile';
|
||||
let bypass = true;
|
||||
let typed = false;
|
||||
const taken = new Set(p.devices.map((d) => d.name.toLowerCase()));
|
||||
// The name a kind gives when none is typed: "Phone", then "Phone 2" (as the portal does).
|
||||
const suggest = (k: KindPick) => {
|
||||
const n = defaultName(kindOf(k));
|
||||
if (!taken.has(fitName(n).toLowerCase())) return fitName(n);
|
||||
for (let i = 2; i < 20; i++) if (!taken.has(fitName(n, ` ${i}`).toLowerCase())) return fitName(n, ` ${i}`);
|
||||
return fitName(n);
|
||||
};
|
||||
const input = h('input', { type: 'text', 'aria-label': _('Name'), autocomplete: 'off', 'data-1p-ignore': true }) as HTMLInputElement;
|
||||
const goBtn = h('button', { class: 'go ready', type: 'submit', 'aria-label': _('Add device') }, ic('arrow')) as HTMLButtonElement;
|
||||
const { el: err, say, unsay } = badLine();
|
||||
// A router's networks are typed with it. Here they are the admin's own to make, so nothing is asked: they are
|
||||
// saved with the device, and what that means for other devices is said under them.
|
||||
let nets: string[] = [];
|
||||
const srv = c.server;
|
||||
const refetch = srv && c.people ? behindRefetch(c.people, srv, [{ p, d: { id: '' } }]) : 0;
|
||||
const means = h(
|
||||
'p',
|
||||
{ class: 'nb-ask-n pb-means', hidden: true },
|
||||
reMark(refetch),
|
||||
N_(refetch, 'device fetches its configuration again', 'devices fetch their configuration again'),
|
||||
);
|
||||
const line = h('span', { class: 'nb-say' });
|
||||
const values = h('span', { class: 'nb-inconf' });
|
||||
const held = takenFor(
|
||||
c.servers ?? (srv ? [srv] : []),
|
||||
(srv?.home ?? []).map((x) => ({ name: x.dev, nets: x.nets })),
|
||||
c.people ?? [],
|
||||
{ id: '' },
|
||||
);
|
||||
const paintNets = () =>
|
||||
putChildren(values, [
|
||||
netValues({
|
||||
key: `behind:new:${p.id}`,
|
||||
nets,
|
||||
was: nets,
|
||||
taken: held,
|
||||
write: true,
|
||||
line,
|
||||
set: (next) =>
|
||||
glide(() => {
|
||||
nets = next;
|
||||
means.hidden = !nets.length || !refetch;
|
||||
paintNets();
|
||||
}),
|
||||
}),
|
||||
line,
|
||||
]);
|
||||
paintNets();
|
||||
// the option row's own shape: its glass, its name and what it means, the values under the words they belong to
|
||||
const behind = h(
|
||||
'div',
|
||||
{ class: 'pb-add' },
|
||||
glass('router', 'blue'),
|
||||
h(
|
||||
'span',
|
||||
{ class: 'sw-t' },
|
||||
h('b', {}, _('Networks behind it')),
|
||||
h('span', { class: 'sw-sub' }, _('Devices at home reach them through it.')),
|
||||
values,
|
||||
means,
|
||||
),
|
||||
);
|
||||
const behindFold = h('div', { class: 'pb-fold', hidden: true }, behind);
|
||||
let router = false;
|
||||
const kinds = kindTiles(PICKS, (k) => {
|
||||
pick = k;
|
||||
// the block is a router's: it opens with the kind and folds away with another
|
||||
if (router !== (kindOf(k) === 'router')) fold(behindFold, (router = kindOf(k) === 'router'));
|
||||
if (!typed) input.value = suggest(k);
|
||||
goBtn.classList.add('ready');
|
||||
});
|
||||
kinds.set(pick);
|
||||
input.value = suggest(pick);
|
||||
const form = h('form', { class: 'field', autocomplete: 'off' }, input, goBtn);
|
||||
guardDeviceName(
|
||||
input,
|
||||
() => form,
|
||||
(w) => (w ? say(w) : unsay()),
|
||||
);
|
||||
input.addEventListener('input', () => {
|
||||
typed = true;
|
||||
goBtn.classList.toggle('ready', !!input.value.trim());
|
||||
unsay();
|
||||
});
|
||||
const lan = adminLan(p, c.server, bypass, (on) => (bypass = on));
|
||||
form.addEventListener('submit', (e) => {
|
||||
e.preventDefault();
|
||||
const name = input.value.trim();
|
||||
if (!name) return shake(form);
|
||||
if (taken.has(name.toLowerCase())) {
|
||||
shake(form);
|
||||
return say(_('This person already has a device with this name.'));
|
||||
}
|
||||
void once(goBtn, async () => {
|
||||
try {
|
||||
// the QR generator and the apps' marks come while the router answers (shell/qr.ts)
|
||||
const kit = loadQr().catch(() => undefined);
|
||||
const r = await api.deviceCreate(p.id, name, kindOf(pick), bypass, kindOf(pick) === 'router' && nets.length ? nets : undefined);
|
||||
c.added?.(r.id);
|
||||
const st = await api.status(1).catch(() => null);
|
||||
const d = st?.people.find((x) => x.id === p.id)?.devices.find((x) => x.id === r.id);
|
||||
if (!d) return;
|
||||
await kit;
|
||||
go(() => setupView({ person: p, device: d, now: c.now, ...c.setup }, r.config, 'top'));
|
||||
} catch (er) {
|
||||
shake(form);
|
||||
say(errorText(er));
|
||||
}
|
||||
});
|
||||
});
|
||||
const free = p.device_limit - p.devices.length;
|
||||
const title = fmt(_('Add a device · %s'), p.name);
|
||||
const el = h(
|
||||
'div',
|
||||
{ class: 'view' },
|
||||
head(title),
|
||||
sub(
|
||||
free > 0
|
||||
? fmt(N_(p.device_limit, '%s of %s slot free', '%s of %s slots free'), num(free), num(p.device_limit))
|
||||
: fmt(_('Over the limit: on the portal they have %s, you can add more'), num(p.device_limit)),
|
||||
),
|
||||
kinds.el,
|
||||
lan,
|
||||
behindFold,
|
||||
form,
|
||||
err,
|
||||
);
|
||||
return { el, label: title };
|
||||
}
|
||||
|
||||
export const addDevice = (c: AddCtx) => openSheet(() => vAdd(c));
|
||||
@@ -0,0 +1,189 @@
|
||||
// Adding a person in the portal's sheet (the concept's addPersonView): their
|
||||
// name in the portal's field with its arrow; the networks they reach (a
|
||||
// track); their server (only with more than one), device limit, end date and
|
||||
// data limit as choice rows, each with its default. The networks and the data
|
||||
// limit come back as last time in this browser (most people are alike).
|
||||
// Create makes them and the same sheet turns to their invite (flows/invite.ts,
|
||||
// "is ready"); without the portal there is no link: it says so and offers
|
||||
// their page.
|
||||
|
||||
import type { Person, Status } from '../../shared/types';
|
||||
import { api } from '../api';
|
||||
import { h } from '../../portal/dom';
|
||||
import { go, head, hint, openSheet, type View } from '../../portal/ui/sheet';
|
||||
import { badLine } from '../../portal/ui/bad-line';
|
||||
import { once } from '../../portal/ui/feedback';
|
||||
import { addMonthsClamped } from '../../shared/format';
|
||||
import { fmt, num, plural } from '../../shared/i18n';
|
||||
import { shake } from '../../shared/shake';
|
||||
import { nameHelp } from '../netcheck';
|
||||
import { ic } from '../ui/icons';
|
||||
import { tabs } from '../ui/tabs';
|
||||
import { choiceRow } from '../ui/choice-row';
|
||||
import { errorText } from '../ui/toast';
|
||||
import { personUrl } from '../shell/routes';
|
||||
import { inviteNext } from './invite';
|
||||
|
||||
export interface AddPersonCtx {
|
||||
st: Status;
|
||||
today: string;
|
||||
/** The server People is filtered to: picked first. */
|
||||
server?: string;
|
||||
/** Once they exist: the page reads the router again. */
|
||||
added(id: string): void;
|
||||
}
|
||||
|
||||
const LAST = 'dl.person.last';
|
||||
|
||||
/** What the last person got (access, data limit), as this browser remembers it. */
|
||||
function last(): { access?: Person['access']; quota?: string } {
|
||||
try {
|
||||
return JSON.parse(localStorage.getItem(LAST) ?? '{}') as { access?: Person['access']; quota?: string };
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
function remember(v: { access: Person['access']; quota: string }) {
|
||||
try {
|
||||
localStorage.setItem(LAST, JSON.stringify(v));
|
||||
} catch {
|
||||
/* no storage: nothing to remember */
|
||||
}
|
||||
}
|
||||
|
||||
/** A network choice's words on the track. */
|
||||
const accessTab = (a: Person['access']): string => ({ internet: _('Internet'), lan: _('Home', 'access'), both: _('Both', 'access') })[a];
|
||||
|
||||
const TERMS = ['', '1', '3', '12'] as const;
|
||||
const termLabel = (t: string): string => (t ? plural(Number(t), '%s month', '%s months') : _('No end date'));
|
||||
const QUOTAS = ['', '10', '50', '100'] as const;
|
||||
const quotaLabel = (q: string): string => (q ? fmt(_('%s GB a month'), num(Number(q))) : _('No limit'));
|
||||
|
||||
function vAdd(c: AddPersonCtx): View {
|
||||
const was = last();
|
||||
let access: Person['access'] = was.access ?? 'internet';
|
||||
let server = c.server && c.st.servers.some((s) => s.id === c.server) ? c.server : (c.st.servers[0]?.id ?? '');
|
||||
let limit = c.st.settings.default_device_limit || 3;
|
||||
let term = '';
|
||||
let quota = (QUOTAS as readonly string[]).includes(was.quota ?? '') ? (was.quota ?? '') : '';
|
||||
const input = h('input', {
|
||||
type: 'text',
|
||||
placeholder: _('Name'),
|
||||
'aria-label': _('Name'),
|
||||
autocomplete: 'off',
|
||||
maxlength: 48,
|
||||
'data-1p-ignore': true,
|
||||
}) as HTMLInputElement;
|
||||
const goBtn = h('button', { class: 'go ready', type: 'submit', 'aria-label': _('Create') }, ic('arrow')) as HTMLButtonElement;
|
||||
const form = h('form', { class: 'field', autocomplete: 'off' }, input, goBtn);
|
||||
const { el: err, say, unsay } = badLine();
|
||||
input.addEventListener('input', () => unsay());
|
||||
const nets = tabs(
|
||||
(['internet', 'lan', 'both'] as const).map((a) => ({ id: a, label: accessTab(a) })),
|
||||
access,
|
||||
(a) => (access = a),
|
||||
{ cls: 'in-row', label: _('Networks') },
|
||||
);
|
||||
const rows = h(
|
||||
'div',
|
||||
{ class: 'add-rows' },
|
||||
c.st.servers.length > 1
|
||||
? choiceRow({
|
||||
title: _('Server'),
|
||||
value: c.st.servers.find((s) => s.id === server)?.name ?? '',
|
||||
options: c.st.servers.map((s) => ({ id: s.id, label: s.name })),
|
||||
on: [server],
|
||||
pick: async ([id]) => {
|
||||
server = id;
|
||||
return c.st.servers.find((s) => s.id === id)?.name ?? '';
|
||||
},
|
||||
})
|
||||
: null,
|
||||
choiceRow({
|
||||
title: _('Devices'),
|
||||
value: fmt(_('up to %s'), num(limit)),
|
||||
options: ['1', '2', '3', '5', '10'].map((n) => ({ id: n, label: n })),
|
||||
on: [String(limit)],
|
||||
pick: async ([n]) => {
|
||||
limit = Number(n);
|
||||
return fmt(_('up to %s'), num(limit));
|
||||
},
|
||||
}),
|
||||
choiceRow({
|
||||
title: _('Term'),
|
||||
value: termLabel(term),
|
||||
options: TERMS.map((t) => ({ id: t, label: termLabel(t) })),
|
||||
on: [term],
|
||||
pick: async ([t]) => {
|
||||
term = t;
|
||||
return termLabel(t);
|
||||
},
|
||||
}),
|
||||
choiceRow({
|
||||
title: _('Traffic'),
|
||||
value: quotaLabel(quota),
|
||||
options: QUOTAS.map((q) => ({ id: q, label: q ? fmt(_('%s GB'), num(Number(q))) : _('No limit') })),
|
||||
on: [quota],
|
||||
pick: async ([q]) => {
|
||||
quota = q;
|
||||
return quotaLabel(q);
|
||||
},
|
||||
}),
|
||||
);
|
||||
const create = async () => {
|
||||
const name = input.value.trim();
|
||||
const help = nameHelp(
|
||||
name,
|
||||
c.st.people.map((p) => p.name),
|
||||
);
|
||||
if (help.bad) {
|
||||
say(help.text);
|
||||
shake(form);
|
||||
input.focus();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const expires = term ? addMonthsClamped(c.today, Number(term)) : '';
|
||||
const r = await api.personCreate(name, '', server, access, String(limit), expires, quota, 'month');
|
||||
remember({ access, quota });
|
||||
c.added(r.id);
|
||||
const p = { id: r.id, name, devices: [], code_set: Date.now() / 1000 };
|
||||
const srv = c.st.servers.find((s) => s.id === server)?.name ?? '';
|
||||
if (r.link) await inviteNext({ person: p, server: srv, ready: true }, r.link);
|
||||
else go(() => noLinkView(r.id, name));
|
||||
} catch (e) {
|
||||
say(errorText(e));
|
||||
shake(form);
|
||||
}
|
||||
};
|
||||
form.addEventListener('submit', (e) => {
|
||||
e.preventDefault();
|
||||
void once(goBtn, create);
|
||||
});
|
||||
requestAnimationFrame(() => input.focus({ preventScroll: true }));
|
||||
const el = h(
|
||||
'div',
|
||||
{ class: 'view add-v' },
|
||||
head(_('New person')),
|
||||
form,
|
||||
err,
|
||||
h('div', { class: 'choice' }, h('div', { class: 'choice-h' }, h('span', {}, _('Networks'))), nets.el),
|
||||
rows,
|
||||
hint(_('All of it can be changed later on their page. Their invite comes next, in this sheet.')),
|
||||
);
|
||||
return { el, label: _('New person') };
|
||||
}
|
||||
|
||||
/** Created, but the portal is off: no link to give. Their page is where devices are added for them. */
|
||||
function noLinkView(id: string, name: string): View {
|
||||
const el = h(
|
||||
'div',
|
||||
{ class: 'view' },
|
||||
head(fmt(_('%s is ready'), name)),
|
||||
hint(_('Turn on the personal portal in System to get their link, or add their devices yourself on their page.')),
|
||||
h('a', { class: 'btn accent block', href: personUrl(id) }, h('span', {}, _('Open their page'))),
|
||||
);
|
||||
return { el, label: fmt(_('%s is ready'), name) };
|
||||
}
|
||||
|
||||
export const addPerson = (c: AddPersonCtx) => openSheet(() => vAdd(c));
|
||||
@@ -0,0 +1,54 @@
|
||||
// A question in the portal's sheet (its .ask: the action's glass in its tone,
|
||||
// what happens, Cancel and the action), before something that cannot be taken
|
||||
// back or that rewrites a device's configuration. The action's button stays
|
||||
// busy (the portal's orb) until its work is done; an error says why in a toast
|
||||
// and leaves the question open.
|
||||
|
||||
import { h, type Kid } from '../../portal/dom';
|
||||
import { closeSheet, type View } from '../../portal/ui/sheet';
|
||||
import { once } from '../../portal/ui/feedback';
|
||||
import { glass } from '../ui/glass';
|
||||
import { errorText, notify } from '../ui/toast';
|
||||
|
||||
export interface Ask {
|
||||
icon: string;
|
||||
tone: 'red' | 'orange' | 'blue';
|
||||
title: string;
|
||||
text: Kid[];
|
||||
action: string;
|
||||
/** The action button's look: red (removes), warn (rewrites). */
|
||||
cls: 'red' | 'warn' | 'accent';
|
||||
run(): Promise<void>;
|
||||
}
|
||||
|
||||
export function askView(o: Ask): View {
|
||||
const ok = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
class: `btn ${o.cls}`,
|
||||
onclick: (e: Event) =>
|
||||
once(e.currentTarget as HTMLButtonElement, async () => {
|
||||
try {
|
||||
await o.run();
|
||||
} catch (err) {
|
||||
notify(errorText(err), 'error', 10000);
|
||||
}
|
||||
}),
|
||||
},
|
||||
h('span', {}, o.action),
|
||||
);
|
||||
const el = h(
|
||||
'div',
|
||||
{ class: 'view' },
|
||||
h(
|
||||
'div',
|
||||
{ class: 'ask' },
|
||||
glass(o.icon, o.tone, 'gi xl'),
|
||||
h('h3', {}, o.title),
|
||||
h('p', {}, ...o.text),
|
||||
h('div', { class: 'btnrow' }, h('button', { type: 'button', class: 'btn soft', onclick: () => closeSheet() }, _('Cancel')), ok),
|
||||
),
|
||||
);
|
||||
return { el, label: o.title, asks: true };
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
// AmneziaWG's build in the portal's sheet (a choice with consequences): the
|
||||
// builds made for this firmware as options (their generation, who makes them,
|
||||
// the version and which apps can connect), the one installed marked and not
|
||||
// pressable, a build that has none for this firmware said so. A pick asks
|
||||
// first (every AmneziaWG tunnel restarts for a few seconds; 3.1 needs
|
||||
// AmneziaVPN 3.1 on the devices), then the updater installs it in the same
|
||||
// sheet (flows/operation.ts). Under them: what a build will bring with a
|
||||
// newer OpenWrt.
|
||||
|
||||
import type { AwgSource, UpdateComponent, UpdatesStatus } from '../api';
|
||||
import { h } from '../../portal/dom';
|
||||
import { go, head, openSheet, sub, type View } from '../../portal/ui/sheet';
|
||||
import { fmt, num } from '../../shared/i18n';
|
||||
import { glass } from '../ui/glass';
|
||||
import { ic } from '../ui/icons';
|
||||
import { operationView, type Operation } from './operation';
|
||||
|
||||
/** "Restarts Home and Family for a few seconds": the tunnels a new kernel module restarts. */
|
||||
export function restartsText(tunnels: string[]): string {
|
||||
if (!tunnels.length) return _('Switching takes a few seconds. Devices keep their configurations.');
|
||||
if (tunnels.length === 1)
|
||||
return fmt(_('Switching restarts the tunnel for a few seconds: %s. Devices keep their configurations.'), tunnels[0]);
|
||||
return fmt(
|
||||
N_(
|
||||
tunnels.length,
|
||||
'Switching restarts %s tunnel for a few seconds: %s. Devices keep their configurations.',
|
||||
'Switching restarts %s tunnels for a few seconds: %s. Devices keep their configurations.',
|
||||
),
|
||||
num(tunnels.length),
|
||||
tunnels.join(', '),
|
||||
);
|
||||
}
|
||||
|
||||
/** What switching to (or installing) `id` asks and runs; `done` reads the page again. */
|
||||
function switchBuild(st: UpdatesStatus, w: UpdateComponent, id: AwgSource, installed: string | null, done: () => void): Operation {
|
||||
const x = w.sources![id]!;
|
||||
return {
|
||||
what: `amneziawg:${id}${w.ru ? ':ru' : ''}`,
|
||||
title: installed ? fmt(_('Switching to AmneziaWG %s'), x.gen ?? '') : _('Installing AmneziaWG'),
|
||||
ask: {
|
||||
icon: 'amneziawg',
|
||||
tone: 'orange',
|
||||
title: installed ? fmt(_('Switch to AmneziaWG %s?'), x.gen ?? '') : fmt(_('Install AmneziaWG %s?'), x.gen ?? ''),
|
||||
text: [
|
||||
[
|
||||
fmt(_('The %s build, %s.'), x.label, x.version ?? ''),
|
||||
restartsText(st.tunnels ?? []),
|
||||
x.gen === '3.1' ? _('Devices need AmneziaVPN 3.1 or newer.') : '',
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' '),
|
||||
],
|
||||
action: installed ? _('Switch') : _('Install'),
|
||||
cls: 'warn',
|
||||
},
|
||||
done,
|
||||
};
|
||||
}
|
||||
|
||||
function view(st: UpdatesStatus, w: UpdateComponent, installed: string | null, done: () => void): View {
|
||||
const srcs = w.sources ?? {};
|
||||
const ids = Object.keys(srcs) as AwgSource[];
|
||||
const opt = (id: AwgSource) => {
|
||||
const x = srcs[id]!;
|
||||
const on = w.current === id && !!installed;
|
||||
const can = !on && !!x.version;
|
||||
const b = h(
|
||||
'button',
|
||||
{ type: 'button', class: `opt${on ? ' on' : ''}`, role: 'listitem', disabled: !can },
|
||||
glass('amneziawg', on ? 'blue' : 'grey'),
|
||||
h(
|
||||
'span',
|
||||
{ class: 'opt-t' },
|
||||
h('b', {}, x.gen ? `AmneziaWG ${x.gen}` : 'AmneziaWG', on ? h('span', { class: 'now' }, ` ${_('now')}`) : null),
|
||||
h('span', {}, `${x.label} · ${x.gen === '3.1' ? 'AmneziaVPN 3.1+' : _('every app')}`),
|
||||
h('span', { class: 'mono' }, x.version ?? _('none yet')),
|
||||
),
|
||||
ic(on ? 'check' : 'chevron', `i opt-chev${on ? ' on' : ''}`),
|
||||
);
|
||||
if (can) b.addEventListener('click', () => go(() => operationView(switchBuild(st, w, id, installed, done))));
|
||||
return b;
|
||||
};
|
||||
const newer = ids
|
||||
.map((id) => {
|
||||
const n = srcs[id]?.newer;
|
||||
return n ? fmt(_('%s moves to %s with OpenWrt %s.'), srcs[id]!.label, n.gen, n.tag.replace(/^v/, '')) : '';
|
||||
})
|
||||
.filter(Boolean);
|
||||
const el = h(
|
||||
'div',
|
||||
{ class: 'view' },
|
||||
head(_('AmneziaWG build')),
|
||||
sub(_('The kernel module and its tools, made for this firmware.')),
|
||||
ids.length
|
||||
? h('div', { class: 'opts', role: 'list' }, ...ids.map(opt))
|
||||
: h('p', { class: 'hint' }, _('Check for updates to see the builds for this router.')),
|
||||
newer.length ? h('p', { class: 'hint' }, newer.join(' ')) : null,
|
||||
);
|
||||
return { el, label: _('AmneziaWG build') };
|
||||
}
|
||||
|
||||
/** The builds; a pick asks and installs in the same sheet, `done` after. */
|
||||
export const awgBuildSheet = (st: UpdatesStatus, w: UpdateComponent, installed: string | null, done: () => void) =>
|
||||
openSheet(() => view(st, w, installed, done));
|
||||
@@ -0,0 +1,161 @@
|
||||
// What a router's owner asked for on their own page, answered: the router itself (it waits, unable to connect,
|
||||
// until it is taken) or networks behind it. An answer is a decision, not a setting: it is made at once, said in a
|
||||
// toast and undone from it («reopen»: the question stands again). Taken, the networks are checked by the router
|
||||
// against everything they must not share addresses with, and its refusal names whose they are. Turned down, the
|
||||
// owner reads why on their page, in the words picked here.
|
||||
//
|
||||
// The question stands in the device's dialog (askBlock) and in the server's Network section (its row); a device's
|
||||
// card only leads to the dialog: a card is no place for a question.
|
||||
|
||||
import type { Declined, Device, Person, Server } from '../../shared/types';
|
||||
import { h } from '../../portal/dom';
|
||||
import { openMenu } from '../../portal/ui/menu';
|
||||
import { declinedWords } from '../../shared/format';
|
||||
import { fmt } from '../../shared/i18n';
|
||||
import { api } from '../api';
|
||||
import { asksOf, behindRefetch, routerAsks, wishOf } from '../servers/behind';
|
||||
import { say } from '../shell/toast';
|
||||
import { said } from '../../portal/ui/chips-motion';
|
||||
import { reMark } from '../ui/edit-rows';
|
||||
import { ic } from '../ui/icons';
|
||||
import { errorText, notify } from '../ui/toast';
|
||||
|
||||
export interface Answer {
|
||||
p: Person;
|
||||
d: Device;
|
||||
/** The networks answered: one of a chip, or all that is asked. */
|
||||
nets: string[];
|
||||
/** The router itself is what is asked for (its networks come with it). */
|
||||
router: boolean;
|
||||
/** The page reads the router again. */
|
||||
changed(): void;
|
||||
/** The router was turned down: it is no device of the admin's lists any more (its dialog shuts). */
|
||||
gone?(): void;
|
||||
}
|
||||
|
||||
/** The answer taken back: the question stands again, as its toast's Undo does it. */
|
||||
function reopen(o: Answer) {
|
||||
api
|
||||
.deviceAnswer(o.d.id, 'reopen', undefined, o.router, o.nets)
|
||||
.then(o.changed)
|
||||
.catch((e) => notify(errorText(e), 'error'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Take what is asked for. Resolves with why it cannot be taken as it is (the router's words: a network that shares
|
||||
* addresses with one something has), or null once it is taken.
|
||||
*/
|
||||
export async function takeAsk(o: Answer): Promise<string | null> {
|
||||
try {
|
||||
await api.deviceAnswer(o.d.id, 'accept', undefined, undefined, o.router ? undefined : o.nets);
|
||||
} catch (e) {
|
||||
return errorText(e);
|
||||
}
|
||||
o.changed();
|
||||
say(o.router ? fmt(_('Router %s accepted'), o.d.name) : fmt(_('%s: %s accepted'), o.d.name, o.nets.join(', ')), {
|
||||
undo: () => reopen(o),
|
||||
undone: _('It is asked for again'),
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Turn down what is asked for, with the reason its owner will read. */
|
||||
async function declineAsk(o: Answer, reason: Declined) {
|
||||
try {
|
||||
await api.deviceAnswer(o.d.id, 'decline', reason, undefined, o.router ? undefined : o.nets);
|
||||
} catch (e) {
|
||||
return notify(errorText(e), 'error');
|
||||
}
|
||||
o.changed();
|
||||
if (o.router) o.gone?.();
|
||||
say(fmt(_('Declined: %s reads so on their page'), o.p.name), { undo: () => reopen(o), undone: _('It is asked for again') });
|
||||
}
|
||||
|
||||
/** «Decline» asks one thing more, in a menu at its button: why, in the words the owner will read. */
|
||||
export function declineMenu(at: HTMLElement, o: Answer) {
|
||||
const reasons: Declined[] = ['overlap', 'unneeded', 'talk'];
|
||||
openMenu(
|
||||
at,
|
||||
[
|
||||
...reasons.map((r) => ({ label: declinedWords(r), icon: 'x', run: () => void declineAsk(o, r) })),
|
||||
null,
|
||||
{ label: _('Without a reason'), icon: 'minus', run: () => void declineAsk(o, 'plain') },
|
||||
],
|
||||
o.router ? o.d.name : o.nets.join(', '),
|
||||
);
|
||||
}
|
||||
|
||||
/** What the admin should know before taking it, one line each. */
|
||||
export function askWarnings(p: Person, d: Device, srv: Pick<Server, 'mesh'> | undefined, router: boolean, nets: boolean): string[] {
|
||||
return [
|
||||
// a router that sends everything into the tunnel brings its whole place's internet with it
|
||||
router && p.access !== 'lan' && !d.lan_bypass
|
||||
? fmt(_('%s has Internet access: all of that place’s internet will go through this tunnel.'), p.name)
|
||||
: null,
|
||||
nets && srv?.mesh === 'off' ? _('Devices do not see each other on this server: only home devices will reach it.') : null,
|
||||
].filter((x): x is string => !!x);
|
||||
}
|
||||
|
||||
/**
|
||||
* What a device asks for, with its two answers: a router asked for is the whole of the question, its networks with
|
||||
* it; on a router that is a device already, the networks asked for since. Taken, it is made at once, with what that
|
||||
* means for other devices said in the block. Null: it asks for nothing.
|
||||
*/
|
||||
export function askBlock(o: {
|
||||
p: Person;
|
||||
d: Device;
|
||||
people: Person[];
|
||||
srv?: Server;
|
||||
write: boolean;
|
||||
changed(): void;
|
||||
gone?(): void;
|
||||
}): HTMLElement | null {
|
||||
const { d, p } = o;
|
||||
const router = routerAsks(d);
|
||||
const nets = router ? wishOf(d) : asksOf(d);
|
||||
if (!router && !nets.length) return null;
|
||||
const answer: Answer = { p, d, nets, router, changed: o.changed, gone: o.gone };
|
||||
const refetch = o.srv && nets.length ? behindRefetch(o.people, o.srv, [{ p, d }]) : 0;
|
||||
const refused = h('span', { class: 'nb-say bad-t', hidden: true });
|
||||
const yes = h('button', { type: 'button', class: 'btn tint sm' }, ic('check'), h('span', {}, _('Accept'))) as HTMLButtonElement;
|
||||
const no = h('button', { type: 'button', class: 'btn soft sm' }, ic('x'), h('span', {}, _('Decline'))) as HTMLButtonElement;
|
||||
yes.addEventListener('click', async () => {
|
||||
yes.disabled = no.disabled = true;
|
||||
const bad = await takeAsk(answer);
|
||||
yes.disabled = no.disabled = false;
|
||||
if (!bad) return;
|
||||
refused.hidden = false;
|
||||
refused.textContent = bad;
|
||||
said(refused);
|
||||
});
|
||||
no.addEventListener('click', () => declineMenu(no, answer));
|
||||
return h(
|
||||
'div',
|
||||
{ class: 'nb-ask' },
|
||||
h(
|
||||
'span',
|
||||
{ class: 'nb-ask-t' },
|
||||
router
|
||||
? fmt(_('%s asks to add this router'), p.name)
|
||||
: fmt(N_(nets.length, '%s asks for a network behind it', '%s asks for networks behind it'), p.name),
|
||||
),
|
||||
nets.length
|
||||
? h(
|
||||
'span',
|
||||
{ class: 'nb-nets' },
|
||||
...nets.map((n) => h('span', { class: 'nb-chip mono nb-asked nb-still' }, h('span', { class: 'nb-cb' }, n))),
|
||||
)
|
||||
: null,
|
||||
...askWarnings(p, d, o.srv, router, nets.length > 0).map((w) => h('span', { class: 'nb-ask-w' }, ic('alert'), w)),
|
||||
refetch
|
||||
? h(
|
||||
'span',
|
||||
{ class: 'nb-ask-n' },
|
||||
reMark(refetch),
|
||||
N_(refetch, 'device fetches its configuration again', 'devices fetch their configuration again'),
|
||||
)
|
||||
: null,
|
||||
refused,
|
||||
o.write ? h('div', { class: 'nb-ask-b' }, yes, no) : null,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
// A circle in the portal's sheet: its name, its colour, and its people as a list to tick. A row a person: their
|
||||
// face, their name, where they are now when that matters (another circle: a person is in one at a time, so ticking
|
||||
// them moves them), and a round mark as the option tiles have. The rows stand in the order the choice is made in:
|
||||
// who is in the circle, who can be (home access, no circle), who is in another circle, and last, under one line
|
||||
// that says why, the people with internet only (in a circle they still reach nobody). A search over the list from
|
||||
// nine people; the head counts the ticked. Save, or Delete for one that exists. The colours are the old page's
|
||||
// eight: a circle stores the index.
|
||||
|
||||
import type { Circle, Person, Status } from '../../shared/types';
|
||||
import { api } from '../api';
|
||||
import { h } from '../../portal/dom';
|
||||
import { closeSheet, head, hint, openSheet, type View } from '../../portal/ui/sheet';
|
||||
import { once } from '../../portal/ui/feedback';
|
||||
import { fmt, plural } from '../../shared/i18n';
|
||||
import { circleNameHelp } from '../netcheck';
|
||||
import { errorText, notify } from '../ui/toast';
|
||||
import { say } from '../shell/toast';
|
||||
import { homeAccess } from '../servers/reach';
|
||||
import { face } from '../ui/face';
|
||||
import { ic } from '../ui/icons';
|
||||
import { field } from './form';
|
||||
import { putChildren } from '../../portal/ui/put';
|
||||
|
||||
/** Circle colours; the circle stores an index. */
|
||||
const CIRCLE_COLORS = ['#3a83f7', '#a78bfa', '#f472b6', '#f59e0b', '#10b981', '#22d3ee', '#ef4444', '#84cc16'];
|
||||
|
||||
export const circleColor = (c: Circle | undefined): string => CIRCLE_COLORS[c?.color ?? 0] ?? CIRCLE_COLORS[0];
|
||||
|
||||
export interface CircleCtx {
|
||||
st: Status;
|
||||
srv: string;
|
||||
changed(): Promise<void>;
|
||||
}
|
||||
|
||||
const COLORS = CIRCLE_COLORS.length;
|
||||
const colorOf = (i: number) => CIRCLE_COLORS[i];
|
||||
|
||||
function circleView(c: CircleCtx, ci: Circle | null): View {
|
||||
const mine = c.st.circles.filter((x) => x.server === c.srv);
|
||||
const used = new Set(mine.map((x) => x.color));
|
||||
let color = ci?.color ?? [...Array(COLORS).keys()].find((i) => !used.has(i)) ?? 0;
|
||||
const name = field(
|
||||
_('Name', 'circle or service'),
|
||||
ci?.name ?? '',
|
||||
(v) =>
|
||||
circleNameHelp(
|
||||
v,
|
||||
mine.filter((x) => x.id !== ci?.id).map((x) => x.name),
|
||||
),
|
||||
{ placeholder: _('Family') },
|
||||
);
|
||||
const swatches = h('div', { class: 'swatches', role: 'radiogroup', 'aria-label': _('Colour') });
|
||||
const paintSwatches = () =>
|
||||
putChildren(
|
||||
swatches,
|
||||
[...Array(COLORS).keys()].map((i) =>
|
||||
h('button', {
|
||||
type: 'button',
|
||||
role: 'radio',
|
||||
class: `swatch${i === color ? ' on' : ''}`,
|
||||
style: `--sw:${colorOf(i)}`,
|
||||
'aria-checked': String(i === color),
|
||||
'aria-label': fmt(_('Colour %s'), i + 1),
|
||||
onclick: () => {
|
||||
color = i;
|
||||
paintSwatches();
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
paintSwatches();
|
||||
|
||||
const people = c.st.people.filter((p) => p.server === c.srv).sort((a, b) => a.name.localeCompare(b.name));
|
||||
const members = new Set(people.filter((p) => ci && p.circle === ci.id).map((p) => p.id));
|
||||
const was = new Set(members);
|
||||
const other = (p: Person) => (p.circle && p.circle !== ci?.id ? mine.find((x) => x.id === p.circle) : undefined);
|
||||
// the order the choice is made in; it stays as the sheet opened, so a tick never makes its row jump away
|
||||
const rank = (p: Person) => (was.has(p.id) ? 0 : !homeAccess(p) ? 3 : other(p) ? 2 : 1);
|
||||
const order = [...people].sort((a, b) => rank(a) - rank(b));
|
||||
const count = h('span', { class: 'kt-pk-n num' });
|
||||
const counted = () => (count.textContent = members.size ? plural(members.size, '%s picked', '%s picked') : _('nobody yet'));
|
||||
const row = (p: Person, quiet = false) => {
|
||||
const o = other(p);
|
||||
const dot = o ? h('i', { class: 'kt-pk-dot' }) : null;
|
||||
if (dot) dot.style.background = circleColor(o);
|
||||
const sub = h('span', { class: 'kt-pk-s' });
|
||||
const b = h(
|
||||
'button',
|
||||
{ type: 'button', role: 'checkbox', class: `kt-pk-r${quiet ? ' quiet' : ''}`, 'data-name': p.name.toLocaleLowerCase() },
|
||||
face(p.name, p.online > 0 ? 'ok' : ''),
|
||||
h('span', { class: 'kt-pk-t' }, h('b', {}, p.name), sub),
|
||||
h('span', { class: 'kt-op-m', 'aria-hidden': 'true' }, ic('check')),
|
||||
);
|
||||
const draw = () => {
|
||||
const on = members.has(p.id);
|
||||
b.classList.toggle('on', on);
|
||||
b.setAttribute('aria-checked', String(on));
|
||||
// another circle: where they are, or, once ticked, that they leave it
|
||||
// …or, for someone already in this circle with internet only, that it does nothing for them yet
|
||||
putChildren(
|
||||
sub,
|
||||
o
|
||||
? [dot!, on ? fmt(_('moves from %s'), o.name) : o.name]
|
||||
: !homeAccess(p) && !quiet
|
||||
? [_('internet only: reaches nobody yet')]
|
||||
: [],
|
||||
);
|
||||
sub.hidden = !sub.childNodes.length;
|
||||
};
|
||||
draw();
|
||||
b.addEventListener('click', () => {
|
||||
if (!members.delete(p.id)) members.add(p.id);
|
||||
draw();
|
||||
counted();
|
||||
});
|
||||
return b;
|
||||
};
|
||||
// who a circle does nothing for, unless they are in this one already (those stay on top, said on their row)
|
||||
const netOnly = order.filter((p) => !homeAccess(p) && !was.has(p.id));
|
||||
const rows = h(
|
||||
'div',
|
||||
{ class: 'kt-pk-l', role: 'group', 'aria-label': _('People') },
|
||||
...order.filter((p) => !netOnly.includes(p)).map((p) => row(p)),
|
||||
netOnly.length
|
||||
? h(
|
||||
'p',
|
||||
{ class: 'kt-pk-g' },
|
||||
fmt(_('Internet only · %s'), netOnly.length),
|
||||
h('span', {}, _('in a circle they still reach nobody, until they get home access')),
|
||||
)
|
||||
: null,
|
||||
...netOnly.map((p) => row(p, true)),
|
||||
);
|
||||
const none = h('p', { class: 'kt-pk-none', hidden: '' }, _('Nobody by that name.'));
|
||||
const q = h('input', {
|
||||
type: 'search',
|
||||
class: 'kt-pk-q',
|
||||
placeholder: _('Find a person'),
|
||||
'aria-label': _('Find a person'),
|
||||
autocomplete: 'off',
|
||||
spellcheck: 'false',
|
||||
}) as HTMLInputElement;
|
||||
q.addEventListener('input', () => {
|
||||
const t = q.value.trim().toLocaleLowerCase();
|
||||
let any = false;
|
||||
rows.querySelectorAll<HTMLElement>('.kt-pk-r').forEach((r) => {
|
||||
const show = !t || (r.dataset.name ?? '').includes(t);
|
||||
r.hidden = !show;
|
||||
any ||= show;
|
||||
});
|
||||
rows.querySelectorAll<HTMLElement>('.kt-pk-g').forEach((g) => (g.hidden = !!t));
|
||||
none.hidden = any;
|
||||
});
|
||||
counted();
|
||||
|
||||
const save = h('button', { type: 'button', class: 'btn accent block' }, h('span', {}, _('Save'))) as HTMLButtonElement;
|
||||
save.addEventListener('click', () =>
|
||||
once(save, async () => {
|
||||
if (!name.check()) return;
|
||||
try {
|
||||
await api.circleSet(ci?.id ?? '', c.srv, name.value(), color, [...members]);
|
||||
closeSheet();
|
||||
say(ci ? fmt(_('%s updated'), name.value()) : fmt(_('%s added'), name.value()));
|
||||
await c.changed();
|
||||
} catch (e) {
|
||||
notify(errorText(e), 'error', 10000);
|
||||
}
|
||||
}),
|
||||
);
|
||||
const del = ci ? (h('button', { type: 'button', class: 'btn soft block bad-t' }, h('span', {}, _('Delete'))) as HTMLButtonElement) : null;
|
||||
del?.addEventListener('click', () =>
|
||||
once(del, async () => {
|
||||
try {
|
||||
await api.circleDelete(ci!.id);
|
||||
closeSheet();
|
||||
say(fmt(_('%s deleted'), ci!.name));
|
||||
await c.changed();
|
||||
} catch (e) {
|
||||
notify(errorText(e), 'error', 10000);
|
||||
}
|
||||
}),
|
||||
);
|
||||
const title = ci ? fmt(_('Edit %s'), ci.name) : _('New circle');
|
||||
requestAnimationFrame(() => !ci && name.input.focus({ preventScroll: true }));
|
||||
const el = h(
|
||||
'div',
|
||||
{ class: 'view kt-circle' },
|
||||
head(title),
|
||||
name.el,
|
||||
h('div', { class: 'choice' }, h('div', { class: 'choice-h' }, h('span', {}, _('Colour'))), swatches),
|
||||
h(
|
||||
'div',
|
||||
{ class: 'choice kt-pk' },
|
||||
h('div', { class: 'choice-h kt-pk-h' }, h('span', {}, _('People')), count),
|
||||
people.length > 8 ? h('label', { class: 'kt-pk-find' }, ic('search'), q) : null,
|
||||
people.length ? h('div', { class: 'kt-pk-box' }, rows, none) : hint(_('Nobody on this server yet.')),
|
||||
),
|
||||
hint(_('Devices of people in one circle reach each other. A person is in one circle at a time.')),
|
||||
h('div', { class: 'fl-acts' }, save, del),
|
||||
);
|
||||
return { el, label: title };
|
||||
}
|
||||
|
||||
/** A circle on this server: a new one (null), or one to change. */
|
||||
export const openCircle = (c: CircleCtx, ci: Circle | null) => openSheet(() => circleView(c, ci));
|
||||
@@ -0,0 +1,79 @@
|
||||
// What is done to one device from its ⋯ (its own page, or its card on its
|
||||
// person's page): turned off or on in one tap, said with Undo; its traffic
|
||||
// history reset and the device removed, each after a question in the sheet
|
||||
// (neither can be taken back).
|
||||
|
||||
import type { Device } from '../../shared/types';
|
||||
import { api } from '../api';
|
||||
import { closeSheet, openSheet } from '../../portal/ui/sheet';
|
||||
import { fmt } from '../../shared/i18n';
|
||||
import { errorText, notify } from '../ui/toast';
|
||||
import { say } from '../shell/toast';
|
||||
import { askView } from './ask';
|
||||
|
||||
export interface DeviceActCtx {
|
||||
device: Device;
|
||||
/** Read the router again and draw what changed. */
|
||||
reload(): void;
|
||||
/** It is gone (removed): where the page goes now. */
|
||||
removed?(): void;
|
||||
}
|
||||
|
||||
/** Turn it off or on: one tap, said with its Undo. */
|
||||
export async function toggleDevice(c: DeviceActCtx, off: boolean) {
|
||||
const d = c.device;
|
||||
try {
|
||||
await api.deviceUpdate(d.id, undefined, off);
|
||||
} catch (e) {
|
||||
notify(errorText(e), 'error', 10000);
|
||||
return;
|
||||
}
|
||||
c.reload();
|
||||
say(off ? fmt(_('%s is turned off'), d.name) : fmt(_('%s is turned on'), d.name), {
|
||||
undo: () => void api.deviceUpdate(d.id, undefined, !off).then(() => c.reload()),
|
||||
undone: off ? fmt(_('%s is turned on'), d.name) : fmt(_('%s is turned off'), d.name),
|
||||
});
|
||||
}
|
||||
|
||||
/** Reset its traffic history, after a question. */
|
||||
export function resetDeviceTraffic(c: DeviceActCtx) {
|
||||
const d = c.device;
|
||||
openSheet(() =>
|
||||
askView({
|
||||
icon: 'chart',
|
||||
tone: 'red',
|
||||
title: fmt(_('Reset traffic history for %s?'), d.name),
|
||||
text: [fmt(_("Clears %s's daily and monthly traffic history. Their person's totals and data limit are not changed."), d.name)],
|
||||
action: _('Reset'),
|
||||
cls: 'red',
|
||||
run: async () => {
|
||||
await api.usageClear('device', d.id);
|
||||
closeSheet();
|
||||
say(_('Traffic history reset'));
|
||||
c.reload();
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/** Remove it, after a question. */
|
||||
export function removeDevice(c: DeviceActCtx) {
|
||||
const d = c.device;
|
||||
openSheet(() =>
|
||||
askView({
|
||||
icon: 'trash',
|
||||
tone: 'red',
|
||||
title: fmt(_('Remove %s?'), d.name),
|
||||
text: [_('Its configuration stops working at once. It can be added again here or on the portal.')],
|
||||
action: _('Remove'),
|
||||
cls: 'red',
|
||||
run: async () => {
|
||||
await api.deviceDelete(d.id);
|
||||
closeSheet();
|
||||
notify(fmt(_('%s removed'), d.name), 'success', 3000);
|
||||
if (c.removed) c.removed();
|
||||
else c.reload();
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
// What the admin's device flows ask (add a device, new keys), on the portal's
|
||||
// own form parts (portal/flows/device-form.ts: the kind tiles, the LAN Bypass
|
||||
// switch) in the admin's voice: the portal speaks to the device's owner
|
||||
// ("your local network"), the admin sets up someone else's device.
|
||||
|
||||
import type { Person, Server } from '../../shared/types';
|
||||
import { lanSwitch } from '../../portal/flows/device-form';
|
||||
import { homeOf } from '../../shared/format';
|
||||
|
||||
/** LAN Bypass as the admin sees it: the device's own local network, its home networks excepted. */
|
||||
export function adminLan(p: Person, srv: Server | undefined, on: boolean, onChange: (on: boolean) => void): HTMLElement {
|
||||
const row = lanSwitch(on, homeOf(p, srv), onChange);
|
||||
const said = row.querySelector<HTMLElement>('.sw-t > .sw-sub:not(.sw-note)');
|
||||
if (said) said.textContent = _('The device’s local network stays reachable while connected.');
|
||||
return row;
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
// A labelled field in a sheet: the name above it (the new person's «choice»
|
||||
// head), the portal's field, and the line under it that says what the value
|
||||
// means or, in red, why it is refused, kept current as it is typed. The
|
||||
// sheets that set a few values at once use it (a home service, a circle, a new
|
||||
// server).
|
||||
|
||||
import { h } from '../../portal/dom';
|
||||
import { shake } from '../../shared/shake';
|
||||
import type { Help } from '../netcheck';
|
||||
|
||||
export interface Field {
|
||||
el: HTMLElement;
|
||||
input: HTMLInputElement;
|
||||
value(): string;
|
||||
/** Check it now: its line says why when it is refused (the field shakes); true when it is fine. */
|
||||
check(): boolean;
|
||||
/** Say the line again (an answer came in that changes it). */
|
||||
refresh(): void;
|
||||
}
|
||||
|
||||
export function field(
|
||||
label: string,
|
||||
value: string,
|
||||
help: (v: string) => Help,
|
||||
o: { placeholder?: string; mono?: boolean; numeric?: boolean; plain?: boolean } = {},
|
||||
): Field {
|
||||
const input = h('input', {
|
||||
type: 'text',
|
||||
value,
|
||||
placeholder: o.placeholder ?? '',
|
||||
'aria-label': label,
|
||||
autocomplete: 'off',
|
||||
autocapitalize: o.plain ? 'none' : null,
|
||||
autocorrect: o.plain ? 'off' : null,
|
||||
spellcheck: 'false',
|
||||
inputmode: o.numeric ? 'numeric' : null,
|
||||
'data-1p-ignore': true,
|
||||
class: o.mono ? 'mono' : null,
|
||||
}) as HTMLInputElement;
|
||||
const box = h('label', { class: 'field fl-f' }, input);
|
||||
const line = h('p', { class: 'hint fl-h' });
|
||||
const say = () => {
|
||||
const r = help(input.value);
|
||||
line.textContent = r.text;
|
||||
line.classList.toggle('bad-t', r.bad);
|
||||
line.hidden = !r.text;
|
||||
return r;
|
||||
};
|
||||
input.addEventListener('input', say);
|
||||
say();
|
||||
return {
|
||||
el: h('div', { class: 'choice fl' }, h('div', { class: 'choice-h' }, h('span', {}, label)), box, line),
|
||||
input,
|
||||
value: () => input.value.trim(),
|
||||
check() {
|
||||
if (!say().bad) return true;
|
||||
shake(box);
|
||||
input.focus();
|
||||
return false;
|
||||
},
|
||||
refresh: () => void say(),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
// Running a Health check's fix where it stands: in the Settings section the
|
||||
// check is about (pages/settings/health.ts), or in Overview's list for a
|
||||
// check no section is about (pages/overview/health.ts). A fix on the router
|
||||
// (health_fix) answers with the checks as they stand after it; a network
|
||||
// restart asks first (every interface restarts) and the checks are run again
|
||||
// once the network is back; an `install:` fix opens the install sheet
|
||||
// (flows/install.ts) with what the feature still needs; «Open Updates» leads
|
||||
// to that section of Settings. An error is said in a toast and nothing
|
||||
// changes.
|
||||
|
||||
import { api, type Health, type Needs } from '../api';
|
||||
import { closeSheet, openSheet } from '../../portal/ui/sheet';
|
||||
import { settingsUrl } from '../shell/routes';
|
||||
import { say } from '../shell/toast';
|
||||
import { visit } from '../shell/visit';
|
||||
import { errorText, notify } from '../ui/toast';
|
||||
import { askView } from './ask';
|
||||
import { installSheet } from './install';
|
||||
|
||||
/** The network restarts a second after the router's answer: the checks are looked at again once it is back (ms). */
|
||||
const NET_BACK = 5000;
|
||||
|
||||
export interface FixPage {
|
||||
/** The checks as the fix left them. */
|
||||
took(r: Health): void;
|
||||
/** Run the checks again and read the router (after an install, after the network is back). */
|
||||
again(): void;
|
||||
}
|
||||
|
||||
/** On the router: the answer is the checks after it. */
|
||||
async function onRouter(fix: string, page: FixPage) {
|
||||
page.took(await api.healthFix(fix));
|
||||
say(_('Done'));
|
||||
if (fix === 'netrestart') setTimeout(page.again, NET_BACK);
|
||||
}
|
||||
|
||||
export async function runFix(fix: string, page: FixPage): Promise<void> {
|
||||
if (fix === 'updates') return visit(settingsUrl('updates'));
|
||||
if (fix.startsWith('install:')) {
|
||||
const feature = fix.slice(8) as keyof Needs;
|
||||
// AmneziaWG's packages are picked by the updater itself; the others' are listed by it
|
||||
const needs = feature === 'awg' ? [] : ((await api.updatesStatus().catch(() => null))?.needs?.[feature] ?? []);
|
||||
return installSheet(feature, needs, page.again);
|
||||
}
|
||||
if (fix !== 'netrestart') return onRouter(fix, page).catch((e) => void notify(errorText(e), 'error', 10000));
|
||||
openSheet(() =>
|
||||
askView({
|
||||
icon: 'refresh',
|
||||
tone: 'orange',
|
||||
title: _('Restart the network?'),
|
||||
text: [_('Every interface restarts. Connections drop for a few seconds.')],
|
||||
action: _('Restart network'),
|
||||
cls: 'warn',
|
||||
run: async () => {
|
||||
await onRouter(fix, page);
|
||||
closeSheet();
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
// Home services in the portal's sheet (from the old Access page, restyled):
|
||||
// one service's name, address and ports, saved or removed (asked first: the
|
||||
// people limited to it lose it); and the devices at home to add them from
|
||||
// (home_hosts: DHCP leases and static hosts, with what they announce over
|
||||
// Bonjour), each device's port groups as chips that add, change or remove its
|
||||
// service at once. Services are shared by all servers.
|
||||
|
||||
import type { Status } from '../../shared/types';
|
||||
import { api, type HomeHost } from '../api';
|
||||
import { h } from '../../portal/dom';
|
||||
import { closeSheet, go, head, hint, openSheet, type View } from '../../portal/ui/sheet';
|
||||
import { once } from '../../portal/ui/feedback';
|
||||
import { fmt } from '../../shared/i18n';
|
||||
import { ipv4Help, nameHelp, portsHelp } from '../netcheck';
|
||||
import { errorText, notify } from '../ui/toast';
|
||||
import { say } from '../shell/toast';
|
||||
import { askView } from './ask';
|
||||
import { field } from './form';
|
||||
import { putChildren } from '../../portal/ui/put';
|
||||
|
||||
type Service = Status['services'][number];
|
||||
|
||||
export interface ServiceCtx {
|
||||
/** The services as the page has them now. */
|
||||
services(): Service[];
|
||||
/** After a change: the page reads the router again. */
|
||||
changed(): Promise<void>;
|
||||
}
|
||||
|
||||
function serviceView(c: ServiceCtx, sv: Service | null): View {
|
||||
const name = field(_('Name', 'circle or service'), sv?.name ?? '', (v) => nameHelp(v, [], _('Shown to people who may reach it.')), {
|
||||
placeholder: _('NAS'),
|
||||
});
|
||||
const addr = field(_('Address'), sv?.address ?? '', (v) => ipv4Help(v), { placeholder: '192.168.1.10', mono: true, plain: true });
|
||||
const ports = field(_('Ports'), (sv?.ports ?? []).join(', '), (v) => portsHelp(v), {
|
||||
placeholder: _('All ports, or e.g. 445, 5000'),
|
||||
mono: true,
|
||||
plain: true,
|
||||
});
|
||||
const save = h('button', { type: 'button', class: 'btn accent block' }, h('span', {}, _('Save'))) as HTMLButtonElement;
|
||||
save.addEventListener('click', () =>
|
||||
once(save, async () => {
|
||||
if (![name, addr, ports].every((f) => f.check())) return;
|
||||
try {
|
||||
await api.serviceSet(sv?.id ?? '', name.value(), addr.value(), ports.value().split(/[ ,]+/).filter(Boolean));
|
||||
closeSheet();
|
||||
say(sv ? fmt(_('%s updated'), name.value()) : fmt(_('%s added'), name.value()));
|
||||
await c.changed();
|
||||
} catch (e) {
|
||||
notify(errorText(e), 'error', 10000);
|
||||
}
|
||||
}),
|
||||
);
|
||||
const del = sv
|
||||
? h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
class: 'btn soft block bad-t',
|
||||
onclick: () =>
|
||||
go(() =>
|
||||
askView({
|
||||
icon: 'trash',
|
||||
tone: 'red',
|
||||
title: fmt(_('Remove %s?'), sv.name),
|
||||
text: [_('People limited to this service lose access to it.')],
|
||||
action: _('Remove'),
|
||||
cls: 'red',
|
||||
run: async () => {
|
||||
await api.serviceDelete(sv.id);
|
||||
closeSheet();
|
||||
say(fmt(_('%s removed'), sv.name));
|
||||
await c.changed();
|
||||
},
|
||||
}),
|
||||
),
|
||||
},
|
||||
h('span', {}, _('Remove')),
|
||||
)
|
||||
: null;
|
||||
const title = sv ? fmt(_('Edit %s'), sv.name) : _('Add service');
|
||||
requestAnimationFrame(() => name.input.focus({ preventScroll: true }));
|
||||
const el = h(
|
||||
'div',
|
||||
{ class: 'view' },
|
||||
head(title),
|
||||
name.el,
|
||||
addr.el,
|
||||
ports.el,
|
||||
h('div', { class: 'fl-acts' }, save, del),
|
||||
hint(_('Home-only people can be limited to these instead of whole networks (chosen on their page). Shared by all servers.')),
|
||||
);
|
||||
return { el, label: title };
|
||||
}
|
||||
|
||||
/** A service: a new one (null), or one to change. */
|
||||
export const openService = (c: ServiceCtx, sv: Service | null) => openSheet(() => serviceView(c, sv));
|
||||
|
||||
/** The port group a Bonjour service type belongs to, by its name. */
|
||||
function mdnsLabels(): Record<string, string> {
|
||||
const web = _('Web');
|
||||
const printer = _('Printer');
|
||||
return {
|
||||
_smb: 'SMB',
|
||||
_afpovertcp: 'AFP',
|
||||
_http: web,
|
||||
_https: web,
|
||||
_ssh: 'SSH',
|
||||
_sftp: 'SFTP',
|
||||
'_sftp-ssh': 'SFTP',
|
||||
_ipp: printer,
|
||||
_ipps: printer,
|
||||
_printer: printer,
|
||||
'_pdl-datastream': printer,
|
||||
_airplay: 'AirPlay',
|
||||
_raop: 'AirPlay',
|
||||
_rfb: _('Screen sharing'),
|
||||
_googlecast: 'Cast',
|
||||
_hap: 'HomeKit',
|
||||
_rdp: _('Remote desktop'),
|
||||
_ftp: 'FTP',
|
||||
};
|
||||
}
|
||||
|
||||
/** Port groups a device at home offers: what it announces over Bonjour, or the usual ones. */
|
||||
function portGroups(x: HomeHost): [string, string[]][] {
|
||||
const labels = mdnsLabels();
|
||||
const by = new Map<string, Set<string>>();
|
||||
for (const s of x.services) {
|
||||
const label = labels[s.type.split('.')[0]];
|
||||
if (!label || !s.port) continue;
|
||||
(by.get(label) ?? by.set(label, new Set()).get(label)!).add(String(s.port));
|
||||
}
|
||||
return by.size
|
||||
? [...by].map(([l, p]) => [l, [...p].sort((a, b) => +a - +b)])
|
||||
: [
|
||||
[_('Web'), ['80', '443']],
|
||||
['SMB', ['445']],
|
||||
['SSH', ['22']],
|
||||
];
|
||||
}
|
||||
|
||||
function hostsView(c: ServiceCtx, srv: string): View {
|
||||
const list = h('div', { class: 'hosts' }, h('p', { class: 'hint' }, _('Looking for devices at home…')));
|
||||
const note = hint('');
|
||||
const busy = new Set<string>();
|
||||
let hosts: HomeHost[] = [];
|
||||
|
||||
/** Ports chosen for a device: add, change or remove its service at once. */
|
||||
const choose = async (x: HomeHost, ports: string[] | null) => {
|
||||
if (busy.has(x.address)) return;
|
||||
busy.add(x.address);
|
||||
paint();
|
||||
try {
|
||||
const sv = c.services().find((s) => s.address === x.address);
|
||||
if (ports === null) {
|
||||
if (sv) {
|
||||
await api.serviceDelete(sv.id);
|
||||
say(fmt(_('%s removed'), sv.name));
|
||||
}
|
||||
} else {
|
||||
await api.serviceSet(sv?.id ?? '', sv?.name ?? (x.name || x.address), x.address, ports);
|
||||
say(sv ? fmt(_('%s updated'), sv.name) : fmt(_('%s added'), x.name || x.address));
|
||||
}
|
||||
await c.changed();
|
||||
} catch (e) {
|
||||
notify(errorText(e), 'error', 10000);
|
||||
} finally {
|
||||
busy.delete(x.address);
|
||||
paint();
|
||||
}
|
||||
};
|
||||
const row = (x: HomeHost) => {
|
||||
const sv = c.services().find((s) => s.address === x.address);
|
||||
const all = !!sv && !sv.ports.length;
|
||||
const chosen = new Set(sv?.ports ?? []);
|
||||
const wait = busy.has(x.address);
|
||||
const chip = (label: string, on: boolean, run: () => void) =>
|
||||
h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
class: `chipb${on ? ' on' : ''}${wait ? ' busy' : ''}`,
|
||||
'aria-pressed': String(on),
|
||||
disabled: wait,
|
||||
onclick: run,
|
||||
},
|
||||
label,
|
||||
);
|
||||
return h(
|
||||
'div',
|
||||
{ class: 'host' },
|
||||
h('div', { class: 'host-t' }, h('b', {}, x.name || x.address), h('span', { class: 'mono' }, x.address)),
|
||||
h(
|
||||
'div',
|
||||
{ class: 'chips' },
|
||||
chip(_('All ports'), all, () => void choose(x, all ? null : [])),
|
||||
...portGroups(x).map(([label, ports]) => {
|
||||
const on = !all && ports.every((p) => chosen.has(p));
|
||||
return chip(`${label} ${ports.join(', ')}`, on, () => {
|
||||
const next = new Set(all ? [] : chosen);
|
||||
for (const p of ports) {
|
||||
if (on) next.delete(p);
|
||||
else next.add(p);
|
||||
}
|
||||
void choose(x, next.size ? [...next] : null);
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
};
|
||||
const paint = () =>
|
||||
putChildren(list, hosts.length ? hosts.map(row) : [h('p', { class: 'hint' }, _('No devices found in the home network right now.'))]);
|
||||
void api
|
||||
.homeHosts(srv)
|
||||
.then((r) => {
|
||||
hosts = r.hosts;
|
||||
note.textContent = r.mdns
|
||||
? _('Ports they announce over Bonjour. Pick what to open, or all ports.')
|
||||
: _('Devices that got an address from this router. Pick the ports to open, or all ports.');
|
||||
paint();
|
||||
})
|
||||
.catch(() => putChildren(list, [h('p', { class: 'hint bad-t' }, _("Couldn't read the devices at home."))]));
|
||||
const el = h('div', { class: 'view' }, head(_('Add from devices at home')), note, list);
|
||||
return { el, label: _('Add from devices at home') };
|
||||
}
|
||||
|
||||
/** The devices at home, each a way to a service of its ports (home_hosts reads this server's home networks). */
|
||||
export const findAtHome = (c: ServiceCtx, srv: string) => openSheet(() => hostsView(c, srv));
|
||||
@@ -0,0 +1,23 @@
|
||||
// Installing what a feature is missing (AmneziaWG for a new server, the
|
||||
// home-like link's packages, HTTPS or ACME for the portal): the question in
|
||||
// the portal's sheet, then the updater's job in the same sheet
|
||||
// (flows/operation.ts). The words are updater/install.ts's.
|
||||
|
||||
import type { Needs } from '../api';
|
||||
import { runOperation } from './operation';
|
||||
import { installOf } from '../updater/install';
|
||||
|
||||
/** What is installed, as the question's glass: the feature's own picture (flows/packages.ts), AmneziaWG's mark. */
|
||||
const ICON: Record<keyof Needs, string> = { https: 'lock', acme: 'cert', home: 'home', awg: 'amneziawg' };
|
||||
|
||||
/** Ask, then install `names` for `feature` in the sheet; `done` once it finished and the service had a moment. */
|
||||
export function installSheet(feature: keyof Needs, names: string[], done?: () => void) {
|
||||
const it = installOf(feature, names);
|
||||
runOperation({
|
||||
what: it.what,
|
||||
title: it.title,
|
||||
ask: { icon: ICON[feature], tone: 'blue', title: it.ask, text: [it.body], action: _('Install'), cls: 'accent' },
|
||||
// the service restarts to pick them up: a moment before the page reads again
|
||||
done: () => setTimeout(() => done?.(), 4000),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
// The invite card as a picture: the person's QR code, link and greeting,
|
||||
// drawn in the browser into a PNG to share (Telegram, AirDrop) or print. The
|
||||
// sheet that offers it is flows/invite.ts.
|
||||
|
||||
import type { Person } from '../../shared/types';
|
||||
import { loadQr } from '../shell/qr';
|
||||
import { fmt } from '../../shared/i18n';
|
||||
|
||||
const W = 1080,
|
||||
H = 1512;
|
||||
/** One margin for everything: header, greeting and the QR tile share both edges. */
|
||||
const M = 96;
|
||||
const SANS = "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif";
|
||||
const MONO = 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace';
|
||||
|
||||
const esc = (s: string) => s.replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]!);
|
||||
|
||||
function cardSvg(p: Pick<Person, 'name'>, server: string, link: string, qrSvg: (text: string, margin: number) => string): string {
|
||||
const url = new URL(link);
|
||||
const word = url.pathname.slice(1);
|
||||
const hi = fmt(_('Hi, %s'), p.name);
|
||||
// Long names shrink to stay on one line (roughly 0.58 em per character).
|
||||
const nameSize = Math.min(92, Math.floor((W - 2 * M) / (0.58 * hi.length)));
|
||||
const tile = W - 2 * M,
|
||||
top = 392,
|
||||
pad = 40;
|
||||
const qr = qrSvg(link, 2).replace('<svg ', `<svg x="${M + pad}" y="${top + pad}" width="${tile - 2 * pad}" height="${tile - 2 * pad}" `);
|
||||
const text = (x: number, y: number, size: number, fill: string, body: string, extra = '') =>
|
||||
`<text x="${x}" y="${y}" font-size="${size}" fill="${fill}" font-family="${SANS}" ${extra}>${body}</text>`;
|
||||
return (
|
||||
`<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}">` +
|
||||
`<rect width="${W}" height="${H}" rx="72" fill="#0b0b0b"/>` +
|
||||
// Mark and server name
|
||||
`<g transform="translate(${M} ${M})"><rect width="60" height="60" rx="15" fill="#fff"/>` +
|
||||
`<g transform="scale(.9375)"><path d="M14 38a18 18 0 0 1 36 0z" fill="#0b0b0b"/><rect x="12" y="43" width="40" height="4" rx="2" fill="#0b0b0b" opacity=".5"/></g></g>` +
|
||||
text(M + 82, M + 42, 36, '#a3a3a3', esc(server)) +
|
||||
// Greeting
|
||||
text(M, 276, nameSize, '#ffffff', esc(hi), 'font-weight="600"') +
|
||||
text(M, 340, 40, '#8a8a8a', esc(fmt(_('Scan to connect to %s'), server))) +
|
||||
// Big QR on a white tile, edge to edge with the text above
|
||||
`<rect x="${M}" y="${top}" width="${tile}" height="${tile}" rx="52" fill="#ffffff"/>` +
|
||||
qr +
|
||||
// The link: three words, then the host
|
||||
`<text x="${W / 2}" y="${top + tile + 100}" font-size="58" fill="#ffffff" font-family="${MONO}" text-anchor="middle">${esc(word)}</text>` +
|
||||
text(W / 2, top + tile + 156, 34, '#737373', esc(url.host), 'text-anchor="middle"') +
|
||||
`</svg>`
|
||||
);
|
||||
}
|
||||
|
||||
/** The card for `p` on `server` with its `link`, as a PNG file. */
|
||||
export async function inviteCardFile(p: Pick<Person, 'id' | 'name'>, server: string, link: string): Promise<File> {
|
||||
const img = new Image();
|
||||
img.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(cardSvg(p, server, link, (await loadQr()).qrSvg))}`;
|
||||
await img.decode();
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = W;
|
||||
canvas.height = H;
|
||||
canvas.getContext('2d')!.drawImage(img, 0, 0, W, H);
|
||||
const png = await new Promise<Blob>((resolve, reject) =>
|
||||
canvas.toBlob((b) => (b ? resolve(b) : reject(new Error(_('Could not draw the card')))), 'image/png'),
|
||||
);
|
||||
return new File([png], `${p.id}-invite.png`, { type: 'image/png' });
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
// A person's invite in the portal's sheet (the concept's inviteView, on the
|
||||
// old admin's invite card): their personal link as a big QR code with its
|
||||
// three words and the server's name, Copy link, Share (the card as a file, or
|
||||
// the link, as the browser can) and Card (the picture saved), the link's other
|
||||
// addresses folded under one row (an HTTP one marked), and the three steps
|
||||
// the person takes. Its ⋯ makes a new link: the old one stops at once, and
|
||||
// the devices added through it may go with it (ticked; asked in the same
|
||||
// sheet). Also the step after adding someone: the same view, "is ready".
|
||||
// The link is never in the status: it is asked for (person_links, write only).
|
||||
|
||||
import type { Person } from '../../shared/types';
|
||||
import { api } from '../api';
|
||||
import { h } from '../../portal/dom';
|
||||
import { go, head, openSheet, sub, type View } from '../../portal/ui/sheet';
|
||||
import { openMenu } from '../../portal/ui/menu';
|
||||
import { once } from '../../portal/ui/feedback';
|
||||
import { fmt, plural } from '../../shared/i18n';
|
||||
import { ic } from '../ui/icons';
|
||||
import { knob } from '../ui/page-head';
|
||||
import { copyText, downloadFile } from '../ui/files';
|
||||
import { attempt, errorText, notify } from '../ui/toast';
|
||||
import { qrBox } from '../shell/qr';
|
||||
import { choiceRow } from '../ui/choice-row';
|
||||
import { askView } from './ask';
|
||||
import { inviteCardFile } from './invite-card';
|
||||
|
||||
export interface InviteCtx {
|
||||
person: Pick<Person, 'id' | 'name' | 'devices' | 'code_set'>;
|
||||
/** The server's name (on the card). */
|
||||
server: string;
|
||||
/** Its title and line when it is the step after adding them. */
|
||||
ready?: boolean;
|
||||
/** Devices were removed with an old link: the page reads the router again. */
|
||||
changed?: () => void;
|
||||
}
|
||||
|
||||
interface Links {
|
||||
link: string;
|
||||
links: string[];
|
||||
}
|
||||
|
||||
/** The personal link and its other addresses; null (said in a toast) while the portal is off. */
|
||||
async function linksOf(id: string): Promise<Links | null> {
|
||||
const r = await attempt(() => api.personLinks(id));
|
||||
if (!r) return null;
|
||||
if (!r.link) {
|
||||
notify(_('The personal portal is off. Turn it on in Settings.'), 'warning');
|
||||
return null;
|
||||
}
|
||||
return { link: r.link, links: r.links ?? [] };
|
||||
}
|
||||
|
||||
const bare = (l: string) => l.replace(/^https?:\/\//, '');
|
||||
|
||||
/** Share what the browser can: the card as a file, else the link; null where it can share neither. */
|
||||
function shareOf(c: InviteCtx, file: () => Promise<File>, link: string): (() => Promise<void>) | null {
|
||||
const nav = navigator as Navigator & { canShare?: (d: unknown) => boolean };
|
||||
if (typeof nav.share !== 'function') return null;
|
||||
const title = fmt(_('Invite %s'), c.person.name);
|
||||
return async () => {
|
||||
try {
|
||||
const f = await file();
|
||||
if (nav.canShare?.({ files: [f] })) await nav.share({ files: [f], title });
|
||||
else await nav.share({ url: link, title, text: _('Your personal VPN link') });
|
||||
} catch (e) {
|
||||
// Closing the share sheet is no error.
|
||||
if ((e as Error)?.name !== 'AbortError') notify(errorText(e), 'error');
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function inviteView(c: InviteCtx, l: Links): View {
|
||||
const p = c.person;
|
||||
const word = new URL(l.link).pathname.slice(1);
|
||||
let card: Promise<File> | null = null;
|
||||
const file = () => (card ??= inviteCardFile(p, c.server, l.link));
|
||||
const share = shareOf(c, file, l.link);
|
||||
const others = l.links.filter((x) => x !== l.link);
|
||||
const http = others.filter((x) => x.startsWith('http:')).length;
|
||||
const more = knob('more', _('New link'));
|
||||
more.addEventListener('click', () =>
|
||||
openMenu(more, [{ label: _('New link'), icon: 'link', tone: 'warn', run: () => go(() => newLinkView(c)) }], p.name),
|
||||
);
|
||||
const el = h(
|
||||
'div',
|
||||
{ class: 'view inv-v' },
|
||||
head(c.ready ? fmt(_('%s is ready'), p.name) : fmt(_('Invite · %s'), p.name), { acts: true }),
|
||||
sub(fmt(_('With this link %s adds their devices and takes their set-up. No account needed.'), p.name)),
|
||||
h(
|
||||
'div',
|
||||
{ class: 'inv-card' },
|
||||
qrBox(l.link),
|
||||
h('div', { class: 'inv-code' }, h('b', { class: 'mono' }, word), h('span', {}, c.server)),
|
||||
),
|
||||
h(
|
||||
'button',
|
||||
{ type: 'button', class: 'btn accent block', onclick: () => void copyText(l.link, _('Personal link copied')) },
|
||||
ic('copy'),
|
||||
h('span', {}, _('Copy link')),
|
||||
),
|
||||
h(
|
||||
'div',
|
||||
{ class: 'btnrow' },
|
||||
share
|
||||
? h(
|
||||
'button',
|
||||
{ type: 'button', class: 'btn soft', onclick: (e: Event) => void once(e.currentTarget as HTMLButtonElement, share) },
|
||||
ic('share'),
|
||||
h('span', {}, _('Share')),
|
||||
)
|
||||
: null,
|
||||
h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
class: 'btn soft',
|
||||
onclick: (e: Event) =>
|
||||
void once(e.currentTarget as HTMLButtonElement, async () => {
|
||||
try {
|
||||
const f = await file();
|
||||
downloadFile(f.name, f);
|
||||
} catch (err) {
|
||||
notify(errorText(err), 'error');
|
||||
}
|
||||
}),
|
||||
},
|
||||
ic('download'),
|
||||
h('span', {}, _('Card')),
|
||||
),
|
||||
),
|
||||
others.length
|
||||
? h(
|
||||
'div',
|
||||
{ class: 'inv-more' },
|
||||
choiceRow({
|
||||
title: _('Other addresses'),
|
||||
value: http
|
||||
? fmt(_('%s, %s over HTTP'), String(others.length), String(http))
|
||||
: plural(others.length, '%s address', '%s addresses'),
|
||||
options: others.map((x) => ({ id: x, label: bare(x), title: x.startsWith('http:') ? _('HTTP: not encrypted') : x })),
|
||||
on: [],
|
||||
multi: true,
|
||||
// A chip copies its address (nothing is picked).
|
||||
pick: async (on) => {
|
||||
const x = on[0];
|
||||
if (x) await copyText(x, _('Link copied'));
|
||||
return null;
|
||||
},
|
||||
}),
|
||||
)
|
||||
: null,
|
||||
);
|
||||
return { el, label: fmt(_('Invite %s'), p.name), acts: more };
|
||||
}
|
||||
|
||||
/**
|
||||
* A new link: the old one stops working at once (the portal checks the code on every request). Devices added
|
||||
* through it keep their tunnel unless removed with it: those added on the portal since it was made are offered,
|
||||
* ticked, so a leaked link is really contained.
|
||||
*/
|
||||
function newLinkView(c: InviteCtx): View {
|
||||
const p = c.person;
|
||||
const since = p.code_set ?? 0;
|
||||
const suspect = p.devices.filter((d) => d.created_by === 'portal' && d.created >= since);
|
||||
let remove = suspect.map((d) => d.id);
|
||||
const pickRow = suspect.length
|
||||
? choiceRow({
|
||||
title: _('Remove with it'),
|
||||
value: plural(remove.length, '%s device', '%s devices'),
|
||||
options: suspect.map((d) => ({ id: d.id, label: d.name })),
|
||||
on: remove,
|
||||
multi: true,
|
||||
open: true,
|
||||
note: _('Added on the portal through the old link: they keep working until they are removed.'),
|
||||
pick: async (on) => {
|
||||
remove = on;
|
||||
return plural(on.length, '%s device', '%s devices');
|
||||
},
|
||||
})
|
||||
: null;
|
||||
const v = askView({
|
||||
icon: 'link',
|
||||
tone: 'orange',
|
||||
title: fmt(_('A new link for %s?'), p.name),
|
||||
text: [_('The old link stops working right away. Send them the new one.')],
|
||||
action: _('Make a new link'),
|
||||
cls: 'warn',
|
||||
run: async () => {
|
||||
const r = await api.personRegen(p.id, remove);
|
||||
if (r.removed) c.changed?.();
|
||||
notify(
|
||||
r.removed ? plural(r.removed, 'New link made, %s device removed', 'New link made, %s devices removed') : _('New link made'),
|
||||
'success',
|
||||
3000,
|
||||
);
|
||||
const link = r.link;
|
||||
if (!link) return;
|
||||
const links = await api.personLinks(p.id).then(
|
||||
(x) => x.links,
|
||||
() => [link],
|
||||
);
|
||||
const kept = { ...c, person: { ...p, devices: p.devices.filter((d) => !remove.includes(d.id)), code_set: Date.now() / 1000 } };
|
||||
go(() => inviteView(kept, { link, links: links.length ? links : [link] }));
|
||||
},
|
||||
});
|
||||
if (pickRow) v.el.querySelector('.ask > p')?.after(pickRow);
|
||||
return v;
|
||||
}
|
||||
|
||||
/** The invite in the sheet (its link asked for first). */
|
||||
export async function openInvite(c: InviteCtx) {
|
||||
const l = await linksOf(c.person.id);
|
||||
if (l) openSheet(() => inviteView(c, l));
|
||||
}
|
||||
|
||||
/** The invite as the next view of a sheet already open (after adding someone), with the link the router gave. */
|
||||
export async function inviteNext(c: InviteCtx, link: string) {
|
||||
const r = await api.personLinks(c.person.id).catch(() => null);
|
||||
go(() => inviteView(c, { link, links: r?.links?.length ? r.links : [link] }));
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
// A job in the portal's sheet as one view from its start to its end (DESIGN.md
|
||||
// › Admin kit › «A job's stage»): the question's own anatomy held through,
|
||||
// so nothing is laid over anything. On top the picture of what the job is
|
||||
// about (a component's mark) in the tone of where it stands, its title and
|
||||
// one line; under them the steps it went through, the one under way last
|
||||
// with its time; its log folded in the portal's inset row; the actions at
|
||||
// the foot, once there is something to decide. The end changes the same
|
||||
// parts in place: the picture's tone, the words, and what stands under them
|
||||
// (the steps stay where a job failed, give way to what a check found, or go).
|
||||
// Nothing is slid to a new place: each part goes to its new height where it
|
||||
// stands (portal/ui/grown.ts) and what is under it travels with its edge, so
|
||||
// the log's row never crosses a button that has just come.
|
||||
// This module only draws: who runs the job and what its words are is the
|
||||
// flow's (flows/operation.ts, flows/restore.ts).
|
||||
|
||||
import { h } from '../../portal/dom';
|
||||
import { accordion } from '../../portal/ui/accordion';
|
||||
import { EASE_OUT, POP, calm, play } from '../../portal/motion';
|
||||
import { grown } from '../../portal/ui/grown';
|
||||
import { putChildren } from '../../portal/ui/put';
|
||||
import type { View } from '../../portal/ui/sheet';
|
||||
import { tip } from '../../portal/ui/tip';
|
||||
import { copyText } from '../ui/files';
|
||||
import { glass } from '../ui/glass';
|
||||
import { ic } from '../ui/icons';
|
||||
|
||||
type StageTone = 'blue' | 'green' | 'orange' | 'red';
|
||||
|
||||
/** A step of the job: done, under way, where it failed, or not reached yet (a job whose steps are known ahead). */
|
||||
export interface StageStep {
|
||||
title: string;
|
||||
state: 'ok' | 'run' | 'bad' | 'wait';
|
||||
}
|
||||
|
||||
interface StageEnd {
|
||||
tone: StageTone;
|
||||
title: string;
|
||||
/** One line under the title (why it failed, what happens next); none when the title says it all. */
|
||||
text?: string;
|
||||
/** What stands in the steps' place (what a check found); the steps stay with `keep`, else they go. */
|
||||
body?: HTMLElement | null;
|
||||
keep?: boolean;
|
||||
/** None while the stage only waits (a page that reads itself again). */
|
||||
acts?: HTMLElement[];
|
||||
}
|
||||
|
||||
export interface Stage {
|
||||
view: View;
|
||||
/** The steps so far, the last one under way (or where it failed). */
|
||||
steps(list: StageStep[]): void;
|
||||
/** The time the job has taken, at the end of its last step. */
|
||||
time(text: string): void;
|
||||
log(lines: string[]): void;
|
||||
/** The line under the title says something else (a wait after the end). */
|
||||
say(text: string): void;
|
||||
/** The actions at the foot change (a wait that ran out offers the way on). */
|
||||
acts(list: HTMLElement[]): void;
|
||||
end(o: StageEnd): void;
|
||||
}
|
||||
|
||||
const MARK = { ok: 'check', bad: 'x' } as const;
|
||||
|
||||
/** What changed comes into focus, as the sheet's own glide brings a changed block in. */
|
||||
const focus = (...els: Element[]) =>
|
||||
els.forEach((el) =>
|
||||
play(
|
||||
el,
|
||||
[
|
||||
{ opacity: 0, filter: 'blur(4px)' },
|
||||
{ opacity: 1, filter: 'none' },
|
||||
],
|
||||
{ duration: 280, easing: EASE_OUT },
|
||||
),
|
||||
);
|
||||
|
||||
/** `steps`: the job's steps when they are known ahead (else it starts at «Starting…»); `log: false`: it keeps none. */
|
||||
export function stage(o: { icon: string; title: string; lead: string; steps?: StageStep[]; log?: boolean }): Stage {
|
||||
const pic = h('span', { class: 'jb-pic' }, glass(o.icon, 'blue', 'gi xl'));
|
||||
const title = h('h3', {}, o.title);
|
||||
const lead = h('p', {}, o.lead);
|
||||
const clock = h('span', { class: 'jb-time num' }, '0:00');
|
||||
const list = h('ol', { class: 'jb-steps' });
|
||||
const body = h('div', { class: 'jb-body', hidden: true });
|
||||
const row = h('div', { class: 'btnrow' });
|
||||
|
||||
let lines: string[] = [];
|
||||
const pre = h('pre', { class: 'jb-log' }, _('Waiting for log output…'));
|
||||
const copy = h('button', { type: 'button', class: 'hp-b', 'aria-label': _('Copy log') }, ic('copy'));
|
||||
copy.addEventListener('click', () => void copyText(lines.join('\n'), _('Log copied')));
|
||||
tip(copy, () => _('Copy log'));
|
||||
const log =
|
||||
o.log === false
|
||||
? null
|
||||
: accordion([{ icon: glass('log', 'grey'), title: _('Operation log'), aside: h('div', { class: 'hpill' }, copy), body: [pre] }], {
|
||||
inset: true,
|
||||
}).el;
|
||||
|
||||
let done = 0;
|
||||
const draw = (steps: StageStep[]) => {
|
||||
putChildren(
|
||||
list,
|
||||
steps.map((s, i) =>
|
||||
h(
|
||||
'li',
|
||||
{ class: `jb-s ${s.state}` },
|
||||
h('span', { class: 'jb-m' }, s.state === 'ok' || s.state === 'bad' ? ic(MARK[s.state]) : h('i')),
|
||||
h('span', { class: 'jb-t' }, s.title),
|
||||
i === steps.length - 1 ? clock : null,
|
||||
),
|
||||
),
|
||||
);
|
||||
// a check that has just come turns in as the portal's after a copy (POP from s.6, b3), one after another
|
||||
const ok = steps.filter((s) => s.state === 'ok').length;
|
||||
if (!calm())
|
||||
[...list.querySelectorAll('.jb-s.ok > .jb-m')].slice(done).forEach((m, i) =>
|
||||
play(
|
||||
m,
|
||||
[
|
||||
{ opacity: 0, transform: 'scale(.6)', filter: 'blur(3px)' },
|
||||
{ opacity: 1, transform: 'none', filter: 'blur(0px)' },
|
||||
],
|
||||
{ duration: POP.duration, delay: i * 60, easing: POP.easing, fill: 'backwards' },
|
||||
),
|
||||
);
|
||||
done = ok;
|
||||
};
|
||||
draw(o.steps ?? [{ title: _('Starting…'), state: 'run' }]);
|
||||
|
||||
// the top is the sheet's handle on a phone, as a view's head is (portal/ui/sheet.ts)
|
||||
const top = h('div', { class: 'ask vgrab' }, pic, title, lead);
|
||||
const mid = h('div', { class: 'jb-mid' }, list, body);
|
||||
const foot = h('div', { class: 'jb-foot' });
|
||||
const el = h('div', { class: `view jb${log ? '' : ' nolog'}` }, top, mid, log, foot);
|
||||
const parts = [top, mid, foot];
|
||||
/** A change of what the parts hold: each goes to its new height where it stands, what is under it with its edge. */
|
||||
const reshape = (change: () => void) => {
|
||||
const was = parts.map((x) => x.offsetHeight);
|
||||
change();
|
||||
parts.forEach((x, i) => grown(x, was[i]));
|
||||
};
|
||||
const setActs = (next: HTMLElement[]) => {
|
||||
putChildren(row, next);
|
||||
putChildren(foot, next.length ? [row] : []);
|
||||
};
|
||||
|
||||
return {
|
||||
view: { el, label: o.title },
|
||||
steps: (steps) => reshape(() => draw(steps)),
|
||||
time: (text) => {
|
||||
if (clock.textContent !== text) clock.textContent = text;
|
||||
},
|
||||
log(next) {
|
||||
if (!next.length || next.join('\n') === lines.join('\n')) return;
|
||||
lines = next;
|
||||
const atEnd = pre.scrollTop + pre.clientHeight >= pre.scrollHeight - 8;
|
||||
pre.textContent = lines.join('\n');
|
||||
if (atEnd) pre.scrollTop = pre.scrollHeight;
|
||||
},
|
||||
say(text) {
|
||||
reshape(() => {
|
||||
lead.textContent = text;
|
||||
lead.hidden = !text;
|
||||
});
|
||||
focus(lead);
|
||||
},
|
||||
acts(next) {
|
||||
reshape(() => setActs(next));
|
||||
focus(row);
|
||||
},
|
||||
end(e) {
|
||||
const g = glass(o.icon, e.tone, 'gi xl');
|
||||
reshape(() => {
|
||||
putChildren(pic, [g]);
|
||||
title.textContent = e.title;
|
||||
lead.textContent = e.text ?? '';
|
||||
lead.hidden = !e.text;
|
||||
list.hidden = !e.keep;
|
||||
if (e.body) putChildren(body, [e.body]);
|
||||
body.hidden = !e.body;
|
||||
setActs(e.acts ?? []);
|
||||
});
|
||||
focus(g, title, lead, body, row);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
// Moving a person to another server, or giving one without a server one
|
||||
// (the concept's vMove): the servers as option rows, then the question as the
|
||||
// next view of the same sheet: their devices that have connected stop until
|
||||
// they take their set-up again (the other server has its own address and
|
||||
// key), circles and home networks of the old server stay behind, a server
|
||||
// that is off is said too. A person without devices, or without a server
|
||||
// yet, moves at once.
|
||||
|
||||
import type { Person, Server, Status } from '../../shared/types';
|
||||
import { api } from '../api';
|
||||
import { h } from '../../portal/dom';
|
||||
import { closeSheet, go, head, openSheet, sub, type View } from '../../portal/ui/sheet';
|
||||
import { fmt, num } from '../../shared/i18n';
|
||||
import { glass } from '../ui/glass';
|
||||
import { ic } from '../ui/icons';
|
||||
import { errorText, notify } from '../ui/toast';
|
||||
import { say } from '../shell/toast';
|
||||
import { askView } from './ask';
|
||||
|
||||
export interface MoveCtx {
|
||||
person: Person;
|
||||
st: Status;
|
||||
/** Moved: the page reads the router again. */
|
||||
moved(): void;
|
||||
}
|
||||
|
||||
async function move(c: MoveCtx, s: Server) {
|
||||
await api.personUpdate(c.person.id, { server: s.id });
|
||||
closeSheet();
|
||||
say(fmt(_('%s: server %s'), c.person.name, s.name));
|
||||
c.moved();
|
||||
}
|
||||
|
||||
function vAsk(c: MoveCtx, s: Server): View {
|
||||
const n = c.person.devices.filter((d) => d.handshake && !d.disabled).length;
|
||||
return askView({
|
||||
icon: 'server',
|
||||
tone: 'orange',
|
||||
title: fmt(_('%s → %s?'), c.person.name, s.name),
|
||||
text: [
|
||||
fmt(
|
||||
N_(
|
||||
n,
|
||||
'%s device stops connecting until it takes its set-up again: %s has its own address and key.',
|
||||
'%s devices stop connecting until they take their set-up again: %s has its own address and key.',
|
||||
),
|
||||
num(n),
|
||||
s.name,
|
||||
),
|
||||
' ',
|
||||
_('Circles and home networks of the old server stay behind.'),
|
||||
s.enabled ? '' : ` ${fmt(_('%s is turned off: devices do not connect until it is on.'), s.name)}`,
|
||||
],
|
||||
action: _('Move'),
|
||||
cls: 'warn',
|
||||
run: () => move(c, s),
|
||||
});
|
||||
}
|
||||
|
||||
function vMove(c: MoveCtx): View {
|
||||
const p = c.person;
|
||||
const cur = c.st.servers.find((s) => s.id === p.server);
|
||||
const others = c.st.servers.filter((s) => s.id !== p.server);
|
||||
const pick = (s: Server) => {
|
||||
if (cur && p.devices.some((d) => d.handshake && !d.disabled)) return go(() => vAsk(c, s));
|
||||
move(c, s).catch((e) => notify(errorText(e), 'error', 10000));
|
||||
};
|
||||
const opts = h(
|
||||
'div',
|
||||
{ class: 'opts', role: 'list' },
|
||||
...others.map((s) =>
|
||||
h(
|
||||
'button',
|
||||
{ type: 'button', class: 'opt', role: 'listitem', onclick: () => pick(s) },
|
||||
glass('server', s.enabled ? 'blue' : 'grey'),
|
||||
h(
|
||||
'span',
|
||||
{ class: 'opt-t' },
|
||||
h('b', {}, s.name),
|
||||
h('span', { class: 'mono' }, `${s.endpoint || _('no address')}:${s.port}`),
|
||||
s.enabled ? null : h('span', { class: 'warn-t' }, _('Turned off')),
|
||||
),
|
||||
ic('chevron', 'i opt-chev'),
|
||||
),
|
||||
),
|
||||
);
|
||||
const title = cur ? fmt(_('Move · %s'), p.name) : fmt(_('Server · %s'), p.name);
|
||||
const el = h(
|
||||
'div',
|
||||
{ class: 'view' },
|
||||
head(title),
|
||||
sub(
|
||||
cur ? fmt(_('Now on %s. Access, end date and limits stay.'), cur.name) : _('No server yet: their devices have nowhere to connect.'),
|
||||
),
|
||||
opts,
|
||||
);
|
||||
return { el, label: title };
|
||||
}
|
||||
|
||||
export const movePerson = (c: MoveCtx) => openSheet(() => vMove(c));
|
||||
@@ -0,0 +1,74 @@
|
||||
// New keys for a device (the portal's Reconnect, the admin's way): what it is
|
||||
// and LAN Bypass asked again, then the set-up of the new keys with the wait
|
||||
// for its first connection (flows/setup.ts). Its configuration stops working
|
||||
// at once: the sheet says so before the button.
|
||||
|
||||
import type { Device, Person, Server } from '../../shared/types';
|
||||
import { api } from '../api';
|
||||
import { h } from '../../portal/dom';
|
||||
import { go, head, openSheet, sub, type View } from '../../portal/ui/sheet';
|
||||
import { once } from '../../portal/ui/feedback';
|
||||
import { kindOf, kindTiles } from '../../portal/flows/device-form';
|
||||
import { PICKS, pickOf, type KindPick } from '../../shared/format';
|
||||
import { fmt } from '../../shared/i18n';
|
||||
import { errorText, notify } from '../ui/toast';
|
||||
import { ic } from '../ui/icons';
|
||||
import { adminLan } from './device-form';
|
||||
import { setupView, type SetupCtx } from './setup';
|
||||
import { loadQr } from '../shell/qr';
|
||||
|
||||
export interface KeysCtx {
|
||||
person: Person;
|
||||
device: Device;
|
||||
server?: Server;
|
||||
now: () => number;
|
||||
/** Once the new keys are made (the page reads the status again). */
|
||||
made?: () => void;
|
||||
setup?: Pick<SetupCtx, 'fresh' | 'done'>;
|
||||
}
|
||||
|
||||
function vNewKeys(c: KeysCtx): View {
|
||||
const d = c.device;
|
||||
let pick: KindPick = pickOf(d.kind);
|
||||
let bypass = d.lan_bypass;
|
||||
const kinds = kindTiles(PICKS, (k) => (pick = k));
|
||||
kinds.set(pick);
|
||||
const lan = adminLan(c.person, c.server, bypass, (on) => (bypass = on));
|
||||
const run = async () => {
|
||||
try {
|
||||
const kind = kindOf(pick, d.kind);
|
||||
const kit = loadQr().catch(() => undefined);
|
||||
const cfg = await api.deviceRotate(d.id, kind, bypass);
|
||||
await kit;
|
||||
c.made?.();
|
||||
go(() =>
|
||||
setupView(
|
||||
{ person: c.person, device: { ...d, kind, lan_bypass: bypass, handshake: 0, online: false }, now: c.now, ...c.setup },
|
||||
cfg,
|
||||
'top',
|
||||
),
|
||||
);
|
||||
} catch (e) {
|
||||
notify(errorText(e), 'error', 10000);
|
||||
}
|
||||
};
|
||||
const goBtn = h(
|
||||
'button',
|
||||
{ type: 'button', class: 'btn warn block nk-go', onclick: (ev: Event) => once(ev.currentTarget as HTMLButtonElement, run) },
|
||||
ic('refresh'),
|
||||
h('span', {}, _('Issue new keys')),
|
||||
);
|
||||
const title = fmt(_('New keys · %s'), d.name);
|
||||
const el = h(
|
||||
'div',
|
||||
{ class: 'view' },
|
||||
head(title),
|
||||
sub(_('Its configuration stops working at once. Set the device up again: the new one opens next.')),
|
||||
kinds.el,
|
||||
lan,
|
||||
goBtn,
|
||||
);
|
||||
return { el, label: title };
|
||||
}
|
||||
|
||||
export const newKeys = (c: KeysCtx) => openSheet(() => vNewKeys(c));
|
||||
@@ -0,0 +1,350 @@
|
||||
// A new server in the portal's sheet, in steps (the old setup wizard,
|
||||
// restyled; every check and default kept): the server (its name, the address
|
||||
// devices connect to, checked on the router where it points as it is typed,
|
||||
// with where the suggestion came from; a router behind CGNAT or another router
|
||||
// says so first, and so does a network restart AmneziaWG needs), AmneziaWG
|
||||
// (the UDP port, the device addresses, the disguise as a track with the
|
||||
// picked level's meters), and for the first server the portal (internet like
|
||||
// a home device, the personal portal and its port). One more server leaves
|
||||
// the portal alone and asks about the internet on its AmneziaWG step. Without
|
||||
// AmneziaWG the sheet offers to install it first. The sheet opens on the
|
||||
// press (the router's defaults come in after), every step keeps the sheet's
|
||||
// one rhythm, and Create closes the sheet as every sheet closes, then the
|
||||
// page goes to the new server (after the network restart, when one is
|
||||
// needed).
|
||||
|
||||
import { api, type SetupDefaults } from '../api';
|
||||
import { h } from '../../portal/dom';
|
||||
import { closeSheet, glide, go, head, hint, onClosed, openSheet, showing, type View } from '../../portal/ui/sheet';
|
||||
import { once } from '../../portal/ui/feedback';
|
||||
import { fmt, locale } from '../../shared/i18n';
|
||||
import { endpointProbe, hostHelp, nameHelp, portalPortHelp, portHelp, rangeHelp, rangeOf, subnetOf } from '../netcheck';
|
||||
import { defaultMethod, type Method } from '../disguise';
|
||||
import { glass } from '../ui/glass';
|
||||
import { switchRow } from '../ui/edit-rows';
|
||||
import { errorText, notify } from '../ui/toast';
|
||||
import { say } from '../shell/toast';
|
||||
import { settingsUrl } from '../shell/routes';
|
||||
import { levelPick } from '../widgets/disguise-levels';
|
||||
import { installSheet } from './install';
|
||||
import { field } from './form';
|
||||
import { putChildren } from '../../portal/ui/put';
|
||||
|
||||
interface Draft {
|
||||
id: string;
|
||||
name: string;
|
||||
endpoint: string;
|
||||
port: number;
|
||||
range: string;
|
||||
preset: Method;
|
||||
portal: boolean;
|
||||
portal_port: number;
|
||||
lan_like: boolean;
|
||||
/** The portal's port follows the server's until it is changed by hand. */
|
||||
portalSame: boolean;
|
||||
}
|
||||
|
||||
/** A note in the sheet: the portal's notice, in its tone. */
|
||||
const note = (tone: 'warn' | 'bad', title: string, text: string, act?: HTMLElement | null) =>
|
||||
h(
|
||||
'div',
|
||||
{ class: `notice ${tone} ns-note` },
|
||||
glass('pulse', tone === 'bad' ? 'red' : 'orange'),
|
||||
h('span', { class: 't' }, h('b', {}, title), h('span', {}, text), act ?? null),
|
||||
);
|
||||
|
||||
function steps(n: number, at: number): HTMLElement {
|
||||
return h(
|
||||
'div',
|
||||
{ class: 'ns-steps', role: 'img', 'aria-label': fmt(_('Step %s of %s'), at + 1, n) },
|
||||
...Array.from({ length: n }, (_x, i) => h('i', { class: i < at ? 'done' : i === at ? 'on' : '' })),
|
||||
);
|
||||
}
|
||||
|
||||
/** A step's lead under its progress: one or two lines of what the step is for. */
|
||||
const lead = (text: string) => h('p', { class: 'ns-lead' }, text);
|
||||
|
||||
function vServer(d: SetupDefaults, s: Draft, extra: boolean, done: () => void): View {
|
||||
const FROM: Record<string, string> = {
|
||||
ddns: _('From your DDNS name.'),
|
||||
cert: _('From your Let’s Encrypt certificate.'),
|
||||
wan: _('Your WAN address now - it may change; a DDNS name is better.'),
|
||||
portal: _('The portal’s address.'),
|
||||
};
|
||||
const name = field(_('Name'), s.name, (v) => nameHelp(v, [], _('Shown to people in their portal and apps.')), { placeholder: _('Home') });
|
||||
// the address as typed, for the probe (the field asks for its line before it exists)
|
||||
let host = s.endpoint;
|
||||
const probe = endpointProbe(
|
||||
() => ({ host, port: s.port }),
|
||||
(x, _id, port) => api.endpointProbe(x, '', port),
|
||||
() => addr.refresh(),
|
||||
{ idle: () => (host.trim() === d.endpoint && d.endpoint_from ? (FROM[d.endpoint_from] ?? '') : '') },
|
||||
);
|
||||
const addr = field(
|
||||
_('Public address'),
|
||||
s.endpoint,
|
||||
(v) => {
|
||||
host = v;
|
||||
return probe.help();
|
||||
},
|
||||
{ placeholder: 'vpn.example.com', mono: true, plain: true },
|
||||
);
|
||||
addr.input.addEventListener('input', probe.schedule);
|
||||
probe.schedule();
|
||||
const aw = d.awg_state;
|
||||
const missing = aw?.missing ?? [];
|
||||
const awgNote = missing.length
|
||||
? note(
|
||||
'bad',
|
||||
_('AmneziaWG isn’t installed'),
|
||||
fmt(
|
||||
_('The tunnel needs %s. Install the build made for this firmware, then create the server.'),
|
||||
new Intl.ListFormat(locale(), { type: 'conjunction' }).format(missing),
|
||||
),
|
||||
h(
|
||||
'button',
|
||||
{ type: 'button', class: 'btn tint sm', onclick: () => installSheet('awg', [], () => location.reload()) },
|
||||
h('span', {}, _('Install')),
|
||||
),
|
||||
)
|
||||
: aw && !aw.loaded
|
||||
? note(
|
||||
'warn',
|
||||
_('AmneziaWG’s kernel module doesn’t load on this firmware'),
|
||||
_('Try another build in System, under Updates, or update OpenWrt. The server can’t start until it loads.'),
|
||||
h('a', { class: 'btn soft sm', href: settingsUrl('updates') }, h('span', {}, _('Open Updates'))),
|
||||
)
|
||||
: null;
|
||||
const wanNote =
|
||||
d.wan_kind === 'cgnat'
|
||||
? note(
|
||||
'warn',
|
||||
_('Your router has no public address (CGNAT)'),
|
||||
_(
|
||||
'The ISP shares one address: devices can only connect if the ISP gives you a public address or IPv6. Ask them, or use a DDNS name that points at an IPv6 address.',
|
||||
),
|
||||
)
|
||||
: d.wan_kind === 'private'
|
||||
? note(
|
||||
'warn',
|
||||
fmt(_('Your router is behind another router (WAN %s)'), d.wan_ip),
|
||||
_('Forward the UDP port on the upstream router to this one and use a DDNS name or that router’s public address here.'),
|
||||
)
|
||||
: null;
|
||||
const next = h('button', { type: 'button', class: 'btn accent block' }, h('span', {}, _('Next'))) as HTMLButtonElement;
|
||||
next.addEventListener('click', () => {
|
||||
if (!name.check() || !addr.check()) return;
|
||||
if (hostHelp(addr.value(), s.port).bad) return;
|
||||
s.name = name.value();
|
||||
s.endpoint = addr.value();
|
||||
go(() => vAwg(d, s, extra, done));
|
||||
});
|
||||
const title = extra ? _('Add a server') : _('Set up Dawnline');
|
||||
const el = h(
|
||||
'div',
|
||||
{ class: 'view ns-v' },
|
||||
head(title),
|
||||
steps(extra ? 2 : 3, 0),
|
||||
lead(
|
||||
extra
|
||||
? _('One more server: another port or disguise for networks the first does not get through, or its own home access rules.')
|
||||
: _('Where devices connect to. A name that always points at your router (DDNS) keeps links working when your IP changes.'),
|
||||
),
|
||||
awgNote,
|
||||
wanNote,
|
||||
name.el,
|
||||
// one line under the address: the router's verdict on what is typed (it says «through Cloudflare» itself)
|
||||
addr.el,
|
||||
next,
|
||||
);
|
||||
return { el, label: title };
|
||||
}
|
||||
|
||||
function likeHome(s: Draft): HTMLElement {
|
||||
return switchRow({
|
||||
title: _('Internet like a home device'),
|
||||
sub: _('Through this router’s proxies and filters. Slower: up to a third on two cores.'),
|
||||
on: s.lan_like,
|
||||
icon: 'home',
|
||||
flip: async (on) => ((s.lan_like = on), true),
|
||||
});
|
||||
}
|
||||
|
||||
function vAwg(d: SetupDefaults, s: Draft, extra: boolean, done: () => void): View {
|
||||
const port = field(
|
||||
_('UDP port'),
|
||||
String(s.port),
|
||||
(v) =>
|
||||
portHelp(
|
||||
Number(v) || 0,
|
||||
d.udp_taken ?? [],
|
||||
Number(v) === 4500
|
||||
? `${_('Opened on the WAN firewall automatically.')} ${_('4500 is IPsec’s port: most networks let it through.')}`
|
||||
: _('Opened on the WAN firewall automatically.'),
|
||||
),
|
||||
{ numeric: true, mono: true },
|
||||
);
|
||||
const range = field(_('Device addresses'), s.range, (v) => rangeHelp(v, d.networks ?? [], rangeOf(d.subnet)), {
|
||||
mono: true,
|
||||
plain: true,
|
||||
});
|
||||
range.el.querySelector('.fl-f')?.append(h('span', { class: 'mono fl-suffix' }, '.x'));
|
||||
const keep = () => {
|
||||
s.port = Number(port.value()) || 0;
|
||||
s.range = range.value();
|
||||
if (s.portalSame) s.portal_port = s.port;
|
||||
};
|
||||
const missing = (d.awg_state?.missing ?? []).length > 0;
|
||||
const nextBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
class: 'btn accent block',
|
||||
disabled: extra && missing,
|
||||
title: extra && missing ? _('Install AmneziaWG first') : null,
|
||||
},
|
||||
h('span', {}, extra ? _('Create server') : _('Next')),
|
||||
) as HTMLButtonElement;
|
||||
nextBtn.addEventListener('click', () => {
|
||||
if (!port.check() || !range.check()) return;
|
||||
keep();
|
||||
if (extra) void once(nextBtn, () => create(d, s, extra, done));
|
||||
else go(() => vPortal(d, s, done));
|
||||
});
|
||||
const el = h(
|
||||
'div',
|
||||
{ class: 'view ns-v' },
|
||||
head('AmneziaWG', { back: true }),
|
||||
steps(extra ? 2 : 3, 1),
|
||||
port.el,
|
||||
range.el,
|
||||
// the levels on a track with the picked one's meters under it: three tiles do not fit a sheet
|
||||
h(
|
||||
'div',
|
||||
{ class: 'choice' },
|
||||
h('div', { class: 'choice-h' }, h('span', {}, _('Disguise'))),
|
||||
levelPick({ caps: d.awg, tools: d.awg_state?.tools !== false, picked: s.preset, pick: (m) => (s.preset = m) }),
|
||||
),
|
||||
// one more server has no portal step: the internet choice comes last here
|
||||
extra ? likeHome(s) : null,
|
||||
d.awg_state?.tools && d.awg_state.handler === false
|
||||
? hint(_('Creating the server restarts the network for a few seconds: AmneziaWG was installed after the network started.'))
|
||||
: null,
|
||||
nextBtn,
|
||||
);
|
||||
return { el, label: 'AmneziaWG' };
|
||||
}
|
||||
|
||||
function vPortal(d: SetupDefaults, s: Draft, done: () => void): View {
|
||||
const ipLinks = () => /^\d{1,3}(\.\d{1,3}){3}$/.test(s.endpoint);
|
||||
const port = field(_('Listening port'), String(s.portal_port), (v) => portalPortHelp(Number(v) || 0, d.tcp_taken ?? [], ipLinks()), {
|
||||
numeric: true,
|
||||
mono: true,
|
||||
});
|
||||
port.el.hidden = !s.portal;
|
||||
port.input.addEventListener('input', () => (s.portalSame = Number(port.value()) === s.port));
|
||||
const portal = switchRow({
|
||||
title: _('Personal portal'),
|
||||
sub: _('Off: only you add devices, from LuCI. On: people manage their devices within the limits you set.'),
|
||||
on: s.portal,
|
||||
icon: 'portal',
|
||||
flip: async (on) => {
|
||||
s.portal = on;
|
||||
// the port's field comes and goes with the switch: the sheet glides to its new height
|
||||
glide(() => (port.el.hidden = !on));
|
||||
return true;
|
||||
},
|
||||
});
|
||||
const missing = (d.awg_state?.missing ?? []).length > 0;
|
||||
const btn = h(
|
||||
'button',
|
||||
{ type: 'button', class: 'btn accent block', disabled: missing, title: missing ? _('Install AmneziaWG first') : null },
|
||||
h('span', {}, _('Create server')),
|
||||
) as HTMLButtonElement;
|
||||
btn.addEventListener('click', () =>
|
||||
once(btn, async () => {
|
||||
if (s.portal && !port.check()) return;
|
||||
s.portal_port = Number(port.value()) || 0;
|
||||
await create(d, s, false, done);
|
||||
}),
|
||||
);
|
||||
const el = h('div', { class: 'view ns-v' }, head(_('Portal'), { back: true }), steps(3, 2), likeHome(s), portal, port.el, btn);
|
||||
return { el, label: _('Portal') };
|
||||
}
|
||||
|
||||
async function create(d: SetupDefaults, s: Draft, extra: boolean, done: () => void) {
|
||||
try {
|
||||
// one more server leaves the portal's settings alone (undefined is not sent)
|
||||
const r = await api.serverCreate(
|
||||
s.id,
|
||||
s.name,
|
||||
d.ifname,
|
||||
s.port,
|
||||
subnetOf(s.range),
|
||||
s.endpoint,
|
||||
d.mtu,
|
||||
s.preset,
|
||||
d.lan_zone,
|
||||
d.wan_zone,
|
||||
s.lan_like,
|
||||
extra ? undefined : s.portal,
|
||||
extra ? undefined : s.portal_port,
|
||||
);
|
||||
done();
|
||||
const to = settingsUrl(undefined, r.id);
|
||||
// The sheet closes as every sheet does, and the page goes to the new server once it is gone (it used to stand
|
||||
// open with a busy button until the page was loaded again under it). A network restart drops the connection
|
||||
// to LuCI for a few seconds: the page waits them out first.
|
||||
onClosed(() => {
|
||||
say(r.network_restart ? _('Restarting the network so it knows AmneziaWG: back in a few seconds') : _('Server created'));
|
||||
setTimeout(() => (location.href = to), r.network_restart ? 10000 : 700);
|
||||
});
|
||||
closeSheet();
|
||||
} catch (e) {
|
||||
notify(errorText(e), 'error', 10000);
|
||||
}
|
||||
}
|
||||
|
||||
/** The wizard's values as it opens. */
|
||||
const draftOf = (d: SetupDefaults, extra: boolean): Draft => ({
|
||||
id: d.id,
|
||||
name: d.name,
|
||||
endpoint: d.endpoint,
|
||||
port: d.port,
|
||||
// the tunnel's first three numbers ("10.77.0"): it is that /24
|
||||
range: rangeOf(d.subnet),
|
||||
preset: defaultMethod(d.awg),
|
||||
// off by default: the portal opens a port on WAN, so it is a choice
|
||||
portal: false,
|
||||
portal_port: d.portal_port || 8443,
|
||||
// off by default: the loop through the LAN costs up to a third of the speed
|
||||
lan_like: false,
|
||||
portalSame: !extra && (d.portal_port || 8443) === d.port,
|
||||
});
|
||||
|
||||
/**
|
||||
* The wizard; `extra`: one more beside those there are (no portal step). `from`: the router's defaults, or the way
|
||||
* to ask for them: the sheet opens at once on the press and its first step comes in when the router has answered
|
||||
* (it used to open only then, with nothing on screen meanwhile).
|
||||
*/
|
||||
export function newServer(from: SetupDefaults | (() => Promise<SetupDefaults>), extra: boolean, done: () => void = () => undefined) {
|
||||
let d: SetupDefaults | null = typeof from === 'function' ? null : from;
|
||||
let s: Draft | null = d ? draftOf(d, extra) : null;
|
||||
const title = extra ? _('Add a server') : _('Set up Dawnline');
|
||||
openSheet(() => {
|
||||
// back from a later step: the first one as it was left
|
||||
if (d && s) return vServer(d, s, extra, done);
|
||||
const el = h('div', { class: 'view ns-v' }, head(title), steps(extra ? 2 : 3, 0), lead(_('Asking the router what it has…')));
|
||||
void (from as () => Promise<SetupDefaults>)().then(
|
||||
(got) => {
|
||||
d = got;
|
||||
s = draftOf(got, extra);
|
||||
if (!showing(el)) return;
|
||||
const first = vServer(got, s, extra, done).el;
|
||||
glide(() => putChildren(el, Array.from(first.childNodes)));
|
||||
},
|
||||
(e) => showing(el) && glide(() => el.append(h('p', { class: 'hint bad-t' }, errorText(e)))),
|
||||
);
|
||||
return { el, label: title };
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
// An updater job in the portal's sheet, from its question to its end:
|
||||
// Dawnline itself, AmneziaWG, the system packages, a check, a translation,
|
||||
// installing what a feature is missing. The question first where the job
|
||||
// restarts something (flows/ask.ts); then the job on its stage
|
||||
// (flows/job-stage.ts): updates_run, followed by updates_status each second,
|
||||
// its phases as the steps, its time and its log; then what came of it, on the
|
||||
// same stage. A check ends in what it found, a row a component. Dawnline's
|
||||
// own job ends in a wait: the router restarts its services under the page,
|
||||
// which reads itself again once the router answers with the new version (no
|
||||
// button to press: the owner, 2026-11-12, «сделать автоматический релоад»). Closing
|
||||
// the sheet leaves the job running on the router: the page picks it up again
|
||||
// (its row in Settings › Updates opens it here).
|
||||
|
||||
import { api, type UpdateJob, type UpdatesStatus } from '../api';
|
||||
import { h } from '../../portal/dom';
|
||||
import { closeSheet, go, onLeave, openSheet, showing, type View } from '../../portal/ui/sheet';
|
||||
import { glass } from '../ui/glass';
|
||||
import { ic } from '../ui/icons';
|
||||
import { errorText } from '../ui/toast';
|
||||
import { fmt } from '../../shared/i18n';
|
||||
import { routerSaid } from '../failure';
|
||||
import {
|
||||
addPhase,
|
||||
checkVerdict,
|
||||
isOurJob,
|
||||
jobComponent,
|
||||
jobIcon,
|
||||
mmss,
|
||||
phaseSteps,
|
||||
runningComponent,
|
||||
type Found,
|
||||
type Verdict,
|
||||
} from '../updater/jobs';
|
||||
import { askView, type Ask } from './ask';
|
||||
import { stage, type Stage } from './job-stage';
|
||||
|
||||
export interface Operation {
|
||||
/** What updates_run gets ("amneziawg:slava:ru", "check:packages", "pkgs:a,b"). */
|
||||
what: string;
|
||||
/** The job as a title ("Updating AmneziaWG"). */
|
||||
title: string;
|
||||
/** Asked first (the job restarts tunnels or services); without it the job starts at once. */
|
||||
ask?: Omit<Ask, 'run'>;
|
||||
/** It ended well: the page reads the router again (the job's last status, or null). */
|
||||
done?: (st: UpdatesStatus | null) => void;
|
||||
/** A check that found one component's update: the operation its "Update" button starts. */
|
||||
update?: (st: UpdatesStatus) => Operation | null;
|
||||
}
|
||||
|
||||
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
/** The admin's translation, added or removed: LuCI's web server restarts after it and the page is read again. */
|
||||
const LANG = /^app:(lang:|nolang$)/;
|
||||
|
||||
const TONE = { new: 'orange', ok: 'blue', bad: 'red', quiet: 'grey' } as const;
|
||||
const MARK = { new: 'arrow', ok: 'check', bad: 'alert', quiet: 'minus' } as const;
|
||||
|
||||
/** What a check found: a row a component, its mark in the tone of where it stands (as its row in Settings). */
|
||||
function foundRows(rows: Found[]): HTMLElement {
|
||||
return h(
|
||||
'div',
|
||||
{ class: 'checks' },
|
||||
...rows.map((r) =>
|
||||
h(
|
||||
'div',
|
||||
{ class: 'chk jb-f' },
|
||||
glass(r.icon, TONE[r.tone]),
|
||||
h('span', { class: 'chk-t' }, h('b', {}, r.name), h('span', { class: r.mono ? 'mono' : null }, r.line)),
|
||||
h('span', { class: `jb-fm ${r.tone}` }, ic(MARK[r.tone])),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
const btn = (cls: string, label: string, run: () => void) =>
|
||||
h('button', { type: 'button', class: `btn ${cls}`, onclick: run }, h('span', {}, label));
|
||||
const closeBtn = (accent: boolean) => btn(accent ? 'accent' : 'soft', accent ? _('Done') : _('Close'), () => closeSheet());
|
||||
|
||||
function reload() {
|
||||
ui.menu?.flushCache();
|
||||
location.reload();
|
||||
}
|
||||
|
||||
/** What a check's end shows: its verdict, the rows it found, and the update's own button where one component has one. */
|
||||
function checkEnd(s: Stage, v: Verdict, next: Operation | null) {
|
||||
const alone = v.rows.length === 1 && v.tone === 'bad';
|
||||
s.end({
|
||||
tone: v.tone === 'bad' ? 'red' : v.tone === 'new' ? 'orange' : 'green',
|
||||
title: v.title,
|
||||
// one component whose check failed: its reason is the line, there is no list to read
|
||||
text: alone ? v.rows[0].line : undefined,
|
||||
body: alone || !v.rows.length ? null : foundRows(v.rows),
|
||||
acts: next ? [closeBtn(false), btn('accent', _('Update'), () => go(() => operationView(next)))] : [closeBtn(v.tone !== 'bad')],
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Dawnline is installed: the router restarts its services under the page, which reads itself again once the router
|
||||
* answers as `target`. Nothing to press meanwhile; only a wait that ran out offers the reload.
|
||||
*/
|
||||
async function awaitRestart(s: Stage, target: string, alive: () => boolean) {
|
||||
s.end({
|
||||
tone: 'green',
|
||||
title: target ? fmt(_('Dawnline %s is installed'), target) : _('Dawnline is installed'),
|
||||
text: _('The router is restarting its services. The page reloads by itself.'),
|
||||
});
|
||||
for (let n = 0; n < 30 && alive(); n++) {
|
||||
await sleep(1500);
|
||||
const st = await api.updatesStatus().catch(() => null);
|
||||
if (st && (!target || st.version === target)) return alive() ? reload() : undefined;
|
||||
}
|
||||
if (!alive()) return;
|
||||
s.say(_('The router has not answered with the new version yet. Reload the page to use it.'));
|
||||
s.acts([btn('accent', _('Reload now'), reload)]);
|
||||
}
|
||||
|
||||
/** The job under way, then its end. `follow`: a job already running (started elsewhere, or before a reload). */
|
||||
function progressView(op: Operation, follow?: UpdateJob): View {
|
||||
const isCheck = follow ? follow.action === 'check' : op.what.startsWith('check');
|
||||
const comp = follow ? runningComponent(follow) : jobComponent(op.what);
|
||||
const s = stage({ icon: jobIcon(comp), title: op.title, lead: _('You can close this: the job carries on on the router.') });
|
||||
const el = s.view.el;
|
||||
let alive = true;
|
||||
onLeave(() => (alive = false));
|
||||
const here = () => alive && showing(el);
|
||||
|
||||
void (async () => {
|
||||
let job: UpdateJob | null = follow ?? null;
|
||||
let id = follow?.id;
|
||||
let prevId: string | undefined;
|
||||
let since = 0;
|
||||
if (!follow) {
|
||||
try {
|
||||
const before = await api.updatesStatus().catch(() => null);
|
||||
prevId = before?.job?.id;
|
||||
since = before?.now ?? 0;
|
||||
const r = await api.updatesRun(op.what);
|
||||
// a quick check may be over already: still this press's job (updates_run never returns an older one)
|
||||
if (r.job && r.job.id !== prevId) ({ job, id } = { job: r.job, id: r.job.id });
|
||||
} catch (e) {
|
||||
return s.end({ tone: 'red', title: _('Not started'), text: errorText(e), acts: [closeBtn(false)] });
|
||||
}
|
||||
}
|
||||
const opened = Date.now();
|
||||
let seen: string[] = [];
|
||||
let state: UpdateJob['state'] | '' = '';
|
||||
let st: UpdatesStatus | null = null;
|
||||
let misses = 0;
|
||||
while (alive) {
|
||||
await sleep(1000);
|
||||
st = await api.updatesStatus().catch(() => null);
|
||||
// rpcd restarts while the network learns AmneziaWG: keep waiting a while
|
||||
if (!st) {
|
||||
if (++misses > 60) break;
|
||||
continue;
|
||||
}
|
||||
misses = 0;
|
||||
const j = st.job;
|
||||
if (!j || !isOurJob(j, id, prevId, since)) {
|
||||
if (Date.now() - opened > 15000) break;
|
||||
continue;
|
||||
}
|
||||
id = j.id;
|
||||
job = j;
|
||||
s.log(j.log);
|
||||
s.time(mmss((j.finished ?? st.now) - j.started));
|
||||
const next = addPhase(seen, j.phase, _('Finished'));
|
||||
if (next !== seen || j.state !== state) {
|
||||
seen = next;
|
||||
state = j.state;
|
||||
if (seen.length && showing(el)) s.steps(phaseSteps(seen, j.state));
|
||||
}
|
||||
if (j.state !== 'running') break;
|
||||
}
|
||||
if (!here()) {
|
||||
if (job?.state === 'done') op.done?.(st);
|
||||
return;
|
||||
}
|
||||
op.done?.(st);
|
||||
if (!job || job.state === 'running')
|
||||
return s.end({
|
||||
tone: 'orange',
|
||||
title: _('No answer'),
|
||||
text: _('The router stopped answering. The job may still finish: open Settings in a minute.'),
|
||||
keep: true,
|
||||
acts: [closeBtn(false)],
|
||||
});
|
||||
if (job.state === 'failed') {
|
||||
const why = (routerSaid(job.error) ?? _('Operation failed')).replace(/\.$/, '');
|
||||
return s.end({
|
||||
tone: 'red',
|
||||
title: isCheck ? _('The check failed') : _('Not installed'),
|
||||
text: isCheck ? `${why}.` : `${why}. ${_('Nothing else was changed.')}`,
|
||||
keep: true,
|
||||
acts: [closeBtn(false)],
|
||||
});
|
||||
}
|
||||
const lang = LANG.exec(job.component ?? '');
|
||||
if (lang) {
|
||||
s.end({
|
||||
tone: 'green',
|
||||
title: lang[1] === 'nolang' ? _('The translation is removed') : _('The translation is installed'),
|
||||
text: _('The page reloads by itself in a few seconds.'),
|
||||
});
|
||||
await sleep(4000);
|
||||
if (alive) reload();
|
||||
return;
|
||||
}
|
||||
if (isCheck)
|
||||
return checkEnd(
|
||||
s,
|
||||
st ? checkVerdict(st, comp) : { tone: 'ok', title: _('Checked'), rows: [] },
|
||||
st ? (op.update?.(st) ?? null) : null,
|
||||
);
|
||||
if (comp === 'app') return awaitRestart(s, job.to ?? '', here);
|
||||
const pkgs = [...((job.result?.pkgs?.updated as string[]) ?? []), ...((job.result?.pkgs?.installed as string[]) ?? [])];
|
||||
s.end({
|
||||
tone: 'green',
|
||||
title:
|
||||
comp === 'pkgs'
|
||||
? _('System packages are updated')
|
||||
: comp === 'amneziawg'
|
||||
? job.to
|
||||
? fmt(_('AmneziaWG %s is installed'), job.to)
|
||||
: _('AmneziaWG is installed')
|
||||
: _('Done'),
|
||||
text: comp === 'pkgs' && pkgs.length ? pkgs.join(', ') : undefined,
|
||||
acts: [closeBtn(true)],
|
||||
});
|
||||
})();
|
||||
return s.view;
|
||||
}
|
||||
|
||||
/** The operation's first view: its question, or straight to its progress (a flow that leads into it goes there). */
|
||||
export function operationView(op: Operation): View {
|
||||
if (!op.ask) return progressView(op);
|
||||
return askView({ ...op.ask, run: async () => go(() => progressView(op)) });
|
||||
}
|
||||
|
||||
/** Run an updater job in the sheet (asked first where it restarts something). */
|
||||
export const runOperation = (op: Operation) => openSheet(() => operationView(op));
|
||||
|
||||
/** Follow a job that is already running (the page found it), titled by `title`. */
|
||||
export function followOperation(job: UpdateJob, title: string, done?: (st: UpdatesStatus | null) => void) {
|
||||
openSheet(() => progressView({ what: '', title, done }, job));
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
// The OpenWrt packages Dawnline adds, by the feature that needs them (the
|
||||
// home-like link; HTTPS and certificates while the portal is on), and a
|
||||
// close-up of them in the portal's sheet: each feature with its packages, the
|
||||
// version installed and the one the feeds offer.
|
||||
|
||||
import type { Needs, UpdateComponent } from '../api';
|
||||
import { h } from '../../portal/dom';
|
||||
import { head, openSheet, sub, type View } from '../../portal/ui/sheet';
|
||||
import { glass } from '../ui/glass';
|
||||
|
||||
export interface SysItem {
|
||||
/** Its glass: what the feature is (a home, a lock, a certificate). */
|
||||
icon: string;
|
||||
title: string;
|
||||
sub: string;
|
||||
pkgs: string[];
|
||||
feature: Exclude<keyof Needs, 'awg'>;
|
||||
optional?: boolean;
|
||||
}
|
||||
|
||||
export function sysItems(): SysItem[] {
|
||||
return [
|
||||
{
|
||||
icon: 'home',
|
||||
title: _('Home-like link'),
|
||||
sub: _('Policy routing and the veth pair'),
|
||||
pkgs: ['ip-full', 'kmod-veth'],
|
||||
feature: 'home',
|
||||
},
|
||||
{
|
||||
icon: 'lock',
|
||||
title: _('HTTPS for the portal'),
|
||||
sub: _('OpenSSL for uhttpd'),
|
||||
pkgs: ['libustream-openssl', 'openssl-util'],
|
||||
feature: 'https',
|
||||
},
|
||||
{
|
||||
icon: 'cert',
|
||||
title: _('Certificates (ACME)'),
|
||||
sub: _('Let’s Encrypt certificate for the portal'),
|
||||
pkgs: ['acme', 'acme-acmesh-dnsapi'],
|
||||
feature: 'acme',
|
||||
optional: true,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
function view(items: SysItem[], pkgs: NonNullable<UpdateComponent['pkgs']>): View {
|
||||
const el = h(
|
||||
'div',
|
||||
{ class: 'view' },
|
||||
head(_('Packages and versions')),
|
||||
sub(_('From the OpenWrt feeds, for what Dawnline uses on this router.')),
|
||||
h(
|
||||
'div',
|
||||
{ class: 'pks' },
|
||||
...items.map((it) =>
|
||||
h(
|
||||
'div',
|
||||
{ class: 'pk' },
|
||||
h('div', { class: 'chk' }, glass(it.icon, 'grey'), h('span', { class: 'chk-t' }, h('b', {}, it.title), h('span', {}, it.sub))),
|
||||
h(
|
||||
'ul',
|
||||
{ class: 'pk-l' },
|
||||
...it.pkgs.map((name) => {
|
||||
const x = pkgs[name];
|
||||
return h(
|
||||
'li',
|
||||
{},
|
||||
h('span', { class: 'mono' }, name),
|
||||
!x?.installed
|
||||
? h('span', { class: 'pk-v' }, _('not installed'))
|
||||
: h('span', { class: `pk-v mono${x.latest ? ' new' : ''}` }, x.latest ? `${x.installed} → ${x.latest}` : x.installed),
|
||||
);
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
return { el, label: _('Packages and versions') };
|
||||
}
|
||||
|
||||
export const packagesSheet = (items: SysItem[], pkgs: NonNullable<UpdateComponent['pkgs']>) => openSheet(() => view(items, pkgs));
|
||||
@@ -0,0 +1,164 @@
|
||||
// What a person's one action does (people/lines.ts Act), from a row of People
|
||||
// or the head of their panel, and the other one-tap changes: pausing and
|
||||
// resuming, a new end date. A reversible change (extend, more data, resume,
|
||||
// pause, a server turned on) is made at once and said in a toast with Undo
|
||||
// (shell/toast.ts, the owner's decision): no question first. What is not one
|
||||
// tap opens its flow: an invite, a move, a device's set-up, adding a device;
|
||||
// advice for a device's network is copied to send. The page reads the router
|
||||
// again after each (its rows morph to what is true now). The action's button
|
||||
// is drawn here too, the same in a row and in a head.
|
||||
|
||||
import type { Person, Server } from '../../shared/types';
|
||||
import { api, type PersonPatch } from '../api';
|
||||
import { h } from '../../portal/dom';
|
||||
import { fmt, num } from '../../shared/i18n';
|
||||
import { errorText, notify } from '../ui/toast';
|
||||
import { copyText } from '../ui/files';
|
||||
import { ic } from '../ui/icons';
|
||||
import { say } from '../shell/toast';
|
||||
import { peopleAt, personUrl } from '../shell/routes';
|
||||
import { visit } from '../shell/visit';
|
||||
import { monthOn, shortDay, type Act } from '../people/lines';
|
||||
import { otherNetAdvice } from '../people/diagnosis';
|
||||
import type { ActCtx } from '../people/ctx';
|
||||
import { showSetup } from './setup';
|
||||
import { addDevice } from './add-device';
|
||||
import { openInvite } from './invite';
|
||||
import { movePerson } from './move-person';
|
||||
|
||||
/** An action's button; its whole label in its title (a device's long name may be cut, a narrow list shows the icon alone). */
|
||||
export function actButton(a: Act, cls = 'tint sm'): HTMLButtonElement {
|
||||
return h(
|
||||
'button',
|
||||
{ type: 'button', class: `btn ${cls}`, 'data-act': a.id, title: a.label, 'aria-label': a.label },
|
||||
ic(a.icon),
|
||||
h('span', {}, a.label),
|
||||
) as HTMLButtonElement;
|
||||
}
|
||||
|
||||
/** A change saved at once; false when the router refused (said in a toast). */
|
||||
async function save(id: string, patch: PersonPatch): Promise<boolean> {
|
||||
try {
|
||||
await api.personUpdate(id, patch);
|
||||
return true;
|
||||
} catch (e) {
|
||||
notify(errorText(e), 'error', 10000);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Change `p` now, say `done` with Undo (which puts `back` and says `undone`), and draw it. */
|
||||
async function oneTap(c: ActCtx, p: Person, patch: PersonPatch, back: PersonPatch, done: string, undone: string): Promise<void> {
|
||||
if (!(await save(p.id, patch))) return;
|
||||
void c.reload();
|
||||
say(done, {
|
||||
undo: () =>
|
||||
void save(p.id, back).then((ok) => {
|
||||
if (ok) void c.reload();
|
||||
}),
|
||||
undone,
|
||||
});
|
||||
}
|
||||
|
||||
/** Pause or resume: one tap, undone from its toast. */
|
||||
export function pause(c: ActCtx, p: Person, paused: boolean): Promise<void> {
|
||||
return paused
|
||||
? oneTap(c, p, { paused: true }, { paused: false }, fmt(_('%s is paused'), p.name), _('Pause lifted'))
|
||||
: oneTap(c, p, { paused: false }, { paused: true }, fmt(_('%s: access resumed'), p.name), fmt(_('%s is paused again'), p.name));
|
||||
}
|
||||
|
||||
/** A new end date by one tap ('' = none), undone from its toast. */
|
||||
export function setEnd(c: ActCtx, p: Person, expires: string): Promise<void> {
|
||||
return oneTap(
|
||||
c,
|
||||
p,
|
||||
{ expires },
|
||||
{ expires: p.expires },
|
||||
expires ? fmt(_('%s: access until %s'), p.name, shortDay(expires)) : fmt(_('%s: access with no end date'), p.name),
|
||||
_('End date as it was'),
|
||||
);
|
||||
}
|
||||
|
||||
/** A server turned on: one tap, undone from its toast (a person's action, People's notice over the list). */
|
||||
export async function serverOn(c: ActCtx, s: Server): Promise<void> {
|
||||
const set = async (on: boolean) => {
|
||||
try {
|
||||
await api.serverUpdate(s.id, { enabled: on ? '1' : '0' });
|
||||
return true;
|
||||
} catch (e) {
|
||||
notify(errorText(e), 'error', 10000);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
if (!(await set(true))) return;
|
||||
void c.reload();
|
||||
say(fmt(_('Server %s turned on'), s.name), {
|
||||
undo: () => void set(false).then((ok) => void (ok && c.reload())),
|
||||
undone: fmt(_('Server %s turned off again'), s.name),
|
||||
});
|
||||
}
|
||||
|
||||
/** Run a person's one action. */
|
||||
export async function runAct(a: Act, p: Person, c: ActCtx): Promise<void> {
|
||||
const st = c.st();
|
||||
const d = a.device ? p.devices.find((x) => x.id === a.device) : undefined;
|
||||
switch (a.id) {
|
||||
case 'extend':
|
||||
return setEnd(c, p, monthOn(p, c.today()));
|
||||
case 'bonus':
|
||||
return oneTap(
|
||||
c,
|
||||
p,
|
||||
{ bonus_gb: String((p.bonus_gb || 0) + (a.gb ?? 10)) },
|
||||
{ bonus_gb: p.bonus_gb ? String(p.bonus_gb) : '' },
|
||||
fmt(_('%s: +%s GB until the reset'), p.name, num(a.gb ?? 10)),
|
||||
_('Limit as it was'),
|
||||
);
|
||||
case 'resume':
|
||||
if (!a.extend) return pause(c, p, false);
|
||||
return oneTap(
|
||||
c,
|
||||
p,
|
||||
{ paused: false, expires: monthOn(p, c.today()) },
|
||||
{ paused: true, expires: p.expires },
|
||||
fmt(_('%s: access until %s'), p.name, shortDay(monthOn(p, c.today()))),
|
||||
fmt(_('%s is paused again'), p.name),
|
||||
);
|
||||
case 'enable': {
|
||||
const s = st.servers.find((x) => x.id === p.server);
|
||||
return s ? serverOn(c, s) : undefined;
|
||||
}
|
||||
case 'limit':
|
||||
if (c.limit) c.limit(p);
|
||||
else visit(personUrl(p.id, 'traffic'));
|
||||
return;
|
||||
case 'server':
|
||||
return movePerson({ person: p, st, moved: () => void c.reload() });
|
||||
case 'invite':
|
||||
return openInvite({
|
||||
person: p,
|
||||
server: st.servers.find((s) => s.id === p.server)?.name ?? '',
|
||||
changed: () => void c.reload(),
|
||||
});
|
||||
case 'show':
|
||||
if (d) await showSetup({ person: p, device: d, now: c.now, done: () => void c.reload() });
|
||||
void c.reload();
|
||||
return;
|
||||
case 'tell':
|
||||
if (d) void copyText(otherNetAdvice(d), _('Advice copied: send it to them'));
|
||||
return;
|
||||
// what they asked for on their own page: answered in the device's dialog
|
||||
case 'answer':
|
||||
return visit(a.device ? peopleAt({ server: p.server, id: p.id, device: a.device }) : personUrl(p.id));
|
||||
case 'add-device':
|
||||
addDevice({
|
||||
person: p,
|
||||
server: st.servers.find((s) => s.id === p.server),
|
||||
now: c.now,
|
||||
added: () => void c.reload(),
|
||||
people: st.people,
|
||||
servers: st.servers,
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
// A device's places as a close-up (a block of the page enlarged, read-only,
|
||||
// so it opens for every login): the period on top, the map pinned under it
|
||||
// with the replay's plate, the places scrolling under the map
|
||||
// (places/render.ts PlacesView). 720 px wide on a computer, opened at that
|
||||
// width (a 400 → 720 glide would resize the map on every frame); the whole
|
||||
// height on a phone, where the page's own maps step aside meanwhile (one WebGL
|
||||
// map at a time). Its address is the page's with sheet=places&device= (a
|
||||
// reload opens it again, Back closes it). `at`: open on that moment (a session
|
||||
// in the Log), the period the shortest that holds it. MapLibre starts once the
|
||||
// sheet stands still and its first frame fades in. While open it follows the
|
||||
// router (the live revision): the device's state and its new connections.
|
||||
// From a person's page: their places, a track over the period picking «All
|
||||
// devices» (their places together, no replay) or one of them; the page's own
|
||||
// address stays, with sheet=places and the device picked as pick=.
|
||||
// Nothing in it jumps: the map's box has its size from the first frame, every
|
||||
// change of the rows (the log coming in, another period or device, a poll) is
|
||||
// refilled in place while the sheet glides to its new height (sheet.ts glide).
|
||||
|
||||
import type { LogEvent, Status } from '../../shared/types';
|
||||
import { api } from '../api';
|
||||
import { h } from '../../portal/dom';
|
||||
import { glide, head, onLeave, openSheet, sub, type View } from '../../portal/ui/sheet';
|
||||
import { fmt } from '../../shared/i18n';
|
||||
import type { MapCallbacks } from '../map';
|
||||
import type { Span } from '../places/render';
|
||||
import { createPoller } from '../state/poller';
|
||||
import { tabs } from '../ui/tabs';
|
||||
import { refill } from '../ui/reshape';
|
||||
import { ic } from '../ui/icons';
|
||||
import { parkMaps } from '../widgets/map-box';
|
||||
import { loadMaps, type MapKit } from '../shell/maps';
|
||||
import { errorText, notify } from '../ui/toast';
|
||||
import { afterOpen, leaveTo, plain } from '../shell/sheets';
|
||||
import { deviceUrl, here, personUrl, withCloseUp } from '../shell/routes';
|
||||
|
||||
const SPAN: Record<Span, number> = { '24h': 86400, '7d': 7 * 86400, '30d': 30 * 86400 };
|
||||
const SPANS: Span[] = ['24h', '7d', '30d'];
|
||||
/** The newest events the close-up reads (30 days of connections and roams of a device, or of a person's devices). */
|
||||
const LIMIT = 5000;
|
||||
/** The track's item for all of a person's devices. */
|
||||
const ALL = '*';
|
||||
|
||||
const spanLabel = (s: Span) => ({ '24h': _('24h'), '7d': _('7 days'), '30d': _('30 days') })[s];
|
||||
const spanWords = (s: Span) => ({ '24h': _('last 24 hours'), '7d': _('last 7 days'), '30d': _('last 30 days') })[s];
|
||||
|
||||
/** A device's events, or a person's (`person`), since the longest period began. */
|
||||
const eventsOf = (st: Status, o: { device?: string; person?: string }) =>
|
||||
api.events(LIMIT, o.person, st.now - SPAN['30d'] - 1, o.person ? undefined : o.device).then((r) => r.events);
|
||||
|
||||
/**
|
||||
* Keep the address saying the close-up is open (on its own history entry), or not once it closes (null). On a
|
||||
* person's page (`own`) it stays theirs, the device picked (none: all of them) beside it.
|
||||
*/
|
||||
function address(device: string | null, own = false) {
|
||||
history.replaceState(history.state, '', withCloseUp(location.href, device, own));
|
||||
}
|
||||
|
||||
/**
|
||||
* Open the close-up of device `id` over the page. `st`: the page's status (the close-up keeps its own fresh copy
|
||||
* while open). `person`: opened on that person's page, `devices` theirs with places (a track picks one, or all of
|
||||
* them: `id` null).
|
||||
*/
|
||||
export function openCloseUp(id: string | null, st: Status, o: { at?: number; devices?: string[]; person?: string } = {}) {
|
||||
const p = st.people.find((x) => (o.person ? x.id === o.person : x.devices.some((d) => d.id === id)));
|
||||
if (!p || (!id && !o.person)) return;
|
||||
const range: Span = o.at ? (SPANS.find((s) => st.now - o.at! <= SPAN[s]) ?? '30d') : '30d';
|
||||
const own = !!o.person;
|
||||
// The map's module first (at once once it is in): the sheet opens with its map.
|
||||
loadMaps().then(
|
||||
(kit) => {
|
||||
// The page's address without the close-up: the sheet's own entry, pushed on top of it, carries it.
|
||||
address(null);
|
||||
openSheet(() => view(kit, p.id, id, st, range, o.at, own ? (o.devices ?? []) : null));
|
||||
address(id, own);
|
||||
},
|
||||
(e) => notify(errorText(e), 'error', 10000),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* `devices`: opened from a person's page, their devices with places: with several, a track over the period picks
|
||||
* whose places show (all of them, or one), in place.
|
||||
*/
|
||||
function view(kit: MapKit, pid: string, id0: string | null, first: Status, range0: Span, at?: number, devices?: string[] | null): View {
|
||||
let st = first;
|
||||
let p = st.people.find((x) => x.id === pid)!;
|
||||
let id = id0;
|
||||
const own = !!devices;
|
||||
const many = !!devices && devices.length > 1;
|
||||
const dev = () => (id ? (p.devices.find((x) => x.id === id) ?? null) : null);
|
||||
const narrow = !matchMedia('(min-width: 760px)').matches;
|
||||
const cb: MapCallbacks = {
|
||||
openPerson: (x) => leaveTo(personUrl(x)),
|
||||
openDevice: (_pid, did) => leaveTo(deviceUrl(did)),
|
||||
};
|
||||
let range = range0;
|
||||
const map = new kit.ConnectionMap(cb, range, narrow ? 240 : 380);
|
||||
const places = new kit.PlacesView(map, range, { geo: st.geo, now: st.now, person: p, device: dev(), events: null });
|
||||
const subEl = sub('');
|
||||
// the title names the person when it is theirs: the line under it says only the period
|
||||
const say = () => (subEl.textContent = many || !id ? spanWords(range) : `${p.name} · ${spanWords(range)}`);
|
||||
say();
|
||||
// Rows edge: they scroll under the map, their edge fades only where more is hidden under it.
|
||||
const rows = h('div', { class: 'lp-rows' }, places.el);
|
||||
const edge = () => rows.classList.toggle('more-down', rows.scrollTop + rows.clientHeight < rows.scrollHeight - 1);
|
||||
rows.addEventListener('scroll', edge, { passive: true });
|
||||
/** A change of what the sheet shows: the rows refill in place, the sheet glides to its new height (SMOOTH). */
|
||||
const change = (fn: () => void) => {
|
||||
glide(fn);
|
||||
requestAnimationFrame(edge);
|
||||
};
|
||||
const track = tabs(
|
||||
SPANS.map((s) => ({ id: s, label: spanLabel(s) })),
|
||||
range,
|
||||
(r) => {
|
||||
range = r;
|
||||
change(() => places.setRange(r));
|
||||
say();
|
||||
},
|
||||
{ cls: 'range', label: _('Period') },
|
||||
);
|
||||
// The way to the device's own page: not on it (it is under the sheet), nor for all of a person's devices.
|
||||
const foot = h('div', { class: 'lp-foot' });
|
||||
const paintFoot = () => {
|
||||
const onItsPage = here().view === 'people' && new URLSearchParams(location.search).get('device') === id;
|
||||
const to = id && !onItsPage ? deviceUrl(id) : null;
|
||||
refill(
|
||||
foot,
|
||||
to
|
||||
? [
|
||||
h(
|
||||
'a',
|
||||
{
|
||||
class: 'pill-link lp-open',
|
||||
href: to,
|
||||
onclick: (e: Event) => {
|
||||
if (!plain(e)) return;
|
||||
e.preventDefault();
|
||||
leaveTo(to);
|
||||
},
|
||||
},
|
||||
_('Open the device'),
|
||||
ic('chevron'),
|
||||
),
|
||||
]
|
||||
: [],
|
||||
);
|
||||
};
|
||||
paintFoot();
|
||||
const title = many || !id ? fmt(_('Where they have been · %s'), p.name) : fmt(_('Where it has been · %s'), dev()?.name ?? '');
|
||||
const which =
|
||||
devices && devices.length > 1
|
||||
? tabs(
|
||||
[
|
||||
{ id: ALL, label: _('All devices') },
|
||||
...devices.map((x) => ({
|
||||
id: x,
|
||||
label: p.devices.find((y) => y.id === x)?.name ?? x,
|
||||
icon: p.devices.find((y) => y.id === x)?.kind,
|
||||
})),
|
||||
],
|
||||
id ?? ALL,
|
||||
(next) => {
|
||||
id = next === ALL ? null : next;
|
||||
address(id, true);
|
||||
change(() => {
|
||||
places.setDevice(dev());
|
||||
paintFoot();
|
||||
});
|
||||
},
|
||||
{ cls: 'range lp-devs', label: _('Device') },
|
||||
).el
|
||||
: null;
|
||||
const mapEl = h('div', { class: 'map-box dl-dmap' }, map.el, places.controls);
|
||||
const el = h(
|
||||
'div',
|
||||
{ class: 'view look-places' },
|
||||
head(title),
|
||||
subEl,
|
||||
h('div', { class: 'dplaces lp' }, which, track.el, mapEl, rows, foot),
|
||||
);
|
||||
const unpark = narrow ? parkMaps() : null;
|
||||
let dead = false;
|
||||
// a person's page reads all their devices' events, so another pick needs none
|
||||
const scope = () => (own ? { person: pid } : { device: id! });
|
||||
|
||||
// The log for its strips, and live: its state and new connections as they come.
|
||||
const poller = createPoller({
|
||||
fetch: () => Promise.all([api.status(1), eventsOf(st, scope())]),
|
||||
every: 30,
|
||||
live: true,
|
||||
active: () => !dead,
|
||||
apply: ([s, ev]: [Status, LogEvent[]]) => {
|
||||
st = s;
|
||||
const p2 = s.people.find((x) => x.id === pid);
|
||||
if (!p2 || (id && !p2.devices.some((x) => x.id === id))) return;
|
||||
p = p2;
|
||||
change(() => places.update({ geo: s.geo, now: s.now, person: p2, device: dev(), events: ev }));
|
||||
},
|
||||
});
|
||||
void (async () => {
|
||||
const ev = await eventsOf(st, scope()).catch(() => [] as LogEvent[]);
|
||||
if (dead) return;
|
||||
change(() => places.update({ events: ev }));
|
||||
await afterOpen();
|
||||
if (dead || !el.isConnected) return;
|
||||
edge();
|
||||
places.el.addEventListener('click', () => requestAnimationFrame(edge));
|
||||
// The map's box stands from the first frame; the map itself fades in once it has drawn (map.ts mount).
|
||||
await map.mount(places.mapData());
|
||||
if (at && !dead) places.seek(at);
|
||||
})();
|
||||
onLeave(() => {
|
||||
dead = true;
|
||||
poller.stop();
|
||||
unpark?.();
|
||||
// Gone with the sheet, once it has left the screen.
|
||||
setTimeout(() => {
|
||||
places.destroy();
|
||||
map.destroy();
|
||||
}, 460);
|
||||
});
|
||||
return { el, label: title };
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
// The personal portal's sheets on the System page: another address for the
|
||||
// links (what the router found and is not picked yet, each with where it
|
||||
// points; or one typed in, checked as the router would), and the
|
||||
// certificate's own files (two paths on the router; both empty: picked
|
||||
// automatically). Each saves through `save` and closes once it took.
|
||||
|
||||
import type { PortalInfo } from '../api';
|
||||
import { h } from '../../portal/dom';
|
||||
import { closeSheet, head, openSheet, sub, type View } from '../../portal/ui/sheet';
|
||||
import { once } from '../../portal/ui/feedback';
|
||||
import { badLine } from '../../portal/ui/bad-line';
|
||||
import { shake } from '../../shared/shake';
|
||||
import { fmt } from '../../shared/i18n';
|
||||
import { glass } from '../ui/glass';
|
||||
import { ic } from '../ui/icons';
|
||||
import { errorText } from '../ui/toast';
|
||||
import { hostHelp, type Help } from '../netcheck';
|
||||
import { field } from './form';
|
||||
|
||||
export type Candidate = PortalInfo['candidates'][number];
|
||||
|
||||
const isIp = (x: string) => /^\d{1,3}(\.\d{1,3}){3}$/.test(x);
|
||||
|
||||
/** Where an address points, in words, and whether that is a warning (plain HTTP, Cloudflare, elsewhere). */
|
||||
export function addressNote(x: Candidate, found: boolean): { text: string; warn: boolean } {
|
||||
if (x.kind === 'ip' || isIp(x.host)) return { text: _('Plain HTTP: the link and VPN keys travel unencrypted'), warn: true };
|
||||
if (x.cloudflare) return { text: _('Behind Cloudflare · often stalls in Russia'), warn: true };
|
||||
if (!x.ips.length) return { text: found ? _('Your address') : _('Checking where it points…'), warn: false };
|
||||
if (x.here)
|
||||
return {
|
||||
text: x.cert ? _('Points at this router · Let’s Encrypt certificate') : _('Points at this router · no certificate yet'),
|
||||
warn: false,
|
||||
};
|
||||
return { text: fmt(_('Points at %s, not this router'), x.ips.join(', ')), warn: true };
|
||||
}
|
||||
|
||||
function addView(cands: Candidate[], picked: string[], save: (host: string) => Promise<void>): View {
|
||||
const free = cands.filter((x) => !picked.includes(x.host));
|
||||
const { el: bad, say, unsay } = badLine();
|
||||
const take = async (host: string) => {
|
||||
await save(host);
|
||||
closeSheet();
|
||||
};
|
||||
const opts = free.map((x) => {
|
||||
const n = addressNote(x, true);
|
||||
const b = h(
|
||||
'button',
|
||||
{ type: 'button', class: 'opt', role: 'listitem' },
|
||||
glass(isIp(x.host) ? 'globe' : 'link', n.warn ? 'orange' : x.here ? 'blue' : 'grey'),
|
||||
h('span', { class: 'opt-t' }, h('b', { class: 'mono' }, x.host), h('span', { class: n.warn ? 'warn-t' : '' }, n.text)),
|
||||
ic('plus', 'i opt-chev'),
|
||||
) as HTMLButtonElement;
|
||||
b.addEventListener('click', () =>
|
||||
once(b, async () => {
|
||||
try {
|
||||
await take(x.host);
|
||||
} catch (e) {
|
||||
say(errorText(e));
|
||||
}
|
||||
}),
|
||||
);
|
||||
return b;
|
||||
});
|
||||
const input = h('input', {
|
||||
type: 'text',
|
||||
placeholder: _('vpn.example.com or an IP'),
|
||||
'aria-label': _('Other address'),
|
||||
autocomplete: 'off',
|
||||
autocapitalize: 'none',
|
||||
autocorrect: 'off',
|
||||
spellcheck: 'false',
|
||||
class: 'mono',
|
||||
'data-1p-ignore': true,
|
||||
}) as HTMLInputElement;
|
||||
const goBtn = h('button', { class: 'go ready', type: 'submit', 'aria-label': _('Add') }, ic('arrow')) as HTMLButtonElement;
|
||||
const form = h('form', { class: 'field', autocomplete: 'off' }, input, goBtn);
|
||||
input.addEventListener('input', () => unsay());
|
||||
form.addEventListener('submit', (e) => {
|
||||
e.preventDefault();
|
||||
const v = input.value.trim().toLowerCase();
|
||||
const check = hostHelp(v);
|
||||
if (check.bad) {
|
||||
say(check.text);
|
||||
return shake(form);
|
||||
}
|
||||
if (picked.includes(v)) return closeSheet();
|
||||
void once(goBtn, async () => {
|
||||
try {
|
||||
await take(v);
|
||||
} catch (err) {
|
||||
say(errorText(err));
|
||||
shake(form);
|
||||
}
|
||||
});
|
||||
});
|
||||
requestAnimationFrame(() => (free.length ? null : input.focus({ preventScroll: true })));
|
||||
const el = h(
|
||||
'div',
|
||||
{ class: 'view' },
|
||||
head(_('Add an address')),
|
||||
sub(_('Links work on every picked address; the first is the main one.')),
|
||||
free.length ? h('div', { class: 'opts', role: 'list' }, ...opts) : null,
|
||||
free.length ? h('p', { class: 'hint pa-or' }, _('Or another one:')) : null,
|
||||
form,
|
||||
bad,
|
||||
);
|
||||
return { el, label: _('Add an address') };
|
||||
}
|
||||
|
||||
/** Pick another address for the links; `save` adds it (rejects with the router's reason). */
|
||||
export const addAddressSheet = (cands: Candidate[], picked: string[], save: (host: string) => Promise<void>) =>
|
||||
openSheet(() => addView(cands, picked, save));
|
||||
|
||||
const pathHelp = (v: string): Help =>
|
||||
!v.trim() || v.trim().startsWith('/') ? { text: '', bad: false } : { text: _('A full path on the router, starting with /.'), bad: true };
|
||||
|
||||
function certView(cert: string, key: string, save: (cert: string, key: string) => Promise<void>): View {
|
||||
const c = field(_('Certificate file'), cert, pathHelp, { placeholder: '/etc/ssl/…/fullchain.crt', mono: true, plain: true });
|
||||
const k = field(_('Key file'), key, pathHelp, { placeholder: '/etc/ssl/…/key', mono: true, plain: true });
|
||||
const { el: bad, say } = badLine();
|
||||
const ok = h('button', { type: 'button', class: 'btn accent' }, h('span', {}, _('Save'))) as HTMLButtonElement;
|
||||
ok.addEventListener('click', () =>
|
||||
once(ok, async () => {
|
||||
if (!c.check() || !k.check()) return;
|
||||
try {
|
||||
await save(c.value(), k.value());
|
||||
closeSheet();
|
||||
} catch (e) {
|
||||
say(errorText(e));
|
||||
shake(ok);
|
||||
}
|
||||
}),
|
||||
);
|
||||
const el = h(
|
||||
'div',
|
||||
{ class: 'view' },
|
||||
head(_('Use your own certificate')),
|
||||
sub(_('Paths on the router. Leave both empty to pick a certificate automatically.')),
|
||||
c.el,
|
||||
k.el,
|
||||
bad,
|
||||
h('div', { class: 'btnrow' }, h('button', { type: 'button', class: 'btn soft', onclick: () => closeSheet() }, _('Cancel')), ok),
|
||||
);
|
||||
return { el, label: _('Use your own certificate') };
|
||||
}
|
||||
|
||||
/** The certificate's own files; `save` stores both paths. */
|
||||
export const certFilesSheet = (cert: string, key: string, save: (cert: string, key: string) => Promise<void>) =>
|
||||
openSheet(() => certView(cert, key, save));
|
||||
@@ -0,0 +1,189 @@
|
||||
// Restoring a backup (one of the list's, or a file) and importing a JSON
|
||||
// export, in the portal's sheet: what is in it and the question, then the
|
||||
// work, then what came of it, in the same sheet. The
|
||||
// router does it in one call (backup_restore, backup_upload, import): its
|
||||
// steps stand on the job's stage (flows/job-stage.ts) in their order while
|
||||
// the call runs, with the time it has taken, and fill when it answers. The
|
||||
// result counts what Dawnline has now (the status read again) and names the
|
||||
// backup made just before.
|
||||
|
||||
import { api, type Backup } from '../api';
|
||||
import { h } from '../../portal/dom';
|
||||
import { closeSheet, glide, go, head, onLeave, openSheet, showing, sub, type View } from '../../portal/ui/sheet';
|
||||
import { once } from '../../portal/ui/feedback';
|
||||
import { badLine } from '../../portal/ui/bad-line';
|
||||
import { calm } from '../../portal/motion';
|
||||
import { bytes } from '../../shared/format';
|
||||
import { fmt, plural } from '../../shared/i18n';
|
||||
import { ic } from '../ui/icons';
|
||||
import { errorText } from '../ui/toast';
|
||||
import { mmss } from '../updater/jobs';
|
||||
import { reasonLabel } from '../system/model';
|
||||
import { putChildren } from '../../portal/ui/put';
|
||||
import { stage } from './job-stage';
|
||||
|
||||
export type Source = { kind: 'backup'; backup: Backup; when: string } | { kind: 'file' } | { kind: 'json' };
|
||||
|
||||
interface Picked {
|
||||
name: string;
|
||||
size: number;
|
||||
/** base64 (an archive) or the parsed export. */
|
||||
data: unknown;
|
||||
}
|
||||
|
||||
/** The router's steps, in its order (backup.uc backup_restore / import_json). */
|
||||
const steps = (json: boolean): string[] =>
|
||||
json
|
||||
? [_('Check the file'), _('Back up the current state'), _('Replace people, devices and servers'), _('Apply the settings')]
|
||||
: [_('Check the backup'), _('Back up the current state'), _('Restore the files'), _('Apply the settings')];
|
||||
|
||||
/** The call under way, then its end; `after` reads the page again. */
|
||||
function workView(src: Source, file: Picked | null, title: string, after: () => void): View {
|
||||
const json = src.kind === 'json';
|
||||
const list = steps(json);
|
||||
const s = stage({
|
||||
icon: 'backup',
|
||||
title,
|
||||
lead: _('Takes up to a minute. Keep this open.'),
|
||||
steps: list.map((t) => ({ title: t, state: 'wait' })),
|
||||
log: false,
|
||||
});
|
||||
const el = s.view.el;
|
||||
const t0 = Date.now();
|
||||
const tick = window.setInterval(() => s.time(mmss((Date.now() - t0) / 1000)), 1000);
|
||||
onLeave(() => clearInterval(tick));
|
||||
const close = (accent: boolean) =>
|
||||
h(
|
||||
'button',
|
||||
{ type: 'button', class: `btn ${accent ? 'accent' : 'soft'}`, onclick: () => closeSheet() },
|
||||
h('span', {}, accent ? _('Done') : _('Close')),
|
||||
);
|
||||
void (async () => {
|
||||
try {
|
||||
if (src.kind === 'backup') await api.backupRestore(src.backup.name);
|
||||
else if (src.kind === 'file') await api.backupUpload(file!.data);
|
||||
else await api.importJson(file!.data);
|
||||
} catch (e) {
|
||||
clearInterval(tick);
|
||||
after();
|
||||
if (!showing(el)) return;
|
||||
return s.end({
|
||||
tone: 'red',
|
||||
title: json ? _('Not imported') : _('Not restored'),
|
||||
text: `${errorText(e).replace(/\.$/, '')}. ${_('Nothing was changed.')}`,
|
||||
acts: [close(false)],
|
||||
});
|
||||
}
|
||||
clearInterval(tick);
|
||||
after();
|
||||
// the steps fill top to bottom as the answer lands, then make way for what came of it
|
||||
if (showing(el)) {
|
||||
s.steps(list.map((t) => ({ title: t, state: 'ok' })));
|
||||
await new Promise((r) => setTimeout(r, calm() ? 0 : 520));
|
||||
}
|
||||
const [st, bk] = await Promise.all([api.status(1).catch(() => null), api.backupList().catch(() => null)]);
|
||||
if (!showing(el)) return;
|
||||
const made = bk?.backups.find((b) => b.reason === (json ? 'pre-import' : 'pre-restore'));
|
||||
const counts = st
|
||||
? fmt(
|
||||
_('Dawnline has %s, %s and %s now.'),
|
||||
plural(st.people.length, '%s person', '%s people'),
|
||||
plural(
|
||||
st.people.reduce((n, p) => n + p.devices.length, 0),
|
||||
'%s device',
|
||||
'%s devices',
|
||||
),
|
||||
plural(st.servers.length, '%s server', '%s servers'),
|
||||
)
|
||||
: '';
|
||||
const kept = made ? fmt(_('What was there before is kept in the backup “%s”.'), reasonLabel(made.reason)) : '';
|
||||
s.end({
|
||||
tone: 'green',
|
||||
title: json ? _('Imported') : _('Restored'),
|
||||
text: [counts, kept].filter(Boolean).join(' '),
|
||||
acts: [close(true)],
|
||||
});
|
||||
})();
|
||||
return { ...s.view, asks: true };
|
||||
}
|
||||
|
||||
function view(src: Source, after: () => void): View {
|
||||
const json = src.kind === 'json';
|
||||
const title = json ? _('Import JSON') : _('Restore a backup');
|
||||
let file: Picked | null = null;
|
||||
const input = h('input', {
|
||||
type: 'file',
|
||||
accept: json ? '.json,application/json' : '.tar.gz,.tgz,application/gzip',
|
||||
class: 'vh',
|
||||
'aria-label': _('File'),
|
||||
}) as HTMLInputElement;
|
||||
const pick = h('label', { class: 'btn soft block fpick' }, input, ic(json ? 'file' : 'archive'), h('span', {}, _('Choose a file')));
|
||||
const what = h('div', { class: 'fsum', hidden: true });
|
||||
const { el: bad, say, unsay } = badLine();
|
||||
const ok = h(
|
||||
'button',
|
||||
{ type: 'button', class: 'btn warn', disabled: src.kind !== 'backup' },
|
||||
h('span', {}, json ? _('Import') : _('Restore')),
|
||||
) as HTMLButtonElement;
|
||||
const show = (name: string, size: number, line: string) => {
|
||||
putChildren(what, [
|
||||
h(
|
||||
'div',
|
||||
{ class: 'filecard' },
|
||||
h(
|
||||
'div',
|
||||
{ class: 'fc-row' },
|
||||
h('span', { class: 'filecard-ic' }, json ? '.json' : '.tgz'),
|
||||
h('span', { class: 't' }, h('span', { class: 'mono' }, name), h('span', {}, `${bytes(size)} · ${line}`)),
|
||||
),
|
||||
),
|
||||
]);
|
||||
what.hidden = false;
|
||||
pick.hidden = true;
|
||||
ok.disabled = false;
|
||||
};
|
||||
if (src.kind === 'backup') show(src.backup.name, src.backup.size, src.when);
|
||||
input.addEventListener('change', () => {
|
||||
const f = input.files?.[0];
|
||||
if (!f) return;
|
||||
unsay();
|
||||
const r = new FileReader();
|
||||
r.onload = () => {
|
||||
const res = String(r.result ?? '');
|
||||
let data: unknown = res.replace(/^data:[^,]*,/, '');
|
||||
if (json) {
|
||||
try {
|
||||
data = JSON.parse(res);
|
||||
} catch {
|
||||
input.value = '';
|
||||
return say(_('Not a JSON file.'));
|
||||
}
|
||||
}
|
||||
file = { name: f.name, size: f.size, data };
|
||||
glide(() => show(f.name, f.size, json ? _('Dawnline export') : _('Dawnline backup')), [what]);
|
||||
};
|
||||
r.onerror = () => say(_('The file could not be read.'));
|
||||
if (json) r.readAsText(f);
|
||||
else r.readAsDataURL(f);
|
||||
});
|
||||
ok.addEventListener('click', () => void once(ok, async () => go(() => workView(src, file, title, after))));
|
||||
const el = h(
|
||||
'div',
|
||||
{ class: 'view' },
|
||||
head(title),
|
||||
sub(
|
||||
json
|
||||
? _('People, devices and servers from a Dawnline export (usage history is not in it).')
|
||||
: _('A Dawnline backup: people, devices, servers and their keys.'),
|
||||
),
|
||||
pick,
|
||||
what,
|
||||
bad,
|
||||
h('p', { class: 'hint op-warn' }, _('Replaces everything Dawnline has now. The current state is backed up first.')),
|
||||
h('div', { class: 'btnrow' }, h('button', { type: 'button', class: 'btn soft', onclick: () => closeSheet() }, _('Cancel')), ok),
|
||||
);
|
||||
return { el, label: title, asks: true };
|
||||
}
|
||||
|
||||
/** Restore `src` (a backup of the list, a file to pick) or import JSON; `after` reads the page again once it is done. */
|
||||
export const restoreSheet = (src: Source, after: () => void) => openSheet(() => view(src, after));
|
||||
@@ -0,0 +1,196 @@
|
||||
// The one question before a server's staged changes are applied
|
||||
// (servers/pending.ts): what changes, which devices fetch their configuration
|
||||
// again after all of it (each counted once: of how many people, those of
|
||||
// people without access now, those not set up yet), and whether they stop
|
||||
// connecting meanwhile or keep working the old way. One change is asked in
|
||||
// its own words; several are named in a list under one title. After it the
|
||||
// page's rollout strip counts the devices (the router marks them stale).
|
||||
|
||||
import { h, type Kid } from '../../portal/dom';
|
||||
import { closeSheet, onClosed, openSheet } from '../../portal/ui/sheet';
|
||||
import { fmt, plural } from '../../shared/i18n';
|
||||
import type { Refetch } from '../servers/rollout';
|
||||
import type { Staged, Summary } from '../servers/pending';
|
||||
import { askView } from './ask';
|
||||
|
||||
/** The question's title for one change. */
|
||||
function title(c: Staged): string {
|
||||
if (c.title) return c.title;
|
||||
switch (c.kind) {
|
||||
case 'address':
|
||||
return fmt(_('Address for devices: %s?'), c.value);
|
||||
case 'port':
|
||||
return fmt(_('UDP port: %s?'), c.value);
|
||||
case 'subnet':
|
||||
return fmt(_('Tunnel network: %s?'), c.value);
|
||||
case 'dns':
|
||||
return fmt(_('DNS for devices: %s?'), c.value);
|
||||
case 'mtu':
|
||||
return fmt(_('MTU: %s?'), c.value);
|
||||
case 'keepalive':
|
||||
return fmt(_('Keep-alive: %s?'), c.value);
|
||||
case 'mesh':
|
||||
case 'rule':
|
||||
return c.apart ? _('Keep devices apart?') : fmt(_('Devices see each other: %s?'), c.value);
|
||||
case 'route':
|
||||
return fmt(_('Internet traffic: %s?'), c.value);
|
||||
case 'wan':
|
||||
return fmt(_('WAN: %s?'), c.value);
|
||||
case 'home':
|
||||
return _('Change the home networks?');
|
||||
case 'behind':
|
||||
return _('Change the networks behind routers?');
|
||||
case 'portal_routers':
|
||||
return fmt(_('Adding a router on people’s pages: %s?'), c.value);
|
||||
case 'portal_nets':
|
||||
return fmt(_('Changing a router’s networks on people’s pages: %s?'), c.value);
|
||||
case 'renew':
|
||||
return _('Generate new disguise values?');
|
||||
case 'disguise':
|
||||
return fmt(_('Disguise: %s?'), c.value);
|
||||
}
|
||||
}
|
||||
|
||||
/** What happens to the `n` devices until they fetch it, for one change. */
|
||||
function consequence(c: Staged, n: number): string {
|
||||
switch (c.kind) {
|
||||
case 'disguise':
|
||||
case 'renew':
|
||||
return plural(
|
||||
n,
|
||||
'%s device stops connecting until it fetches its configuration again: it has the old disguise.',
|
||||
'%s devices stop connecting until they fetch their configuration again: theirs has the old disguise.',
|
||||
);
|
||||
case 'address':
|
||||
return plural(
|
||||
n,
|
||||
'%s device stops connecting until it fetches its configuration again: it has the old address.',
|
||||
'%s devices stop connecting until they fetch their configuration again: theirs has the old address.',
|
||||
);
|
||||
case 'port':
|
||||
return plural(
|
||||
n,
|
||||
'%s device stops connecting until it fetches its configuration again: it has the old port.',
|
||||
'%s devices stop connecting until they fetch their configuration again: theirs has the old port.',
|
||||
);
|
||||
case 'subnet':
|
||||
return plural(
|
||||
n,
|
||||
'%s device stops connecting until it fetches its configuration again: its address is from the old network.',
|
||||
'%s devices stop connecting until they fetch their configuration again: their addresses are from the old network.',
|
||||
);
|
||||
case 'dns':
|
||||
return plural(
|
||||
n,
|
||||
'%s device keeps asking the old DNS until it fetches its configuration again. Its connection is not interrupted.',
|
||||
'%s devices keep asking the old DNS until they fetch their configuration again. Their connection is not interrupted.',
|
||||
);
|
||||
case 'mtu':
|
||||
return plural(
|
||||
n,
|
||||
'%s device stays on the old MTU until it fetches its configuration again. Its connection is not interrupted.',
|
||||
'%s devices stay on the old MTU until they fetch their configuration again. Their connection is not interrupted.',
|
||||
);
|
||||
case 'keepalive':
|
||||
return plural(
|
||||
n,
|
||||
'%s device keeps its old keep-alive until it fetches its configuration again. Its connection is not interrupted.',
|
||||
'%s devices keep their old keep-alive until they fetch their configuration again. Their connection is not interrupted.',
|
||||
);
|
||||
case 'mesh':
|
||||
return c.apart
|
||||
? `${_('The router stops letting devices reach each other at once.')} ${plural(
|
||||
n,
|
||||
'%s device fetches its configuration again to drop the extra routes.',
|
||||
'%s devices fetch their configuration again to drop the extra routes.',
|
||||
)}`
|
||||
: plural(
|
||||
n,
|
||||
'%s device sees the others once it fetches its configuration again. Until then it works the old way.',
|
||||
'%s devices see the others once they fetch their configuration again. Until then they work the old way.',
|
||||
);
|
||||
case 'home':
|
||||
return plural(
|
||||
n,
|
||||
'%s device reaches the new home networks once it fetches its configuration again. Until then it works the old way.',
|
||||
'%s devices reach the new home networks once they fetch their configuration again. Until then they work the old way.',
|
||||
);
|
||||
case 'behind':
|
||||
return plural(
|
||||
n,
|
||||
'%s device reaches these networks once it fetches its configuration again. Until then it works the old way.',
|
||||
'%s devices reach these networks once they fetch their configuration again. Until then they work the old way.',
|
||||
);
|
||||
// the router's own side: no device fetches anything for these (they are never asked about alone)
|
||||
case 'rule':
|
||||
case 'route':
|
||||
case 'wan':
|
||||
case 'portal_routers':
|
||||
case 'portal_nets':
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
/** The same for several changes at once: the worst of them says it. */
|
||||
const together = (s: Summary): string =>
|
||||
s.breaks
|
||||
? plural(
|
||||
s.refetch.n,
|
||||
'%s device stops connecting until it fetches its configuration again.',
|
||||
'%s devices stop connecting until they fetch their configuration again.',
|
||||
)
|
||||
: plural(
|
||||
s.refetch.n,
|
||||
'%s device works the old way until it fetches its configuration again. Its connection is not interrupted.',
|
||||
'%s devices work the old way until they fetch their configuration again. Their connection is not interrupted.',
|
||||
);
|
||||
|
||||
/** Whose devices they are, beyond the count. */
|
||||
const whose = (r: Refetch): Kid[] => [
|
||||
r.people > 1 ? ` ${plural(r.people, 'They belong to %s person.', 'They belong to %s people.')}` : null,
|
||||
r.paused
|
||||
? ` ${plural(r.paused, '%s of them belongs to someone without access now: it fetches it when access is back.', '%s of them belong to people without access now: they fetch it when access is back.')}`
|
||||
: null,
|
||||
r.fresh
|
||||
? ` ${plural(r.fresh, '%s more is not set up yet: it gets the new one right away.', '%s more are not set up yet: they get the new one right away.')}`
|
||||
: null,
|
||||
];
|
||||
|
||||
/** «3 devices fetch the configuration», after the toast's own words. */
|
||||
export const fetches = (n: number): string => plural(n, '%s device fetches the configuration', '%s devices fetch the configuration');
|
||||
|
||||
/**
|
||||
* Ask once about every staged change, then `run` them. Resolves with whether they were made (the question shut:
|
||||
* false; the router refusing: its reason in a toast, the question stays open).
|
||||
*/
|
||||
export function askChanges(list: Staged[], s: Summary, run: () => Promise<void>): Promise<boolean> {
|
||||
const one = list.length === 1 ? list[0] : null;
|
||||
const more = list.map((x) => x.more).filter(Boolean);
|
||||
const text: Kid[] = one
|
||||
? [h('span', {}, consequence(one, s.refetch.n)), ...whose(s.refetch), one.more ? ` ${one.more}` : null]
|
||||
: [
|
||||
h('span', { class: 'ask-list' }, ...list.map((x) => h('b', {}, x.label))),
|
||||
h('span', {}, together(s)),
|
||||
...whose(s.refetch),
|
||||
more.length ? ` ${more.join(' ')}` : null,
|
||||
];
|
||||
return new Promise((res) => {
|
||||
let took = false;
|
||||
openSheet(() =>
|
||||
askView({
|
||||
icon: 'refresh',
|
||||
tone: 'orange',
|
||||
title: one ? title(one) : plural(list.length, 'Apply %s change?', 'Apply %s changes?'),
|
||||
text,
|
||||
action: one ? _('Change') : _('Apply'),
|
||||
cls: 'warn',
|
||||
run: async () => {
|
||||
await run();
|
||||
took = true;
|
||||
closeSheet();
|
||||
},
|
||||
}),
|
||||
);
|
||||
onClosed(() => res(took));
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
// A device's set-up in the portal's sheet: which app (AmneziaWG: its .conf;
|
||||
// AmneziaVPN: its key), then in which form it is handed over (a QR code, the
|
||||
// .conf file, the plain text: a track of the three, the code first for a
|
||||
// phone or a tablet, the file for a computer or a router), and Copy and
|
||||
// Download under it. Showing it marks nothing as given out: that is what
|
||||
// making a configuration (Add, New keys) and the portal's fetch do. Inside a
|
||||
// flow (Add, New keys) the portal's way under the head says how the first connection goes
|
||||
// (portal/ui/wait-way.ts, watched on the router's status, flows/watch.ts):
|
||||
// once connected what is under it folds and the sheet closes by itself onto
|
||||
// the page. Show set-up has no such wait: it shows the forms and stays.
|
||||
|
||||
import type { ClientConfig, Device, Person, Status } from '../../shared/types';
|
||||
import { api } from '../api';
|
||||
import { h } from '../../portal/dom';
|
||||
import { glide, head, onLeave, openSheet, sub, type View } from '../../portal/ui/sheet';
|
||||
import { follow, waitWay } from '../../portal/ui/wait-way';
|
||||
import { vpnKey, vpnQrText } from '../../shared/vpnkey';
|
||||
import { fmt } from '../../shared/i18n';
|
||||
import { kindLabel } from '../../shared/format';
|
||||
import { tabs } from '../ui/tabs';
|
||||
import { ic } from '../ui/icons';
|
||||
import { loadQr, qrBox } from '../shell/qr';
|
||||
import { copyText, downloadFile } from '../ui/files';
|
||||
import { attempt } from '../ui/toast';
|
||||
import { statusWatcher } from './watch';
|
||||
import { putChildren } from '../../portal/ui/put';
|
||||
|
||||
type App = 'awg' | 'vpn';
|
||||
|
||||
export interface SetupCtx {
|
||||
person: Person;
|
||||
device: Device;
|
||||
/** The router's clock now (seconds). */
|
||||
now: () => number;
|
||||
/** A status the sheet read while it waited (the page repaints with it). */
|
||||
fresh?: (st: Status) => void;
|
||||
/** Once the sheet closed itself after the first connection. */
|
||||
done?: () => void;
|
||||
}
|
||||
|
||||
const handheld = (d: Device) => d.kind === 'phone' || d.kind === 'tablet';
|
||||
|
||||
/** One line of a configuration: a section's head in the accent, a key's name in the text's colour. */
|
||||
function confLine(line: string): Node {
|
||||
if (/^\s*\[.+\]\s*$/.test(line)) return h('span', { class: 'sec' }, line);
|
||||
const m = /^(\s*[A-Za-z0-9]+\s*=)(.*)$/.exec(line);
|
||||
return m ? h('span', {}, h('span', { class: 'k' }, m[1]), m[2]) : document.createTextNode(line);
|
||||
}
|
||||
|
||||
/** How the set-up is handed over: a code to scan, the file, or its text to read and copy. */
|
||||
type Form = 'qr' | 'file' | 'text';
|
||||
|
||||
/**
|
||||
* The set-up as a view: which app, then in which form (a QR code, the .conf file, the plain text; AmneziaVPN's key
|
||||
* has no file), the form itself, and Copy and Download under it. `way`: 'top' inside a flow (Add, New keys), where
|
||||
* the portal's way under the head waits for the first connection; null for Show set-up, which only shows it.
|
||||
*/
|
||||
export function setupView(c: SetupCtx, cfg: ClientConfig, way: 'top' | null): View {
|
||||
const d = c.device;
|
||||
let app: App = 'awg';
|
||||
let form: Form = handheld(d) ? 'qr' : 'file';
|
||||
let key = '';
|
||||
const keyOf = async () => (key ||= await vpnKey(cfg, cfg.server || c.person.name));
|
||||
const text = async () => (app === 'awg' ? cfg.conf : await keyOf());
|
||||
const box = h('div', { class: 'setup-show' });
|
||||
const forms = h('div', { class: 'setup-forms' });
|
||||
const dl = h(
|
||||
'button',
|
||||
{ type: 'button', class: 'btn soft', onclick: () => downloadFile(cfg.filename, cfg.conf, 'application/octet-stream') },
|
||||
ic('download'),
|
||||
h('span', {}, _('Download .conf')),
|
||||
);
|
||||
/**
|
||||
* The forms' track and the form picked, drawn from the text at hand. Not asked for here: the view must stand whole
|
||||
* the moment it is put in the sheet, which measures it then (drawn a moment later, the sheet took an empty
|
||||
* view's height and jumped when the code landed: the owner, 2026-11-12, «анимация размера модалки снапает»).
|
||||
*/
|
||||
const draw = (t: string) => {
|
||||
// AmneziaVPN takes a key, not a file: its forms are the code and the key's text
|
||||
if (app === 'vpn' && form === 'file') form = 'text';
|
||||
putChildren(forms, [
|
||||
tabs<Form>(
|
||||
[
|
||||
// «QR» alone: three names must fit a phone's track
|
||||
{ id: 'qr', label: 'QR', icon: 'qr' },
|
||||
...(app === 'awg' ? [{ id: 'file' as Form, label: '.conf', icon: 'file' }] : []),
|
||||
{ id: 'text', label: app === 'awg' ? _('Text') : _('Key'), icon: 'code' },
|
||||
],
|
||||
form,
|
||||
(f) => {
|
||||
form = f;
|
||||
void paint();
|
||||
},
|
||||
// drawn again on every pick: its pill goes on from the last one's place (ui/carry.ts)
|
||||
{ cls: 'forms', label: _('Form'), keep: 'setup-form' },
|
||||
).el,
|
||||
]);
|
||||
dl.hidden = app !== 'awg';
|
||||
if (form === 'qr')
|
||||
putChildren(box, [
|
||||
h(
|
||||
'div',
|
||||
{ class: 'inv-card su-qr' },
|
||||
qrBox(app === 'awg' ? t : vpnQrText(t)),
|
||||
h(
|
||||
'div',
|
||||
{ class: 'inv-code' },
|
||||
h('span', {}, _('Scan it with the app on the device')),
|
||||
h('b', {}, app === 'awg' ? 'AmneziaWG' : 'AmneziaVPN'),
|
||||
),
|
||||
),
|
||||
]);
|
||||
else if (form === 'file')
|
||||
putChildren(box, [
|
||||
h(
|
||||
'div',
|
||||
{ class: 'filecard' },
|
||||
h(
|
||||
'div',
|
||||
{ class: 'fc-row' },
|
||||
h('span', { class: 'filecard-ic' }, '.conf'),
|
||||
h(
|
||||
'span',
|
||||
{ class: 't' },
|
||||
h('span', { class: 'mono' }, cfg.filename),
|
||||
h('span', {}, _('Import the file in AmneziaWG on the device')),
|
||||
),
|
||||
),
|
||||
),
|
||||
]);
|
||||
else
|
||||
putChildren(box, [
|
||||
h(
|
||||
'pre',
|
||||
{
|
||||
class: `conf su-text${app === 'vpn' ? ' wrap' : ''}`,
|
||||
tabindex: '0',
|
||||
'aria-label': app === 'awg' ? cfg.filename : _('AmneziaVPN key'),
|
||||
},
|
||||
app === 'awg' ? t.split('\n').flatMap((l, i) => (i ? ['\n', confLine(l)] : [confLine(l)])) : t,
|
||||
),
|
||||
]);
|
||||
};
|
||||
/** Another form or app picked: the sheet glides to the new height and width, what changed comes into focus. */
|
||||
const paint = async () => {
|
||||
const t = await text();
|
||||
glide(() => draw(t), [box]);
|
||||
};
|
||||
const apps = tabs(
|
||||
[
|
||||
{ id: 'awg' as App, label: 'AmneziaWG', icon: 'amneziawg' },
|
||||
{ id: 'vpn' as App, label: 'AmneziaVPN', icon: 'amnezia' },
|
||||
],
|
||||
app,
|
||||
(a) => {
|
||||
app = a;
|
||||
void paint();
|
||||
},
|
||||
{ cls: 'apps', label: _('App') },
|
||||
);
|
||||
const body = h(
|
||||
'div',
|
||||
{ class: 'setup-b' },
|
||||
apps.el,
|
||||
forms,
|
||||
box,
|
||||
h(
|
||||
'div',
|
||||
{ class: 'btnrow' },
|
||||
h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
class: 'btn soft',
|
||||
onclick: async () => void copyText(await text(), app === 'awg' ? _('Configuration copied') : _('Key copied')),
|
||||
},
|
||||
ic('copy'),
|
||||
h('span', {}, _('Copy')),
|
||||
),
|
||||
dl,
|
||||
),
|
||||
);
|
||||
// the configuration is at hand (AmneziaWG is what a sheet opens on): drawn before the view is handed over
|
||||
draw(cfg.conf);
|
||||
const noun = kindLabel(d.kind).toLocaleLowerCase();
|
||||
const subline = sub(
|
||||
way === 'top'
|
||||
? fmt(_('%s · %s. Waiting for its first connection with the new configuration.'), c.person.name, noun)
|
||||
: `${c.person.name} · ${noun}`,
|
||||
);
|
||||
const title = fmt(_('Set-up · %s'), d.name);
|
||||
// Show set-up only shows it (the owner, 2026-11-11: no «waiting for a connection» there, only the forms)
|
||||
if (!way) return { el: h('div', { class: 'view setup-v' }, head(title), subline, body), label: title };
|
||||
const w = waitWay(d);
|
||||
const watch = statusWatcher(c.now(), c.fresh);
|
||||
const el = h('div', { class: 'view setup-v' }, head(title), subline, w.el, body);
|
||||
const f = follow(d, w, { sub: subline, rest: body, closed: c.done });
|
||||
onLeave(watch(d, f.seen, f.gaveUp));
|
||||
return { el, label: title };
|
||||
}
|
||||
|
||||
/** Show the set-up: the sheet with its forms, nothing more. */
|
||||
export async function showSetup(c: SetupCtx) {
|
||||
// the QR generator and the apps' marks come while the router answers (shell/qr.ts)
|
||||
const kit = loadQr().catch(() => undefined);
|
||||
const cfg = await attempt(() => api.deviceConfig(c.device.id));
|
||||
await kit;
|
||||
if (cfg) openSheet(() => setupView(c, cfg, null));
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
// One line of text, or a note, in the portal's sheet (a person's name, the
|
||||
// admin's note on them): the portal's field with its arrow, the router's
|
||||
// reason in red under it when it refuses, the sheet closing once it took.
|
||||
|
||||
import { h } from '../../portal/dom';
|
||||
import { closeSheet, head, hint, openSheet, type View } from '../../portal/ui/sheet';
|
||||
import { badLine } from '../../portal/ui/bad-line';
|
||||
import { once } from '../../portal/ui/feedback';
|
||||
import { shake } from '../../shared/shake';
|
||||
import { ic } from '../ui/icons';
|
||||
import { errorText } from '../ui/toast';
|
||||
|
||||
export interface TextSheet {
|
||||
title: string;
|
||||
value: string;
|
||||
placeholder: string;
|
||||
/** Several lines (a note). */
|
||||
long?: boolean;
|
||||
max: number;
|
||||
hint?: string;
|
||||
/** Why `v` is refused, or null. */
|
||||
refuse(v: string): string | null;
|
||||
/** Save it; rejects with the router's reason. */
|
||||
save(v: string): Promise<void>;
|
||||
}
|
||||
|
||||
function view(o: TextSheet): View {
|
||||
const input = (
|
||||
o.long
|
||||
? h('textarea', { rows: 1, maxlength: o.max, placeholder: o.placeholder, 'aria-label': o.title }, o.value)
|
||||
: h('input', {
|
||||
type: 'text',
|
||||
value: o.value,
|
||||
maxlength: o.max,
|
||||
placeholder: o.placeholder,
|
||||
'aria-label': o.title,
|
||||
autocomplete: 'off',
|
||||
'data-1p-ignore': true,
|
||||
})
|
||||
) as HTMLInputElement | HTMLTextAreaElement;
|
||||
const go = h('button', { class: 'go ready', type: 'submit', 'aria-label': _('Save') }, ic('arrow')) as HTMLButtonElement;
|
||||
const form = h('form', { class: `field${o.long ? ' long' : ''}`, autocomplete: 'off' }, input, go);
|
||||
const { el: err, say, unsay } = badLine();
|
||||
input.addEventListener('input', () => unsay());
|
||||
const save = async () => {
|
||||
const v = input.value.trim();
|
||||
const why = o.refuse(v);
|
||||
if (why) {
|
||||
say(why);
|
||||
shake(form);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await o.save(v);
|
||||
closeSheet();
|
||||
} catch (e) {
|
||||
say(errorText(e));
|
||||
shake(form);
|
||||
}
|
||||
};
|
||||
form.addEventListener('submit', (e) => {
|
||||
e.preventDefault();
|
||||
void once(go, save);
|
||||
});
|
||||
if (o.long)
|
||||
input.addEventListener('keydown', (e) => {
|
||||
if ((e as KeyboardEvent).key === 'Enter' && ((e as KeyboardEvent).metaKey || (e as KeyboardEvent).ctrlKey)) {
|
||||
e.preventDefault();
|
||||
void once(go, save);
|
||||
}
|
||||
});
|
||||
requestAnimationFrame(() => {
|
||||
input.focus({ preventScroll: true });
|
||||
input.setSelectionRange(input.value.length, input.value.length);
|
||||
});
|
||||
const el = h('div', { class: 'view' }, head(o.title), form, err, o.hint ? hint(o.hint) : null);
|
||||
return { el, label: o.title };
|
||||
}
|
||||
|
||||
export const textSheet = (o: TextSheet) => openSheet(() => view(o));
|
||||
@@ -0,0 +1,77 @@
|
||||
// Removing Dawnline from the router, in the portal's sheet: what goes (the
|
||||
// tunnels, firewall rules, access table, hostnames and the portal; people and
|
||||
// keys stay in a backup made first) and the word the router demands, typed
|
||||
// in the field. The button stays shut until the word is there. After it the
|
||||
// page reloads (the views have nothing left to show).
|
||||
|
||||
import { api } from '../api';
|
||||
import { h } from '../../portal/dom';
|
||||
import { openSheet, closeSheet, type View } from '../../portal/ui/sheet';
|
||||
import { once } from '../../portal/ui/feedback';
|
||||
import { badLine } from '../../portal/ui/bad-line';
|
||||
import { fmt } from '../../shared/i18n';
|
||||
import { glass } from '../ui/glass';
|
||||
import { errorText } from '../ui/toast';
|
||||
import { say } from '../shell/toast';
|
||||
|
||||
/** The word rpc uninstall demands: the same in every language. */
|
||||
const WORD = 'remove';
|
||||
|
||||
function view(): View {
|
||||
const input = h('input', {
|
||||
type: 'text',
|
||||
placeholder: WORD,
|
||||
'aria-label': _('Type the word to confirm'),
|
||||
autocomplete: 'off',
|
||||
autocapitalize: 'none',
|
||||
autocorrect: 'off',
|
||||
spellcheck: 'false',
|
||||
class: 'mono',
|
||||
'data-1p-ignore': true,
|
||||
}) as HTMLInputElement;
|
||||
const { el: bad, say: refuse, unsay } = badLine();
|
||||
const go = h('button', { type: 'button', class: 'btn red', disabled: true }, h('span', {}, _('Remove'))) as HTMLButtonElement;
|
||||
input.addEventListener('input', () => {
|
||||
unsay();
|
||||
go.disabled = input.value.trim() !== WORD;
|
||||
});
|
||||
go.addEventListener('click', () =>
|
||||
once(go, async () => {
|
||||
try {
|
||||
await api.uninstall(input.value.trim());
|
||||
} catch (e) {
|
||||
return refuse(errorText(e));
|
||||
}
|
||||
closeSheet();
|
||||
say(_('Dawnline removed'));
|
||||
setTimeout(() => location.reload(), 800);
|
||||
}),
|
||||
);
|
||||
const el = h(
|
||||
'div',
|
||||
{ class: 'view' },
|
||||
h(
|
||||
'div',
|
||||
{ class: 'ask' },
|
||||
glass('trash', 'red', 'gi xl'),
|
||||
h('h3', {}, _('Remove Dawnline?')),
|
||||
h(
|
||||
'p',
|
||||
{},
|
||||
fmt(
|
||||
_(
|
||||
'Everyone is disconnected and the tunnel, firewall rules and portal are removed. A backup is made first. Type “%s” to confirm.',
|
||||
),
|
||||
WORD,
|
||||
),
|
||||
),
|
||||
h('label', { class: 'field rm-f' }, input),
|
||||
bad,
|
||||
h('div', { class: 'btnrow' }, h('button', { type: 'button', class: 'btn soft', onclick: () => closeSheet() }, _('Cancel')), go),
|
||||
),
|
||||
);
|
||||
requestAnimationFrame(() => input.focus({ preventScroll: true }));
|
||||
return { el, label: _('Remove Dawnline?'), asks: true };
|
||||
}
|
||||
|
||||
export const uninstallSheet = () => openSheet(view);
|
||||
@@ -0,0 +1,173 @@
|
||||
// Dawnline's other versions in the portal's sheet: every release from GitHub
|
||||
// as rows of one list, newest first (the one installed and a pre-release
|
||||
// marked), five more at a press. A row opens the version's own page in the
|
||||
// same sheet: its notes (flows/whats-new.ts) and Install at their foot; going
|
||||
// back to an older version asks first. Under the list, a tag typed by hand.
|
||||
// The install itself is the page's (Dawnline's update job in its sheet), so a
|
||||
// pick closes this sheet and hands the tag over.
|
||||
|
||||
import { api, type Release } from '../api';
|
||||
import { h } from '../../portal/dom';
|
||||
import { closeSheet, glide, go, head, openSheet, showing, sub, type View } from '../../portal/ui/sheet';
|
||||
import { badLine } from '../../portal/ui/bad-line';
|
||||
import { shake } from '../../shared/shake';
|
||||
import { fmtDay } from '../../shared/format';
|
||||
import { fmt } from '../../shared/i18n';
|
||||
import { ic } from '../ui/icons';
|
||||
import { errorText } from '../ui/toast';
|
||||
import { askView } from './ask';
|
||||
import { notesView, unread } from './whats-new';
|
||||
import { putChildren } from '../../portal/ui/put';
|
||||
|
||||
/** A release tag as the router takes it (updates_run app@<tag>). */
|
||||
const TAG = /^v?[0-9][0-9A-Za-z.+~-]{0,40}$/;
|
||||
/** A page of releases, as the router reads them. */
|
||||
const PAGE = 5;
|
||||
|
||||
/** Whether a version may be installed now: yes, not while a job runs, never by a login that only views. */
|
||||
export type Can = 'yes' | 'busy' | 'view';
|
||||
|
||||
const older = (v: string, cur: string) => v.localeCompare(cur, undefined, { numeric: true }) < 0;
|
||||
|
||||
/** Pages already read (a failed one is not kept: opening it again asks once more). */
|
||||
const pages = new Map<number, Release[]>();
|
||||
|
||||
function view(cur: string, install: (tag: string) => void, can: Can): View {
|
||||
const busy = can !== 'yes';
|
||||
let shown = 0;
|
||||
let more = true;
|
||||
const rows: HTMLElement[] = [];
|
||||
const list = h('div', { class: 'vers' });
|
||||
const pick = (tag: string) => {
|
||||
const v = tag.replace(/^v/, '');
|
||||
if (!older(v, cur)) {
|
||||
closeSheet();
|
||||
return install(tag);
|
||||
}
|
||||
go(() =>
|
||||
askView({
|
||||
icon: 'dawnline',
|
||||
tone: 'orange',
|
||||
title: fmt(_('Install Dawnline %s?'), v),
|
||||
text: [
|
||||
fmt(_('It is older than %s. A backup of the settings is made first; restore it from Backups if something looks wrong.'), cur),
|
||||
],
|
||||
action: _('Install'),
|
||||
cls: 'warn',
|
||||
run: async () => {
|
||||
closeSheet();
|
||||
install(tag);
|
||||
},
|
||||
}),
|
||||
);
|
||||
};
|
||||
/** A version's own page: its notes, and what installs it (none for the one installed, or while a job runs). */
|
||||
const open = (r: Release) => {
|
||||
const v = r.tag.replace(/^v/, '');
|
||||
const foot =
|
||||
busy || v === cur
|
||||
? null
|
||||
: h(
|
||||
'button',
|
||||
{ type: 'button', class: `btn ${older(v, cur) ? 'warn' : 'accent'}`, onclick: () => pick(r.tag) },
|
||||
h('span', {}, fmt(_('Install %s'), v)),
|
||||
);
|
||||
go(() => notesView({ component: 'app', tag: r.tag, title: `Dawnline ${v}`, back: true, foot }));
|
||||
};
|
||||
const row = (r: Release) => {
|
||||
const v = r.tag.replace(/^v/, '');
|
||||
return h(
|
||||
'button',
|
||||
{ type: 'button', class: 'chk ver', onclick: () => open(r) },
|
||||
h(
|
||||
'span',
|
||||
{ class: 'chk-t' },
|
||||
h(
|
||||
'b',
|
||||
{},
|
||||
h('span', { class: 'mono' }, v),
|
||||
v === cur ? h('span', { class: 'ver-tag now' }, _('Installed')) : null,
|
||||
r.prerelease ? h('span', { class: 'ver-tag pre' }, _('Pre-release')) : null,
|
||||
),
|
||||
r.published ? h('span', {}, fmtDay(r.published)) : null,
|
||||
),
|
||||
ic('chevron', 'i ver-chev'),
|
||||
);
|
||||
};
|
||||
/** The list as it stands, and under it what there is to say or do: more of them, why there are none. */
|
||||
const draw = (tail: HTMLElement | null) =>
|
||||
glide(() =>
|
||||
putChildren(
|
||||
list,
|
||||
[rows.length ? h('div', { class: 'checks' }, ...rows) : null, tail].filter((x): x is HTMLElement => !!x),
|
||||
),
|
||||
);
|
||||
const moreBtn = () =>
|
||||
h('button', { type: 'button', class: 'btn soft sm ver-more', onclick: () => void read() }, h('span', {}, _('Show older')));
|
||||
const read = async () => {
|
||||
const at = shown + 1;
|
||||
let got = pages.get(at);
|
||||
if (!got) {
|
||||
draw(h('p', { class: 'hint' }, _('Loading versions…')));
|
||||
try {
|
||||
got = (await api.updatesReleases(at)).releases;
|
||||
pages.set(at, got);
|
||||
} catch (e) {
|
||||
if (showing(el)) draw(unread(fmt(_('Failed to load versions: %s'), errorText(e)), () => void read()));
|
||||
return;
|
||||
}
|
||||
if (!showing(el)) return;
|
||||
}
|
||||
shown = at;
|
||||
more = got.length >= PAGE;
|
||||
rows.push(...got.map(row));
|
||||
draw(more ? moreBtn() : rows.length ? null : h('p', { class: 'hint' }, _('No versions found.')));
|
||||
};
|
||||
|
||||
const field = h('input', {
|
||||
type: 'text',
|
||||
placeholder: _('Tag, e.g. 0.3.1'),
|
||||
'aria-label': _('Release tag'),
|
||||
autocomplete: 'off',
|
||||
autocapitalize: 'none',
|
||||
spellcheck: 'false',
|
||||
class: 'mono',
|
||||
'data-1p-ignore': true,
|
||||
}) as HTMLInputElement;
|
||||
const goBtn = h('button', { class: 'go', type: 'submit', 'aria-label': _('Install') }, ic('arrow'));
|
||||
const form = h('form', { class: 'field', autocomplete: 'off' }, field, goBtn);
|
||||
const { el: bad, say, unsay } = badLine();
|
||||
field.addEventListener('input', () => {
|
||||
unsay();
|
||||
goBtn.classList.toggle('ready', !!field.value.trim());
|
||||
});
|
||||
form.addEventListener('submit', (e) => {
|
||||
e.preventDefault();
|
||||
const t = field.value.trim();
|
||||
if (!t) return;
|
||||
if (!TAG.test(t)) {
|
||||
say(_('Enter a release tag like 0.3.1'));
|
||||
return shake(form);
|
||||
}
|
||||
pick(t);
|
||||
});
|
||||
const el = h(
|
||||
'div',
|
||||
{ class: 'view' },
|
||||
head(_('Other versions')),
|
||||
sub(
|
||||
can === 'busy'
|
||||
? fmt(_('Installed: %s. Another version can be installed once the job under way is over.'), cur)
|
||||
: fmt(_('Installed: %s. Every release on GitHub, newest first.'), cur),
|
||||
),
|
||||
list,
|
||||
busy ? null : h('p', { class: 'hint ver-name' }, _('A version by its tag')),
|
||||
busy ? null : form,
|
||||
busy ? null : bad,
|
||||
);
|
||||
void read();
|
||||
return { el, label: _('Other versions') };
|
||||
}
|
||||
|
||||
/** Dawnline's releases; `install` runs a picked tag on the page (`can`: whether one may start now). */
|
||||
export const versionsSheet = (cur: string, install: (tag: string) => void, can: Can) => openSheet(() => view(cur, install, can));
|
||||
@@ -0,0 +1,57 @@
|
||||
// The admin's watcher for the set-up sheet's way (portal/ui/wait-way.ts
|
||||
// Watcher): while the sheet waits for a device's first connection with its
|
||||
// new configuration, the status is read on the live revision (the agent moves
|
||||
// it when the device connects) and on a timer for what the revision does not
|
||||
// carry (its knocks: Device.setup), 5 s for the first minute, then 15 s, ten
|
||||
// minutes at most, not while the tab is hidden. Each answer is read into the
|
||||
// way's state (portal/way.ts).
|
||||
|
||||
import type { Device, Status } from '../../shared/types';
|
||||
import type { Watcher } from '../../portal/ui/wait-way';
|
||||
import { wayState, type WayState } from '../../portal/way';
|
||||
import { api } from '../api';
|
||||
import { onLiveChange } from '../state/live';
|
||||
|
||||
/** A watcher that counts from `opened` (router clock); `fresh` gets each status it read (the page repaints with it). */
|
||||
export function statusWatcher(opened: number, fresh?: (st: Status) => void): Watcher {
|
||||
return (d: Device, seen, gaveUp) => {
|
||||
let done = false;
|
||||
let timer = 0;
|
||||
let polls = 0;
|
||||
let last: WayState = 'waiting';
|
||||
const started = Date.now();
|
||||
const poll = async () => {
|
||||
clearTimeout(timer);
|
||||
timer = 0;
|
||||
if (done) return;
|
||||
if (last !== 'connected' && Date.now() - started > 600_000) {
|
||||
done = true;
|
||||
off();
|
||||
gaveUp();
|
||||
return;
|
||||
}
|
||||
if (document.visibilityState === 'visible') {
|
||||
const st = await api.status(1).catch(() => null);
|
||||
if (done) return;
|
||||
if (st) {
|
||||
fresh?.(st);
|
||||
const dev = st.people.flatMap((p) => p.devices).find((x) => x.id === d.id);
|
||||
const next = wayState(dev, opened);
|
||||
if (next !== last) {
|
||||
last = next;
|
||||
seen(next);
|
||||
}
|
||||
}
|
||||
}
|
||||
polls++;
|
||||
timer = window.setTimeout(poll, polls < 12 ? 5000 : 15000);
|
||||
};
|
||||
const off = onLiveChange(() => void poll());
|
||||
timer = window.setTimeout(poll, 2000);
|
||||
return () => {
|
||||
done = true;
|
||||
clearTimeout(timer);
|
||||
off();
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
// "What's new" in the portal's sheet: a release's notes (Dawnline by tag, or
|
||||
// the AmneziaWG build's release) as the router fetched them from GitHub,
|
||||
// without their "What's new" heading and Install section (updater/markdown.ts),
|
||||
// its date and whether it is a pre-release on one row with two quiet keys (Copy, the page on GitHub).
|
||||
// The same view is a version's page among Dawnline's other versions
|
||||
// (flows/versions.ts): a step with the way back and what installs it at its foot.
|
||||
|
||||
import { api } from '../api';
|
||||
import { h, put } from '../../portal/dom';
|
||||
import { glide, head, openSheet, showing, type View } from '../../portal/ui/sheet';
|
||||
import { fmtDay } from '../../shared/format';
|
||||
import { ic } from '../ui/icons';
|
||||
import { copyText } from '../ui/files';
|
||||
import { tip } from '../../portal/ui/tip';
|
||||
import { errorText } from '../ui/toast';
|
||||
import { forRouter, markdown, safeHref } from '../updater/markdown';
|
||||
import { putChildren } from '../../portal/ui/put';
|
||||
|
||||
export interface Notes {
|
||||
component: 'app' | 'amneziawg';
|
||||
tag: string;
|
||||
title: string;
|
||||
/** The AmneziaWG build whose release it is. */
|
||||
build?: string;
|
||||
/** A step of a flow: the head has the way back. */
|
||||
back?: boolean;
|
||||
/** What stands under the notes (a version's Install). */
|
||||
foot?: HTMLElement | null;
|
||||
}
|
||||
|
||||
/** What stands in a list's place while there is none: why, and the way to ask again. */
|
||||
export function unread(why: string, again: () => void): HTMLElement {
|
||||
return h(
|
||||
'div',
|
||||
{ class: 'rd-none' },
|
||||
h('span', {}, why),
|
||||
h('button', { type: 'button', class: 'btn soft sm', onclick: again }, h('span', {}, _('Try again'))),
|
||||
);
|
||||
}
|
||||
|
||||
export function notesView(o: Notes): View {
|
||||
const body = h('div', { class: 'notes' });
|
||||
const meta = h('div', { class: 'notes-meta' });
|
||||
const el = h(
|
||||
'div',
|
||||
{ class: 'view' },
|
||||
head(o.title, { back: o.back }),
|
||||
meta,
|
||||
body,
|
||||
o.foot ? h('div', { class: 'btnrow' }, o.foot) : null,
|
||||
);
|
||||
const read = () => {
|
||||
putChildren(body, [h('p', { class: 'hint' }, _('Loading release notes…'))]);
|
||||
void api
|
||||
.updatesNotes(o.component, o.tag, o.build ?? '')
|
||||
.then((r) => {
|
||||
if (!showing(el)) return;
|
||||
const text = forRouter(r.body || '');
|
||||
const url = safeHref(r.url);
|
||||
const copy = h(
|
||||
'button',
|
||||
{ type: 'button', class: 'knob notes-k', 'aria-label': _('Copy'), onclick: () => void copyText(text, _('Release notes copied')) },
|
||||
ic('copy'),
|
||||
);
|
||||
const open = url
|
||||
? h('a', { class: 'knob notes-k', href: url, target: '_blank', rel: 'noopener', 'aria-label': _('On GitHub') }, ic('open'))
|
||||
: null;
|
||||
tip(copy, () => _('Copy'));
|
||||
if (open) tip(open, () => _('On GitHub'));
|
||||
glide(() => {
|
||||
put(
|
||||
meta,
|
||||
r.published ? h('span', { class: 'notes-date' }, fmtDay(r.published)) : null,
|
||||
r.prerelease ? h('span', { class: 'notes-pre' }, _('Pre-release')) : null,
|
||||
h('span', { class: 'sp' }),
|
||||
// two quiet keys with their names as tooltips: words here wrapped to a second row on a phone
|
||||
text.trim() ? copy : null,
|
||||
url ? open : null,
|
||||
);
|
||||
putChildren(body, text.trim() ? markdown(text) : [h('p', { class: 'hint' }, _('This release has no notes.'))]);
|
||||
});
|
||||
})
|
||||
.catch((e) => showing(el) && glide(() => putChildren(body, [unread(errorText(e), () => glide(read))])));
|
||||
};
|
||||
read();
|
||||
return { el, label: o.title };
|
||||
}
|
||||
|
||||
/** The notes of `tag` in the sheet; `build`: the AmneziaWG build whose release it is. */
|
||||
export const whatsNew = (component: 'app' | 'amneziawg', tag: string, title: string, build?: string) =>
|
||||
openSheet(() => notesView({ component, tag, title, build }));
|
||||
@@ -1,512 +0,0 @@
|
||||
// Interfaces card (Server page): auto-detected WAN and LAN, plus a picker for
|
||||
// the interfaces that make up a server's home network.
|
||||
|
||||
import type { MeshMode, Server, Status } from '../shared/types';
|
||||
import { E } from './e';
|
||||
import { api, type IfaceCategory, type InterfacesData, type NetDevice } from './api';
|
||||
import { circleChips, homeServices } from './access';
|
||||
import { button } from './ui/button';
|
||||
import { attempt, notify } from './ui/toast';
|
||||
import { seg, sw } from './ui/controls';
|
||||
import { attachTip } from './ui/tooltip';
|
||||
import { warnNote } from './ui/layout';
|
||||
import { installMissing } from './pkgs';
|
||||
import { icon } from '../shared/icons';
|
||||
import { fill, fmt, locale, plural } from '../shared/i18n';
|
||||
|
||||
/** Groups of "Other interfaces", in order, with their headings. */
|
||||
const groups = (): [IfaceCategory, string][] => [
|
||||
['wan', 'WAN'],
|
||||
['ethernet', 'Ethernet'],
|
||||
['wifi', 'Wi-Fi'],
|
||||
['vpn', _('VPN & tunnels')],
|
||||
['other', _('Other')],
|
||||
];
|
||||
|
||||
const ICON: Record<NetDevice['kind'], string> = {
|
||||
wan: 'globe',
|
||||
ethernet: 'ethernet',
|
||||
bridge: 'bridge',
|
||||
wifi: 'wifi',
|
||||
vpn: 'tunnel',
|
||||
other: 'link',
|
||||
};
|
||||
|
||||
/**
|
||||
* "Internet like a home device" off: traffic leaves past the router's own
|
||||
* proxies and filters, while DNS still goes through the router, which may
|
||||
* answer with addresses only those proxies serve. Said wherever it is chosen.
|
||||
*/
|
||||
export function likeHomeOffText(ifname: string): (Node | string)[] {
|
||||
// The step to take, in bold.
|
||||
const add = E('b', {}, fill(_('add its interface %s to their source interfaces yourself'), E('span', { class: 'dl-mono' }, ifname)));
|
||||
return [
|
||||
...fill(
|
||||
_(
|
||||
'Off: internet traffic goes straight to the WAN, the fastest way. DNS still goes through this router. Proxies and filters here handle the tunnel only if you %s.',
|
||||
),
|
||||
add,
|
||||
),
|
||||
' ',
|
||||
// What breaks, not only what is missed: the one part to notice.
|
||||
E('span', { class: 'dl-warn' }, _('If the router’s DNS hands out proxy addresses, those sites won’t open without it.')),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* What "like a home device" costs: every packet crosses the router twice
|
||||
* (through the netns and back over the LAN bridge). Measured on a dual-core
|
||||
* MT7981: about 225 Mbit/s down without it, 160 with it, the CPU full either way.
|
||||
*/
|
||||
export function likeHomeCost(): HTMLElement {
|
||||
return warnNote(
|
||||
_(
|
||||
'Slower: every packet crosses the router twice. On a dual-core router expect up to a third less speed, and lost packets at full load.',
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/** Server → Access cards; `update` takes a new status without touching the draft. */
|
||||
export interface AccessCards {
|
||||
el: HTMLElement;
|
||||
update(st: Status): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Server → Access: how internet traffic leaves (Internet) and what home access
|
||||
* reaches (Home network: networks, devices reaching each other, services).
|
||||
* Both cards share one draft; either Save stores it. Changes that apply at
|
||||
* once (devices reaching each other, services, circles) call `refresh`, which
|
||||
* brings a new status here through `update`: the draft stays as it is.
|
||||
*/
|
||||
export function accessCards(srv: Server, first: Status, refresh: () => Promise<unknown>): AccessCards {
|
||||
const serverId = srv.id;
|
||||
let st = first;
|
||||
const root = E(
|
||||
'div',
|
||||
{ class: 'dl-stack gap16' },
|
||||
E('section', { class: 'dl-setsec' }, E('div', { class: 'dl-setsec-body' }, E('p', { class: 'dl-muted' }, _('Loading interfaces…')))),
|
||||
);
|
||||
let d: InterfacesData;
|
||||
let autoWan = true,
|
||||
wanDev = '',
|
||||
autoLan = true,
|
||||
lanLike = true,
|
||||
mesh: MeshMode = 'all';
|
||||
// "Other interfaces" stays open or folded across repaints.
|
||||
let otherOpen = false;
|
||||
// Built once: it reads the devices at home, which should not happen on every repaint.
|
||||
const services = homeServices(st, serverId, refresh);
|
||||
let lans = new Set<string>();
|
||||
let initial = '';
|
||||
|
||||
const snapshot = () => JSON.stringify([lanLike, autoWan, autoWan ? '' : wanDev, autoLan, [...lans].sort()]);
|
||||
const liveLan = () => d.detected.lan || d.saved.lan || '';
|
||||
const currentWan = () => (autoWan ? d.detected.wan || d.saved.wan : wanDev) || '';
|
||||
const byName = () => new Map(d.devices.map((x) => [x.name, x]));
|
||||
|
||||
/** Home devices as the server would use them after Save. */
|
||||
const homeDevs = (): NetDevice[] => {
|
||||
const m = byName();
|
||||
const names = [...(autoLan && liveLan() ? [liveLan()] : []), ...[...lans].filter((n) => n !== liveLan())];
|
||||
return names.filter((n) => n !== currentWan()).map((n) => m.get(n) ?? ({ name: n, nets: [], missing: true } as unknown as NetDevice));
|
||||
};
|
||||
|
||||
const take = (r: InterfacesData, resetChoice: boolean) => {
|
||||
d = r;
|
||||
if (resetChoice) {
|
||||
autoWan = r.config.auto_wan;
|
||||
wanDev = r.config.wan_device || r.detected.wan || r.saved.wan || '';
|
||||
autoLan = r.config.auto_lan;
|
||||
lanLike = r.config.lan_like;
|
||||
mesh = r.config.mesh ?? (r.config.device_mesh ? 'all' : 'off');
|
||||
lans = new Set(r.config.lan_devices);
|
||||
initial = snapshot();
|
||||
}
|
||||
paint();
|
||||
};
|
||||
|
||||
const load = async (reset: boolean) => {
|
||||
const r = await api.interfaces(serverId).catch((e: Error) => {
|
||||
notify(e.message, 'error');
|
||||
return null;
|
||||
});
|
||||
if (r) take(r, reset);
|
||||
};
|
||||
|
||||
/** Can be part of the home network (or already is). */
|
||||
function pickable(x: NetDevice): boolean {
|
||||
const isAuto = autoLan && x.name === liveLan();
|
||||
const blocked = !!x.own || !!x.master || x.name === currentWan() || isAuto;
|
||||
return isAuto || lans.has(x.name) || (!blocked && (x.nets.length > 0 || !!x.missing));
|
||||
}
|
||||
|
||||
function tile(x: NetDevice): HTMLElement {
|
||||
const isAuto = autoLan && x.name === liveLan();
|
||||
const isWan = x.name === currentWan();
|
||||
const sel = !isAuto && lans.has(x.name);
|
||||
const blocked = !!x.own || !!x.master || isWan || isAuto;
|
||||
const usable = !blocked && (x.nets.length > 0 || sel || !!x.missing);
|
||||
const noZone = (sel || isAuto) && !x.zone && !x.missing;
|
||||
const sub = x.missing
|
||||
? _('Not present right now')
|
||||
: x.own
|
||||
? _('This server')
|
||||
: x.master
|
||||
? fmt(_('Port of %s'), x.master)
|
||||
: isWan
|
||||
? `${_('Internet')}${x.zone ? ` · ${fmt(_('zone %s'), x.zone)}` : ''}`
|
||||
: x.nets.length
|
||||
? x.nets.join(', ')
|
||||
: _('No IPv4 network');
|
||||
const el = E(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
class: `dl-if${sel ? ' sel' : ''}${isAuto ? ' auto' : ''}${!usable && !sel && !isAuto ? ' off' : ''}${noZone ? ' warn' : ''}`,
|
||||
'aria-pressed': sel || isAuto ? 'true' : 'false',
|
||||
// aria-disabled, not disabled: the tooltip should still explain why.
|
||||
'aria-disabled': usable ? null : 'true',
|
||||
click: () => {
|
||||
if (!usable) return;
|
||||
if (lans.has(x.name)) lans.delete(x.name);
|
||||
else lans.add(x.name);
|
||||
paint();
|
||||
},
|
||||
},
|
||||
[
|
||||
E('span', { class: 'dl-if-ic' }, icon(ICON[x.kind] ?? 'link')),
|
||||
E('span', { class: 'dl-if-main' }, [E('span', { class: 'dl-if-name' }, x.name), E('span', { class: 'dl-if-sub' }, sub)]),
|
||||
isAuto ? E('span', { class: 'dl-if-badge ok' }, _('Auto')) : sel ? E('span', { class: 'dl-if-check' }, icon('check')) : '',
|
||||
],
|
||||
);
|
||||
attachTip(el, () => [
|
||||
E('div', { class: 'dl-tip-title' }, x.name),
|
||||
E('div', { class: 'dl-muted' }, [
|
||||
x.logical ? fmt(_('Interface %s'), x.logical) : _('No netifd interface'),
|
||||
' · ',
|
||||
x.zone ? fmt(_('zone %s'), x.zone) : _('no firewall zone'),
|
||||
]),
|
||||
x.members.length ? E('div', { class: 'dl-muted' }, fmt(_('Ports: %s'), x.members.join(', '))) : '',
|
||||
x.nets.length ? E('div', { class: 'dl-mono' }, x.nets.join(', ')) : '',
|
||||
noZone ? E('div', { class: 'dl-warn' }, _('Not in a firewall zone: the firewall rejects this traffic.')) : '',
|
||||
x.master ? E('div', { class: 'dl-muted' }, fmt(_('Choose %s to include it.'), x.master)) : '',
|
||||
]);
|
||||
return el;
|
||||
}
|
||||
|
||||
/** Tile colour: green while traffic really enters the LAN, orange when it should but can't. */
|
||||
function likeHomeTone(): string {
|
||||
const lh = d.like_home;
|
||||
// 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';
|
||||
}
|
||||
|
||||
function likeHomeText(): (Node | string)[] {
|
||||
const lh = d.like_home;
|
||||
if (!lanLike) return likeHomeOffText(srv.ifname);
|
||||
if (d.needs?.length)
|
||||
return [
|
||||
E('span', { class: 'dl-warn' }, fmt(_('Needs %s.'), new Intl.ListFormat(locale(), { type: 'conjunction' }).format(d.needs))),
|
||||
' ',
|
||||
_('Until they are installed, internet traffic goes straight to the WAN.'),
|
||||
];
|
||||
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 fill(
|
||||
_('Internet traffic enters %s as %s, so whatever handles home traffic (proxies, filters, DNS) handles it too.'),
|
||||
E('span', { class: 'dl-mono' }, lh.dev ?? ''),
|
||||
E('span', { class: 'dl-mono' }, lh.address ?? ''),
|
||||
);
|
||||
return [
|
||||
E('span', { class: 'dl-warn' }, fmt(_('Not working: %s'), lh.error ?? _('the link is down'))),
|
||||
' ',
|
||||
_('Internet traffic goes straight to the WAN for now.'),
|
||||
];
|
||||
}
|
||||
|
||||
const meshText = (m: MeshMode): string =>
|
||||
({
|
||||
off: _("Devices of different people never reach each other; a person's own devices don't either."),
|
||||
all: _('Devices of people with home access reach each other, like home devices do. Internet-only people never.'),
|
||||
circles: _('Within a circle: family sees family, guests see guests. Everyone reaches their own devices. Internet-only people never.'),
|
||||
})[m];
|
||||
|
||||
function setrow(
|
||||
ic: string,
|
||||
label: (Node | string)[] | string,
|
||||
sub: (Node | string)[] | string,
|
||||
ctl: Node | (Node | string)[] | '',
|
||||
tone = '',
|
||||
below?: Node,
|
||||
) {
|
||||
return E('div', { class: below ? 'dl-setrow head' : 'dl-setrow' }, [
|
||||
E('div', { class: 'dl-lh-main' }, [
|
||||
E('span', { class: `dl-need-ic ${tone}` }, icon(ic)),
|
||||
E('div', { class: 'dl-stack' }, [E('span', { class: 'dl-setrow-label' }, label), E('span', { class: 'dl-sub' }, sub), below ?? '']),
|
||||
]),
|
||||
E('div', { class: 'dl-setrow-ctl' }, ctl),
|
||||
]);
|
||||
}
|
||||
|
||||
const hint = (live: string | null, saved: string) => {
|
||||
const mono = (t: string) => E('span', { class: 'dl-mono' }, t);
|
||||
if (live)
|
||||
return E('span', {}, [
|
||||
' ',
|
||||
...(saved && saved !== live ? fill(_('Now: %s, was %s.'), mono(live), mono(saved)) : fill(_('Now: %s.'), mono(live))),
|
||||
]);
|
||||
return E('span', {}, [' ', ...(saved ? fill(_('Not found now: using %s.'), mono(saved)) : [_('Not found.')])]);
|
||||
};
|
||||
|
||||
function paint() {
|
||||
const wanSel = E(
|
||||
'select',
|
||||
{
|
||||
class: 'cbi-input-select',
|
||||
'aria-label': _('Internet interface'),
|
||||
change: (ev: Event) => {
|
||||
wanDev = (ev.target as HTMLSelectElement).value;
|
||||
paint();
|
||||
},
|
||||
},
|
||||
d.devices
|
||||
.filter((x) => !x.own && !x.master && x.zone && !x.missing)
|
||||
.map((x) =>
|
||||
E('option', { value: x.name, selected: x.name === wanDev ? 'selected' : null }, `${x.name} · ${fmt(_('zone %s'), x.zone)}`),
|
||||
),
|
||||
) as HTMLSelectElement;
|
||||
|
||||
const home = homeDevs();
|
||||
const nets = home.flatMap((x) => x.nets.map((n) => [n, x.name] as const));
|
||||
// Draft vs saved, per card: [lanLike, autoWan, wan, autoLan, lans].
|
||||
const now = JSON.parse(snapshot()) as unknown[];
|
||||
const was = JSON.parse(initial) as unknown[];
|
||||
const changed = (...i: number[]) => i.some((k) => JSON.stringify(now[k]) !== JSON.stringify(was[k]));
|
||||
const netDirty = changed(0, 1, 2);
|
||||
const homeDirty = changed(3, 4);
|
||||
const save = (on: boolean) =>
|
||||
button(
|
||||
_('Save'),
|
||||
async () => {
|
||||
const r = await attempt(
|
||||
() => api.serverInterfaces(serverId, autoWan, autoWan ? '' : wanDev, autoLan, [...lans], lanLike, mesh !== 'off', mesh),
|
||||
_('Access saved'),
|
||||
);
|
||||
if (!r) return;
|
||||
take(r, true);
|
||||
if (r.nets_changed && r.lan_only)
|
||||
notify(
|
||||
plural(
|
||||
r.lan_only,
|
||||
'%s person has Home-only access: their devices need the configuration again to reach the new networks.',
|
||||
'%s people have Home-only access: their devices need the configuration again to reach the new networks.',
|
||||
),
|
||||
'warning',
|
||||
10000,
|
||||
);
|
||||
},
|
||||
'positive',
|
||||
{ disabled: !on },
|
||||
);
|
||||
|
||||
const internet = E('section', { class: 'dl-setsec dl-ifcard' }, [
|
||||
E('div', { class: 'dl-setsec-body' }, [
|
||||
E('div', { class: 'dl-panel-head' }, [
|
||||
E('h3', {}, _('Internet')),
|
||||
E('span', { class: 'dl-spacer' }),
|
||||
E('span', { class: 'dl-sub' }, _('People with Internet or Both')),
|
||||
]),
|
||||
setrow(
|
||||
'home',
|
||||
_('Internet like a home device'),
|
||||
likeHomeText(),
|
||||
[
|
||||
lanLike && d.needs?.length ? button(_('Install'), () => installMissing('home', d.needs!, () => load(false)), 'positive') : '',
|
||||
sw(lanLike, _('Internet like a home device'), (v) => {
|
||||
lanLike = v;
|
||||
paint();
|
||||
}),
|
||||
],
|
||||
likeHomeTone(),
|
||||
lanLike ? likeHomeCost() : undefined,
|
||||
),
|
||||
setrow(
|
||||
'globe',
|
||||
_('Auto-detect WAN'),
|
||||
[
|
||||
_('The interface with the default route: the server port opens there and Internet access leaves through it.'),
|
||||
hint(d.detected.wan, d.saved.wan),
|
||||
],
|
||||
[
|
||||
autoWan ? '' : wanSel,
|
||||
sw(autoWan, _('Auto-detect WAN'), (v) => {
|
||||
autoWan = v;
|
||||
paint();
|
||||
}),
|
||||
],
|
||||
),
|
||||
]),
|
||||
E('div', { class: 'dl-setsec-foot' }, [
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-sub' },
|
||||
lanLike
|
||||
? [
|
||||
_('Internet like a home device'),
|
||||
currentWan() ? [' · ', ...fill(_('leaves through %s'), E('span', { class: 'dl-mono' }, currentWan()))] : '',
|
||||
]
|
||||
: currentWan()
|
||||
? fill(_('Internet straight to %s'), E('span', { class: 'dl-mono' }, currentWan()))
|
||||
: _('No WAN found'),
|
||||
),
|
||||
save(netDirty),
|
||||
]),
|
||||
]);
|
||||
|
||||
const meshSeg = seg(
|
||||
[
|
||||
['off', _('Off')],
|
||||
['all', _('Everyone')],
|
||||
['circles', _('Circles')],
|
||||
] as [MeshMode, string][],
|
||||
mesh,
|
||||
{
|
||||
label: _('Devices reach each other'),
|
||||
cls: 'sm',
|
||||
optimistic: false,
|
||||
// Applies at once, like the choices on a person's page.
|
||||
onChange: async (v) => {
|
||||
const t = { off: _('Off'), all: _('Everyone'), circles: _('Circles') }[v];
|
||||
if (!(await attempt(() => api.serverUpdate(serverId, { mesh: v }), fmt(_('Devices reach each other: %s'), t)))) return;
|
||||
mesh = v;
|
||||
d.config.mesh = v;
|
||||
paint();
|
||||
await refresh();
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const homeCard = E('section', { class: 'dl-setsec dl-ifcard' }, [
|
||||
E('div', { class: 'dl-setsec-body' }, [
|
||||
E('div', { class: 'dl-panel-head' }, [
|
||||
E('h3', {}, _('Home network')),
|
||||
E('span', { class: 'dl-spacer' }),
|
||||
E('span', { class: 'dl-sub' }, _('People with Home or Both')),
|
||||
button([icon('reset'), ' ', _('Rescan')], () => load(false), 'neutral', { title: _('Read the interfaces again') }),
|
||||
]),
|
||||
setrow(
|
||||
'network',
|
||||
_('Networks'),
|
||||
_(
|
||||
'Everyone with home access reaches these, unless their page leaves one out; their devices can be reached from here too. Click one to add or remove it.',
|
||||
),
|
||||
'',
|
||||
'',
|
||||
netPicker(),
|
||||
),
|
||||
setrow(
|
||||
'link',
|
||||
_('Devices reach each other'),
|
||||
meshText(mesh),
|
||||
meshSeg,
|
||||
'',
|
||||
mesh === 'circles' ? circleChips(st, serverId, refresh) : undefined,
|
||||
),
|
||||
services.el,
|
||||
]),
|
||||
E('div', { class: 'dl-setsec-foot' }, [
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-sub dl-if-summary' },
|
||||
nets.length
|
||||
? fill(
|
||||
_('Home access reaches %s'),
|
||||
E(
|
||||
'span',
|
||||
{},
|
||||
nets.flatMap(([n, dev], i) => [i ? ', ' : '', E('span', { class: 'dl-mono' }, n), ` (${dev})`]),
|
||||
),
|
||||
)
|
||||
: _('No home network: Home access reaches nothing but this router.'),
|
||||
),
|
||||
save(homeDirty),
|
||||
]),
|
||||
]);
|
||||
|
||||
// Keep the page where it is: replacing the cards would otherwise jump to the top.
|
||||
const y = window.scrollY;
|
||||
root.style.minHeight = `${root.offsetHeight}px`;
|
||||
dom.content(root, [internet, homeCard]);
|
||||
root.style.minHeight = '';
|
||||
window.scrollTo({ top: y });
|
||||
}
|
||||
|
||||
/** Interfaces that can be home networks as tiles; the rest folded, by kind. */
|
||||
function netPicker(): HTMLElement {
|
||||
const avail = d.devices.filter(pickable);
|
||||
const rest = d.devices.filter((x) => !pickable(x));
|
||||
return E('div', { class: 'dl-stack gap8 dl-netpick' }, [
|
||||
avail.length
|
||||
? E('div', { class: 'dl-ifgrid' }, avail.map(tile))
|
||||
: E('span', { class: 'dl-warn' }, _('No home network: Home access reaches nothing but this router.')),
|
||||
E('label', { class: 'dl-boxrow' }, [
|
||||
E('span', { class: 'dl-stack' }, [
|
||||
E('span', {}, _('Auto-detect LAN')),
|
||||
E('span', { class: 'dl-sub' }, [_('Adds the LAN this router uses.'), hint(d.detected.lan, d.saved.lan)]),
|
||||
]),
|
||||
sw(autoLan, _('Auto-detect LAN'), (v) => {
|
||||
autoLan = v;
|
||||
paint();
|
||||
}),
|
||||
]),
|
||||
rest.length
|
||||
? E(
|
||||
'details',
|
||||
{
|
||||
class: 'dl-params',
|
||||
open: otherOpen ? '' : null,
|
||||
toggle: (ev: Event) => (otherOpen = (ev.currentTarget as HTMLDetailsElement).open),
|
||||
},
|
||||
[
|
||||
E('summary', {}, [
|
||||
icon('chevron'),
|
||||
E('span', {}, _('Other interfaces')),
|
||||
E('span', { class: 'dl-pcount' }, String(rest.length)),
|
||||
]),
|
||||
E('div', { class: 'dl-params-body' }, [
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-sub' },
|
||||
_('The WAN, this server, ports and Wi-Fi of a bridge (they come with it) and interfaces without an IPv4 network.'),
|
||||
),
|
||||
...groups().map(([cat, label]) => {
|
||||
const list = rest.filter((x) => x.category === cat);
|
||||
return list.length
|
||||
? E('div', { class: 'dl-ifgroup' }, [E('h4', {}, label), E('div', { class: 'dl-ifgrid' }, list.map(tile))])
|
||||
: '';
|
||||
}),
|
||||
]),
|
||||
],
|
||||
)
|
||||
: '',
|
||||
]);
|
||||
}
|
||||
|
||||
load(true);
|
||||
return {
|
||||
el: root,
|
||||
update(n: Status) {
|
||||
st = n;
|
||||
services.update(n);
|
||||
if (d) paint();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,178 +0,0 @@
|
||||
// Invite card: a picture with the person's QR code, link and three steps,
|
||||
// made in the browser to share (Telegram, AirDrop) or print.
|
||||
|
||||
import type { Person } from '../shared/types';
|
||||
import { E } from './e';
|
||||
import { api } from './api';
|
||||
import { button } from './ui/button';
|
||||
import { closeModal, modal } from './ui/modal';
|
||||
import { copyText, downloadFile } from './ui/files';
|
||||
import { attempt, notify } from './ui/toast';
|
||||
import { icon } from '../shared/icons';
|
||||
import { qrSvg } from '../shared/qr';
|
||||
import { fill, fmt } from '../shared/i18n';
|
||||
|
||||
const W = 1080,
|
||||
H = 1512;
|
||||
/** One margin for everything: header, greeting and the QR tile share both edges. */
|
||||
const M = 96;
|
||||
const SANS = "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif";
|
||||
const MONO = 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace';
|
||||
|
||||
const esc = (s: string) => s.replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]!);
|
||||
|
||||
function cardSvg(p: Pick<Person, 'name'>, server: string, link: string): string {
|
||||
const url = new URL(link);
|
||||
const word = url.pathname.slice(1);
|
||||
const hi = fmt(_('Hi, %s'), p.name);
|
||||
// Long names shrink to stay on one line (roughly 0.58 em per character).
|
||||
const nameSize = Math.min(92, Math.floor((W - 2 * M) / (0.58 * hi.length)));
|
||||
const tile = W - 2 * M,
|
||||
top = 392,
|
||||
pad = 40;
|
||||
const qr = qrSvg(link, 2).replace('<svg ', `<svg x="${M + pad}" y="${top + pad}" width="${tile - 2 * pad}" height="${tile - 2 * pad}" `);
|
||||
const text = (x: number, y: number, size: number, fill: string, body: string, extra = '') =>
|
||||
`<text x="${x}" y="${y}" font-size="${size}" fill="${fill}" font-family="${SANS}" ${extra}>${body}</text>`;
|
||||
return (
|
||||
`<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}">` +
|
||||
`<rect width="${W}" height="${H}" rx="72" fill="#0b0b0b"/>` +
|
||||
// Mark and server name
|
||||
`<g transform="translate(${M} ${M})"><rect width="60" height="60" rx="15" fill="#fff"/>` +
|
||||
`<g transform="scale(.9375)"><path d="M14 38a18 18 0 0 1 36 0z" fill="#0b0b0b"/><rect x="12" y="43" width="40" height="4" rx="2" fill="#0b0b0b" opacity=".5"/></g></g>` +
|
||||
text(M + 82, M + 42, 36, '#a3a3a3', esc(server)) +
|
||||
// Greeting
|
||||
text(M, 276, nameSize, '#ffffff', esc(hi), 'font-weight="600"') +
|
||||
text(M, 340, 40, '#8a8a8a', esc(fmt(_('Scan to connect to %s'), server))) +
|
||||
// Big QR on a white tile, edge to edge with the text above
|
||||
`<rect x="${M}" y="${top}" width="${tile}" height="${tile}" rx="52" fill="#ffffff"/>` +
|
||||
qr +
|
||||
// The link: three words, then the host
|
||||
`<text x="${W / 2}" y="${top + tile + 100}" font-size="58" fill="#ffffff" font-family="${MONO}" text-anchor="middle">${esc(word)}</text>` +
|
||||
text(W / 2, top + tile + 156, 34, '#737373', esc(url.host), 'text-anchor="middle"') +
|
||||
`</svg>`
|
||||
);
|
||||
}
|
||||
|
||||
async function toPng(svg: string): Promise<Blob> {
|
||||
const img = new Image();
|
||||
img.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
|
||||
await img.decode();
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = W;
|
||||
canvas.height = H;
|
||||
canvas.getContext('2d')!.drawImage(img, 0, 0, W, H);
|
||||
return new Promise((resolve, reject) =>
|
||||
canvas.toBlob((b) => (b ? resolve(b) : reject(new Error(_('Could not draw the card')))), 'image/png'),
|
||||
);
|
||||
}
|
||||
|
||||
/** Who to invite; without `link` the card asks the router for the person's links (they are not in the status). */
|
||||
type Invitee = Pick<Person, 'id' | 'name'> & { link?: string | null; links?: string[] };
|
||||
|
||||
/** The personal link and its other addresses (person_links); null while the portal is off. */
|
||||
async function personLinks(id: string): Promise<{ link: string; links: string[] } | null> {
|
||||
const r = await attempt(() => api.personLinks(id));
|
||||
if (!r) return null;
|
||||
if (!r.link) {
|
||||
notify(_('The personal portal is off. Turn it on in Settings.'), 'warning');
|
||||
return null;
|
||||
}
|
||||
return { link: r.link, links: r.links ?? [] };
|
||||
}
|
||||
|
||||
/** Copy a person's personal link. */
|
||||
export async function copyPersonLink(id: string) {
|
||||
const r = await personLinks(id);
|
||||
if (r) await copyText(r.link, _('Personal link copied'));
|
||||
}
|
||||
|
||||
/**
|
||||
* The card with Copy link and Share / Download. Also the "is ready" step
|
||||
* after adding someone.
|
||||
*/
|
||||
export async function inviteCard(p: Invitee, server: string, opts: { title?: string; lead?: string } = {}) {
|
||||
let link = p.link;
|
||||
let links = p.links;
|
||||
if (link === undefined) {
|
||||
const r = await personLinks(p.id);
|
||||
if (!r) return;
|
||||
link = r.link;
|
||||
links = r.links;
|
||||
}
|
||||
if (!link) {
|
||||
notify(_('The personal portal is off. Turn it on in Settings.'), 'warning');
|
||||
return;
|
||||
}
|
||||
const href = link;
|
||||
const png = await attempt(() => toPng(cardSvg(p, server, href)));
|
||||
if (!png) return;
|
||||
const file = new File([png], `${p.id}-invite.png`, { type: 'image/png' });
|
||||
const url = URL.createObjectURL(png);
|
||||
const nav = navigator as Navigator & { canShare?: (d: unknown) => boolean };
|
||||
// Three tiers: the card as a file, the link through the share sheet (older
|
||||
// Android, Firefox on phones), else a download of the card.
|
||||
const canShareFile = !!nav.canShare?.({ files: [file] });
|
||||
const canShareLink = !canShareFile && typeof nav.share === 'function' && (nav.canShare?.({ url: href }) ?? true);
|
||||
const close = () => {
|
||||
URL.revokeObjectURL(url);
|
||||
closeModal();
|
||||
};
|
||||
const shareIt = async (data: ShareData) => {
|
||||
try {
|
||||
await nav.share(data);
|
||||
} catch {
|
||||
/* cancelled */
|
||||
}
|
||||
};
|
||||
const share = canShareFile
|
||||
? button([icon('link'), ' ', _('Share card')], () => shareIt({ files: [file], title: fmt(_('Invite %s'), p.name) }), 'positive')
|
||||
: canShareLink
|
||||
? button(
|
||||
[icon('link'), ' ', _('Share link')],
|
||||
() => shareIt({ url: href, title: fmt(_('Invite %s'), p.name), text: _('Your personal VPN link') }),
|
||||
'positive',
|
||||
)
|
||||
: button([icon('download'), ' ', _('Download card')], () => downloadFile(file.name, png), 'positive');
|
||||
modal(
|
||||
opts.title ?? fmt(_('Invite %s'), p.name),
|
||||
E('div', { class: 'dl-invite' }, [
|
||||
E('img', { src: url, alt: fmt(_('Invite card for %s'), p.name) }),
|
||||
E('div', { class: 'dl-invite-side' }, [
|
||||
E(
|
||||
'p',
|
||||
{ class: 'dl-muted' },
|
||||
opts.lead ?? fmt(_('Send %s the card or the link. They open it, add their devices and connect - no account needed.'), p.name),
|
||||
),
|
||||
E(
|
||||
'button',
|
||||
{ type: 'button', class: 'dl-invite-link', title: _('Copy link'), click: () => copyText(href, _('Personal link copied')) },
|
||||
[E('span', {}, href.replace(/^https:\/\//, '')), icon('copy')],
|
||||
),
|
||||
...(links ?? [])
|
||||
.filter((l) => l !== href)
|
||||
.map((l) =>
|
||||
E(
|
||||
'button',
|
||||
{ type: 'button', class: 'dl-invite-link alt', title: _('Copy this link'), click: () => copyText(l, _('Link copied')) },
|
||||
[
|
||||
E('span', {}, l.replace(/^https?:\/\//, '')),
|
||||
E('span', { class: `dl-pill ${l.startsWith('http:') ? 'warn' : ''}` }, l.startsWith('http:') ? 'HTTP' : _('Also')),
|
||||
icon('copy'),
|
||||
],
|
||||
),
|
||||
),
|
||||
E('ol', { class: 'dl-invite-steps' }, [
|
||||
E('li', {}, fill(_('Install %s on the device'), E('b', {}, 'AmneziaVPN'))),
|
||||
E('li', {}, _('Open the link or scan the code')),
|
||||
E('li', {}, _('Add the device and connect')),
|
||||
]),
|
||||
E('div', { class: 'dl-invite-actions' }, [
|
||||
share,
|
||||
button([icon('copy'), ' ', _('Copy link')], () => copyText(href, _('Personal link copied'))),
|
||||
]),
|
||||
]),
|
||||
]),
|
||||
[E('button', { class: 'cbi-button cbi-button-neutral', click: close }, _('Done'))],
|
||||
'wide',
|
||||
);
|
||||
}
|
||||
+5
-111
@@ -1,16 +1,12 @@
|
||||
// Activity log actions shared by Diagnostics, Settings, the person page and
|
||||
// the device drawer: export, and the clear / reset dialogs.
|
||||
// Downloading the activity log (the Log's ⋯, System › History and storage):
|
||||
// events and service log lines as CSV or JSON, names resolved, oldest first.
|
||||
// Clearing it is the Log's sheet (pages/log/clear.ts).
|
||||
|
||||
import type { LogEvent, Status } from '../shared/types';
|
||||
import { E } from './e';
|
||||
import { api, type LogCategory, type LogFilter, type ServiceLogEntry } from './api';
|
||||
import { button } from './ui/button';
|
||||
import { cancelButton, closeModal, modal } from './ui/modal';
|
||||
import type { ServiceLogEntry } from './api';
|
||||
import { downloadFile } from './ui/files';
|
||||
import { attempt, errorText, notify } from './ui/toast';
|
||||
import { CATEGORIES, categoryLabel, categoryOf, eventBy, sourceName } from './events/model';
|
||||
import { categoryOf, eventBy, sourceName } from './events/model';
|
||||
import { toCsv } from './events/csv';
|
||||
import { fmt, plural } from '../shared/i18n';
|
||||
|
||||
function names(st: Pick<Status, 'people'>) {
|
||||
const people = new Map(st.people.map((p) => [p.id, p.name]));
|
||||
@@ -71,105 +67,3 @@ export function exportEvents(
|
||||
};
|
||||
downloadFile(name, toCsv(cols, rows, head), 'text/csv');
|
||||
}
|
||||
|
||||
/** The ages the dialog offers, in days ('' = everything). */
|
||||
const AGES = ['', '7', '30', '90'];
|
||||
|
||||
const ageLabel = (v: string) => (v ? plural(Number(v), 'Older than %s day', 'Older than %s days') : _('Everything'));
|
||||
|
||||
const removed = (n: number) => (n ? plural(n, '%s event removed', '%s events removed') : _('Nothing matched'));
|
||||
|
||||
/**
|
||||
* Ask what to clear and do it. `base` pins person/device; the dialog lets you
|
||||
* pick a category (unless `category` is given) and an age.
|
||||
*/
|
||||
export function clearLogDialog(
|
||||
title: string,
|
||||
what: string,
|
||||
base: LogFilter,
|
||||
done: () => unknown,
|
||||
category?: LogCategory | 'system',
|
||||
withSystem = false,
|
||||
) {
|
||||
const cat = E('select', { class: 'cbi-input-select' }, [
|
||||
E('option', { value: '' }, _('All categories')),
|
||||
...CATEGORIES.map((c) => E('option', { value: c, selected: c === category ? 'selected' : null }, categoryLabel(c))),
|
||||
withSystem ? E('option', { value: 'system', selected: category === 'system' ? 'selected' : null }, _('System')) : '',
|
||||
]) as HTMLSelectElement;
|
||||
const age = E(
|
||||
'select',
|
||||
{ class: 'cbi-input-select' },
|
||||
AGES.map((v) => E('option', { value: v }, ageLabel(v))),
|
||||
) as HTMLSelectElement;
|
||||
modal(
|
||||
title,
|
||||
[
|
||||
E('p', { class: 'dl-muted' }, `${what} ${_('This cannot be undone; export first if you want a copy.')}`),
|
||||
E('label', { class: 'dl-fld' }, [E('span', { class: 'dl-fld-label' }, _('Category')), cat]),
|
||||
E('label', { class: 'dl-fld' }, [E('span', { class: 'dl-fld-label' }, _('Which events')), age]),
|
||||
],
|
||||
[
|
||||
cancelButton(),
|
||||
' ',
|
||||
button(
|
||||
_('Clear'),
|
||||
async () => {
|
||||
// The activity log first, then the service log ("System"; "All categories"
|
||||
// clears it too where it is shown). Each result is reported on its own.
|
||||
let n = 0;
|
||||
if (cat.value !== 'system') {
|
||||
try {
|
||||
n += (await api.logsClear({ ...base, category: cat.value, older_days: age.value })).removed;
|
||||
} catch (e) {
|
||||
notify(errorText(e), 'error', 10000);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (withSystem && (cat.value === 'system' || cat.value === '')) {
|
||||
try {
|
||||
n += (await api.serviceLogClear(age.value)).removed;
|
||||
} catch (e) {
|
||||
closeModal();
|
||||
// The router's reason last, as it came.
|
||||
const failed = fmt(_('The service log was not cleared: %s'), errorText(e));
|
||||
notify(cat.value === 'system' ? failed : `${fmt(_('Activity: %s.'), removed(n).toLowerCase())} ${failed}`, 'error', 10000);
|
||||
done();
|
||||
return;
|
||||
}
|
||||
}
|
||||
closeModal();
|
||||
notify(removed(n), 'success', 3000);
|
||||
done();
|
||||
},
|
||||
'negative',
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/** Confirm and reset traffic history for everyone, a person or a device. */
|
||||
export function resetUsageDialog(scope: 'all' | 'person' | 'device', id: string, label: string, done: () => unknown) {
|
||||
const body =
|
||||
scope === 'device'
|
||||
? fmt(_("Clears %s's daily and monthly traffic history. Their person's totals and data limit are not changed."), label)
|
||||
: scope === 'person'
|
||||
? fmt(_("Clears %s's traffic history and that of their devices. Their data limit starts again from zero."), label)
|
||||
: _('Clears traffic history for everyone. Data limits start again from zero.');
|
||||
modal(
|
||||
scope === 'all' ? _('Reset all traffic history?') : fmt(_('Reset traffic history for %s?'), label),
|
||||
[E('p', { class: 'dl-muted' }, body)],
|
||||
[
|
||||
cancelButton(),
|
||||
' ',
|
||||
button(
|
||||
_('Reset'),
|
||||
async () => {
|
||||
if (!(await attempt(() => api.usageClear(scope, id), _('Traffic history reset')))) return;
|
||||
closeModal();
|
||||
done();
|
||||
},
|
||||
'negative',
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
Vendored
+9
@@ -76,6 +76,9 @@ interface LuciRpc {
|
||||
filter?: (data: any, args: unknown[], ...extra: unknown[]) => any;
|
||||
reject?: boolean;
|
||||
}): (...args: any[]) => Promise<T>;
|
||||
/** Where LuCI sends its calls (uhttpd's /ubus, or LuCI's own door to it). */
|
||||
getBaseURL?(): string;
|
||||
getSessionID?(): string;
|
||||
}
|
||||
|
||||
interface LuciPoll {
|
||||
@@ -95,6 +98,8 @@ interface LuciDom {
|
||||
|
||||
interface LuciEnv {
|
||||
sessionid?: string;
|
||||
/** uhttpd's own ubus door (uhttpd-mod-ubus), where an event stream can be held; absent behind another web server. */
|
||||
ubuspath?: string;
|
||||
rpctimeout?: number;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
@@ -102,8 +107,12 @@ interface LuciEnv {
|
||||
interface LuciL {
|
||||
env: LuciEnv;
|
||||
url(...parts: string[]): string;
|
||||
/** false when the current view is read-only for this login (its ACL grants read only); LuCI 23.05+. */
|
||||
hasViewPermission?(): boolean | null;
|
||||
resolveDefault<T>(p: Promise<T>, def: T): Promise<T>;
|
||||
resource(...parts: string[]): string;
|
||||
/** Load a LuCI module (`dawnline.map` → resources/dawnline/map.js) once per page load: its instance. */
|
||||
require(name: string): Promise<unknown>;
|
||||
itemlist(node: Node, items: unknown[], separators?: unknown): HTMLElement;
|
||||
bind<F extends (...args: any[]) => any>(fn: F, self: unknown, ...args: unknown[]): F;
|
||||
raise(type: string, fmt: string, ...args: unknown[]): never;
|
||||
|
||||
+88
-58
@@ -1,66 +1,96 @@
|
||||
// LuCI module `dawnline.app`: one factory per admin view. The thin files in
|
||||
// view/dawnline/*.js do `return view.extend(app.<page>())`.
|
||||
// LuCI module `dawnline.app`: the admin's pages on the portal's design system
|
||||
// inside LuCI, one factory per view; the thin files in view/dawnline/*.js do
|
||||
// `return view.extend(app.<page>())` with `'require dawnline.app as app'`. A
|
||||
// page renders into a Shadow DOM host (shell/host.ts) with its own section row;
|
||||
// what floats above it goes in the layer on <body> (shell/layer.ts). Two
|
||||
// modules of its own come with it: the stylesheet (`dawnline.style`, loaded
|
||||
// with each view's data: shell/style.ts) and the map (`dawnline.map`, loaded
|
||||
// when a page draws one: shell/maps.ts). The old addresses (menu.d nodes kept
|
||||
// for bookmarks, links in notes and the history) are views here too, each
|
||||
// sending the browser on at once (shell/redirects.ts).
|
||||
|
||||
import { PeoplePage } from './pages/people';
|
||||
import { ServerPage } from './pages/server';
|
||||
import { SettingsPage } from './pages/settings';
|
||||
import { ComponentsPage } from './pages/components';
|
||||
import { PersonPage } from './pages/person';
|
||||
import { DiagnosticsPage } from './pages/diagnostics';
|
||||
import { styleNode } from './styles';
|
||||
import { standStill } from '../portal/motion';
|
||||
import { tipsLeaveWith } from '../portal/ui/tip';
|
||||
import { onNavigate } from './ui/nav';
|
||||
import { shadowHost } from './shell/host';
|
||||
import { useLayer } from './shell/layer';
|
||||
import { redirected } from './shell/moved';
|
||||
import { loadStyle } from './shell/style';
|
||||
import { pageView, type Page } from './shell/view';
|
||||
import { setPages, stagePage, type Kind } from './shell/pages';
|
||||
import { OverviewPage, type OverviewData } from './pages/overview';
|
||||
import { LogPage, type LogData } from './pages/log';
|
||||
import { ServerPage, type ServerData } from './pages/server';
|
||||
import { SettingsPage, type SettingsPageData } from './pages/settings';
|
||||
|
||||
interface Page {
|
||||
load(): Promise<any>;
|
||||
render(data: any): Node | Promise<Node>;
|
||||
/** No footer at all (otherwise LuCI's, without its form buttons). */
|
||||
noFooter?: boolean;
|
||||
}
|
||||
// The admin's pages stand still: a change is drawn in place at once; only a page or a view coming in (its blocks
|
||||
// rise, ui/entrance.ts) and what is opened or pressed move (a sheet, a menu, a toast, a switch, a track's pill, the
|
||||
// map). DESIGN.md › Motion › 16.
|
||||
standStill();
|
||||
// a tooltip goes with the page it stood on
|
||||
tipsLeaveWith(onNavigate);
|
||||
|
||||
function factory<P extends Page>(Cls: new () => P) {
|
||||
return () => {
|
||||
const page = new Cls();
|
||||
const v: Record<string, unknown> = {
|
||||
load: () => page.load(),
|
||||
render: async (data: unknown) => {
|
||||
const node = await page.render(data);
|
||||
const root = document.createElement('div');
|
||||
root.className = 'dl-root';
|
||||
root.append(styleNode(), node);
|
||||
return root;
|
||||
},
|
||||
addFooter(this: any) {
|
||||
return page.noFooter ? document.createElement('div') : this.super('addFooter', []);
|
||||
},
|
||||
};
|
||||
// No page is a LuCI form (changes go through RPC): nothing to Save & Apply.
|
||||
return Object.assign(v, { handleSave: null, handleSaveApply: null, handleReset: null });
|
||||
};
|
||||
}
|
||||
/** No LuCI form (changes go through RPC): no footer, nothing to Save & Apply. */
|
||||
const noForm = {
|
||||
addFooter: () => document.createElement('div'),
|
||||
handleSave: null,
|
||||
handleSaveApply: null,
|
||||
handleReset: null,
|
||||
};
|
||||
|
||||
// The old Overview address opens the Servers page (it holds each server's overview now).
|
||||
const overview = factory(ServerPage);
|
||||
const people = factory(PeoplePage);
|
||||
const server = factory(ServerPage);
|
||||
const settings = factory(SettingsPage);
|
||||
const person = factory(PersonPage);
|
||||
const diagnostics = factory(DiagnosticsPage);
|
||||
const updates = factory(ComponentsPage);
|
||||
|
||||
/** Health and Activity became Diagnostics tabs: old addresses and bookmarks go there. */
|
||||
function moved(tab: '' | 'log') {
|
||||
function factory<D>(Cls: new () => Page<D>, kind: Kind) {
|
||||
return () => ({
|
||||
load: () => {
|
||||
ui.menu?.flushCache();
|
||||
location.replace(`${L.url('admin/services/dawnline/diagnostics')}${tab ? `?tab=${tab}` : ''}`);
|
||||
return new Promise(() => {});
|
||||
},
|
||||
render: () => document.createElement('div'),
|
||||
handleSave: null,
|
||||
handleSaveApply: null,
|
||||
handleReset: null,
|
||||
...pageView(
|
||||
() => new Cls(),
|
||||
redirected,
|
||||
(page, got, css) => {
|
||||
useLayer(css);
|
||||
const { host, root } = shadowHost(css, 'dl-host');
|
||||
// the page on screen from here on: a move to another page of Dawnline's changes it in place (shell/pages.ts)
|
||||
stagePage(root, page, got, kind);
|
||||
return host;
|
||||
},
|
||||
loadStyle,
|
||||
),
|
||||
...noForm,
|
||||
});
|
||||
}
|
||||
const health = moved('');
|
||||
const activity = moved('log');
|
||||
|
||||
export { overview, people, person, activity, server, settings, health, diagnostics, updates };
|
||||
/** A node that only leads elsewhere now: its view sends the browser on. */
|
||||
function moved() {
|
||||
return () => ({
|
||||
load: () => redirected() ?? Promise.resolve(null),
|
||||
render: () => document.createElement('div'),
|
||||
...noForm,
|
||||
});
|
||||
}
|
||||
|
||||
const overview = factory<OverviewData>(OverviewPage, 'overview');
|
||||
const log = factory<LogData>(LogPage, 'log');
|
||||
// A server's page is two views: `server` (its Overview and its settings) and `people` (its people and their places,
|
||||
// the People page inside the server's frame, so every address of a person or a device stays what it was).
|
||||
const server = factory<ServerData>(ServerPage, 'server');
|
||||
const people = factory<ServerData>(ServerPage, 'server');
|
||||
// Settings sends its own old queries on (?section=, ?tab=) before it loads anything.
|
||||
const settings = factory<SettingsPageData>(SettingsPage, 'settings');
|
||||
|
||||
// every page by its kind, for a move from one to another inside the view
|
||||
setPages({
|
||||
overview: () => new OverviewPage(),
|
||||
log: () => new LogPage(),
|
||||
server: () => new ServerPage(),
|
||||
settings: () => new SettingsPage(),
|
||||
});
|
||||
|
||||
// A person and a device are panels of a server's People, Places its map view, the router's own settings sections of
|
||||
// Settings, Health a part of Overview: their nodes send the browser there.
|
||||
const person = moved();
|
||||
const device = moved();
|
||||
const places = moved();
|
||||
const system = moved();
|
||||
const activity = moved();
|
||||
const health = moved();
|
||||
const diagnostics = moved();
|
||||
const updates = moved();
|
||||
|
||||
export { overview, log, places, device, people, person, server, system, activity, health, diagnostics, settings, updates };
|
||||
@@ -0,0 +1,19 @@
|
||||
// LuCI module `dawnline.map`: the admin's map (map.ts: MapLibre on a globe,
|
||||
// its markers, plates and labels), a device's places under it
|
||||
// (places/render.ts) and their stylesheet, apart from the pages' module
|
||||
// (main.ts) so that one stays small. A page loads it on demand when it draws
|
||||
// a map (shell/maps.ts: L.require). Its own copy of what it shares with the
|
||||
// pages has no state of theirs: `bind` hands it the pages' layer, where the
|
||||
// marker card floats.
|
||||
|
||||
import css from './styles/shadow/maps.css';
|
||||
import { setLayer } from '../portal/ui/layer';
|
||||
import { ConnectionMap } from './map';
|
||||
import { PlacesView } from './places/render';
|
||||
|
||||
/** The pages' layer (shell/layer.ts): the marker card goes there, as the sheet and the menus do. */
|
||||
function bind(root: ShadowRoot) {
|
||||
setLayer(root);
|
||||
}
|
||||
|
||||
export { ConnectionMap, PlacesView, css, bind };
|
||||
+537
-66
@@ -8,11 +8,15 @@
|
||||
import type { Geo, GeoPoint, Person } from '../shared/types';
|
||||
import { E } from './e';
|
||||
import { ago, initials } from '../shared/format';
|
||||
import { fmt, num, plural } from '../shared/i18n';
|
||||
import { fmt, lang, num, plural } from '../shared/i18n';
|
||||
import { icon, iconSvg } from '../shared/icons';
|
||||
import { onNavigate } from './ui/nav';
|
||||
import { isDark } from './ui/theme';
|
||||
import { placeKey, shimmerOpacity } from './places/model';
|
||||
import { layer } from '../portal/ui/layer';
|
||||
import { EASE_IN, EASE_OUT, SMOOTH, calm, play } from '../portal/motion';
|
||||
import { appear } from '../portal/ui/morph';
|
||||
import { failureText } from './failure';
|
||||
|
||||
// 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';
|
||||
@@ -29,6 +33,25 @@ const STYLE_DARK = 'https://basemaps.cartocdn.com/gl/dark-matter-gl-style/style.
|
||||
const STYLE_LIGHT = 'https://basemaps.cartocdn.com/gl/positron-gl-style/style.json';
|
||||
|
||||
export type Range = 'online' | '24h' | '7d' | '30d';
|
||||
|
||||
/** A CSS cubic-bezier as a function of progress (0–1), for what a script moves frame by frame (the zones' fades). */
|
||||
function bezier(x1: number, y1: number, x2: number, y2: number): (x: number) => number {
|
||||
const at = (a: number, b: number, t: number) => 3 * a * t * (1 - t) ** 2 + 3 * b * t * t * (1 - t) + t ** 3;
|
||||
return (x) => {
|
||||
if (x <= 0 || x >= 1) return Math.min(1, Math.max(0, x));
|
||||
let lo = 0;
|
||||
let hi = 1;
|
||||
for (let i = 0; i < 24; i++) {
|
||||
const m = (lo + hi) / 2;
|
||||
if (at(x1, x2, m) < x) lo = m;
|
||||
else hi = m;
|
||||
}
|
||||
return at(y1, y2, (lo + hi) / 2);
|
||||
};
|
||||
}
|
||||
const curve = (css: string) => bezier(...((css.match(/[\d.]+/g) ?? []).map(Number) as [number, number, number, number]));
|
||||
const EASE_IN_FN = curve(EASE_IN);
|
||||
const EASE_OUT_FN = curve(EASE_OUT);
|
||||
const WINDOW: Record<Range, number> = { online: 0, '24h': 86400, '7d': 7 * 86400, '30d': 30 * 86400 };
|
||||
|
||||
let loading: Promise<any> | null = null;
|
||||
@@ -74,6 +97,8 @@ function loadMapLibre(host: HTMLElement): Promise<any> {
|
||||
}
|
||||
|
||||
/** A click on a marker brings the map at least this close (a city). */
|
||||
/** The map fades in over this long once its first whole frame is drawn (ms). */
|
||||
const MAP_IN = 420;
|
||||
const CLICK_ZOOM = 10;
|
||||
/** Places closer than this are one city: a click shows them together at city level. */
|
||||
const CITY_KM = 30;
|
||||
@@ -88,6 +113,47 @@ const LOD_MID = 7;
|
||||
/** mapcn's arc colours: its default blue for live tunnels, a neutral gray for recently seen. */
|
||||
const LIVE = '#3b82f6';
|
||||
const RECENT = '#8a8a8a';
|
||||
/** Markers' names stay this far inside the map's edges. */
|
||||
const EDGE_PX = 6;
|
||||
/** The basemap's place names (CARTO's layer ids): towns and cities, not countries or seas. */
|
||||
const BASE_PLACES = /^place_(city|capital|town|villages|hamlet|suburbs)/;
|
||||
/** The basemap's names that can be in the page's language: places, waters. */
|
||||
const BASE_NAMES = /^(place_|water)/;
|
||||
|
||||
/**
|
||||
* Initials for a marker, from the name's words alone: a part in brackets ("Kirill (guest)")
|
||||
* or a word with no letters ("—", "2") would give "K(" or "K2".
|
||||
*/
|
||||
export function markInitials(name: string): string {
|
||||
const words = (s: string) =>
|
||||
s
|
||||
.split(/\s+/)
|
||||
.map((w) => w.replace(/[^\p{L}\p{N}]/gu, ''))
|
||||
.filter((w) => /\p{L}/u.test(w));
|
||||
// Brackets and all ("(guest)" alone): its letters.
|
||||
const own = words(name.replace(/\([^)]*\)|\[[^\]]*\]/g, ' '));
|
||||
const all = own.length ? own : words(name);
|
||||
return initials(all.length ? all.join(' ') : name);
|
||||
}
|
||||
|
||||
/**
|
||||
* A basemap name in language `lg` where the tiles have it, else as the style writes it. A zoom
|
||||
* step stays on top (MapLibre takes zoom there alone): each of its outputs gets the name.
|
||||
*/
|
||||
function inLanguage(field: unknown, lg: string): unknown {
|
||||
const own = ['get', `name:${lg}`];
|
||||
if (Array.isArray(field) && field[0] === 'step') return field.map((x, i) => (i >= 2 && i % 2 === 0 ? ['coalesce', own, x] : x));
|
||||
return ['coalesce', own, field];
|
||||
}
|
||||
|
||||
/** A rectangle on the map (px from its top left corner). */
|
||||
interface Box {
|
||||
l: number;
|
||||
t: number;
|
||||
r: number;
|
||||
b: number;
|
||||
}
|
||||
const hits = (a: Box, b: Box, gap = 2) => a.l < b.r + gap && b.l < a.r + gap && a.t < b.b + gap && b.t < a.b + gap;
|
||||
|
||||
/**
|
||||
* mapcn's arc (buildArcCoordinates): a quadratic Bézier between two
|
||||
@@ -122,6 +188,8 @@ export function arc(from: [number, number], to: [number, number], curvature = 0.
|
||||
export interface MapCallbacks {
|
||||
openPerson: (personId: string) => void;
|
||||
openDevice: (personId: string, deviceId: string) => void;
|
||||
/** A page that lists the places beside the map (People › Map): a marker picks its city there (placeKey) instead of opening its card. */
|
||||
pickPlace?: (key: string) => void;
|
||||
}
|
||||
|
||||
export interface MapData {
|
||||
@@ -198,7 +266,20 @@ export class ConnectionMap {
|
||||
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 = '';
|
||||
/** Each group's accuracy zone (one per city: placeKey), for hiding it once all of the city's people fold away. */
|
||||
private zoneOf = new Map<string, string>();
|
||||
/** The basemap's town layers and their own filters (namePlaces adds to them); the names last hidden. */
|
||||
private baseFilters = new Map<string, unknown>();
|
||||
private namesKey: string | null = null;
|
||||
/** The plates of people (pileUp) where they stand this frame, for their names (layoutLabels). */
|
||||
private pileSpots: { el: HTMLElement; x: number; y: number; city: string }[] = [];
|
||||
/** Each name's first gap from its marker (its CSS margin), kept while it is flipped to the other side. */
|
||||
private labelGap = new WeakMap<HTMLElement, number>();
|
||||
private focused: string | null = null;
|
||||
/** What the last fit framed: the way back from a city (showCity). */
|
||||
private lastFit: [number, number][] = [];
|
||||
/** A city the page holds the camera on (showCity): a fresh status does not frame everyone again meanwhile. */
|
||||
private held: string | null = null;
|
||||
/** Destroyed: a mount still waiting for the library stops there instead of drawing into a dropped element. */
|
||||
private dead = false;
|
||||
/** A device's places (its window) by placeKey: what the replay switches on and off. */
|
||||
@@ -213,6 +294,19 @@ export class ConnectionMap {
|
||||
private card: HTMLElement;
|
||||
readonly el: HTMLElement;
|
||||
private status: HTMLElement;
|
||||
/** In a rescope's redraw: what goes fades, what comes blurs in, the camera glides on SMOOTH. */
|
||||
private crossing = false;
|
||||
/** The zones on the map (by place) and their last features; a crossing's fades under way, by zone. */
|
||||
private zoneShown = new Set<string>();
|
||||
private zoneFeat = new Map<string, { properties: { zone: string } }>();
|
||||
private zoneFade = new Map<
|
||||
string,
|
||||
{ f: { properties: { zone: string } }; k: number; from: number; to: number; t0: number; ms: number; ease: (x: number) => number }
|
||||
>();
|
||||
private zoneRaf = 0;
|
||||
private drew!: () => void;
|
||||
/** Once the map has drawn its first whole frame (its style and what it shows are in): it fades in then (mount). */
|
||||
readonly drawn = new Promise<void>((r) => (this.drew = r));
|
||||
|
||||
constructor(
|
||||
private cb: MapCallbacks,
|
||||
@@ -230,7 +324,7 @@ export class ConnectionMap {
|
||||
try {
|
||||
this.gl = await loadMapLibre(this.el);
|
||||
} catch (e) {
|
||||
this.status.textContent = (e as Error).message;
|
||||
this.status.textContent = failureText(e);
|
||||
return;
|
||||
}
|
||||
if (this.dead) return;
|
||||
@@ -250,6 +344,21 @@ export class ConnectionMap {
|
||||
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());
|
||||
// The map comes in, it does not strike (the owner, 2026-11-12: «сделай чтобы карты появлялись плавно»): its
|
||||
// canvas and its markers stay unseen until the first whole frame is drawn (the style, the tiles in sight, our
|
||||
// layers), then fade in together. Every map of the admin is this one, so it is done here, once; the box it
|
||||
// stands in is there from the first frame. With less motion asked for the fade is short.
|
||||
const stage = this.map.getCanvasContainer();
|
||||
stage.style.opacity = '0';
|
||||
this.map.once('load', () => {
|
||||
this.drew();
|
||||
stage.style.opacity = '';
|
||||
if (this.dead) return;
|
||||
stage.animate(
|
||||
{ opacity: [0, 1] },
|
||||
{ duration: matchMedia('(prefers-reduced-motion: reduce)').matches ? 160 : MAP_IN, easing: 'cubic-bezier(0.23, 1, 0.32, 1)' },
|
||||
);
|
||||
});
|
||||
// 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');
|
||||
@@ -282,7 +391,8 @@ export class ConnectionMap {
|
||||
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.addSource('dl-areas', { type: 'geojson', data: { type: 'FeatureCollection', features: [] }, promoteId: 'zone' });
|
||||
this.zoneFade.clear();
|
||||
this.map.addLayer({
|
||||
id: 'dl-area',
|
||||
type: 'circle',
|
||||
@@ -290,10 +400,13 @@ export class ConnectionMap {
|
||||
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],
|
||||
// ×k: a zone coming or going in a crossing (rescope) fades by its feature state
|
||||
'circle-opacity': ['*', ['coalesce', ['feature-state', 'k'], 1], ['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],
|
||||
'circle-stroke-opacity': ['*', ['coalesce', ['feature-state', 'k'], 1], ['case', ['get', 'online'], 0.35, 0.15]],
|
||||
// Soft at the edge as it grows: an approximate place has no sharp border.
|
||||
'circle-blur': ['interpolate', ['linear'], ['zoom'], 5, 0, 8, 0.25],
|
||||
},
|
||||
});
|
||||
// A device's move in its replay: a dotted arc, transparent but where the shimmer is (band, bandAt).
|
||||
@@ -316,9 +429,45 @@ export class ConnectionMap {
|
||||
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.baseLabels();
|
||||
this.draw();
|
||||
}
|
||||
|
||||
/**
|
||||
* The basemap's words in the page's language where the tiles have it (CARTO writes places in
|
||||
* English); its own filters kept, to hide the towns our markers name (namePlaces).
|
||||
*/
|
||||
private baseLabels() {
|
||||
this.baseFilters.clear();
|
||||
this.namesKey = null;
|
||||
const lg = lang().split('-')[0];
|
||||
for (const l of this.map.getStyle()?.layers ?? []) {
|
||||
if (l.type !== 'symbol' || !l.layout?.['text-field']) continue;
|
||||
if (lg !== 'en' && BASE_NAMES.test(l.id)) this.map.setLayoutProperty(l.id, 'text-field', inLanguage(l.layout['text-field'], lg));
|
||||
if (BASE_PLACES.test(l.id)) this.baseFilters.set(l.id, l.filter ?? null);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The basemap's town names where our markers name the place (the server's chip, a place's
|
||||
* label): a second name, often in another language, under or beside ours. A person's page
|
||||
* and a device's window name every place they show: the basemap's towns go there.
|
||||
*/
|
||||
private namePlaces(cities: string[]) {
|
||||
const all = !!(this.data?.person || this.data?.device);
|
||||
const key = all ? '*' : [...new Set(cities.filter(Boolean))].sort().join('|');
|
||||
if (key === this.namesKey) return;
|
||||
this.namesKey = key;
|
||||
const lg = lang().split('-')[0];
|
||||
const named = ['literal', key.split('|')];
|
||||
const ours = ['any', ...['name', `name:${lg}`, 'name:en'].map((f) => ['in', ['coalesce', ['get', f], ''], named])];
|
||||
for (const [id, base] of this.baseFilters) {
|
||||
if (!this.map.getLayer(id)) continue;
|
||||
this.map.setLayoutProperty(id, 'visibility', all ? 'none' : 'visible');
|
||||
if (!all) this.map.setFilter(id, key ? (base ? ['all', base, ['!', ours]] : ['!', ours]) : base);
|
||||
}
|
||||
}
|
||||
|
||||
setRange(r: Range) {
|
||||
this.range = r;
|
||||
this.fitKey = null;
|
||||
@@ -330,8 +479,105 @@ export class ConnectionMap {
|
||||
this.draw();
|
||||
}
|
||||
|
||||
/**
|
||||
* Another scope of the same map (a person's places ↔ one device's): the markers that go fade where they stand
|
||||
* (out, b4, 180 EASE_IN), the new ones blur in (280 / 60 EASE_OUT), the zones fade with them, and the camera glides
|
||||
* from where it is to the new framing on SMOOTH; a second rescope takes each on from where it is.
|
||||
*/
|
||||
rescope(data: MapData) {
|
||||
this.dropCard();
|
||||
this.before = null;
|
||||
this.data = data;
|
||||
this.crossing = true;
|
||||
try {
|
||||
this.draw();
|
||||
} finally {
|
||||
this.crossing = false;
|
||||
}
|
||||
}
|
||||
|
||||
/** A marker of the old scope fades where it stands (from how it shows: one still coming in, from as far as it came). */
|
||||
private leave(m: any) {
|
||||
const el = m.getElement() as HTMLElement;
|
||||
const cs = getComputedStyle(el);
|
||||
const o = +cs.opacity;
|
||||
const prior = el.getAnimations();
|
||||
el.style.pointerEvents = 'none';
|
||||
el.setAttribute('aria-hidden', 'true');
|
||||
const a = play(
|
||||
el,
|
||||
[
|
||||
{ opacity: o, filter: cs.filter === 'none' ? 'blur(0px)' : cs.filter },
|
||||
{ opacity: 0, filter: 'blur(4px)' },
|
||||
],
|
||||
{ duration: 180 * o, easing: EASE_IN, fill: 'forwards' },
|
||||
);
|
||||
prior.forEach((x) => x.cancel());
|
||||
a.onfinish = () => m.remove();
|
||||
}
|
||||
|
||||
/**
|
||||
* The zones, by place: at once, or in a crossing faded (feature state k): the ones that go 1 → 0 (180 EASE_IN),
|
||||
* the new ones 0 → 1 (280 / 60 EASE_OUT), each from where it is; the gone ones leave the source once faded.
|
||||
*/
|
||||
private setZones(features: { properties: { zone: string } }[]) {
|
||||
const src = this.map.getSource('dl-areas');
|
||||
const now = performance.now();
|
||||
if (!this.crossing || calm()) {
|
||||
cancelAnimationFrame(this.zoneRaf);
|
||||
this.zoneRaf = 0;
|
||||
this.zoneFade.clear();
|
||||
this.map.removeFeatureState({ source: 'dl-areas' });
|
||||
src.setData({ type: 'FeatureCollection', features });
|
||||
this.zoneShown = new Set(features.map((f) => f.properties.zone));
|
||||
this.zoneFeat = new Map(features.map((f) => [f.properties.zone, f]));
|
||||
return;
|
||||
}
|
||||
const next = new Map(features.map((f) => [f.properties.zone, f]));
|
||||
const was = new Map(this.zoneFade);
|
||||
this.zoneFade.clear();
|
||||
for (const [z, f] of next) {
|
||||
const o = was.get(z);
|
||||
const k = o ? o.k : this.zoneShown.has(z) ? 1 : 0;
|
||||
this.zoneFade.set(z, { f, k, from: k, to: 1, t0: now + 60, ms: 280 * (1 - k), ease: EASE_OUT_FN });
|
||||
}
|
||||
for (const z of new Set([...this.zoneShown, ...was.keys()])) {
|
||||
if (next.has(z)) continue;
|
||||
const o = was.get(z);
|
||||
const f = o?.f ?? this.zoneFeat.get(z);
|
||||
const k = o ? o.k : 1;
|
||||
if (f && k > 0) this.zoneFade.set(z, { f, k, from: k, to: 0, t0: now, ms: 180 * k, ease: EASE_IN_FN });
|
||||
}
|
||||
for (const [z, x] of this.zoneFade) this.map.setFeatureState({ source: 'dl-areas', id: z }, { k: x.k });
|
||||
src.setData({ type: 'FeatureCollection', features: [...this.zoneFade.values()].map((x) => x.f) });
|
||||
this.zoneShown = new Set(next.keys());
|
||||
this.zoneFeat = new Map([...this.zoneFade].map(([z, x]) => [z, x.f]));
|
||||
cancelAnimationFrame(this.zoneRaf);
|
||||
const step = (t: number) => {
|
||||
if (!this.map) return;
|
||||
let busy = false;
|
||||
for (const [z, x] of this.zoneFade) {
|
||||
const q = x.ms ? Math.min(1, Math.max(0, (t - x.t0) / x.ms)) : 1;
|
||||
x.k = x.from + (x.to - x.from) * x.ease(q);
|
||||
this.map.setFeatureState({ source: 'dl-areas', id: z }, { k: x.k });
|
||||
if (q < 1) busy = true;
|
||||
}
|
||||
if (busy) {
|
||||
this.zoneRaf = requestAnimationFrame(step);
|
||||
return;
|
||||
}
|
||||
this.zoneRaf = 0;
|
||||
const gone = [...this.zoneFade].filter(([, x]) => x.to === 0).map(([z]) => z);
|
||||
if (!gone.length) return;
|
||||
gone.forEach((z) => this.zoneFade.delete(z));
|
||||
src.setData({ type: 'FeatureCollection', features: [...this.zoneFade.values()].map((x) => x.f) });
|
||||
};
|
||||
this.zoneRaf = requestAnimationFrame(step);
|
||||
}
|
||||
|
||||
destroy() {
|
||||
this.dead = true;
|
||||
cancelAnimationFrame(this.zoneRaf);
|
||||
this.dropCard();
|
||||
for (const p of this.piles.values()) p.marker.remove();
|
||||
this.piles.clear();
|
||||
@@ -377,7 +623,10 @@ export class ConnectionMap {
|
||||
const groups = this.groups(visiblePoints(data, this.range));
|
||||
// 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();
|
||||
for (const m of this.markers) {
|
||||
if (this.crossing) this.leave(m);
|
||||
else m.remove();
|
||||
}
|
||||
this.markers = [];
|
||||
|
||||
// Every marker in its city: the IP gives no more, so people sharing a city (or the server's)
|
||||
@@ -386,15 +635,27 @@ export class ConnectionMap {
|
||||
const placed = groups.map((g) => ({ g, at: spots?.get(g.key) ?? ([g.lon, g.lat] as [number, number]) }));
|
||||
this.slots = [];
|
||||
|
||||
this.map.getSource('dl-areas').setData({
|
||||
type: 'FeatureCollection',
|
||||
// The accuracy zone stays on the city itself.
|
||||
features: placed.map(({ g }) => ({
|
||||
// The accuracy zone stays on the city itself, once per city: a zone per person there would
|
||||
// stack their translucent discs into an opaque one. Live while anyone there is.
|
||||
const zones = new Map<string, { online: boolean; at: [number, number] }>();
|
||||
this.zoneOf.clear();
|
||||
for (const { g } of placed) {
|
||||
const k = placeKey(g);
|
||||
this.zoneOf.set(g.key, k);
|
||||
const z = zones.get(k);
|
||||
if (z) z.online ||= g.online;
|
||||
else zones.set(k, { online: g.online, at: [g.lon, g.lat] });
|
||||
}
|
||||
// the zones' filter again at the next declutter (who is in which zone may have changed)
|
||||
this.hiddenKey = '\0';
|
||||
this.setZones(
|
||||
[...zones].map(([zone, z]) => ({
|
||||
type: 'Feature',
|
||||
properties: { online: g.online, key: g.key },
|
||||
geometry: { type: 'Point', coordinates: [g.lon, g.lat] },
|
||||
properties: { online: z.online, zone },
|
||||
geometry: { type: 'Point', coordinates: z.at },
|
||||
})),
|
||||
});
|
||||
);
|
||||
this.namePlaces([home?.city ?? '', ...placed.map(({ g }) => g.city)]);
|
||||
this.map.getSource('dl-arcs').setData({
|
||||
type: 'FeatureCollection',
|
||||
features: home
|
||||
@@ -409,6 +670,12 @@ export class ConnectionMap {
|
||||
// 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.
|
||||
// No server on the map (the scope became a person's or a device's places): its plate goes with it, or
|
||||
// paintDock() would look for the hub of a map that has none.
|
||||
if (!home) {
|
||||
this.dock = null;
|
||||
this.dockKey = '';
|
||||
}
|
||||
if (home) {
|
||||
const host = E('span', { class: 'dl-mk-host' });
|
||||
host.innerHTML = `<span class="dl-mk-host-tile">${iconSvg('server', 'dl-mk-host-ic')}</span>`;
|
||||
@@ -437,6 +704,7 @@ export class ConnectionMap {
|
||||
const person = data.people.find((x) => x.id === g.person);
|
||||
if (data.person) {
|
||||
const el = data.device ? this.deviceMarker(g, at, person, numbers.get(placeKey(g)) ?? 0) : this.placeMarker(g, at, person);
|
||||
el.dataset.city = placeKey(g);
|
||||
this.add(el, at);
|
||||
continue;
|
||||
}
|
||||
@@ -454,7 +722,7 @@ export class ConnectionMap {
|
||||
: fmt(N_(n, '%s: %s device in an unknown city', '%s: %s devices in an unknown city'), person?.name ?? _('Someone'), num(n)),
|
||||
},
|
||||
[
|
||||
E('span', { class: 'dl-mk-av' }, [initials(person?.name ?? '?'), badge]),
|
||||
E('span', { class: 'dl-mk-av' }, [markInitials(person?.name ?? '?'), badge]),
|
||||
E('span', { class: 'dl-mk-label below' }, g.city || g.cc || '?'),
|
||||
],
|
||||
);
|
||||
@@ -483,7 +751,13 @@ export class ConnectionMap {
|
||||
.map((x) => x.g.key)
|
||||
.sort()
|
||||
.join(';');
|
||||
if (key !== this.fitKey && !this.popup) {
|
||||
if (key !== this.fitKey && !this.popup && this.held) {
|
||||
// the page holds a city: framed again when it lets go
|
||||
this.fitKey = key;
|
||||
const coords: [number, number][] = placed.map((x) => x.at);
|
||||
if (home && (!coords.length || this.range !== 'online' || placed.some((x) => x.g.online))) coords.push([home.lon, home.lat]);
|
||||
this.lastFit = coords;
|
||||
} else if (key !== this.fitKey && !this.popup) {
|
||||
const animate = this.fitted && !this.fitBlind;
|
||||
this.fitBlind = !this.el.clientWidth || !this.el.clientHeight;
|
||||
this.fitKey = key;
|
||||
@@ -496,7 +770,8 @@ export class ConnectionMap {
|
||||
} 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.lastFit = coords;
|
||||
this.fit(coords, animate, this.crossing);
|
||||
}
|
||||
}
|
||||
this.status.textContent = placed.length || home ? '' : _('No locations yet');
|
||||
@@ -505,6 +780,7 @@ export class ConnectionMap {
|
||||
}
|
||||
|
||||
private add(el: HTMLElement, at: [number, number], fixed = false, who?: string, where?: string, key?: string, g?: Group) {
|
||||
if (g) el.dataset.city = placeKey(g);
|
||||
// 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');
|
||||
if (key && this.piledKeys.has(key)) el.classList.add('piled');
|
||||
@@ -512,6 +788,8 @@ export class ConnectionMap {
|
||||
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);
|
||||
// a crossing's new marker blurs in where it stands
|
||||
if (this.crossing) appear(el);
|
||||
this.markers.push(marker);
|
||||
this.slots.push({ marker, el, at, fixed, who, where, g });
|
||||
}
|
||||
@@ -554,12 +832,15 @@ export class ConnectionMap {
|
||||
Object.assign(it, { r: 0, fixed: true });
|
||||
});
|
||||
this.pileUp(items);
|
||||
// A folded person leaves no trace either: their accuracy zone and arc go with their marker.
|
||||
// A folded person leaves no trace either: their arc goes with their marker, and their city's
|
||||
// zone once everyone there has folded away.
|
||||
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);
|
||||
const open = new Set([...this.zoneOf].filter(([g]) => !this.foldedKeys.has(g)).map(([, z]) => z));
|
||||
const gone = [...new Set(this.zoneOf.values())].filter((z) => !open.has(z));
|
||||
if (this.map.getLayer('dl-area')) this.map.setFilter('dl-area', ['!', ['in', ['get', 'zone'], ['literal', gone]]]);
|
||||
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]);
|
||||
@@ -569,14 +850,161 @@ export class ConnectionMap {
|
||||
// Hovering lights a person. A marker or avatar that went from under the pointer (a plate split
|
||||
// or closed as the map zoomed) sends no mouseleave: the light goes once nothing is hovered.
|
||||
if (this.focused && !this.el.querySelector('.dl-mk:hover, .dl-mk-face:hover')) this.focus(null);
|
||||
// The server's plate reaches right while people ride in it: markers keep clear of all of it,
|
||||
// not only of the server's tile (a row of circles along it, as tall as the plate).
|
||||
const hub = this.slots.findIndex((s) => s.fixed);
|
||||
if (hub >= 0 && this.merged.length && this.dock) {
|
||||
const host = this.dock.parentElement as HTMLElement;
|
||||
const r = host.offsetHeight / 2;
|
||||
const from = items[hub].x + host.offsetWidth / 2;
|
||||
const to = from + this.dock.offsetWidth;
|
||||
for (let x = from + r; x < to + r / 2; x += r) items.push({ x: Math.min(x, to - r), y: items[hub].y, r: r + 3, fixed: true });
|
||||
}
|
||||
// Past the markers come the people plates (fixed, in the spreading only to be moved clear of).
|
||||
const at = items.map((it) => ({ x: it.x, y: it.y }));
|
||||
separate(items).forEach(([dx, dy], i) => {
|
||||
const m = this.slots[i];
|
||||
if (!m || m.fixed) return;
|
||||
if (items[i].fixed) [dx, dy] = [0, 0];
|
||||
m.marker.setOffset([dx, dy]);
|
||||
pointer(m.el, dx, dy);
|
||||
at[i] = { x: items[i].x + dx, y: items[i].y + dy };
|
||||
});
|
||||
this.layoutLabels(at);
|
||||
}
|
||||
|
||||
/**
|
||||
* Markers' names, where the markers now stand (`at`, by slot): each inside the map (moved
|
||||
* sideways at its edges, under the marker still; to the marker's other side at the top or
|
||||
* bottom), clear of the other names, the markers and the map's own controls (the credits'
|
||||
* "i", a device window's replay plate); a name with no room fades out. Where people are, a
|
||||
* city is named once: on the server's chip when it is the server's, else on its first plate or
|
||||
* marker (live, then most recent first). The server's name and the place the replay is on
|
||||
* always show.
|
||||
*/
|
||||
private layoutLabels(at: { x: number; y: number }[]) {
|
||||
const W = this.el.clientWidth;
|
||||
const H = this.el.clientHeight;
|
||||
if (!W || !H || !this.data) return;
|
||||
const far = this.el.classList.contains('dl-lod-far');
|
||||
const people = !this.data.person && !this.data.device;
|
||||
const bodyOf = (el: HTMLElement) =>
|
||||
el.querySelector(':scope > .dl-mk-host, :scope > .dl-mk-av, :scope > .dl-mk-tile, :scope > .dl-mk-pile-box') as HTMLElement | null;
|
||||
type Cand = {
|
||||
lab: HTMLElement;
|
||||
owner: HTMLElement;
|
||||
x: number;
|
||||
y: number;
|
||||
h: number;
|
||||
w: number;
|
||||
lh: number;
|
||||
down: boolean;
|
||||
rank: number;
|
||||
ts: number;
|
||||
city: string;
|
||||
keep: boolean;
|
||||
};
|
||||
const cands: Cand[] = [];
|
||||
const bodies: { owner: HTMLElement; box: Box }[] = [];
|
||||
// Reads first, all of them (one layout), then the writes.
|
||||
const add = (
|
||||
owner: HTMLElement,
|
||||
x: number,
|
||||
y: number,
|
||||
o: { rank: number; ts?: number; city?: string; keep?: boolean; named?: boolean },
|
||||
) => {
|
||||
const body = bodyOf(owner);
|
||||
const bw = body?.offsetWidth ?? 0;
|
||||
const bh = body?.offsetHeight ?? 0;
|
||||
// The server's plate reaches right while people ride in it.
|
||||
const dock = body?.classList.contains('docked') ? ((body.querySelector('.dl-mk-dock') as HTMLElement | null)?.offsetWidth ?? 0) : 0;
|
||||
bodies.push({ owner, box: { l: x - bw / 2, r: x + bw / 2 + dock, t: y - bh / 2, b: y + bh / 2 } });
|
||||
const lab = owner.querySelector(':scope > .dl-mk-label') as HTMLElement | null;
|
||||
if (!lab || o.named === false) return;
|
||||
if (!this.labelGap.has(lab)) {
|
||||
const cs = getComputedStyle(lab);
|
||||
this.labelGap.set(lab, parseFloat(lab.classList.contains('below') ? cs.marginTop : cs.marginBottom) || 4);
|
||||
}
|
||||
cands.push({
|
||||
lab,
|
||||
owner,
|
||||
x,
|
||||
y,
|
||||
h: owner.offsetHeight,
|
||||
w: lab.offsetWidth,
|
||||
lh: lab.offsetHeight,
|
||||
down: lab.classList.contains('below'),
|
||||
rank: o.rank,
|
||||
ts: o.ts ?? 0,
|
||||
city: people ? (o.city ?? '') : '',
|
||||
keep: !!o.keep,
|
||||
});
|
||||
};
|
||||
this.slots.forEach((s, i) => {
|
||||
if (s.el.classList.contains('merged') || s.el.classList.contains('piled')) return;
|
||||
const on = s.el.classList.contains('online');
|
||||
// Far out people's names are off (map.css): no room taken.
|
||||
const named = !(far && s.el.classList.contains('dl-mk') && !s.el.classList.contains('step'));
|
||||
if (s.fixed) add(s.el, at[i].x, at[i].y, { rank: 0, city: this.data!.geo.home?.city ?? '', keep: true });
|
||||
else {
|
||||
const keep = (!!this.replaying && on) || s.el.classList.contains('hl');
|
||||
add(s.el, at[i].x, at[i].y, { rank: keep ? 1 : on ? 2 : 3, ts: s.g?.ts, city: s.g?.city || s.g?.cc || '', named, keep });
|
||||
}
|
||||
});
|
||||
for (const p of this.pileSpots) add(p.el, p.x, p.y, { rank: 1, city: p.city, ts: Infinity });
|
||||
const m = this.el.getBoundingClientRect();
|
||||
const k = m.width / W || 1;
|
||||
const controls: Box[] = [];
|
||||
for (const c of [this.el.querySelector('.maplibregl-ctrl-attrib'), this.el.parentElement?.querySelector(':scope > .dl-map-replay')]) {
|
||||
const r = c?.getBoundingClientRect();
|
||||
if (r?.width)
|
||||
controls.push({ l: (r.left - m.left) / k, t: (r.top - m.top) / k, r: (r.right - m.left) / k, b: (r.bottom - m.top) / k });
|
||||
}
|
||||
cands.sort((a, b) => a.rank - b.rank || b.ts - a.ts);
|
||||
const shown: Box[] = [];
|
||||
const named = new Set<string>();
|
||||
const writes: (() => void)[] = [];
|
||||
for (const c of cands) {
|
||||
// Sideways: centred, else ending or starting just past the marker; always inside the map's
|
||||
// edges and still under (or over) its marker.
|
||||
const lefts = [c.x - c.w / 2, c.x + 10 - c.w, c.x - 10].map((l) =>
|
||||
Math.min(Math.max(Math.min(Math.max(l, EDGE_PX), W - EDGE_PX - c.w), c.x - c.w + 8), c.x - 8),
|
||||
);
|
||||
const gap = this.labelGap.get(c.lab) ?? 4;
|
||||
// Its own side first (in each of the three places), then the marker's other side.
|
||||
const spots = [c.down, !c.down].flatMap((down) =>
|
||||
lefts.map((l) => {
|
||||
const t =
|
||||
down === c.down
|
||||
? down
|
||||
? c.y + c.h / 2 + gap
|
||||
: c.y - c.h / 2 - gap - c.lh
|
||||
: down
|
||||
? c.y + c.h / 2 + 4
|
||||
: c.y - c.h / 2 - 4 - c.lh;
|
||||
return { flip: down !== c.down, l, box: { l, r: l + c.w, t, b: t + c.lh } };
|
||||
}),
|
||||
);
|
||||
const inside = (b: Box) => b.t >= EDGE_PX && b.b <= H - EDGE_PX;
|
||||
const clear = (b: Box) =>
|
||||
!shown.some((x) => hits(x, b)) &&
|
||||
!controls.some((x) => hits(x, b, 0)) &&
|
||||
!bodies.some((x) => x.owner !== c.owner && hits(x.box, b, 1));
|
||||
let pick = c.city && named.has(c.city) ? undefined : spots.find((x) => inside(x.box) && clear(x.box));
|
||||
if (!pick && c.keep) pick = spots.find((x) => inside(x.box)) ?? spots[0];
|
||||
const shift = pick ? pick.l - (c.x - c.w / 2) : 0;
|
||||
const flip = !!pick?.flip;
|
||||
writes.push(() => {
|
||||
c.lab.classList.toggle('off', !pick);
|
||||
if (!pick) return;
|
||||
c.lab.classList.toggle('flip', flip);
|
||||
c.lab.style.translate = Math.abs(shift) > 0.5 ? `${shift.toFixed(1)}px 0` : '';
|
||||
});
|
||||
if (!pick) continue;
|
||||
shown.push(pick.box);
|
||||
if (c.city) named.add(c.city);
|
||||
}
|
||||
for (const w of writes) w();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -638,12 +1066,12 @@ export class ConnectionMap {
|
||||
this.dockKey = key;
|
||||
dock.parentElement?.classList.toggle('docked', this.merged.length > 0);
|
||||
// Emptied, it keeps its last avatars while it slides back.
|
||||
const home = this.slots.find((x) => x.fixed)!.at;
|
||||
if (this.merged.length)
|
||||
const hub = this.slots.find((x) => x.fixed);
|
||||
if (hub && this.merged.length)
|
||||
fillFaces(
|
||||
dock,
|
||||
this.merged,
|
||||
this.faceActions(() => [home]),
|
||||
this.faceActions(() => [hub.at]),
|
||||
this.dockQuiet,
|
||||
);
|
||||
this.dockQuiet = false;
|
||||
@@ -664,6 +1092,7 @@ export class ConnectionMap {
|
||||
*/
|
||||
private pileUp(items: { x: number; y: number; r: number; fixed: boolean }[]) {
|
||||
const live = new Set<string>();
|
||||
this.pileSpots = [];
|
||||
if (!this.data?.person && !this.data?.device) {
|
||||
const free = items.flatMap((it, i) => (!it.fixed && this.slots[i].el.querySelector(':scope > .dl-mk-av') ? [i] : []));
|
||||
const root = new Map(free.map((i) => [i, i]));
|
||||
@@ -724,6 +1153,8 @@ export class ConnectionMap {
|
||||
}
|
||||
const c = this.map.project(at);
|
||||
items.push({ x: c.x, y: c.y, r: (pile.el.offsetWidth || 60) / 2 + 3, fixed: true });
|
||||
const cities = new Set(slots.map((x) => x.g?.city || x.g?.cc || '?'));
|
||||
this.pileSpots.push({ el: pile.el, x: c.x, y: c.y, city: cities.size === 1 ? [...cities][0] : '' });
|
||||
}
|
||||
}
|
||||
this.piledKeys = new Set(this.slots.filter((x) => x.el.classList.contains('piled')).map((x) => x.el.dataset.key ?? ''));
|
||||
@@ -889,7 +1320,12 @@ export class ConnectionMap {
|
||||
// The same place a moment later: only its time changes.
|
||||
if (prev && state && prev.active === state.active) {
|
||||
const x = state.active ? this.places.get(state.active) : null;
|
||||
if (x?.when) x.when.textContent = state.when;
|
||||
if (x?.when && x.when.textContent !== state.when) {
|
||||
const grew = x.when.textContent?.length !== state.when.length;
|
||||
x.when.textContent = state.when;
|
||||
// a name of another length: kept inside the map again
|
||||
if (grew) this.declutter();
|
||||
}
|
||||
return;
|
||||
}
|
||||
for (const key of this.places.keys()) if (key !== state?.active) this.paintPlace(key, animate);
|
||||
@@ -900,8 +1336,53 @@ export class ConnectionMap {
|
||||
}
|
||||
|
||||
/** A device's place lit while its row under the map is hovered; null for none. */
|
||||
/**
|
||||
* A city's markers in focus (a row of the page's list under the pointer, or the city it opened): they stay, the
|
||||
* others and their arcs fade, as hovering a person does. null: as it was.
|
||||
*/
|
||||
hoverCity(key: string | null) {
|
||||
if (!key) {
|
||||
for (const s of this.slots) s.el.classList.remove('dim', 'hl');
|
||||
return this.focus(this.focused);
|
||||
}
|
||||
for (const s of this.slots) {
|
||||
if (s.fixed) continue;
|
||||
s.el.classList.toggle('dim', s.el.dataset.city !== key);
|
||||
s.el.classList.toggle('hl', s.el.dataset.city === key);
|
||||
}
|
||||
const keys = this.slots.filter((s) => s.el.dataset.city === key && s.el.dataset.key).map((s) => s.el.dataset.key!);
|
||||
const opacity = ['case', ['in', ['get', 'key'], ['literal', keys]], 0.85, 0.15];
|
||||
for (const id of ['dl-arc-live', 'dl-arc-recent']) if (this.map?.getLayer(id)) this.map.setPaintProperty(id, 'line-opacity', opacity);
|
||||
}
|
||||
|
||||
/**
|
||||
* The camera on a city (the page opened it): from where it is to the city's own framing on one SMOOTH curve, held
|
||||
* there while it is open; null: back to everyone's framing the same way.
|
||||
*/
|
||||
showCity(key: string | null) {
|
||||
this.held = key;
|
||||
if (!this.map || !this.gl) return;
|
||||
const pts = key ? this.slots.filter((s) => s.el.dataset.city === key).map((s) => s.at) : this.lastFit;
|
||||
if (!pts.length) return;
|
||||
if (!key) return this.fit(pts, true, true);
|
||||
const b = new this.gl.LngLatBounds(pts[0], pts[0]);
|
||||
pts.forEach((p) => b.extend(p));
|
||||
const cam = this.map.cameraForBounds(b, { padding: 80, maxZoom: CLICK_ZOOM });
|
||||
if (!cam) return;
|
||||
this.glide(cam.zoom ?? null, () =>
|
||||
this.map.easeTo({
|
||||
center: cam.center,
|
||||
zoom: cam.zoom,
|
||||
duration: calm() ? 0 : SMOOTH.duration,
|
||||
easing: (t: number) => SMOOTH.at(t * SMOOTH.duration),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
hoverPlace(key: string | null) {
|
||||
for (const [k, x] of this.places) x.el.classList.toggle('hl', k === key);
|
||||
// its name shows, over whichever it shares the room with
|
||||
this.declutter();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -972,7 +1453,7 @@ export class ConnectionMap {
|
||||
* 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) {
|
||||
private fit(coords: [number, number][], animate = false, smooth = false) {
|
||||
if (!coords.length) return;
|
||||
const km = (a: [number, number], b: [number, number]) => {
|
||||
const r = Math.PI / 180;
|
||||
@@ -993,36 +1474,54 @@ export class ConnectionMap {
|
||||
const b = new this.gl.LngLatBounds(pts[0], pts[0]);
|
||||
pts.forEach((c) => b.extend(c));
|
||||
const h = this.el.clientHeight || 380;
|
||||
const w = this.el.clientWidth || 600;
|
||||
// A person's and a device's places have their name (and "now") under the tile; a device's
|
||||
// window has the replay's controls in its top corner.
|
||||
const below = !!this.data?.person;
|
||||
// window has the replay's controls in its top corner: its places come in below them (half a
|
||||
// tile and a gap), so the moment's plate, as wide as the map while it plays, covers none.
|
||||
const plate = this.el.parentElement?.querySelector(':scope > .dl-map-replay') as HTMLElement | null;
|
||||
const under = Math.max(38, plate?.offsetHeight ? plate.offsetTop + plate.offsetHeight : 0) + 21;
|
||||
const opts = {
|
||||
// Just enough room for the labels: the server's chip above its plate, a place's name above its dot.
|
||||
// Room for the labels: the server's chip above its plate, names under markers (two lines on
|
||||
// a person's page); at the sides half a name, less what layoutLabels moves inwards.
|
||||
padding: {
|
||||
top: this.data?.device ? Math.min(56, h / 4) : Math.min(60, h / 5),
|
||||
bottom: below ? Math.min(52, h / 4) : Math.min(40, h / 8),
|
||||
left: 48,
|
||||
right: 48,
|
||||
top: this.data?.device ? Math.min(under, h / 3) : Math.min(60, h / 5),
|
||||
bottom: this.data?.person && !this.data.device ? Math.min(56, h / 4) : Math.min(44, h / 5),
|
||||
left: Math.min(64, w / 6),
|
||||
right: Math.min(64, w / 6),
|
||||
},
|
||||
// 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 });
|
||||
// a crossing: from where the camera is (a glide under way included) to the new framing, one smooth curve
|
||||
else if (smooth)
|
||||
this.glide(this.map.cameraForBounds(b, opts)?.zoom ?? null, () =>
|
||||
this.map.fitBounds(b, {
|
||||
...opts,
|
||||
linear: true,
|
||||
duration: calm() ? 0 : SMOOTH.duration,
|
||||
easing: (t: number) => SMOOTH.at(t * SMOOTH.duration),
|
||||
}),
|
||||
);
|
||||
else this.glide(this.map.cameraForBounds(b, opts)?.zoom ?? null, () => this.map.fitBounds(b, { ...opts, duration: 1200 }));
|
||||
}
|
||||
|
||||
/** A programmatic move to `zoom`: markers are decluttered for where it ends, then follow it. */
|
||||
private glide(zoom: number | null, move: () => void) {
|
||||
// a move under way stops where it is (its own end handler runs now), this one goes on from there
|
||||
this.map.stop();
|
||||
this.targetZoom = zoom;
|
||||
this.declutter();
|
||||
move();
|
||||
this.map.once('moveend', () => {
|
||||
this.targetZoom = null;
|
||||
this.declutter();
|
||||
});
|
||||
move();
|
||||
}
|
||||
|
||||
private openPopup(g: Group, at: [number, number], el?: HTMLElement) {
|
||||
// the page lists the places beside the map: the marker picks its city there
|
||||
if (this.cb.pickPlace) return this.cb.pickPlace(placeKey(g));
|
||||
const data = this.data!;
|
||||
const where = [g.city, g.cc || g.country].filter(Boolean).join(', ');
|
||||
const people = [...new Set(g.points.map((p) => p.person))];
|
||||
@@ -1064,7 +1563,8 @@ export class ConnectionMap {
|
||||
this.zoomInTo(this.nearby(at), true);
|
||||
this.dropCard();
|
||||
const card = E('div', { class: 'dl-root dl-popcard', role: 'dialog' }, [E('span', { class: 'dl-popcard-tip' }), body]);
|
||||
document.body.appendChild(card);
|
||||
// In the pages' floating layer (a shadow root on <body>, handed in by bind: map-module.ts): never clipped by the map.
|
||||
layer().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;
|
||||
@@ -1088,14 +1588,16 @@ export class ConnectionMap {
|
||||
};
|
||||
// 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.
|
||||
// Read along the event's path: from a shadow root the document sees only its host as the target.
|
||||
const inside = (ev: Event, sel: string) => ev.composedPath().some((n) => n instanceof Element && n.matches(sel));
|
||||
const outside = (ev: Event) => {
|
||||
if (!(ev.target as HTMLElement | null)?.closest('.dl-popcard, .maplibregl-marker')) this.closePopup(true);
|
||||
if (!inside(ev, '.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();
|
||||
if (!inside(ev, '.dl-popcard')) this.closePopup();
|
||||
};
|
||||
const close = () => this.closePopup();
|
||||
this.map.on('move', place);
|
||||
@@ -1258,7 +1760,7 @@ function fillFaces(
|
||||
keep.delete(f.key);
|
||||
if (!b) {
|
||||
const nb = E('button', { type: 'button', class: `dl-mk-face${quiet ? '' : ' in'}`, 'data-key': f.key }, [
|
||||
E('span', { class: 'dl-mk-av' }, initials(f.who)),
|
||||
E('span', { class: 'dl-mk-av' }, markInitials(f.who)),
|
||||
// Beside the avatar, not over it: the plate makes room for one icon, two, or a number.
|
||||
E('span', { class: 'dl-mk-badge' }),
|
||||
]);
|
||||
@@ -1366,34 +1868,3 @@ interface Group {
|
||||
ts: number;
|
||||
points: GeoPoint[];
|
||||
}
|
||||
|
||||
/** Segmented range control for the map header. */
|
||||
export function rangeControl(initial: Range, onChange: (r: Range) => void, online = true): HTMLElement {
|
||||
const opts: [Range, string][] = [
|
||||
['online', _('Online now')],
|
||||
['24h', _('24h')],
|
||||
['7d', _('7 days')],
|
||||
['30d', _('30 days')],
|
||||
];
|
||||
const el = E('div', { class: 'dl-seg', role: 'tablist' });
|
||||
for (const [v, label] of opts) {
|
||||
if (v === 'online' && !online) continue;
|
||||
el.appendChild(
|
||||
E(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
role: 'tab',
|
||||
class: v === initial ? 'on' : '',
|
||||
'data-v': v,
|
||||
click: () => {
|
||||
el.querySelectorAll('button').forEach((b) => b.classList.toggle('on', b.dataset.v === v));
|
||||
onChange(v);
|
||||
},
|
||||
},
|
||||
label,
|
||||
),
|
||||
);
|
||||
}
|
||||
return el;
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
// What Overview says, as data: the router's state in one phrase that counts
|
||||
// the checks, the checks as its list (the one notice, the other failing ones,
|
||||
// what passed), where a problem is fixed and which keep their fix in the
|
||||
// list, who waits for a decision and how many of them get a row, a server
|
||||
// card's numbers and who of its rollout is named, who moved most this month,
|
||||
// today by the hour, and the watchdog's news. Pure: no DOM.
|
||||
|
||||
import type { HealthCheck, Pair, Person, Server, Status } from '../../shared/types';
|
||||
import type { ServiceLog } from '../api';
|
||||
import { plural } from '../../shared/i18n';
|
||||
import { settingsUrl } from '../shell/routes';
|
||||
import { stageOf } from '../servers/path';
|
||||
import { aboutPortal } from '../system/model';
|
||||
import type { RolloutItem } from '../servers/rollout';
|
||||
import { byAttention, cardParts } from '../people/card';
|
||||
import type { Today } from '../people/lines';
|
||||
|
||||
/** The router's last-minute rate (status) stands for a speed while it is this fresh (s). */
|
||||
export const RATE_FRESH = 180;
|
||||
/** People who wait shown with their action (a phone: fewer); the rest are one link away. */
|
||||
const WAIT_ROWS = 5;
|
||||
const WAIT_ROWS_NARROW = 3;
|
||||
/** Devices still waiting for a new configuration that a server's card names. */
|
||||
const NAMED = 4;
|
||||
|
||||
const failing = (c: HealthCheck) => c.status === 'error' || c.status === 'warn';
|
||||
|
||||
/** The one problem the page puts in its notice: the first that failed, an error before a warning. */
|
||||
export function topProblem(checks: HealthCheck[] | null): HealthCheck | null {
|
||||
const bad = (checks ?? []).filter(failing);
|
||||
return bad.find((c) => c.status === 'error') ?? bad[0] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The phrase under the router's name: the checks summed up, the worst first (it leads down to their list). Null
|
||||
* checks: not read yet, or (`failed`) the router did not answer the run.
|
||||
*/
|
||||
export function stateLine(checks: HealthCheck[] | null, failed = false): { text: string; tone: '' | 'ok' | 'warn' | 'bad' } {
|
||||
if (!checks) return { text: failed ? _('The checks did not run') : _('Checking…'), tone: '' };
|
||||
const bad = checks.filter((c) => c.status === 'error').length;
|
||||
const warn = checks.filter((c) => c.status === 'warn').length;
|
||||
if (bad) return { text: plural(bad, '%s problem', '%s problems'), tone: 'bad' };
|
||||
if (warn) return { text: plural(warn, '%s warning', '%s warnings'), tone: 'warn' };
|
||||
return { text: _('Everything works'), tone: 'ok' };
|
||||
}
|
||||
|
||||
export interface CheckList {
|
||||
/** The page's one notice: the most pressing check that did not pass. */
|
||||
top: HealthCheck | null;
|
||||
/** The other checks that did not pass, errors first (the router's order within each). */
|
||||
failing: HealthCheck[];
|
||||
/** What passed and what was skipped, in the router's order: all of them stay on the page. */
|
||||
passed: HealthCheck[];
|
||||
/** How many passed, of how many ran (a skipped check did not run). */
|
||||
ok: number;
|
||||
of: number;
|
||||
}
|
||||
|
||||
/** The checks as Overview lists them. */
|
||||
export function checkList(checks: HealthCheck[]): CheckList {
|
||||
const top = topProblem(checks);
|
||||
const rest = checks.filter((c) => failing(c) && c !== top);
|
||||
return {
|
||||
top,
|
||||
failing: [...rest.filter((c) => c.status === 'error'), ...rest.filter((c) => c.status !== 'error')],
|
||||
passed: checks.filter((c) => !failing(c)),
|
||||
ok: checks.filter((c) => c.status === 'ok').length,
|
||||
of: checks.filter((c) => c.status !== 'skip').length,
|
||||
};
|
||||
}
|
||||
|
||||
/** The checks about one thing: the router itself, one server, the portal. */
|
||||
export interface CheckGroup {
|
||||
kind: 'router' | 'server' | 'portal';
|
||||
/** A server's group: its id and its name. */
|
||||
server?: string;
|
||||
name?: string;
|
||||
/** What passed and what was skipped, each under the name it has inside the group (the server's name is the group's). */
|
||||
passed: { check: HealthCheck; title: string }[];
|
||||
/** How many passed, of how many ran (a skipped check did not run). */
|
||||
ok: number;
|
||||
of: number;
|
||||
/** The worst of its checks; `off`: none of them ran (a server turned off). */
|
||||
tone: 'ok' | 'warn' | 'bad' | 'off';
|
||||
}
|
||||
|
||||
/**
|
||||
* The checks by what they are about, as Overview lists what passed: the router's own first, then each server's (a
|
||||
* server's own check carries its id: `up_<id>`), then the portal's. A group with no check is left out. Inside a
|
||||
* server's group a check loses the « (name)» the router adds to tell servers apart.
|
||||
*/
|
||||
export function checkGroups(checks: HealthCheck[], servers: Pick<Server, 'id' | 'name'>[]): CheckGroup[] {
|
||||
// the longest id first: one server's id may end another's
|
||||
const byId = [...servers].sort((a, b) => b.id.length - a.id.length);
|
||||
const of = (c: HealthCheck) => (aboutPortal(c.id) ? 'portal' : (byId.find((s) => c.id.endsWith(`_${s.id}`))?.id ?? 'router'));
|
||||
const group = (kind: CheckGroup['kind'], key: string, srv?: Pick<Server, 'id' | 'name'>): CheckGroup | null => {
|
||||
const own = checks.filter((c) => of(c) === key);
|
||||
if (!own.length) return null;
|
||||
const label = srv ? ` (${srv.name})` : '';
|
||||
const ran = own.filter((c) => c.status !== 'skip');
|
||||
return {
|
||||
kind,
|
||||
server: srv?.id,
|
||||
name: srv?.name,
|
||||
passed: own
|
||||
.filter((c) => !failing(c))
|
||||
.map((c) => ({ check: c, title: label && c.title.endsWith(label) ? c.title.slice(0, -label.length) : c.title })),
|
||||
ok: own.filter((c) => c.status === 'ok').length,
|
||||
of: ran.length,
|
||||
tone: own.some((c) => c.status === 'error') ? 'bad' : own.some((c) => c.status === 'warn') ? 'warn' : ran.length ? 'ok' : 'off',
|
||||
};
|
||||
};
|
||||
return [group('router', 'router'), ...servers.map((s) => group('server', s.id, s)), group('portal', 'portal')].filter(
|
||||
(g): g is CheckGroup => !!g,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a check is fixed: what it is about (a stage of its server's path on the server's page; the portal or
|
||||
* Updates in Settings), or null: it is about none of them and its fix stands beside it in Overview's own list.
|
||||
*/
|
||||
export function fixPlace(c: Pick<HealthCheck, 'id' | 'fix'>, servers: string[]): string | null {
|
||||
if (c.fix === 'updates') return settingsUrl('updates');
|
||||
if (aboutPortal(c.id)) return settingsUrl('portal');
|
||||
for (const s of servers) {
|
||||
const own = c.id.endsWith(`_${s}`);
|
||||
const stage = stageOf(c.id, s);
|
||||
if (stage) return settingsUrl(stage, own && servers.length > 1 ? s : undefined);
|
||||
if (own) return settingsUrl(undefined, servers.length > 1 ? s : undefined);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The fix a check keeps in Overview's own list: only one that nothing in Settings is about (the clock, the agent,
|
||||
* the flash, the data) has it here; the others are fixed in their Settings section. Null: no fix here.
|
||||
*/
|
||||
export const ownFix = (c: Pick<HealthCheck, 'id' | 'fix'>, servers: string[]): string | null =>
|
||||
fixPlace(c, servers) === null ? c.fix : null;
|
||||
|
||||
/**
|
||||
* People who wait for a decision, the most pressing first: the cards' «Needs a decision» group in its order
|
||||
* (people/card.ts), the one People's chip and group head count, so the two pages count and list alike.
|
||||
*/
|
||||
export function waiting(people: Person[], t: Today): Person[] {
|
||||
const need = people
|
||||
.map((p) => ({ p, parts: cardParts(p, undefined, t), speed: 0, week: 0, pausedAt: '' }))
|
||||
.filter((x) => x.parts.group === 'need');
|
||||
return byAttention(need, t.today).map((x) => x.p);
|
||||
}
|
||||
|
||||
/** The people who wait that get a row (`narrow`: a phone's fewer), how many wait in all, how many are left to People. */
|
||||
export function waitRows(people: Person[], t: Today, narrow: boolean): { rows: Person[]; total: number; more: number } {
|
||||
const w = waiting(people, t);
|
||||
const rows = w.slice(0, narrow ? WAIT_ROWS_NARROW : WAIT_ROWS);
|
||||
return { rows, total: w.length, more: w.length - rows.length };
|
||||
}
|
||||
|
||||
/**
|
||||
* A server card's numbers: its people, its speed to the devices now (bytes/s; null: it does not run, or the
|
||||
* router's last minute is stale) and what moved today (null: no day counted yet; `today`: the router's day).
|
||||
*/
|
||||
export function serverNumbers(
|
||||
s: Pick<Server, 'id' | 'enabled' | 'up' | 'rate' | 'series'>,
|
||||
st: Pick<Status, 'people' | 'now'>,
|
||||
today: string,
|
||||
): { people: number; down: number | null; today: number | null } {
|
||||
const r = s.rate?.[s.rate.length - 1];
|
||||
const day = s.series?.[s.series.length - 1];
|
||||
return {
|
||||
people: st.people.filter((p) => p.server === s.id).length,
|
||||
down: s.enabled && s.up && r && st.now - r[0] < RATE_FRESH ? r[2] : null,
|
||||
today: !day ? null : day.day === today ? day.rx + day.tx : 0,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Of a rollout's devices, those that still wait: the first few named on the server's card, how many more are
|
||||
* left to People, and how many people they all belong to (the reminder says it).
|
||||
*/
|
||||
export function stillWaiting(items: RolloutItem[], named = NAMED): { named: RolloutItem[]; more: number; people: number } {
|
||||
const w = items.filter((i) => i.d.config_stale);
|
||||
return { named: w.slice(0, named), more: Math.max(0, w.length - named), people: new Set(w.map((i) => i.p.id)).size };
|
||||
}
|
||||
|
||||
/** Who moved most this month (`n` of them, only those who moved anything). */
|
||||
export function topMonth(people: Person[], n = 3): { p: Person; bytes: number }[] {
|
||||
return people
|
||||
.map((p) => ({ p, bytes: p.month[0] + p.month[1] }))
|
||||
.filter((x) => x.bytes > 0)
|
||||
.sort((a, b) => b.bytes - a.bytes)
|
||||
.slice(0, n);
|
||||
}
|
||||
|
||||
/**
|
||||
* The last 24 hours, a bar an hour, the current hour last: each hour's share of the busiest one (0..1); null
|
||||
* only where the router sent fewer than 24 (an older one). `hours` is status.hours.
|
||||
*/
|
||||
export function hourBars(hours: Pair[]): { share: number | null; bytes: number }[] {
|
||||
const sums = hours.map((v) => v[0] + v[1]);
|
||||
const hi = Math.max(1, ...sums);
|
||||
return Array.from({ length: 24 }, (_x, i) => (i < sums.length ? { share: sums[i] / hi, bytes: sums[i] } : { share: null, bytes: 0 }));
|
||||
}
|
||||
|
||||
/** The watchdog's news for the checks' foot: the agent gone quiet, else its last repair today; null: nothing new. */
|
||||
export function systemNews(
|
||||
sl: ServiceLog | null,
|
||||
): { kind: 'quiet'; minutes: number } | { kind: 'repair'; ts: number; name: string } | null {
|
||||
const wd = sl?.watchdog;
|
||||
if (!wd) return null;
|
||||
if (wd.beat != null && wd.now - wd.beat > 180) return { kind: 'quiet', minutes: Math.round((wd.now - wd.beat) / 60) };
|
||||
const last = wd.repairs.filter((r) => wd.now - r.ts < 86400).sort((a, b) => b.ts - a.ts)[0];
|
||||
return last ? { kind: 'repair', ts: last.ts, name: last.name } : null;
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
// Components → Activity: the latest updates, and checks that found something.
|
||||
|
||||
import type { UpdateEvent } from '../../api';
|
||||
import { E } from '../../e';
|
||||
import { icon } from '../../../shared/icons';
|
||||
import { ago, duration } from '../../../shared/format';
|
||||
import { fill, locale, plural } from '../../../shared/i18n';
|
||||
import { jobComponent } from '../../updater/jobs';
|
||||
import { translationName } from './hero';
|
||||
import type { ComponentsPage } from './index';
|
||||
|
||||
function compName(comp: string): string {
|
||||
if (comp === 'app') return 'Dawnline';
|
||||
if (comp === 'amneziawg') return 'AmneziaWG';
|
||||
return comp === 'pkgs' ? _('System packages') : _('Components');
|
||||
}
|
||||
|
||||
/** A finding as the history keeps it: a component and version, or "2 system packages". */
|
||||
function itemText(item: string): string {
|
||||
const n = /^(\d+) system packages?$/.exec(item)?.[1];
|
||||
return n ? plural(Number(n), '%s system package', '%s system packages') : item;
|
||||
}
|
||||
|
||||
export function activity(page: ComponentsPage): HTMLElement {
|
||||
const st = page.st;
|
||||
const row = (e: UpdateEvent) => {
|
||||
const comp = jobComponent(e.component ?? 'app');
|
||||
const who = E('b', {}, compName(comp));
|
||||
let tone = 'ok',
|
||||
ic = 'check',
|
||||
text: (Node | string)[];
|
||||
if (e.kind === 'found') {
|
||||
tone = 'accent';
|
||||
ic = 'download';
|
||||
// The items are the router's words, kept in the history ("Dawnline 0.3.3", "2 system packages").
|
||||
text = fill(
|
||||
e.auto ? _('%s found by the automatic check') : _('%s found by a check'),
|
||||
E('b', {}, (e.items ?? []).map(itemText).join(', ')),
|
||||
);
|
||||
} else if (e.state === 'failed') {
|
||||
tone = 'bad';
|
||||
ic = 'x';
|
||||
text = [...fill(e.kind === 'install' ? _('%s update failed') : _('%s check failed'), who), e.error ? ` · ${e.error}` : ''];
|
||||
} else if (/^app:(lang:|nolang$)/.test(e.component ?? '')) {
|
||||
// The admin's translation, added or removed in Components.
|
||||
const lang = /^app:lang:(.+)$/.exec(e.component ?? '')?.[1];
|
||||
text = lang ? fill(_('%s added by you'), E('b', {}, translationName(lang))) : [_('Translation removed by you')];
|
||||
} else {
|
||||
const ver = e.from && e.to && e.from !== e.to ? `${e.from} → ${e.to}` : (e.to ?? '');
|
||||
text = [
|
||||
...(ver
|
||||
? fill<Node | string>(e.auto ? _('%s %s automatically') : _('%s %s by you'), who, ver)
|
||||
: fill(e.auto ? _('%s updated automatically') : _('%s updated by you'), who)),
|
||||
e.took ? ` · ${duration(e.took)}` : '',
|
||||
];
|
||||
}
|
||||
return E('div', { class: 'dl-row' }, [
|
||||
E('span', { class: `dl-ev-tile ev ${tone}` }, icon(ic)),
|
||||
E('span', { class: 'dl-row-main' }, text),
|
||||
E('span', { class: 'dl-faint dl-nowrap', title: new Date(e.ts * 1000).toLocaleString(locale()) }, ago(e.ts, st.now)),
|
||||
]);
|
||||
};
|
||||
const h = st.history ?? [];
|
||||
return E('section', { class: 'dl-panel flush' }, [
|
||||
E('div', { class: 'dl-panel-head pad' }, [
|
||||
E('h3', {}, _('Activity')),
|
||||
E('span', { class: 'dl-spacer' }),
|
||||
E('a', { href: `${L.url('admin/services/dawnline/diagnostics')}?tab=log` }, _('All in Log →')),
|
||||
]),
|
||||
h.length
|
||||
? E('div', {}, h.slice(0, 8).map(row))
|
||||
: E('p', { class: 'dl-sub dl-comp-empty' }, _('Updates, and checks that found something, show up here.')),
|
||||
]);
|
||||
}
|
||||
@@ -1,194 +0,0 @@
|
||||
// Components → AmneziaWG: the installed build, its update, and the builds for
|
||||
// this firmware with the Russian translation (Build and translation).
|
||||
|
||||
import type { AwgSource, UpdateComponent } from '../../api';
|
||||
import { E } from '../../e';
|
||||
import { button } from '../../ui/button';
|
||||
import { confirmDialog } from '../../ui/modal';
|
||||
import { sw } from '../../ui/controls';
|
||||
import { pill } from '../../ui/badges';
|
||||
import { icon } from '../../../shared/icons';
|
||||
import { fmt, num } from '../../../shared/i18n';
|
||||
import { whatsNew } from '../../updater/notes';
|
||||
import type { ComponentsPage, MenuEntry } from './index';
|
||||
|
||||
export function awgRows(page: ComponentsPage, w: UpdateComponent | undefined): Node[] {
|
||||
const st = page.st;
|
||||
const kept = st.kept?.amneziawg;
|
||||
const srcs = w?.sources ?? {};
|
||||
const ids = Object.keys(srcs) as AwgSource[];
|
||||
const cur = w?.current ?? null;
|
||||
const curSrc = cur ? srcs[cur] : undefined;
|
||||
const ru = !!w?.ru;
|
||||
// What the router says is missing right now wins over the last check (which may predate a removal).
|
||||
const missing = st.needs?.awg ?? [];
|
||||
const installed = missing.length ? null : (w?.installed ?? null);
|
||||
const actions: MenuEntry[] = [];
|
||||
if (cur && installed)
|
||||
actions.push({
|
||||
label: _('Reinstall this build'),
|
||||
warn: true,
|
||||
ic: 'reset',
|
||||
run: () => page.op(`amneziawg:${cur}${ru ? ':ru' : ''}`, _('Reinstalling AmneziaWG'), installed),
|
||||
});
|
||||
if (kept)
|
||||
actions.push({
|
||||
label: fmt(_('Roll back to %s'), kept.version),
|
||||
ic: 'archive',
|
||||
warn: true,
|
||||
run: async () => {
|
||||
if (
|
||||
await confirmDialog(
|
||||
fmt(_('Roll back AmneziaWG to %s?'), kept.version),
|
||||
_('The build kept on the router is installed again. Every AmneziaWG tunnel restarts for a few seconds.'),
|
||||
_('Roll back'),
|
||||
)
|
||||
)
|
||||
void page.op('amneziawg:rollback', _('Rolling back AmneziaWG'), installed ?? undefined);
|
||||
},
|
||||
});
|
||||
const menu: (MenuEntry | null)[] = [
|
||||
w?.release
|
||||
? {
|
||||
label: _('What’s new'),
|
||||
ic: 'file',
|
||||
run: () => whatsNew('amneziawg', w.release!, fmt(_('What’s new in the %s build'), curSrc?.label ?? 'AmneziaWG'), cur ?? 'slava'),
|
||||
}
|
||||
: null,
|
||||
{
|
||||
label: _('Open on GitHub'),
|
||||
ic: 'globe',
|
||||
run: () => window.open(`https://github.com/${curSrc?.repo ?? 'Slava-Shchipunov/awg-openwrt'}`, '_blank', 'noopener'),
|
||||
},
|
||||
...(actions.length ? [null, ...actions] : []),
|
||||
].filter((x, k, a) => x !== null || (k > 0 && a[k - 1] !== null));
|
||||
const tun = st.tunnels ?? [];
|
||||
const restarts = !tun.length
|
||||
? _('Switching takes a few seconds. Devices keep their configurations.')
|
||||
: tun.length === 1
|
||||
? fmt(_('Switching restarts the tunnel for a few seconds: %s. Devices keep their configurations.'), tun[0])
|
||||
: fmt(
|
||||
N_(
|
||||
tun.length,
|
||||
'Switching restarts %s tunnel for a few seconds: %s. Devices keep their configurations.',
|
||||
'Switching restarts %s tunnels for a few seconds: %s. Devices keep their configurations.',
|
||||
),
|
||||
num(tun.length),
|
||||
tun.join(', '),
|
||||
);
|
||||
// The notice under the builds: "Switching restarts Home and Family for a few seconds."
|
||||
const names = tun.length > 1 ? fmt(_('%s and %s'), tun.slice(0, -1).join(', '), tun[tun.length - 1]) : tun[0];
|
||||
const notice = tun.length ? fmt(_('Switching restarts %s for a few seconds.'), names) : _('Switching takes a few seconds.');
|
||||
const switchTo = async (id: AwgSource) => {
|
||||
const x = srcs[id]!;
|
||||
const ok = await confirmDialog(
|
||||
installed ? fmt(_('Switch to AmneziaWG %s?'), x.gen) : fmt(_('Install AmneziaWG %s?'), x.gen),
|
||||
[fmt(_('The %s build, %s.'), x.label, x.version), restarts, x.gen === '3.1' ? _('Devices need AmneziaVPN 3.1 or newer.') : '']
|
||||
.filter(Boolean)
|
||||
.join(' '),
|
||||
installed ? _('Switch') : _('Install'),
|
||||
);
|
||||
if (ok)
|
||||
void page.op(
|
||||
`amneziawg:${id}${ru ? ':ru' : ''}`,
|
||||
installed ? fmt(_('Switching to AmneziaWG %s'), x.gen) : _('Installing AmneziaWG'),
|
||||
installed ?? undefined,
|
||||
);
|
||||
};
|
||||
const build = (id: AwgSource) => {
|
||||
const x = srcs[id]!;
|
||||
const on = cur === id && !!installed;
|
||||
return E('div', { class: 'dl-row' }, [
|
||||
E('span', { class: 'dl-row-main dl-stack' }, [
|
||||
E('b', {}, x.gen ? `AmneziaWG ${x.gen}` : 'AmneziaWG'),
|
||||
E('span', { class: 'dl-sub' }, `${x.label} · ${x.gen === '3.1' ? 'AmneziaVPN 3.1+' : _('every app')}`),
|
||||
]),
|
||||
E('span', { class: 'dl-mono dl-faint dl-comp-bver' }, x.version ?? _('none yet')),
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-comp-bact' },
|
||||
on
|
||||
? pill('ok', _('Active', 'build'))
|
||||
: x.version
|
||||
? button(installed ? _('Switch') : _('Install'), () => switchTo(id), installed ? 'neutral' : 'positive', {
|
||||
disabled: page.busy,
|
||||
})
|
||||
: pill('', _('No build')),
|
||||
),
|
||||
]);
|
||||
};
|
||||
const newer = ids
|
||||
.map((id) =>
|
||||
srcs[id]?.newer
|
||||
? fmt(_('%s moves to %s with OpenWrt %s.'), srcs[id]!.label, srcs[id]!.newer!.gen, srcs[id]!.newer!.tag.replace(/^v/, ''))
|
||||
: '',
|
||||
)
|
||||
.filter(Boolean);
|
||||
const ruSw = sw(ru, _('Russian translation'), (v) => {
|
||||
if (!cur) return;
|
||||
void page.op(
|
||||
`amneziawg:${cur}${v ? ':ru' : ''}`,
|
||||
v ? _('Adding the Russian translation') : _('Removing the Russian translation'),
|
||||
installed ?? undefined,
|
||||
);
|
||||
});
|
||||
ruSw.disabled = !cur || !installed || page.busy;
|
||||
const open = page.awgOpen ?? !installed;
|
||||
const fold = E('details', { class: 'dl-params dl-comp-fold', open: open ? 'open' : null }, [
|
||||
E('summary', {}, [icon('chevron'), E('span', {}, _('Build and translation'))]),
|
||||
E('div', { class: 'dl-params-body' }, [
|
||||
// The builds and the translation in one list.
|
||||
E('div', { class: 'dl-list' }, [
|
||||
...(ids.length
|
||||
? ids.map(build)
|
||||
: [E('div', { class: 'dl-row' }, E('span', { class: 'dl-sub' }, _('Check for updates to see the builds for this router.')))]),
|
||||
E('div', { class: 'dl-row' }, [
|
||||
E('span', { class: 'dl-row-main dl-stack' }, [
|
||||
E('b', {}, _('Russian translation')),
|
||||
E('span', { class: 'dl-sub' }, _('LuCI pages for AmneziaWG')),
|
||||
]),
|
||||
E('span', { class: 'dl-comp-bact' }, ruSw),
|
||||
]),
|
||||
]),
|
||||
// One notice: what switching does, and what the builds will bring.
|
||||
(installed && ids.length) || newer.length
|
||||
? E('div', { class: `dl-comp-status ${installed && ids.length ? 'warn' : 'acc'}` }, [
|
||||
icon(installed && ids.length ? 'alert' : 'download'),
|
||||
E('span', {}, [installed && ids.length ? E('b', {}, notice) : '', ...newer.map((t) => ` ${t}`)]),
|
||||
])
|
||||
: '',
|
||||
]),
|
||||
]);
|
||||
fold.addEventListener('toggle', () => (page.awgOpen = (fold as HTMLDetailsElement).open));
|
||||
const right: Node[] = [];
|
||||
if (w?.update && installed && cur)
|
||||
right.push(
|
||||
button(
|
||||
fmt(_('Update to %s'), w.latest),
|
||||
() => page.op(`amneziawg:${cur}${ru ? ':ru' : ''}`, _('Updating AmneziaWG'), installed),
|
||||
'neutral',
|
||||
{
|
||||
disabled: page.busy,
|
||||
},
|
||||
),
|
||||
);
|
||||
else right.push((w || missing.length) && !installed ? pill('warn', _('Not installed')) : page.state('amneziawg', w, w?.latest ?? ''));
|
||||
right.push(page.round(() => page.op('check:amneziawg', _('Checking AmneziaWG'), installed ?? undefined), menu));
|
||||
return [
|
||||
page.row(
|
||||
'shield',
|
||||
'AmneziaWG',
|
||||
[
|
||||
installed
|
||||
? `${installed}${w?.release ? ` · ${fmt(_('%s build'), w.release)}` : ''}`
|
||||
: missing.length
|
||||
? fmt(_('missing %s'), missing.join(', '))
|
||||
: w
|
||||
? _('not installed')
|
||||
: _('version not checked'),
|
||||
],
|
||||
right,
|
||||
),
|
||||
E('div', { class: 'dl-comp-foldwrap' }, fold),
|
||||
];
|
||||
}
|
||||
@@ -1,355 +0,0 @@
|
||||
// Components → the Dawnline block: version, what the update brings, its
|
||||
// settings at a glance, every release to install (Versions) and the admin's
|
||||
// translation.
|
||||
|
||||
import { E } from '../../e';
|
||||
import { api, type UpdateComponent } from '../../api';
|
||||
import { button, iconButton } from '../../ui/button';
|
||||
import { confirmDialog } from '../../ui/modal';
|
||||
import { errorText, notify } from '../../ui/toast';
|
||||
import { input, sw } from '../../ui/controls';
|
||||
import { pill } from '../../ui/badges';
|
||||
import { icon } from '../../../shared/icons';
|
||||
import { ago, duration, fmtDay } from '../../../shared/format';
|
||||
import { fmt, plural } from '../../../shared/i18n';
|
||||
import { whatsNew } from '../../updater/notes';
|
||||
import type { ComponentsPage, MenuEntry } from './index';
|
||||
|
||||
/** How often Settings → Updates checks, by its interval id. */
|
||||
function checksEvery(interval: string): string {
|
||||
const t: Record<string, string> = {
|
||||
'6h': _('checks every 6 h'),
|
||||
'12h': _('checks every 12 h'),
|
||||
'1d': _('checks daily'),
|
||||
'7d': _('checks weekly'),
|
||||
};
|
||||
return t[interval] ?? t['1d'];
|
||||
}
|
||||
|
||||
/** A release date (GitHub gives a timestamp). */
|
||||
const released = (d: string | null | undefined) => (d ? fmtDay(d) : '');
|
||||
|
||||
/**
|
||||
* One change as a short line: the part before "; " or ": " when that says
|
||||
* enough, else the first 90 characters at a word boundary.
|
||||
*/
|
||||
function short(p: string): string {
|
||||
const head = /^(.{20,}?)(?:;\s|:\s)/.exec(p)?.[1];
|
||||
if (head) return head;
|
||||
if (p.length <= 90) return p;
|
||||
return `${p.slice(0, 90).replace(/[\s,;:]+\S*$/, '')}…`;
|
||||
}
|
||||
|
||||
export function hero(page: ComponentsPage, a: UpdateComponent | undefined): HTMLElement {
|
||||
const st = page.st;
|
||||
const pol = st.policy;
|
||||
const kept = st.kept?.app;
|
||||
const tag = a?.update && a.tag ? a.tag : st.version;
|
||||
const notesOf = (t: string) => () => whatsNew('app', t, fmt(_('What’s new in Dawnline %s'), t.replace(/^v/, '')));
|
||||
// What the offered release brings, or what the installed one brought when it is the latest.
|
||||
const items = a?.tag && (a.update || a.status === 'latest') ? bullets(page, a.tag, a.update ? st.version : '') : null;
|
||||
const ptag = a?.tag ?? tag;
|
||||
const nextCheck =
|
||||
pol.check && st.auto?.check ? st.auto.check + ({ '6h': 6, '12h': 12, '1d': 24, '7d': 168 }[pol.interval] ?? 24) * 3600 : 0;
|
||||
const side = (label: string, value: (Node | string)[]) =>
|
||||
E('div', { class: 'dl-stack gap4' }, [E('span', { class: 'dl-metric-label' }, label), E('span', { class: 'dl-comp-side-v' }, value)]);
|
||||
const menu: (MenuEntry | null)[] = [
|
||||
{ label: _('What’s new'), ic: 'file', run: notesOf(tag) },
|
||||
{ label: _('Open on GitHub'), ic: 'globe', run: () => window.open(`https://github.com/${st.repo}`, '_blank', 'noopener') },
|
||||
null,
|
||||
{
|
||||
label: fmt(_('Reinstall %s'), st.version),
|
||||
ic: 'reset',
|
||||
warn: true,
|
||||
run: () => page.op('app:reinstall', _('Reinstalling Dawnline'), st.version),
|
||||
},
|
||||
kept
|
||||
? {
|
||||
label: fmt(_('Roll back to %s'), kept.version),
|
||||
ic: 'archive',
|
||||
warn: true,
|
||||
run: async () => {
|
||||
if (
|
||||
await confirmDialog(
|
||||
fmt(_('Roll back to Dawnline %s?'), kept.version),
|
||||
fmt(_('The copy kept on the router replaces %s. A backup of the settings is made first.'), st.version),
|
||||
_('Roll back'),
|
||||
)
|
||||
)
|
||||
void page.op('app:rollback', _('Rolling back Dawnline'), st.version);
|
||||
},
|
||||
}
|
||||
: null,
|
||||
];
|
||||
return E('section', { class: 'dl-panel flush dl-comp-hero' }, [
|
||||
E('div', { class: 'dl-comp-hero-main' }, [
|
||||
E('div', { class: 'dl-comp-hero-head' }, [
|
||||
E('span', { class: 'dl-group-ic' }, icon('sunrise')),
|
||||
E('b', { class: 'dl-comp-name' }, 'Dawnline'),
|
||||
page.state('app', a, a?.latest ?? ''),
|
||||
E('span', { class: 'dl-spacer' }),
|
||||
page.round(() => page.op('check:app', _('Checking Dawnline'), st.version), menu, true),
|
||||
]),
|
||||
// Version, what it is, and the update: one line.
|
||||
E('div', { class: 'dl-comp-verrow' }, [
|
||||
E('div', { class: 'dl-stack' }, [
|
||||
E('div', { class: 'dl-comp-big' }, [
|
||||
st.version,
|
||||
a?.update
|
||||
? E('small', {}, `→ ${a.latest}`)
|
||||
: a?.status === 'dev' && a.latest
|
||||
? E('small', { class: 'dl-faint' }, fmt(_('release %s'), a.latest))
|
||||
: '',
|
||||
]),
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-faint dl-comp-meta' },
|
||||
a?.error
|
||||
? ''
|
||||
: a?.update
|
||||
? a.published
|
||||
? fmt(_('released %s'), released(a.published))
|
||||
: ''
|
||||
: a?.status === 'dev'
|
||||
? _('ahead of the latest release')
|
||||
: a
|
||||
? [_('latest release'), a.published ? fmt(_('released %s'), released(a.published)) : ''].filter(Boolean).join(' · ')
|
||||
: _('not checked yet'),
|
||||
),
|
||||
]),
|
||||
]),
|
||||
// Three points at most; the rest is one click away.
|
||||
items?.items.length
|
||||
? E('div', { class: 'dl-stack gap4' }, [
|
||||
E(
|
||||
'ul',
|
||||
{ class: 'dl-comp-bullets' },
|
||||
items.items.map((b) => E('li', {}, b)),
|
||||
),
|
||||
items.total > items.items.length
|
||||
? E(
|
||||
'button',
|
||||
{ type: 'button', class: 'dl-linkbtn dl-comp-more', click: notesOf(ptag) },
|
||||
plural(items.total - items.items.length, '+%s more in What’s new', '+%s more in What’s new'),
|
||||
)
|
||||
: '',
|
||||
])
|
||||
: '',
|
||||
a?.error ? E('p', { class: 'dl-sub dl-comp-lead dl-upd-bad' }, a.error) : '',
|
||||
// The update and its notes; without an update What's new stays in ⋯.
|
||||
a?.update
|
||||
? E('div', { class: 'dl-comp-btns' }, [
|
||||
button(_('Update now'), () => page.op('app', _('Updating Dawnline'), st.version), 'positive', { disabled: page.busy }),
|
||||
button(_('What’s new'), notesOf(tag)),
|
||||
])
|
||||
: '',
|
||||
versions(page),
|
||||
translation(page),
|
||||
]),
|
||||
E('div', { class: 'dl-comp-hero-side' }, [
|
||||
side(_('Source'), [icon('globe'), E('a', { href: `https://github.com/${st.repo}`, target: '_blank', rel: 'noopener' }, st.repo)]),
|
||||
side(_('Auto-update'), [
|
||||
pol.auto ? pill('ok', _('On')) : pill('', _('Off')),
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-muted' },
|
||||
pol.auto
|
||||
? pol.mode === 'immediate'
|
||||
? _('as soon as found')
|
||||
: fmt(pol.interval === '7d' ? _('weekly at %s') : _('daily at %s'), pol.time)
|
||||
: pol.check
|
||||
? checksEvery(pol.interval)
|
||||
: _('checks off'),
|
||||
),
|
||||
]),
|
||||
side(
|
||||
_('Last check'),
|
||||
st.check
|
||||
? [
|
||||
ago(st.check.time, st.now),
|
||||
nextCheck > st.now ? E('span', { class: 'dl-faint' }, `· ${fmt(_('next in %s'), duration(nextCheck - st.now))}`) : '',
|
||||
]
|
||||
: [_('Never')],
|
||||
),
|
||||
side(
|
||||
_('Rollback'),
|
||||
kept
|
||||
? [E('span', { class: 'dl-mono' }, kept.version), E('span', { class: 'dl-faint' }, _('kept on flash'))]
|
||||
: [E('span', { class: 'dl-muted' }, pol.keep ? _('Kept after the next update') : _('Off'))],
|
||||
),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* The first points of what a release brings (fetched once per tag): the
|
||||
* release notes' list, else the commits since `from` (or the release's own commit).
|
||||
*/
|
||||
function bullets(page: ComponentsPage, tag: string, from: string): { items: string[]; total: number } | null {
|
||||
if (page.notes.has(tag)) return page.notes.get(tag) ?? null;
|
||||
page.notes.set(tag, null);
|
||||
const clean = (x: string) => x.replace(/\*\*|`|\[([^\]]+)\]\([^)]*\)/g, (_m, t) => t ?? '').trim();
|
||||
void (async () => {
|
||||
const body = (await api.updatesNotes('app', tag, '').catch(() => null))?.body ?? '';
|
||||
let pts = body
|
||||
.split('\n')
|
||||
.map((l) => /^\s*[-*+]\s+(.*)$/.exec(l)?.[1])
|
||||
.filter((x): x is string => !!x);
|
||||
if (!pts.length) pts = (await api.updatesChanges(from, tag).catch(() => null))?.items ?? [];
|
||||
const out = { items: pts.slice(0, 3).map((x) => short(clean(x))), total: pts.length };
|
||||
page.notes.set(tag, out);
|
||||
if (out.items.length && page.root.isConnected) page.paint();
|
||||
})();
|
||||
return null;
|
||||
}
|
||||
|
||||
/** A translation's name, by its language code. */
|
||||
export function translationName(lang: string): string {
|
||||
return lang === 'ru' ? _('Russian translation') : lang;
|
||||
}
|
||||
|
||||
/**
|
||||
* The admin's translation, switched like AmneziaWG's: luci-i18n-dawnline-ru
|
||||
* from the release of the installed version (the updater installs and
|
||||
* removes it, then LuCI's web server restarts to read it).
|
||||
*/
|
||||
function translation(page: ComponentsPage): HTMLElement {
|
||||
const ru = (page.st.translations ?? []).includes('ru');
|
||||
const s = sw(ru, translationName('ru'), (v) => {
|
||||
void page.op(
|
||||
v ? 'app:lang:ru' : 'app:nolang',
|
||||
v ? _('Adding the Russian translation') : _('Removing the Russian translation'),
|
||||
page.st.version,
|
||||
);
|
||||
});
|
||||
s.disabled = page.busy;
|
||||
const fold = E('details', { class: 'dl-params dl-comp-fold', open: page.langOpen ? 'open' : null }, [
|
||||
E('summary', {}, [
|
||||
icon('chevron'),
|
||||
E('span', {}, _('Translation')),
|
||||
E('span', { class: 'dl-sub' }, ru ? _('Russian') : _('English only')),
|
||||
]),
|
||||
E('div', { class: 'dl-params-body' }, [
|
||||
E('div', { class: 'dl-list' }, [
|
||||
E('div', { class: 'dl-row' }, [
|
||||
E('span', { class: 'dl-row-main dl-stack' }, [
|
||||
E('b', {}, translationName('ru')),
|
||||
E('span', { class: 'dl-sub' }, _('LuCI pages for Dawnline')),
|
||||
]),
|
||||
E('span', { class: 'dl-comp-bact' }, s),
|
||||
]),
|
||||
]),
|
||||
]),
|
||||
]);
|
||||
fold.addEventListener('toggle', () => (page.langOpen = (fold as HTMLDetailsElement).open));
|
||||
return fold;
|
||||
}
|
||||
|
||||
function versions(page: ComponentsPage): HTMLElement {
|
||||
const body = E('div', { class: 'dl-params-body' });
|
||||
const fold = E('details', { class: 'dl-params dl-comp-vers', open: page.versOpen ? 'open' : null }, [
|
||||
E('summary', {}, [icon('chevron'), E('span', {}, _('Versions')), E('span', { class: 'dl-sub' }, _('install any release'))]),
|
||||
body,
|
||||
]);
|
||||
fold.addEventListener('toggle', () => {
|
||||
page.versOpen = (fold as HTMLDetailsElement).open;
|
||||
if (page.versOpen) void paintVersions(page, body);
|
||||
});
|
||||
if (page.versOpen) void paintVersions(page, body);
|
||||
return fold;
|
||||
}
|
||||
|
||||
async function paintVersions(page: ComponentsPage, body: HTMLElement) {
|
||||
const tag = input('', { placeholder: _('Tag, e.g. 0.3.1'), class: 'cbi-input-text dl-mono', 'aria-label': _('Release tag') });
|
||||
const installTag = (t: string) => {
|
||||
t = t.trim();
|
||||
if (!/^v?[0-9][0-9A-Za-z.+~-]{0,40}$/.test(t)) return notify(_('Enter a release tag like 0.3.1'), 'warning');
|
||||
void install(page, t);
|
||||
};
|
||||
tag.addEventListener('keydown', (ev: KeyboardEvent) => {
|
||||
if (ev.key === 'Enter') {
|
||||
ev.preventDefault();
|
||||
installTag(tag.value);
|
||||
}
|
||||
});
|
||||
const head = E('div', { class: 'dl-comp-tag' }, [
|
||||
tag,
|
||||
button(_('Install'), () => installTag(tag.value), 'neutral', { disabled: page.busy }),
|
||||
]);
|
||||
const pageNo = page.versPage;
|
||||
const turn = (d: number) => {
|
||||
page.versPage = Math.max(1, page.versPage + d);
|
||||
void paintVersions(page, body);
|
||||
};
|
||||
const pager = (more: boolean) =>
|
||||
E('div', { class: 'dl-comp-pager' }, [
|
||||
E('button', { type: 'button', class: 'dl-linkbtn', disabled: pageNo <= 1 ? 'disabled' : null, click: () => turn(-1) }, _('← Newer')),
|
||||
E('span', { class: 'dl-faint' }, fmt(_('Page %s'), pageNo)),
|
||||
E('button', { type: 'button', class: 'dl-linkbtn', disabled: more ? null : 'disabled', click: () => turn(1) }, _('Older →')),
|
||||
]);
|
||||
let rows = page.versCache.get(pageNo);
|
||||
if (!rows) {
|
||||
dom.content(body, [head, E('p', { class: 'dl-muted dl-loading' }, _('Loading versions…'))]);
|
||||
try {
|
||||
rows = (await api.updatesReleases(pageNo)).releases;
|
||||
} catch (e) {
|
||||
// Not kept: opening the list again, or Try again, asks once more.
|
||||
if (pageNo !== page.versPage || !body.isConnected) return;
|
||||
dom.content(body, [
|
||||
head,
|
||||
E('div', { class: 'dl-row-actions' }, [
|
||||
E('span', { class: 'dl-muted' }, fmt(_('Failed to load versions: %s'), errorText(e))),
|
||||
button(_('Try again'), () => paintVersions(page, body)),
|
||||
]),
|
||||
pager(false),
|
||||
]);
|
||||
return;
|
||||
}
|
||||
page.versCache.set(pageNo, rows);
|
||||
if (pageNo !== page.versPage || !body.isConnected) return;
|
||||
}
|
||||
if (!rows.length)
|
||||
return dom.content(body, [
|
||||
head,
|
||||
E('p', { class: 'dl-muted' }, pageNo > 1 ? _('No more versions.') : _('No versions found.')),
|
||||
pager(false),
|
||||
]);
|
||||
const cur = page.st.version;
|
||||
dom.content(body, [
|
||||
head,
|
||||
...rows.map((r) => {
|
||||
const v = r.tag.replace(/^v/, '');
|
||||
return E('div', { class: 'dl-comp-ver' }, [
|
||||
E('span', { class: 'dl-mono' }, v),
|
||||
E('span', { class: 'dl-sub' }, released(r.published)),
|
||||
r.prerelease ? pill('warn', _('Pre-release')) : '',
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-comp-ic' },
|
||||
iconButton('file', _('What’s new'), () => whatsNew('app', r.tag, fmt(_('What’s new in Dawnline %s'), v))),
|
||||
),
|
||||
v === cur ? pill('ok', _('Installed')) : button(_('Install'), () => install(page, r.tag), 'neutral', { disabled: page.busy }),
|
||||
]);
|
||||
}),
|
||||
pager(rows.length >= 5),
|
||||
]);
|
||||
}
|
||||
|
||||
/** A release by tag; going back asks first (settings written by a newer version may not carry over). */
|
||||
async function install(page: ComponentsPage, tag: string) {
|
||||
const v = tag.replace(/^v/, '');
|
||||
const older = v.localeCompare(page.st.version, undefined, { numeric: true }) < 0;
|
||||
if (
|
||||
older &&
|
||||
!(await confirmDialog(
|
||||
fmt(_('Install Dawnline %s?'), v),
|
||||
fmt(
|
||||
_('It is older than %s. A backup of the settings is made first; restore it from Settings if something looks wrong.'),
|
||||
page.st.version,
|
||||
),
|
||||
_('Install'),
|
||||
))
|
||||
)
|
||||
return;
|
||||
void page.op(`app@${tag}`, fmt(_('Installing Dawnline %s'), v), page.st.version);
|
||||
}
|
||||
@@ -1,261 +0,0 @@
|
||||
// Components: Dawnline, AmneziaWG and the OpenWrt packages Dawnline adds, each
|
||||
// with its version, a check, updates, other versions and roll back. Every
|
||||
// operation runs in the updater and is followed in one modal with its log
|
||||
// (see ../../updater/operation). Settings → Updates holds the automatic checks
|
||||
// and updates. The blocks live in ./hero, ./awg, ./packages and ./activity.
|
||||
|
||||
import { E } from '../../e';
|
||||
import { api, type Release, type UpdateComponent, type UpdateJob, type UpdatesStatus } from '../../api';
|
||||
import { button, iconButton } from '../../ui/button';
|
||||
import { dropdown } from '../../ui/menu';
|
||||
import { notify } from '../../ui/toast';
|
||||
import { attachTip } from '../../ui/tooltip';
|
||||
import { pill } from '../../ui/badges';
|
||||
import { icon } from '../../../shared/icons';
|
||||
import { ago } from '../../../shared/format';
|
||||
import { fmt, num, plural } from '../../../shared/i18n';
|
||||
import { runOperation } from '../../updater/operation';
|
||||
import { jobComponent, runningComponent } from '../../updater/jobs';
|
||||
import { hero } from './hero';
|
||||
import { awgRows } from './awg';
|
||||
import { packageRows } from './packages';
|
||||
import { activity } from './activity';
|
||||
|
||||
/** A ⋯ menu entry; null in a list is a separator. */
|
||||
export interface MenuEntry {
|
||||
label: string;
|
||||
ic: string;
|
||||
warn?: boolean;
|
||||
run: () => unknown;
|
||||
}
|
||||
|
||||
export class ComponentsPage {
|
||||
st!: UpdatesStatus;
|
||||
root = E('div', { class: 'dl-upd' });
|
||||
/**
|
||||
* The job the modal follows, so the poll does not open a second one:
|
||||
* 'starting' from the click until the operation knows its job.
|
||||
*/
|
||||
following: string | null = null;
|
||||
/** Versions list: open state and the loaded pages (failed loads are not kept). */
|
||||
versOpen = false;
|
||||
versPage = 1;
|
||||
versCache = new Map<number, Release[]>();
|
||||
/** Release notes of the version on offer, for the bullets in the Dawnline block. */
|
||||
notes = new Map<string, { items: string[]; total: number } | null>();
|
||||
/** The AmneziaWG "Build and translation" fold, once opened or closed by hand. */
|
||||
awgOpen: boolean | null = null;
|
||||
/** Dawnline's Translation fold. */
|
||||
langOpen = false;
|
||||
|
||||
load() {
|
||||
return api.updatesStatus();
|
||||
}
|
||||
|
||||
render(st: UpdatesStatus) {
|
||||
this.st = st;
|
||||
this.paint();
|
||||
// A job started elsewhere (another tab, the schedule) or before a reload: follow it.
|
||||
if (st.job?.state === 'running') void this.follow(st.job);
|
||||
poll.add(async () => {
|
||||
if (!this.root.isConnected) return;
|
||||
const n = await api.updatesStatus().catch(() => null);
|
||||
if (!n) return;
|
||||
const was = this.st;
|
||||
this.st = n;
|
||||
// While a click is starting its job, that job is the click's to follow.
|
||||
if (n.job?.state === 'running' && this.following !== 'starting' && n.job.id !== this.following) void this.follow(n.job);
|
||||
if (
|
||||
n.job?.id !== was.job?.id ||
|
||||
n.job?.state !== was.job?.state ||
|
||||
n.job?.phase !== was.job?.phase ||
|
||||
n.check?.time !== was.check?.time
|
||||
)
|
||||
this.paint();
|
||||
}, 5);
|
||||
return this.root;
|
||||
}
|
||||
|
||||
get busy() {
|
||||
return this.st.job?.state === 'running';
|
||||
}
|
||||
|
||||
async refresh(st?: UpdatesStatus | null) {
|
||||
this.st = st ?? (await api.updatesStatus().catch(() => null)) ?? this.st;
|
||||
this.paint();
|
||||
}
|
||||
|
||||
/** Run `what` in the operation modal; the cards refresh when it ends. */
|
||||
async op(what: string, title: string, version?: string) {
|
||||
if (this.busy || this.following === 'starting') {
|
||||
notify(_('Another component action is already running'), 'warning');
|
||||
return;
|
||||
}
|
||||
this.following = 'starting';
|
||||
this.paint();
|
||||
const comp = jobComponent(what);
|
||||
const job = await runOperation(what, {
|
||||
title,
|
||||
version,
|
||||
onJob: (j) => (this.following = j.id),
|
||||
onDone: (s) => this.refresh(s),
|
||||
onUpdate: (s) => {
|
||||
const c = s.check?.components ?? {};
|
||||
if (comp === 'amneziawg' && c.amneziawg?.current)
|
||||
void this.op(
|
||||
`amneziawg:${c.amneziawg.current}${c.amneziawg.ru ? ':ru' : ''}`,
|
||||
_('Updating AmneziaWG'),
|
||||
c.amneziawg.installed ?? undefined,
|
||||
);
|
||||
else void this.op('app', _('Updating Dawnline'), this.st.version);
|
||||
},
|
||||
});
|
||||
if (this.following === 'starting') this.following = job?.id ?? null;
|
||||
void this.refresh();
|
||||
}
|
||||
|
||||
async follow(job: UpdateJob) {
|
||||
this.following = job.id;
|
||||
// [check, automatic update, update] per component.
|
||||
const titles: Record<string, string[]> = {
|
||||
app: [_('Checking Dawnline'), _('Automatic update: Dawnline'), _('Updating Dawnline')],
|
||||
amneziawg: [_('Checking AmneziaWG'), _('Automatic update: AmneziaWG'), _('Updating AmneziaWG')],
|
||||
pkgs: [_('Checking system packages'), _('Automatic update: system packages'), _('Updating system packages')],
|
||||
all: [_('Checking components'), _('Automatic update: components'), _('Updating components')],
|
||||
};
|
||||
await runOperation(
|
||||
null,
|
||||
{
|
||||
title: (titles[runningComponent(job)] ?? titles.all)[job.action === 'check' ? 0 : job.auto ? 1 : 2],
|
||||
onDone: (s) => this.refresh(s),
|
||||
},
|
||||
job,
|
||||
);
|
||||
}
|
||||
|
||||
paint() {
|
||||
const st = this.st;
|
||||
const c = st.check?.components ?? {};
|
||||
const fw = st.firmware;
|
||||
const pk = packageRows(this, c.packages);
|
||||
// AmneziaWG missing from the router is not "up to date", whatever the last check said.
|
||||
const awgMissing = (st.needs?.awg ?? []).length > 0;
|
||||
const awgUpdate = !awgMissing && c.amneziawg?.update && c.amneziawg.installed ? 1 : 0;
|
||||
const n = awgUpdate + pk.updates;
|
||||
dom.content(this.root, [
|
||||
E('div', { class: 'dl-pagehead' }, [
|
||||
E('div', { class: 'dl-stack' }, [
|
||||
E('h2', { class: 'dl-h1' }, _('Components')),
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-faint' },
|
||||
[
|
||||
fw?.version ? `OpenWrt ${fw.version} · ${fw.target}` : '',
|
||||
st.check ? fmt(_('checked %s'), ago(st.check.time, st.now)) : _('not checked yet'),
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' · '),
|
||||
),
|
||||
]),
|
||||
E('div', { class: 'dl-row-actions' }, [
|
||||
E(
|
||||
'a',
|
||||
{ class: 'cbi-button cbi-button-neutral dl-icon-btn', href: `${L.url('admin/services/dawnline/settings')}?section=updates` },
|
||||
[icon('edit'), ' ', _('Settings')],
|
||||
),
|
||||
button([icon('refresh'), ' ', _('Check all')], () => this.op('check', _('Checking all components')), 'neutral', {
|
||||
disabled: this.busy,
|
||||
}),
|
||||
]),
|
||||
]),
|
||||
hero(this, c.app),
|
||||
E('div', { class: 'dl-comp-cols' }, [
|
||||
E('section', { class: 'dl-panel flush' }, [
|
||||
E('div', { class: 'dl-panel-head pad' }, [
|
||||
E('h3', {}, _('Components')),
|
||||
E('span', { class: 'dl-spacer' }),
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-faint dl-comp-count' },
|
||||
awgMissing
|
||||
? n
|
||||
? `${_('AmneziaWG not installed')} · ${plural(n, '%s update', '%s updates')}`
|
||||
: _('AmneziaWG not installed')
|
||||
: !c.amneziawg && !c.packages
|
||||
? ''
|
||||
: n
|
||||
? fmt(N_(n, '%s of %s needs an update', '%s of %s need an update'), num(n), num(1 + pk.total))
|
||||
: _('Everything is up to date'),
|
||||
),
|
||||
]),
|
||||
E('div', {}, [...awgRows(this, c.amneziawg), ...pk.rows]),
|
||||
]),
|
||||
activity(this),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
|
||||
/** The state pill of a component; a running job wins. */
|
||||
state(comp: string, x: UpdateComponent | undefined, latest: string): Node {
|
||||
const j = this.st.job;
|
||||
if (j?.state === 'running') {
|
||||
const norm = (v: string) => (v === 'packages' ? 'pkgs' : v);
|
||||
const comps = j.action === 'check' ? [norm(j.component || 'all')] : (j.component ?? '').split(' ').map((v) => norm(jobComponent(v)));
|
||||
if (comps.includes(comp) || comps.includes('all'))
|
||||
return E('button', { type: 'button', class: 'dl-pill info dl-comp-run', title: _('Show progress'), click: () => this.follow(j) }, [
|
||||
j.action === 'check' ? _('Checking…') : _('Updating…'),
|
||||
]);
|
||||
}
|
||||
if (!x) return pill('', _('Not checked'));
|
||||
if (x.error) return pill('warn', _('Check failed'), x.error);
|
||||
if (x.update) return pill('info', _('Update available'));
|
||||
if (x.status === 'dev') return pill('info', _('Newer than release'), fmt(_('The latest release is %s'), latest));
|
||||
return pill('ok', _('Up to date'));
|
||||
}
|
||||
|
||||
/** ⋯ menu; null is a separator. Actions refuse to start while a job runs (see op). */
|
||||
more(items: (MenuEntry | null)[]) {
|
||||
const b: HTMLButtonElement = button(
|
||||
[icon('more')],
|
||||
() =>
|
||||
dropdown(
|
||||
b,
|
||||
items
|
||||
// A separator only between items: none first, last or twice in a row.
|
||||
.filter((x, i, a) => x !== null || (i > 0 && i < a.length - 1 && a[i - 1] !== null && a.slice(i + 1).some(Boolean)))
|
||||
.map((x) => (x ? { label: x.label, icon: icon(x.ic), warn: x.warn, run: x.run } : null)),
|
||||
),
|
||||
'neutral',
|
||||
{ title: _('More'), 'aria-label': _('More') },
|
||||
);
|
||||
return b;
|
||||
}
|
||||
|
||||
/** Check and ⋯; `label` adds the word (the Dawnline block), the list keeps round icons with a tooltip. */
|
||||
round(check: () => void, menu: (MenuEntry | null)[], label = false) {
|
||||
const busy = this.busy ? ' is-busy' : '';
|
||||
let btn: HTMLButtonElement;
|
||||
if (label)
|
||||
btn = button([icon('refresh'), ' ', _('Check')], check, 'neutral', {
|
||||
class: `cbi-button cbi-button-neutral dl-comp-check${busy}`,
|
||||
'aria-label': _('Check for updates'),
|
||||
});
|
||||
else {
|
||||
btn = iconButton('refresh', _('Check for updates'), check, 'neutral', busy.trim());
|
||||
// Dawnline's own tooltip (the browser's title tip is slow and plain).
|
||||
btn.removeAttribute('title');
|
||||
btn.setAttribute('aria-label', _('Check for updates'));
|
||||
attachTip(btn, () => [_('Check for updates')]);
|
||||
}
|
||||
return E('span', { class: 'dl-comp-ic' }, [btn, this.more(menu)]);
|
||||
}
|
||||
|
||||
/** A row of the list: icon tile, name and a mono line, then its controls. */
|
||||
row(ic: string, name: string, sub: (Node | string)[], right: (Node | string)[]) {
|
||||
return E('div', { class: 'dl-row' }, [
|
||||
E('span', { class: 'dl-group-ic' }, icon(ic)),
|
||||
E('span', { class: 'dl-row-main dl-stack' }, [E('b', {}, name), E('span', { class: 'dl-mono dl-faint dl-comp-sub' }, sub)]),
|
||||
...right,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -1,109 +0,0 @@
|
||||
// Components → system packages: one row per feature in use (the home-like
|
||||
// link; HTTPS and certificates while the portal is on).
|
||||
|
||||
import type { UpdateComponent } from '../../api';
|
||||
import { button } from '../../ui/button';
|
||||
import { confirmDialog } from '../../ui/modal';
|
||||
import { E } from '../../e';
|
||||
import { fmt } from '../../../shared/i18n';
|
||||
import type { ComponentsPage, MenuEntry } from './index';
|
||||
|
||||
interface SysItem {
|
||||
title: string;
|
||||
sub: string;
|
||||
pkgs: string[];
|
||||
feature: 'home' | 'https' | 'acme';
|
||||
optional?: boolean;
|
||||
}
|
||||
|
||||
function sysItems(): SysItem[] {
|
||||
return [
|
||||
{ title: _('Home-like link'), sub: _('Policy routing and the veth pair'), pkgs: ['ip-full', 'kmod-veth'], feature: 'home' },
|
||||
{ title: _('HTTPS for the portal'), sub: _('OpenSSL for uhttpd'), pkgs: ['libustream-openssl', 'openssl-util'], feature: 'https' },
|
||||
{
|
||||
title: _('Certificates (ACME)'),
|
||||
sub: _('Let’s Encrypt certificate for the portal'),
|
||||
pkgs: ['acme', 'acme-acmesh-dnsapi'],
|
||||
feature: 'acme',
|
||||
optional: true,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
const ICONS: Record<string, string> = { home: 'network', https: 'lock', acme: 'file' };
|
||||
|
||||
export function packageRows(page: ComponentsPage, p: UpdateComponent | undefined): { rows: Node[]; updates: number; total: number } {
|
||||
const st = page.st;
|
||||
const pkgs = p?.pkgs ?? {};
|
||||
const items = sysItems().filter((it) => (it.feature === 'home' ? st.home : st.portal));
|
||||
const runPkgs = async (names: string[], what: string, shown = names) => {
|
||||
const ok = await confirmDialog(
|
||||
fmt(_('Update %s?'), what),
|
||||
fmt(_('%s from the OpenWrt feeds. Services that use them restart for a moment.'), shown.join(', ')),
|
||||
_('Update'),
|
||||
);
|
||||
if (ok) void page.op(`pkgs:${names.join(',')}`, fmt(_('Updating %s'), what));
|
||||
};
|
||||
const menu: (MenuEntry | null)[] = [
|
||||
{ label: _('Check system packages'), ic: 'refresh', run: () => page.op('check:packages', _('Checking system packages')) },
|
||||
{
|
||||
label: _('Open the OpenWrt package list'),
|
||||
ic: 'globe',
|
||||
run: () => window.open('https://openwrt.org/packages/start', '_blank', 'noopener'),
|
||||
},
|
||||
];
|
||||
let updates = 0;
|
||||
const rows = items.map((it) => {
|
||||
const present = it.pkgs.filter((x) => pkgs[x]?.installed);
|
||||
const upd = [...new Set(present.flatMap((x) => [...(pkgs[x]?.latest ? [x] : []), ...(pkgs[x]?.with ?? [])]))];
|
||||
const lacks = st.needs?.[it.feature] ?? it.pkgs.filter((x) => !pkgs[x]?.installed);
|
||||
const main = present.find((x) => pkgs[x]?.latest);
|
||||
const vers = present.map((x) => `${x} ${pkgs[x]?.installed ?? ''}`).join(', ');
|
||||
if (lacks.length)
|
||||
return page.row(
|
||||
ICONS[it.feature],
|
||||
it.title,
|
||||
[it.optional ? _('not installed') : fmt(_('missing %s'), lacks.join(', '))],
|
||||
[
|
||||
button(
|
||||
_('Install'),
|
||||
() => page.op(`pkgs:${lacks.join(',')}`, fmt(_('Installing %s'), it.title)),
|
||||
it.optional ? 'neutral' : 'positive',
|
||||
{
|
||||
disabled: page.busy,
|
||||
},
|
||||
),
|
||||
E('span', { class: 'dl-comp-ic' }, page.more(menu)),
|
||||
],
|
||||
);
|
||||
if (p && upd.length) {
|
||||
updates++;
|
||||
return page.row(
|
||||
ICONS[it.feature],
|
||||
it.title,
|
||||
main ? [`${pkgs[main]!.installed} → ${pkgs[main]!.latest}`, upd.length > 1 ? ` · +${upd.length - 1}` : ''] : [upd.join(', ')],
|
||||
[
|
||||
button(
|
||||
_('Update'),
|
||||
() =>
|
||||
runPkgs(
|
||||
present.filter((x) => pkgs[x]?.latest || pkgs[x]?.with?.length),
|
||||
it.title,
|
||||
upd,
|
||||
),
|
||||
'neutral',
|
||||
{ disabled: page.busy },
|
||||
),
|
||||
E('span', { class: 'dl-comp-ic' }, page.more(menu)),
|
||||
],
|
||||
);
|
||||
}
|
||||
return page.row(
|
||||
ICONS[it.feature],
|
||||
it.title,
|
||||
[vers || it.sub],
|
||||
[page.state('pkgs', p, ''), E('span', { class: 'dl-comp-ic' }, page.more(menu))],
|
||||
);
|
||||
});
|
||||
return { rows, updates, total: items.length };
|
||||
}
|
||||
@@ -1,223 +0,0 @@
|
||||
// Diagnostics → Health: the watchdog, the checks and the latest problems.
|
||||
|
||||
import type { HealthCheck, LogEvent, Status } from '../../../shared/types';
|
||||
import { E } from '../../e';
|
||||
import { api, type Health, type ServiceLog } from '../../api';
|
||||
import { button } from '../../ui/button';
|
||||
import { attempt } from '../../ui/toast';
|
||||
import { sw, setSwitch } from '../../ui/controls';
|
||||
import { callout } from '../../ui/layout';
|
||||
import { icon } from '../../../shared/icons';
|
||||
import { ago, clock } from '../../../shared/format';
|
||||
import { fmt, num, plural } from '../../../shared/i18n';
|
||||
import { isProblem, type LogItem } from '../../events/model';
|
||||
import { eventRow, systemRow } from '../../events/render';
|
||||
import { fixAction, runFix } from '../../widgets/health';
|
||||
|
||||
const ICON: Record<HealthCheck['status'], string> = { ok: 'check', warn: 'alert', error: 'x', skip: 'pause' };
|
||||
|
||||
/** Diagnostics → Health: the watchdog, the checks and the latest problems from the log. */
|
||||
export class HealthTab {
|
||||
st: Status;
|
||||
el = E('div', {});
|
||||
wdEl = E('div', {});
|
||||
checksEl = E('div', { class: 'dl-panel' });
|
||||
recentEl = E('div', { class: 'dl-panel flush dl-recent' });
|
||||
sl: ServiceLog;
|
||||
events: LogEvent[];
|
||||
checks: HealthCheck[] | null = null;
|
||||
/** Shows the Log tab on its Problems filter. */
|
||||
toLog: () => void;
|
||||
summary = E('div', {});
|
||||
|
||||
constructor(st: Status, sl: ServiceLog, events: LogEvent[], toLog: () => void) {
|
||||
this.st = st;
|
||||
this.sl = sl;
|
||||
this.events = events;
|
||||
this.toLog = toLog;
|
||||
dom.content(this.el, [this.summary, this.wdEl, E('div', { class: 'dl-health-cols' }, [this.checksEl, this.recentEl])]);
|
||||
this.paintChecks();
|
||||
this.paintLive(sl, events);
|
||||
}
|
||||
|
||||
/** Run the checks (they take a moment: DNS, ports, certificates). */
|
||||
async run(fix?: string) {
|
||||
const r = fix ? await runFix(fix) : await api.health().catch(() => null);
|
||||
if (!r) return;
|
||||
this.take(r);
|
||||
// The network restarts a second after the answer: look again once it is back.
|
||||
if (fix === 'netrestart') setTimeout(() => this.el.isConnected && void this.run(), 5000);
|
||||
}
|
||||
|
||||
take(r: Health) {
|
||||
this.checks = r.checks;
|
||||
this.paintChecks();
|
||||
this.paintLive(r, this.events);
|
||||
}
|
||||
|
||||
paintChecks() {
|
||||
const checks = this.checks;
|
||||
if (!checks) {
|
||||
dom.content(this.summary, '');
|
||||
dom.content(this.checksEl, [
|
||||
E('div', { class: 'dl-panel-head' }, [E('h3', {}, _('Checks'))]),
|
||||
E('p', { class: 'dl-muted dl-loading' }, _('Running checks…')),
|
||||
]);
|
||||
return;
|
||||
}
|
||||
const bad = checks.filter((c) => c.status === 'error').length;
|
||||
const warn = checks.filter((c) => c.status === 'warn').length;
|
||||
dom.content(
|
||||
this.summary,
|
||||
bad
|
||||
? callout('error', plural(bad, '%s problem needs attention.', '%s problems need attention.'))
|
||||
: warn
|
||||
? callout('warn', plural(warn, '%s warning.', '%s warnings.'))
|
||||
: callout('ok', _('All checks passed.')),
|
||||
);
|
||||
const repaired = new Map<string, number>();
|
||||
for (const x of this.sl.watchdog.repairs) repaired.set(x.id, Math.max(repaired.get(x.id) ?? 0, x.ts));
|
||||
const refresh = () => this.run();
|
||||
dom.content(this.checksEl, [
|
||||
E('div', { class: 'dl-panel-head' }, [E('h3', {}, _('Checks')), E('span', { class: 'dl-spacer' }), button(_('Run again'), refresh)]),
|
||||
E(
|
||||
'ul',
|
||||
{ class: 'dl-checks' },
|
||||
checks.map((c) =>
|
||||
E('li', {}, [
|
||||
E('span', { class: `dl-check-icon ${c.status}` }, icon(ICON[c.status])),
|
||||
E('div', { class: 'dl-check-body' }, [
|
||||
// The check's title and detail come from the router.
|
||||
E('div', { class: 'dl-check-title' }, c.title),
|
||||
E('div', { class: 'dl-check-detail' }, c.detail),
|
||||
repaired.has(c.id)
|
||||
? E('div', { class: 'dl-check-repaired' }, fmt(_('Repaired by the watchdog at %s'), clock(repaired.get(c.id)!)))
|
||||
: '',
|
||||
]),
|
||||
fixAction(c, (fix) => void this.run(fix), refresh),
|
||||
]),
|
||||
),
|
||||
),
|
||||
]);
|
||||
}
|
||||
|
||||
/** The watchdog card and recent problems; refreshed by the page poll without running the checks again. */
|
||||
paintLive(sl: ServiceLog, events: LogEvent[]) {
|
||||
this.sl = sl;
|
||||
this.events = events;
|
||||
const wd = sl.watchdog;
|
||||
const stale = wd.beat != null && wd.now - wd.beat > 180;
|
||||
const today = wd.repairs.filter((x) => wd.now - x.ts < 86400);
|
||||
const lastRep = today[today.length - 1];
|
||||
const toggle = sw(wd.enabled, _('Watchdog repairs'), async (v) => {
|
||||
const ok = await attempt(() => api.settingsUpdate({ watchdog: v ? '1' : '0' }), v ? _('Watchdog on') : _('Watchdog off'));
|
||||
if (!ok) setSwitch(toggle, !v);
|
||||
const n = await api.serviceLog().catch(() => null);
|
||||
if (n) this.paintLive(n, this.events);
|
||||
});
|
||||
dom.content(
|
||||
this.wdEl,
|
||||
E('div', { class: 'dl-panel dl-wd' }, [
|
||||
E('div', { class: 'dl-wd-head' }, [
|
||||
E('span', { class: `dl-wd-tile${wd.enabled ? '' : ' off'}` }, icon('shield')),
|
||||
E('div', { class: 'dl-stack' }, [
|
||||
E('span', { class: 'dl-wd-title' }, _('Watchdog')),
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-sub' },
|
||||
wd.enabled
|
||||
? _('Every minute it checks the tunnels and services and repairs what it can on its own.')
|
||||
: _('Off: problems are only written to the log. Nothing is repaired on its own.'),
|
||||
),
|
||||
]),
|
||||
E('span', { class: 'dl-spacer' }),
|
||||
toggle,
|
||||
]),
|
||||
E('div', { class: 'dl-wd-foot' }, [
|
||||
E(
|
||||
'div',
|
||||
{ class: 'dl-wd-chips' },
|
||||
wd.targets.map((t) =>
|
||||
E(
|
||||
'span',
|
||||
{
|
||||
class: `dl-check-chip${t.ok ? '' : ' error'}`,
|
||||
title: t.ok
|
||||
? _('OK')
|
||||
: t.tries
|
||||
? `${_('Not working')} · ${plural(t.tries, '%s repair', '%s repairs')}`
|
||||
: _('Not working'),
|
||||
},
|
||||
// The target's name comes from the router.
|
||||
[icon(t.ok ? 'check' : 'x'), t.name],
|
||||
),
|
||||
),
|
||||
),
|
||||
E(
|
||||
'span',
|
||||
{ class: `dl-sub${stale ? ' dl-warn-text' : ''}` },
|
||||
stale
|
||||
? fmt(_('The agent has not checked in for %s min; cron restarts it after 5.'), num(Math.round((wd.now - wd.beat!) / 60)))
|
||||
: [
|
||||
wd.last ? fmt(_('Looked %s'), ago(wd.last, wd.now)) : _('Starts within a minute'),
|
||||
' · ',
|
||||
today.length
|
||||
? fmt(
|
||||
N_(today.length, '%s repair today, last %s at %s', '%s repairs today, last %s at %s'),
|
||||
num(today.length),
|
||||
lastRep.name,
|
||||
clock(lastRep.ts),
|
||||
)
|
||||
: _('no repairs today'),
|
||||
],
|
||||
),
|
||||
]),
|
||||
]),
|
||||
);
|
||||
this.paintRecent();
|
||||
}
|
||||
|
||||
/** Problems from the last 7 days, both kinds, newest first. */
|
||||
paintRecent() {
|
||||
const since = (this.sl.watchdog.now || Date.now() / 1000) - 7 * 86400;
|
||||
const items: LogItem[] = [...this.events.map((ev) => ({ ts: ev.ts, ev })), ...this.sl.log.map((sys) => ({ ts: sys.ts, sys }))]
|
||||
.filter((x) => x.ts >= since && isProblem(x))
|
||||
.sort((a, b) => b.ts - a.ts);
|
||||
const head = E('div', { class: 'dl-panel-head pad' }, [
|
||||
E('h3', {}, _('Recent problems')),
|
||||
E('span', { class: 'dl-spacer' }),
|
||||
items.length ? E('a', { href: '#', click: (e: Event) => (e.preventDefault(), this.toLog()) }, `${_('All in Log')} →`) : '',
|
||||
]);
|
||||
if (!items.length) {
|
||||
dom.content(this.recentEl, [
|
||||
head,
|
||||
E('div', { class: 'dl-recent-empty' }, [
|
||||
E('span', { class: 'dl-check-icon ok' }, icon('check')),
|
||||
_('No problems in the last 7 days.'),
|
||||
]),
|
||||
]);
|
||||
return;
|
||||
}
|
||||
dom.content(this.recentEl, [
|
||||
head,
|
||||
...items.slice(0, 8).map((x) => {
|
||||
if (x.sys) {
|
||||
const e = x.sys;
|
||||
const key = `${e.ts}|${e.msg}`;
|
||||
return systemRow(
|
||||
e,
|
||||
this.open.has(key),
|
||||
() => {
|
||||
if (!this.open.delete(key)) this.open.add(key);
|
||||
this.paintRecent();
|
||||
},
|
||||
clock(e.ts),
|
||||
);
|
||||
}
|
||||
return eventRow(this.st, x.ev!, { time: clock(x.ts) });
|
||||
}),
|
||||
]);
|
||||
}
|
||||
|
||||
open = new Set<string>();
|
||||
}
|
||||
@@ -1,118 +0,0 @@
|
||||
// Diagnostics: Health (watchdog, checks, recent problems) and Log (activity
|
||||
// and the service log in one list) as two tabs. ?tab=log opens the Log; the
|
||||
// old Health and Activity addresses come here.
|
||||
|
||||
import type { Status } from '../../../shared/types';
|
||||
import { E } from '../../e';
|
||||
import { api, type ServiceLog } from '../../api';
|
||||
import { createPoller } from '../../state/poller';
|
||||
import { HealthTab } from './health';
|
||||
import { LogTab } from './log';
|
||||
|
||||
type Tab = 'health' | 'log';
|
||||
type Events = Awaited<ReturnType<typeof api.events>>;
|
||||
type Loaded = [Status, Events, ServiceLog];
|
||||
|
||||
const TABS: Tab[] = ['health', 'log'];
|
||||
|
||||
const tabLabel = (t: Tab) => (t === 'log' ? _('Log') : _('Health'));
|
||||
|
||||
/** The whole log is large (up to 20,000 events): fetched only for the Log tab. A "since" cursor on the router would make it cheap. */
|
||||
const LOG_LIMIT = 20000;
|
||||
|
||||
export class DiagnosticsPage {
|
||||
tab: Tab = new URLSearchParams(location.search).get('tab') === 'log' ? 'log' : 'health';
|
||||
health!: HealthTab;
|
||||
log!: LogTab;
|
||||
segEl = E('div', { class: 'dl-seg dl-srvsections dl-diag-tabs', role: 'tablist', 'aria-label': _('Diagnostics') });
|
||||
subEl = E('span', { class: 'dl-muted' });
|
||||
actionsEl = E('div', { class: 'dl-row-actions' });
|
||||
bodyEl = E('div', {});
|
||||
/** When the events were last fetched (ms); switching to the Log refreshes stale ones. */
|
||||
eventsAt = 0;
|
||||
|
||||
load(): Promise<Loaded> {
|
||||
// The checks take a moment: Health shows first and runs them in the background (see show()).
|
||||
this.eventsAt = Date.now();
|
||||
return Promise.all([api.status(1), api.events(LOG_LIMIT), api.serviceLog()]);
|
||||
}
|
||||
|
||||
render([st, ev, sl]: Loaded): HTMLElement {
|
||||
this.log = new LogTab(st, ev, sl.log);
|
||||
this.health = new HealthTab(st, sl, ev.events, () => {
|
||||
this.show('log');
|
||||
this.log.show('problems');
|
||||
});
|
||||
this.show(this.tab);
|
||||
// The service log every 10 s; the activity log only while the Log tab shows it.
|
||||
createPoller({
|
||||
fetch: async () => {
|
||||
const withEvents = this.tab === 'log';
|
||||
const [n, e] = await Promise.all([
|
||||
api.serviceLog().catch(() => null),
|
||||
withEvents ? api.events(LOG_LIMIT).catch(() => null) : Promise.resolve(null),
|
||||
]);
|
||||
return n || e ? { n, e } : null;
|
||||
},
|
||||
every: 10,
|
||||
active: () => this.bodyEl.isConnected,
|
||||
apply: ({ n, e }) => this.take(n, e),
|
||||
});
|
||||
return E('div', {}, [
|
||||
E('div', { class: 'dl-pagehead' }, [
|
||||
E('div', { class: 'dl-stack' }, [E('h2', { class: 'dl-h1' }, _('Diagnostics')), this.subEl]),
|
||||
this.actionsEl,
|
||||
]),
|
||||
this.segEl,
|
||||
this.bodyEl,
|
||||
]);
|
||||
}
|
||||
|
||||
take(n: ServiceLog | null, e: Events | null) {
|
||||
if (e) {
|
||||
this.log.take(e);
|
||||
this.eventsAt = Date.now();
|
||||
}
|
||||
if (n) this.log.system = n.log;
|
||||
if (n) this.health.paintLive(n, e?.events ?? this.health.events);
|
||||
if (this.tab === 'log') this.log.paint();
|
||||
}
|
||||
|
||||
/**
|
||||
* Show a tab. The address stays as it is: changing it (even with
|
||||
* history.replaceState) makes Outline's router load the whole page again.
|
||||
*/
|
||||
show(tab: Tab) {
|
||||
this.tab = tab;
|
||||
dom.content(
|
||||
this.segEl,
|
||||
TABS.map((k) =>
|
||||
E(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
role: 'tab',
|
||||
class: k === tab ? 'on' : '',
|
||||
'aria-selected': k === tab ? 'true' : 'false',
|
||||
click: () => k !== this.tab && this.show(k),
|
||||
},
|
||||
tabLabel(k),
|
||||
),
|
||||
),
|
||||
);
|
||||
// Both tabs stay alive; only the visible one is in the page.
|
||||
this.bodyEl.replaceChildren(tab === 'log' ? this.log.el : this.health.el);
|
||||
this.subEl.textContent =
|
||||
tab === 'log' ? this.log.sub : _('Everything Dawnline depends on, checked live. The watchdog repairs what it can on its own.');
|
||||
dom.content(this.actionsEl, tab === 'log' ? this.log.actions() : '');
|
||||
if (tab === 'log') {
|
||||
this.log.paint();
|
||||
// Health doesn't poll the activity log: catch up when the Log opens.
|
||||
if (Date.now() - this.eventsAt > 10_000)
|
||||
void api
|
||||
.events(LOG_LIMIT)
|
||||
.then((e) => this.take(null, e))
|
||||
.catch(() => null);
|
||||
} else if (!this.health.checks) void this.health.run();
|
||||
}
|
||||
}
|
||||
@@ -1,191 +0,0 @@
|
||||
// Diagnostics → Log: people's activity and the service log (tunnel and
|
||||
// service starts, stops, watchdog repairs, errors) in one list, grouped by
|
||||
// day, with filters, export and clearing.
|
||||
|
||||
import type { LogEvent, Status } from '../../../shared/types';
|
||||
import { E } from '../../e';
|
||||
import { api, type LogCategory, type LogsInfo, type ServiceLogEntry } from '../../api';
|
||||
import { button } from '../../ui/button';
|
||||
import { dropdown } from '../../ui/menu';
|
||||
import { icon } from '../../../shared/icons';
|
||||
import { CATEGORIES, categoryLabel, categoryOf, isProblem, retentionText, type LogItem } from '../../events/model';
|
||||
import { dayTitle, eventRow, systemRow } from '../../events/render';
|
||||
import { clearLogDialog, exportEvents } from '../../logs';
|
||||
import { fmt, locale, num } from '../../../shared/i18n';
|
||||
|
||||
export type LogKind = 'all' | LogCategory | 'system';
|
||||
type Events = Awaited<ReturnType<typeof api.events>>;
|
||||
|
||||
/** Rows painted at a time; "Show more" adds another page. */
|
||||
const PAGE = 300;
|
||||
const KINDS: LogKind[] = ['all', 'connections', 'people', 'system', 'problems'];
|
||||
|
||||
export class LogTab {
|
||||
st: Status;
|
||||
events: LogEvent[] = [];
|
||||
system: ServiceLogEntry[] = [];
|
||||
policy!: LogsInfo['policy'];
|
||||
kind: LogKind = 'all';
|
||||
shown = PAGE;
|
||||
open = new Set<string>();
|
||||
list = E('div', {});
|
||||
/** Retention, for the page subtitle. */
|
||||
sub = '';
|
||||
tabs = E('div', { class: 'dl-seg', role: 'tablist' });
|
||||
el: HTMLElement;
|
||||
|
||||
constructor(st: Status, ev: Events, system: ServiceLogEntry[]) {
|
||||
this.st = st;
|
||||
this.take(ev);
|
||||
this.system = system;
|
||||
this.el = E('div', {}, [E('div', { class: 'dl-toolbar' }, [this.tabs]), this.list]);
|
||||
this.paint();
|
||||
}
|
||||
|
||||
/** Export and Clear, for the page head. */
|
||||
actions(): HTMLElement[] {
|
||||
const suffix = () => (this.kind === 'all' ? '' : this.kind);
|
||||
const run = (format: 'csv' | 'json') => () => {
|
||||
const items = this.filtered().reverse();
|
||||
exportEvents(
|
||||
this.st,
|
||||
items.filter((x) => x.ev).map((x) => x.ev!),
|
||||
format,
|
||||
suffix(),
|
||||
items.filter((x) => x.sys).map((x) => x.sys!),
|
||||
);
|
||||
};
|
||||
const exp = button([icon('download'), ` ${_('Export')}`], () =>
|
||||
dropdown(exp, [
|
||||
{ label: _('CSV (spreadsheet)'), icon: icon('download'), run: run('csv') },
|
||||
{ label: 'JSON', icon: icon('download'), run: run('json') },
|
||||
]),
|
||||
);
|
||||
const clear = button([icon('trash'), ` ${_('Clear')}`], () =>
|
||||
clearLogDialog(
|
||||
_('Clear the log'),
|
||||
_('Removes events from the log on the router.'),
|
||||
{},
|
||||
() => this.reload(),
|
||||
this.kind === 'all' ? undefined : this.kind,
|
||||
true,
|
||||
),
|
||||
);
|
||||
return [exp, clear];
|
||||
}
|
||||
|
||||
take(r: Events) {
|
||||
this.events = r.events;
|
||||
this.policy = r.policy;
|
||||
const off = CATEGORIES.filter((c) => !r.policy.categories.includes(c));
|
||||
const kept = retentionText(r.policy);
|
||||
this.sub = off.length ? `${kept} ${fmt(_('Not recorded: %s.'), off.map((c) => categoryLabel(c).toLowerCase()).join(', '))}` : kept;
|
||||
}
|
||||
|
||||
async reload() {
|
||||
const [r, sl] = await Promise.all([api.events(20000).catch(() => null), api.serviceLog().catch(() => null)]);
|
||||
if (r) this.take(r);
|
||||
if (sl) this.system = sl.log;
|
||||
this.paint();
|
||||
}
|
||||
|
||||
items(): LogItem[] {
|
||||
return [...this.events.map((ev) => ({ ts: ev.ts, ev })), ...this.system.map((sys) => ({ ts: sys.ts, sys }))].sort(
|
||||
(a, b) => b.ts - a.ts,
|
||||
);
|
||||
}
|
||||
|
||||
matches(x: LogItem, k: LogKind) {
|
||||
if (k === 'all') return true;
|
||||
if (k === 'problems') return isProblem(x);
|
||||
if (k === 'system') return !!x.sys;
|
||||
return !!x.ev && categoryOf(x.ev.type) === k;
|
||||
}
|
||||
|
||||
/** Newest first, matching the current tab. */
|
||||
filtered(): LogItem[] {
|
||||
return this.items().filter((x) => this.matches(x, this.kind));
|
||||
}
|
||||
|
||||
paintTabs(all: LogItem[]) {
|
||||
dom.content(
|
||||
this.tabs,
|
||||
KINDS.map((k) =>
|
||||
E(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
role: 'tab',
|
||||
class: k === this.kind ? 'on' : '',
|
||||
'aria-selected': k === this.kind ? 'true' : 'false',
|
||||
click: () => this.show(k),
|
||||
},
|
||||
[
|
||||
k === 'all' ? _('All') : k === 'system' ? _('System') : categoryLabel(k),
|
||||
E('b', {}, String(all.filter((x) => this.matches(x, k)).length)),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
show(k: LogKind) {
|
||||
this.kind = k;
|
||||
this.shown = PAGE;
|
||||
this.paint();
|
||||
}
|
||||
|
||||
paint() {
|
||||
this.paintTabs(this.items());
|
||||
const items = this.filtered();
|
||||
if (!items.length) {
|
||||
dom.content(
|
||||
this.list,
|
||||
E('div', { class: 'dl-empty' }, [
|
||||
E('p', {}, this.events.length || this.system.length ? _('No events match.') : _('The log is empty.')),
|
||||
]),
|
||||
);
|
||||
return;
|
||||
}
|
||||
const groups: HTMLElement[] = [];
|
||||
let day = '';
|
||||
let panel: HTMLElement | null = null;
|
||||
for (const x of items.slice(0, this.shown)) {
|
||||
const t = dayTitle(x.ts);
|
||||
if (t !== day) {
|
||||
day = t;
|
||||
panel = E('div', { class: 'dl-panel flush' }, E('div', { class: 'dl-panel-head pad' }, E('h3', {}, t)));
|
||||
groups.push(panel);
|
||||
}
|
||||
const time = new Date(x.ts * 1000).toLocaleTimeString(locale(), { hour: '2-digit', minute: '2-digit' });
|
||||
if (x.sys) {
|
||||
const key = `${x.sys.ts}|${x.sys.msg}`;
|
||||
panel!.appendChild(
|
||||
systemRow(
|
||||
x.sys,
|
||||
this.open.has(key),
|
||||
() => {
|
||||
if (!this.open.delete(key)) this.open.add(key);
|
||||
this.paint();
|
||||
},
|
||||
time,
|
||||
),
|
||||
);
|
||||
} else {
|
||||
panel!.appendChild(eventRow(this.st, x.ev!, { time }));
|
||||
}
|
||||
}
|
||||
if (items.length > this.shown)
|
||||
groups.push(
|
||||
E(
|
||||
'div',
|
||||
{ class: 'dl-more-row' },
|
||||
button(fmt(_('Show %s more of %s'), num(Math.min(PAGE, items.length - this.shown)), num(items.length - this.shown)), () => {
|
||||
this.shown += PAGE;
|
||||
this.paint();
|
||||
}),
|
||||
),
|
||||
);
|
||||
dom.content(this.list, groups);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
// Clearing the log: a question in the portal's sheet (its icon, what happens,
|
||||
// Cancel and Clear), with what to clear (a kind, the one the log shows by
|
||||
// default) and how old. The activity log and the service log ("System") are
|
||||
// cleared on the router each on its own; what each did is said in a toast.
|
||||
// One device's or one person's log clears only theirs.
|
||||
|
||||
import type { LogCategory, LogFilter } from '../../api';
|
||||
import { api } from '../../api';
|
||||
import { h } from '../../../portal/dom';
|
||||
import { closeSheet, openSheet, type View } from '../../../portal/ui/sheet';
|
||||
import { once } from '../../../portal/ui/feedback';
|
||||
import { glass } from '../../ui/glass';
|
||||
import { tabs } from '../../ui/tabs';
|
||||
import { errorText, notify } from '../../ui/toast';
|
||||
import { fmt, plural } from '../../../shared/i18n';
|
||||
import type { LogKind } from '../../events/find';
|
||||
import { KIND_ICON, kindLabel } from './filters';
|
||||
|
||||
type What = 'all' | LogCategory | 'system';
|
||||
/** The ages offered, in days ('' = everything). */
|
||||
const AGES = ['', '7', '30', '90'] as const;
|
||||
type Age = (typeof AGES)[number];
|
||||
|
||||
/** Short, for the track under "Which events": everything, or "7+ days" old. */
|
||||
const ageLabel = (v: Age) => (v ? plural(Number(v), '%s+ day', '%s+ days') : _('All'));
|
||||
const removed = (n: number) => (n ? plural(n, '%s event removed', '%s events removed') : _('Nothing matched'));
|
||||
|
||||
/**
|
||||
* Ask and clear. `base`: one person's or device's log (then the service log
|
||||
* stays: it is no one's); `kind`: what the log shows now, picked first.
|
||||
*/
|
||||
export function clearLog(base: LogFilter, kind: LogKind, done: () => unknown) {
|
||||
const whole = !base.person && !base.device;
|
||||
const kinds: What[] = whole ? ['all', 'connections', 'people', 'problems', 'system'] : ['all', 'connections', 'people', 'problems'];
|
||||
let what: What = kinds.includes(kind) ? kind : 'all';
|
||||
let age: Age = '';
|
||||
const view = (): View => {
|
||||
// The kinds as in the log's bar: icons, the picked one with its word (a sheet is narrow).
|
||||
const whatTrack = tabs(
|
||||
kinds.map((k) => ({ id: k, label: kindLabel(k), icon: KIND_ICON[k] })),
|
||||
what,
|
||||
(k) => (what = k),
|
||||
{ cls: 'icons', label: _('Category') },
|
||||
);
|
||||
const ageTrack = tabs(
|
||||
AGES.map((a) => ({ id: a || 'all', label: ageLabel(a) })),
|
||||
age || 'all',
|
||||
(a) => (age = a === 'all' ? '' : (a as Age)),
|
||||
{ label: _('Which events') },
|
||||
);
|
||||
const ok = h(
|
||||
'button',
|
||||
{ type: 'button', class: 'btn red', onclick: (ev: Event) => once(ev.currentTarget as HTMLButtonElement, () => run(what, age)) },
|
||||
h('span', {}, _('Clear')),
|
||||
) as HTMLButtonElement;
|
||||
const el = h(
|
||||
'div',
|
||||
{ class: 'view' },
|
||||
h(
|
||||
'div',
|
||||
{ class: 'ask clear-log' },
|
||||
glass('trash', 'red', 'gi xl'),
|
||||
h('h3', {}, _('Clear the log')),
|
||||
h('p', {}, `${_('Removes events from the log on the router.')} ${_('This cannot be undone; export first if you want a copy.')}`),
|
||||
h(
|
||||
'div',
|
||||
{ class: 'ask-picks' },
|
||||
h('span', { class: 'ask-pick-l' }, _('Category')),
|
||||
whatTrack.el,
|
||||
h('span', { class: 'ask-pick-l' }, _('Which events')),
|
||||
ageTrack.el,
|
||||
),
|
||||
h('div', { class: 'btnrow' }, h('button', { type: 'button', class: 'btn soft', onclick: () => closeSheet() }, _('Cancel')), ok),
|
||||
),
|
||||
);
|
||||
return { el, label: _('Clear the log'), asks: true };
|
||||
};
|
||||
|
||||
// The activity log first, then the service log ("System"; "All" clears it too on the whole log).
|
||||
async function run(w: What, a: Age) {
|
||||
let n = 0;
|
||||
if (w !== 'system') {
|
||||
try {
|
||||
n += (await api.logsClear({ ...base, category: w === 'all' ? '' : w, older_days: a })).removed;
|
||||
} catch (e) {
|
||||
notify(errorText(e), 'error', 10000);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (whole && (w === 'system' || w === 'all')) {
|
||||
try {
|
||||
n += (await api.serviceLogClear(a)).removed;
|
||||
} catch (e) {
|
||||
closeSheet();
|
||||
// The router's reason last, as it came.
|
||||
const failed = fmt(_('The service log was not cleared: %s'), errorText(e));
|
||||
notify(w === 'system' ? failed : `${fmt(_('Activity: %s.'), removed(n).toLowerCase())} ${failed}`, 'error', 10000);
|
||||
done();
|
||||
return;
|
||||
}
|
||||
}
|
||||
closeSheet();
|
||||
notify(removed(n), 'success', 3000);
|
||||
done();
|
||||
}
|
||||
|
||||
openSheet(view);
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
// The Log's feed: days as groups, each a head that stays in sight while its rows scroll, over a raised card of the
|
||||
// feed's rows (widgets/feed.ts draws them; here the time is their first column and the server a quiet word at a
|
||||
// row's end, styles/shadow/log.css `lg-*`). Under them «Show more»; and what stands in the feed's place when
|
||||
// nothing shows: no entry fits the filters (with the way to take them off), or the log is empty.
|
||||
|
||||
import { h } from '../../../portal/dom';
|
||||
import { fmt, num } from '../../../shared/i18n';
|
||||
import { dayTitle } from '../../events/clock';
|
||||
import { byDay, type FeedItem } from '../../events/sessions';
|
||||
import { emptyState } from '../../ui/empty';
|
||||
import { secHead } from '../../ui/page-head';
|
||||
import { feedRows, type FeedContext } from '../../widgets/feed';
|
||||
|
||||
/** The rows under their days' heads; `today`: the router's day now. */
|
||||
export function dayGroups(c: FeedContext, items: FeedItem[], today: string): HTMLElement[] {
|
||||
return byDay(items, c.tz).map((g) => {
|
||||
const rows = feedRows(c, g.items);
|
||||
// the server leaves the sentence: one column at the rows' end
|
||||
for (const s of rows.querySelectorAll<HTMLElement>('.ev-srv')) {
|
||||
s.classList.add('lg-srv');
|
||||
s.closest('.ev')?.append(s);
|
||||
}
|
||||
const head = secHead(dayTitle(g.day, today), num(g.items.length));
|
||||
head.classList.add('lg-dh');
|
||||
return h('section', { class: 'grp lg-day', 'data-key': g.day }, head, h('div', { class: 'card flat-list' }, rows));
|
||||
});
|
||||
}
|
||||
|
||||
/** «Show 300 more of 1,240»: `rest` rows are not drawn yet, `page` come with a press. */
|
||||
export function moreRow(rest: number, page: number, more: () => void): HTMLElement {
|
||||
const b = h(
|
||||
'button',
|
||||
{ type: 'button', class: 'btn soft' },
|
||||
h('span', {}, fmt(_('Show %s more of %s'), num(Math.min(page, rest)), num(rest))),
|
||||
);
|
||||
b.addEventListener('click', more);
|
||||
return h('div', { class: 'more-row' }, b);
|
||||
}
|
||||
|
||||
/** Nothing to show. `any`: the log has entries, none of them fits (`text`: the search, when that is why). */
|
||||
export function nothing(o: { any: boolean; text: string; reset: () => void }): HTMLElement {
|
||||
if (!o.any) return emptyState({ icon: 'log', title: _('The log is empty.'), text: _('Entries appear when someone connects.') });
|
||||
const b = h('button', { type: 'button', class: 'btn soft sm' }, h('span', {}, _('Reset the filters')));
|
||||
b.addEventListener('click', o.reset);
|
||||
return emptyState({
|
||||
icon: 'log',
|
||||
title: o.text ? fmt(_('Nothing matches “%s”.'), o.text) : _('No such entries'),
|
||||
text: _('No log entry fits these filters.'),
|
||||
action: b,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
// The Log's bar (ui/filter-bar.ts): the kinds of entries as a track with each kind's count; under it the search
|
||||
// (text, a person, an address; «/» reaches it) and the filters as chips: a day in one press (Today, Yesterday,
|
||||
// 7 days), then a person, a device and, with more than one, a server, each picked from a list that says how many
|
||||
// entries the choice would leave (ui/list-drop.ts). An active chip names its value and opens its list again; its ×
|
||||
// takes it off, «Reset» takes off everything, and the count says «4 of 63». The bar holds nothing itself: the page
|
||||
// keeps what is asked (events/scope.ts, in the address) and draws the bar again when it changes.
|
||||
|
||||
import type { Status } from '../../../shared/types';
|
||||
import { fmt, num, plural } from '../../../shared/i18n';
|
||||
import { kindLabel as deviceKind } from '../../../shared/format';
|
||||
import { categoryLabel } from '../../events/model';
|
||||
import { KINDS, type LogKind } from '../../events/find';
|
||||
import { DAYS, WHOLE, narrowed, type Choices, type LogDay, type LogQuery } from '../../events/scope';
|
||||
import { focusInside } from '../../state/poller';
|
||||
import { filterBar, filterChip, searchField } from '../../ui/filter-bar';
|
||||
import { openList, type ListItem } from '../../ui/list-drop';
|
||||
import { tabs } from '../../ui/tabs';
|
||||
|
||||
export const KIND_ICON: Record<LogKind, string> = {
|
||||
all: 'log',
|
||||
connections: 'plug',
|
||||
people: 'people',
|
||||
system: 'sunrise',
|
||||
problems: 'alert',
|
||||
};
|
||||
|
||||
export const kindLabel = (k: LogKind): string => (k === 'all' ? _('All') : k === 'system' ? _('System') : categoryLabel(k));
|
||||
|
||||
const dayLabel = (d: LogDay): string => ({ today: _('Today'), yesterday: _('Yesterday'), '7d': _('7 days') })[d];
|
||||
|
||||
/** A device's line icon by its kind (a phone for the rest). */
|
||||
const kindIcon = (k: string | undefined): string => (k === 'computer' || k === 'tablet' || k === 'router' ? k : 'phone');
|
||||
|
||||
export interface LogBar {
|
||||
el: HTMLElement;
|
||||
/** The counts beside each kind. */
|
||||
counts(n: Record<LogKind, number>): void;
|
||||
/**
|
||||
* The chips for what is asked now and the count «4 of 63». A quiet repaint (the router's news) leaves chips
|
||||
* that hold the focus or an open list as they are.
|
||||
*/
|
||||
paint(q: LogQuery, v: { choices: Choices; shown: number; of: number }, quiet?: boolean): void;
|
||||
/** Everything off: the search emptied, the track back on «All», the page told once. */
|
||||
reset(): void;
|
||||
}
|
||||
|
||||
interface BarHost {
|
||||
page: HTMLElement;
|
||||
/** What the address asked for. */
|
||||
q: LogQuery;
|
||||
st(): Pick<Status, 'people' | 'servers'>;
|
||||
/** The name the log kept of a person or a device the router no longer has. */
|
||||
kept(what: 'person' | 'device', id: string): string | undefined;
|
||||
/** Filters changed (`typed`: by the search, a key at a time). */
|
||||
set(patch: Partial<LogQuery>, typed?: boolean): void;
|
||||
}
|
||||
|
||||
/** A chip that picks one of a list: offered by its name, active with its value; its × takes the filter off. */
|
||||
function pickChip(o: {
|
||||
key: string;
|
||||
title: string;
|
||||
/** The chip's words while it is on («Person: Lena»). */
|
||||
value: string | null;
|
||||
items: () => ListItem[];
|
||||
pick: (id: string) => void;
|
||||
off: () => void;
|
||||
}): HTMLElement {
|
||||
const el = filterChip({
|
||||
label: o.value ?? o.title,
|
||||
on: o.value != null,
|
||||
menu: 'list',
|
||||
cls: 'lg-pick',
|
||||
press: (from) => openList(from, o.items(), o.title, o.pick),
|
||||
off: o.off,
|
||||
});
|
||||
el.dataset.f = o.key;
|
||||
return el;
|
||||
}
|
||||
|
||||
function chips(q: LogQuery, c: Choices, o: BarHost): HTMLElement[] {
|
||||
const st = o.st();
|
||||
const entries = (n: number) => plural(n, '%s entry', '%s entries');
|
||||
const owned = st.people.flatMap((p) => p.devices.map((d) => ({ d, p })));
|
||||
const personName = (id: string) => st.people.find((p) => p.id === id)?.name ?? o.kept('person', id) ?? _('Removed person');
|
||||
const deviceName = (id: string) => owned.find((x) => x.d.id === id)?.d.name ?? o.kept('device', id) ?? _('Removed device');
|
||||
const server = st.servers.find((s) => s.id === q.server);
|
||||
const kids: (HTMLElement | null)[] = DAYS.map((d) => {
|
||||
// a day is one of three, not one more filter: its chip is the word alone
|
||||
const el = filterChip({ label: dayLabel(d), on: q.day === d, cls: 'lg-daychip', press: () => o.set({ day: q.day === d ? '' : d }) });
|
||||
el.dataset.f = d;
|
||||
return el;
|
||||
});
|
||||
kids.push(
|
||||
c.people.length
|
||||
? pickChip({
|
||||
key: 'person',
|
||||
title: _('Person'),
|
||||
value: q.person ? fmt(_('Person: %s'), personName(q.person)) : null,
|
||||
items: () =>
|
||||
c.people.map((x) => ({ id: x.id, label: personName(x.id), sub: entries(x.n), icon: 'person', on: x.id === q.person })),
|
||||
pick: (id) => o.set({ person: id }),
|
||||
off: () => o.set({ person: '' }),
|
||||
})
|
||||
: null,
|
||||
c.devices.length
|
||||
? pickChip({
|
||||
key: 'device',
|
||||
title: _('Device'),
|
||||
value: q.device ? fmt(_('Device: %s'), deviceName(q.device)) : null,
|
||||
items: () =>
|
||||
c.devices.map((x) => {
|
||||
const own = owned.find((y) => y.d.id === x.id);
|
||||
return {
|
||||
id: x.id,
|
||||
label: deviceName(x.id),
|
||||
// whose it is, what it is, how many entries
|
||||
sub: [own?.p.name, own ? deviceKind(own.d.kind) : null, entries(x.n)].filter(Boolean).join(' · '),
|
||||
icon: kindIcon(own?.d.kind),
|
||||
on: x.id === q.device,
|
||||
};
|
||||
}),
|
||||
pick: (id) => o.set({ device: id }),
|
||||
off: () => o.set({ device: '' }),
|
||||
})
|
||||
: null,
|
||||
st.servers.length > 1 || server
|
||||
? pickChip({
|
||||
key: 'server',
|
||||
title: _('Server'),
|
||||
value: server ? fmt(_('Server: %s'), server.name) : null,
|
||||
items: () =>
|
||||
c.servers.map((x) => {
|
||||
const s = st.servers.find((y) => y.id === x.id)!;
|
||||
return {
|
||||
id: s.id,
|
||||
label: s.name,
|
||||
sub: [s.enabled ? null : _('Turned off'), entries(x.n)].filter(Boolean).join(' · '),
|
||||
icon: 'terminal',
|
||||
on: s.id === q.server,
|
||||
};
|
||||
}),
|
||||
pick: (id) => o.set({ server: id }),
|
||||
off: () => o.set({ server: '' }),
|
||||
})
|
||||
: null,
|
||||
);
|
||||
return kids.filter((k): k is HTMLElement => !!k);
|
||||
}
|
||||
|
||||
export function logBar(o: BarHost): LogBar {
|
||||
// «Reset» moves the track itself: the page then hears of everything at once, not of the kind first
|
||||
let silent = false;
|
||||
const track = tabs(
|
||||
KINDS.map((k) => ({ id: k, label: kindLabel(k), icon: KIND_ICON[k], sub: '' })),
|
||||
o.q.kind,
|
||||
(k) => {
|
||||
if (!silent) o.set({ kind: k });
|
||||
},
|
||||
{ cls: 'icons log-kind', label: _('Which entries'), keep: 'log-kind' },
|
||||
);
|
||||
const search = searchField({
|
||||
placeholder: _('Text, person, IP'),
|
||||
label: _('Find in the log'),
|
||||
page: o.page,
|
||||
value: o.q.q,
|
||||
typed: (v) => o.set({ q: v.trim() }, true),
|
||||
});
|
||||
const bar = filterBar({ top: [track.el], lead: search.el });
|
||||
bar.el.classList.add('lg-bar');
|
||||
const row = bar.el.querySelector<HTMLElement>('.kt-chips')!;
|
||||
const reset = () => {
|
||||
search.clear();
|
||||
silent = true;
|
||||
// the track's own press: its pill glides back to «All»
|
||||
track.el.querySelector<HTMLElement>('.tab[data-id="all"]')?.click();
|
||||
silent = false;
|
||||
o.set(WHOLE);
|
||||
};
|
||||
return {
|
||||
el: bar.el,
|
||||
reset,
|
||||
counts: (n) => track.subs((k) => num(n[k])),
|
||||
paint(q, v, quiet = false) {
|
||||
bar.count(v.shown, v.of, v.shown === v.of);
|
||||
const held = focusInside(row);
|
||||
if (quiet && (held || row.querySelector('[aria-expanded="true"]'))) return;
|
||||
// the chip that was pressed from the keyboard keeps the focus when the row is drawn again
|
||||
const at = held ? (row.getRootNode() as Document | ShadowRoot).activeElement?.closest<HTMLElement>('[data-f]')?.dataset.f : null;
|
||||
// an empty log has nothing to filter
|
||||
bar.chips(v.of ? chips(q, v.choices, o) : [], narrowed(q) ? reset : null);
|
||||
if (at) row.querySelector<HTMLElement>(`[data-f="${at}"] .kt-fb`)?.focus({ preventScroll: true });
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,324 @@
|
||||
// The Log: what happened, people's activity and the service log in one feed. The page's own section row on top;
|
||||
// the head with the count, how long the log is kept and what it does not record, «Export» (what is shown now, as
|
||||
// CSV or JSON) and, for a login that may write, ⋯ with clearing (clear.ts); the bar (filters.ts): the kinds with
|
||||
// their counts, the search, and the filters as chips (a day, a person, a device, a server); then the days as
|
||||
// groups of rows under heads that stay in sight (days.ts). Names in the rows lead to the person's and the
|
||||
// device's panel in People.
|
||||
//
|
||||
// Every filter is in the address (events/scope.ts reads and writes it; log?person=, ?device=, ?kind=, ?day=,
|
||||
// ?server=, ?q=) and a change replaces the history entry: Back leaves the Log. The whole log is read once and
|
||||
// narrowed here, so a filter never asks the router again.
|
||||
//
|
||||
// Live: the revision fetches what is new (events after the newest shown) and the service log, with a slow
|
||||
// fallback; a clear fetches everything again.
|
||||
|
||||
import type { LogEvent, Status } from '../../../shared/types';
|
||||
import { share } from '../../../shared/live/share';
|
||||
import { api, type LogsInfo, type ServiceLogEntry } from '../../api';
|
||||
import { h } from '../../../portal/dom';
|
||||
import { openMenu } from '../../../portal/ui/menu';
|
||||
import { fmt, plural } from '../../../shared/i18n';
|
||||
import { CATEGORIES, categoryLabel, retentionText } from '../../events/model';
|
||||
import { sessions, type FeedItem } from '../../events/sessions';
|
||||
import { routerDay } from '../../events/clock';
|
||||
import { haystack, kindCounts, matchesKind, matchesQuery } from '../../events/find';
|
||||
import { choices, inScope, logQueryParams, parseLogQuery, withFilters, type Clock, type LogQuery } from '../../events/scope';
|
||||
import { exportEvents } from '../../logs';
|
||||
import { createPoller, repaint } from '../../state/poller';
|
||||
import { glass } from '../../ui/glass';
|
||||
import { ic } from '../../ui/icons';
|
||||
import { openList } from '../../ui/list-drop';
|
||||
import { fact, knob, pageHead, setFacts } from '../../ui/page-head';
|
||||
import { publishScrollPad } from '../../ui/rail';
|
||||
import { canWrite } from '../../shell/role';
|
||||
import { deviceUrl, logUrl, personUrl } from '../../shell/routes';
|
||||
import { navRow } from '../../shell/nav';
|
||||
import { rowText, type FeedContext } from '../../widgets/feed';
|
||||
import { dayGroups, moreRow, nothing } from './days';
|
||||
import { logBar, type LogBar } from './filters';
|
||||
import { clearLog } from './clear';
|
||||
|
||||
/** The newest events fetched (the router keeps up to its log_max, 2,000 by default). */
|
||||
const LIMIT = 20000;
|
||||
/** Rows drawn at a time; "Show more" adds another page. */
|
||||
const PAGE = 300;
|
||||
/** How long the search rests before the address follows it (ms). */
|
||||
const TYPED = 300;
|
||||
|
||||
type Events = Awaited<ReturnType<typeof api.events>>;
|
||||
export type LogData = [Status, Events, ServiceLogEntry[]];
|
||||
|
||||
export class LogPage {
|
||||
private q: LogQuery = parseLogQuery(location.search.replace(/^\?/, ''));
|
||||
private st!: Status;
|
||||
/** The router's clock minus the browser's (s): "today" stays the router's while the page is open past midnight. */
|
||||
private skew = 0;
|
||||
private events: LogEvent[] = [];
|
||||
private system: ServiceLogEntry[] = [];
|
||||
private policy!: LogsInfo['policy'];
|
||||
/** The feed's rows for what was read last (null: to be folded again). */
|
||||
private feed: FeedItem[] | null = null;
|
||||
/** The minute the list was last drawn in. */
|
||||
private minute = 0;
|
||||
private shown = PAGE;
|
||||
private open = new Set<string>();
|
||||
/** What each row says, for the search (said anew when the person filter changes: their name leaves the rows). */
|
||||
private said = new WeakMap<FeedItem, string>();
|
||||
private page = h('div', { class: 'page log' });
|
||||
private list = h('div', { class: 'feed lg-feed' });
|
||||
private head!: HTMLElement;
|
||||
private bar!: LogBar;
|
||||
private writing = 0;
|
||||
|
||||
/** The page builds on the router's answer from its first line: it waits for it under its shape (shell/waiting.ts). */
|
||||
load(): Promise<LogData> {
|
||||
return Promise.all([api.status(1), api.events(LIMIT), api.serviceLog().then((s) => s.log)]);
|
||||
}
|
||||
|
||||
render([st, ev, sys]: LogData): HTMLElement {
|
||||
this.st = st;
|
||||
this.skew = st.now - Date.now() / 1000;
|
||||
this.take(ev, sys, false);
|
||||
// a server the router no longer has filters nothing
|
||||
if (this.q.server && !st.servers.some((s) => s.id === this.q.server)) this.q = { ...this.q, server: '' };
|
||||
this.bar = logBar({
|
||||
page: this.page,
|
||||
q: this.q,
|
||||
st: () => this.st,
|
||||
kept: (what, id) => this.kept(what, id),
|
||||
set: (patch, typed) => this.set(patch, typed),
|
||||
});
|
||||
this.head = pageHead({ icon: glass('log', 'grey'), title: _('Log'), acts: [this.exportButton(), this.clearKnob()] });
|
||||
this.page.append(navRow(), this.head, this.bar.el, this.list);
|
||||
this.paint();
|
||||
publishScrollPad(this.page);
|
||||
createPoller({
|
||||
fetch: (live) => this.fetch(live),
|
||||
every: 30,
|
||||
live: true,
|
||||
active: () => this.list.isConnected,
|
||||
apply: (d, quiet) => {
|
||||
const was = [this.events, this.system, this.st, this.policy, this.minute];
|
||||
const st = d.st ? share(this.st, d.st) : this.st;
|
||||
// names the rows say come from it
|
||||
if (st !== this.st) this.feed = null;
|
||||
this.st = st;
|
||||
this.take(d.ev, d.sys, d.since > 0);
|
||||
this.minute = Math.floor(Date.now() / 60_000);
|
||||
// the same answer again, in the background: the list stands as it is (what it says of «now» moves with the minute)
|
||||
const now = [this.events, this.system, this.st, this.policy, this.minute];
|
||||
if (quiet && now.every((v, i) => v === was[i])) return;
|
||||
this.paint({ quiet });
|
||||
},
|
||||
});
|
||||
return this.page;
|
||||
}
|
||||
|
||||
/* ---------- the head ---------- */
|
||||
|
||||
/** «Export»: what is shown now, in one of two forms. */
|
||||
private exportButton(): HTMLElement {
|
||||
const b = h(
|
||||
'button',
|
||||
{ type: 'button', class: 'btn soft sm lg-exp', 'aria-haspopup': 'menu', title: _('Download what is shown now') },
|
||||
ic('download'),
|
||||
h('span', {}, _('Export')),
|
||||
);
|
||||
b.addEventListener('click', () =>
|
||||
openList(
|
||||
b,
|
||||
[
|
||||
{ id: 'csv', label: 'CSV', sub: _('A spreadsheet'), icon: 'file' },
|
||||
{ id: 'json', label: 'JSON', sub: _('For a script'), icon: 'code' },
|
||||
],
|
||||
_('Export the log'),
|
||||
(f) => this.export(f as 'csv' | 'json'),
|
||||
{ role: 'menu' },
|
||||
),
|
||||
);
|
||||
return b;
|
||||
}
|
||||
|
||||
/** ⋯: clearing, for a login that may. */
|
||||
private clearKnob(): HTMLElement | null {
|
||||
if (!canWrite()) return null;
|
||||
const more = knob('more', _('Clear the log'));
|
||||
more.setAttribute('aria-haspopup', 'menu');
|
||||
more.addEventListener('click', () =>
|
||||
openMenu(
|
||||
more,
|
||||
[
|
||||
{
|
||||
label: _('Clear the log'),
|
||||
icon: 'trash',
|
||||
tone: 'bad',
|
||||
run: () =>
|
||||
clearLog({ person: this.q.person || undefined, device: this.q.device || undefined }, this.q.kind, () => void this.reload()),
|
||||
},
|
||||
],
|
||||
_('Log'),
|
||||
),
|
||||
);
|
||||
return more;
|
||||
}
|
||||
|
||||
/** The head's facts: how many entries, how long they are kept, what is not recorded, a read-only login. */
|
||||
private paintFacts(all: number) {
|
||||
const p = this.policy;
|
||||
const off = CATEGORIES.filter((c) => !p.categories.includes(c));
|
||||
setFacts(this.head, [
|
||||
fact(plural(all, '%s entry', '%s entries')),
|
||||
fact(p.keep_days > 0 ? fmt(_('kept %s'), plural(p.keep_days, '%s day', '%s days')) : _('kept with no age limit'), {
|
||||
title: retentionText(p),
|
||||
}),
|
||||
off.length
|
||||
? fact(fmt(_('not recorded: %s'), off.map((c) => categoryLabel(c).toLocaleLowerCase()).join(', ')), { cls: 'warn-t' })
|
||||
: null,
|
||||
canWrite() ? null : fact([ic('eye'), _('View only')]),
|
||||
]);
|
||||
}
|
||||
|
||||
/* ---------- what the router said ---------- */
|
||||
|
||||
/**
|
||||
* New rows: on the live revision, events after the newest shown (a second back, de-duplicated: two in one
|
||||
* second), with the status again when one names someone this page does not know yet; else everything.
|
||||
*/
|
||||
private async fetch(live: boolean) {
|
||||
const newest = this.events.length ? this.events[this.events.length - 1].ts : 0;
|
||||
const since = live && newest ? newest - 1 : 0;
|
||||
const [ev, sys] = await Promise.all([api.events(LIMIT, undefined, since || undefined), api.serviceLog().then((s) => s.log)]);
|
||||
const known = new Set(this.st.people.flatMap((p) => [p.id, ...p.devices.map((d) => d.id)]));
|
||||
const stranger = ev.events.some((e) => (e.person && !known.has(e.person)) || (e.device && !known.has(e.device)));
|
||||
return { ev, sys, since, st: stranger ? await api.status(1).catch(() => null) : null };
|
||||
}
|
||||
|
||||
/** Take an answer: `add`: events after the newest (merged), else all of them. */
|
||||
private take(r: Events, sys: ServiceLogEntry[], add: boolean) {
|
||||
// each answer laid over the last (shared/live/share.ts): what did not change is the object it was, so
|
||||
// «nothing new» is seen as that
|
||||
const before = [this.events, this.system];
|
||||
if (add) {
|
||||
const key = (e: LogEvent) => `${e.ts}|${e.type}|${e.device ?? ''}|${e.person ?? ''}|${e.detail ?? ''}`;
|
||||
const have = new Set(this.events.slice(-50).map(key));
|
||||
const fresh = r.events.filter((e) => !have.has(key(e)));
|
||||
if (fresh.length) this.events = [...this.events, ...fresh].slice(-LIMIT);
|
||||
} else this.events = share(this.events, r.events);
|
||||
this.system = share(this.system, sys);
|
||||
this.policy = share(this.policy, r.policy);
|
||||
if (this.events !== before[0] || this.system !== before[1]) this.feed = null;
|
||||
}
|
||||
|
||||
/** Everything again (after a clear). */
|
||||
private async reload() {
|
||||
const d = await this.fetch(false).catch(() => null);
|
||||
if (!d) return;
|
||||
if (d.st) this.st = d.st;
|
||||
this.take(d.ev, d.sys, false);
|
||||
this.paint();
|
||||
}
|
||||
|
||||
/** The name the log kept of someone or something removed since (the newest entry's). */
|
||||
private kept(what: 'person' | 'device', id: string): string | undefined {
|
||||
for (let i = this.events.length - 1; i >= 0; i--) {
|
||||
const e = this.events[i];
|
||||
if (what === 'person' ? e.person === id && e.pname : e.device === id && e.dname) return what === 'person' ? e.pname : e.dname;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/* ---------- the filters ---------- */
|
||||
|
||||
/** A filter changed: the address follows (the same history entry), the rows are drawn again from the top. */
|
||||
private set(patch: Partial<LogQuery>, typed = false) {
|
||||
const own = this.q.person;
|
||||
this.q = withFilters(this.q, patch, this.st.people);
|
||||
if (this.q.person !== own) this.said = new WeakMap();
|
||||
clearTimeout(this.writing);
|
||||
const write = () => {
|
||||
if (this.page.isConnected) history.replaceState(history.state, '', logUrl(logQueryParams(this.q)));
|
||||
};
|
||||
// typing: the address follows once it rests (a browser refuses an address rewritten a hundred times in a row)
|
||||
if (typed) this.writing = window.setTimeout(write, TYPED);
|
||||
else write();
|
||||
this.shown = PAGE;
|
||||
this.paint({ still: typed });
|
||||
}
|
||||
|
||||
private clock(): Clock {
|
||||
return { now: Date.now() / 1000 + this.skew, tz: this.st.tz };
|
||||
}
|
||||
|
||||
private context(): FeedContext {
|
||||
return {
|
||||
st: this.st,
|
||||
tz: this.st.tz,
|
||||
own: this.q.person || undefined,
|
||||
links: { person: (id) => personUrl(id), device: (_p, d) => deviceUrl(d) },
|
||||
open: this.open,
|
||||
toggled: () => this.paint(),
|
||||
};
|
||||
}
|
||||
|
||||
/** Every row of the log, newest first. */
|
||||
private items(): FeedItem[] {
|
||||
if (!this.feed) {
|
||||
const online = new Set(this.st.people.flatMap((p) => p.devices.filter((d) => d.online).map((d) => d.id)));
|
||||
this.feed = sessions(this.events, this.system, (d) => online.has(d));
|
||||
}
|
||||
return this.feed;
|
||||
}
|
||||
|
||||
/** The rows that show: of the scope (who, where, when), of the kind picked, with the words searched. */
|
||||
private matching(scoped: FeedItem[]): FeedItem[] {
|
||||
const { kind, q } = this.q;
|
||||
const c = this.context();
|
||||
const said = (x: FeedItem) => {
|
||||
let s = this.said.get(x);
|
||||
if (s == null) this.said.set(x, (s = rowText(c, x)));
|
||||
return s;
|
||||
};
|
||||
return scoped.filter((x) => matchesKind(x, kind) && (!q || matchesQuery(haystack(x, this.st, said(x)), q)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Draw the bar and the rows that match. `quiet`: the router's news, which leaves a list that holds the focus
|
||||
* alone; `still`: a search being typed, the rows follow at once.
|
||||
*/
|
||||
private paint(o: { quiet?: boolean; still?: boolean } = {}) {
|
||||
const all = this.items();
|
||||
const clock = this.clock();
|
||||
const scoped = all.filter(inScope(this.q, this.st, clock));
|
||||
const items = this.matching(scoped);
|
||||
this.paintFacts(all.length);
|
||||
this.bar.counts(kindCounts(scoped));
|
||||
this.bar.paint(this.q, { choices: choices(all, this.q, this.st, clock), shown: items.length, of: all.length }, o.quiet);
|
||||
const rest = items.length - this.shown;
|
||||
const more = () => {
|
||||
this.shown += PAGE;
|
||||
this.paint();
|
||||
};
|
||||
const content = items.length
|
||||
? [
|
||||
...dayGroups(this.context(), items.slice(0, this.shown), routerDay(clock.now, clock.tz)),
|
||||
// no «Show more» when all of them show (a null would be put in as the word «null»)
|
||||
...(rest > 0 ? [moreRow(rest, PAGE, more)] : []),
|
||||
]
|
||||
: nothing({ any: all.length > 0, text: this.q.q, reset: () => this.bar.reset() });
|
||||
// rows that stay glide to their places, new ones blur in, those filtered away fade where they stood
|
||||
repaint(this.list, content, o.quiet, o.still);
|
||||
}
|
||||
|
||||
/** Download what shows now: the events behind the rows (a session with its disconnect) and the service lines. */
|
||||
private export(format: 'csv' | 'json') {
|
||||
const q = this.q;
|
||||
const items = this.matching(this.items().filter(inScope(q, this.st, this.clock())));
|
||||
exportEvents(
|
||||
this.st,
|
||||
items.flatMap((x) => (x.ev ? [x.ev, ...(x.end ? [x.end] : [])] : [])),
|
||||
format,
|
||||
[q.device || q.person, q.kind === 'all' ? '' : q.kind, q.day].filter(Boolean).join('-'),
|
||||
items.flatMap((x) => (x.sys ? [x.sys] : [])),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,503 +0,0 @@
|
||||
// A server's Overview section (first tab on the Servers page): who is
|
||||
// online, traffic, disguise, the connection map, activity and what needs
|
||||
// attention — all limited to the people on that server.
|
||||
|
||||
import type { Device, GeoPoint, Person, Status } from '../../shared/types';
|
||||
import { E } from '../e';
|
||||
import { api } from '../api';
|
||||
import { attachTip, refreshTip } from '../ui/tooltip';
|
||||
import { icon } from '../../shared/icons';
|
||||
import { ago, bits, bytes, date, daysLeft, duration, endsIn, endsSoon, initials, todayOf } from '../../shared/format';
|
||||
import { fill, fmt, plural } from '../../shared/i18n';
|
||||
import { ConnectionMap, rangeControl, type Range } from '../map';
|
||||
import { personUrl } from '../urls';
|
||||
import { eventRow } from '../events/render';
|
||||
import { scoped } from '../state/scope';
|
||||
import { focusInside, repaint } from '../state/poller';
|
||||
import type { LiveMeter } from '../state/meter';
|
||||
import { daysTile, LiveSpeedTile } from '../widgets/tiles';
|
||||
import { SpeedLines } from '../widgets/lines';
|
||||
import { coreOf } from '../cores';
|
||||
import { healthNotices, runFix } from '../widgets/health';
|
||||
import { attempt } from '../ui/toast';
|
||||
import { isIpv4 } from '../netcheck';
|
||||
import { onNavigate } from '../ui/nav';
|
||||
|
||||
interface Attention {
|
||||
tone: string;
|
||||
text: (Node | string)[];
|
||||
/** A button or link that deals with it. */
|
||||
action?: Node;
|
||||
}
|
||||
|
||||
/** Things worth the admin's attention, most important first. */
|
||||
function attention(st: Status): Attention[] {
|
||||
const out: Attention[] = [];
|
||||
const link = (href: string, t: string) => E('a', { href }, t);
|
||||
const diagnostics = () => link(L.url('admin/services/dawnline/diagnostics'), _('Open Diagnostics'));
|
||||
const today = todayOf(st.series);
|
||||
// AmneziaWG itself can't run: the health notice says so once, not "Tunnel down" for every server.
|
||||
const awg = !!st.awg_state && !st.awg_state.ok;
|
||||
for (const s of st.servers)
|
||||
if (s.enabled && s.blocked)
|
||||
// The reason (the router's words), not just "down": its interface name is taken by a network section Dawnline didn't make.
|
||||
out.push({ tone: 'bad', text: [s.blocked, ' ', diagnostics()] });
|
||||
else if (s.enabled && !s.up && !awg) out.push({ tone: 'bad', text: [fmt(_('Tunnel %s is down.'), s.ifname), ' ', diagnostics()] });
|
||||
for (const p of st.people) {
|
||||
const who = () => link(personUrl(p.id), p.name);
|
||||
if (p.state === 'quota') out.push({ tone: 'warn', text: fill(_('%s reached the data limit.'), who()) });
|
||||
else if (p.state === 'expired') out.push({ tone: 'warn', text: fill(_('%s’s access has ended.'), who()) });
|
||||
else {
|
||||
const left = daysLeft(p.expires, today);
|
||||
if (endsSoon(p, left)) out.push({ tone: '', text: fill<Node | string>(_('%s’s access %s.'), who(), endsIn(left as number)) });
|
||||
// "Keep access" at the end date: nothing changes on its own, so it is said here.
|
||||
else if (left != null && left < 0 && p.expire_action === 'notify')
|
||||
out.push({ tone: '', text: fill<Node | string>(_('%s’s end date passed (%s) · access kept.'), who(), date(p.expires)) });
|
||||
if (p.quota_limit && p.quota_used >= p.quota_limit * 0.9)
|
||||
out.push({ tone: '', text: fill(_('%s has used 90% of the data limit.'), who()) });
|
||||
}
|
||||
}
|
||||
const stale = st.people.flatMap((p) => p.devices.filter((d) => d.config_stale).map((d) => [p, d] as const));
|
||||
if (stale.length)
|
||||
out.push({
|
||||
tone: 'warn',
|
||||
text:
|
||||
stale.length === 1
|
||||
? fill(
|
||||
_('%s needs its configuration again.'),
|
||||
link(personUrl(stale[0][0].id, stale[0][1].id), `${stale[0][0].name} · ${stale[0][1].name}`),
|
||||
)
|
||||
: [
|
||||
plural(
|
||||
stale.length,
|
||||
'%s device needs its configuration again (networks or DNS changed).',
|
||||
'%s devices need their configuration again (networks or DNS changed).',
|
||||
),
|
||||
],
|
||||
});
|
||||
// A server that gives devices an IPv4 that is no longer the router's: one click puts the new one in.
|
||||
for (const s of st.servers)
|
||||
if (st.wan && isIpv4(s.endpoint) && s.endpoint !== st.wan)
|
||||
out.push({
|
||||
tone: 'warn',
|
||||
text: [
|
||||
fmt(_('Public address changed: %s still gives devices %s, the router is %s now.'), s.name, s.endpoint, st.wan),
|
||||
' ',
|
||||
E(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
class: 'dl-fix',
|
||||
click: async (ev: Event) => {
|
||||
const b = ev.currentTarget as HTMLButtonElement;
|
||||
b.disabled = true;
|
||||
await attempt(
|
||||
() => api.serverUpdate(s.id, { endpoint: st.wan }),
|
||||
fmt(_('%s uses %s now - devices need their configuration again'), s.name, st.wan),
|
||||
);
|
||||
b.disabled = false;
|
||||
},
|
||||
},
|
||||
_('Use the new address'),
|
||||
),
|
||||
' ',
|
||||
_('A DDNS name would follow it by itself.'),
|
||||
],
|
||||
});
|
||||
if (st.servers.some((s) => s.lan_like) && st.like_home.error)
|
||||
out.push({
|
||||
tone: 'warn',
|
||||
// The reason is the router's.
|
||||
text: [
|
||||
fmt(_('Internet through the LAN is off: %s'), st.like_home.error),
|
||||
' ',
|
||||
link(L.url('admin/services/dawnline/diagnostics'), _('Details')),
|
||||
],
|
||||
});
|
||||
// Only while setting up: an admin who keeps the portal off has decided so.
|
||||
if (!st.settings.portal_enabled && !st.people.length)
|
||||
out.push({ tone: '', text: [_('The personal portal is off.'), ' ', link(L.url('admin/services/dawnline/settings'), _('Turn on'))] });
|
||||
return out;
|
||||
}
|
||||
|
||||
export class ServerOverview {
|
||||
st!: Status;
|
||||
el = E('div', { class: 'dl-srvov' });
|
||||
map: ConnectionMap | null = null;
|
||||
/** Whether the map card was made for locations on (a map) or off (a link to Settings); null before the first. */
|
||||
mapOn: boolean | null = null;
|
||||
range: Range = 'online';
|
||||
parts: Record<string, HTMLElement> = {};
|
||||
healthAt = 0;
|
||||
/** Speed now, live: one tile for this Overview's life, its numbers put in place each second. */
|
||||
speed = new LiveSpeedTile();
|
||||
|
||||
/** `meter` is the Servers page's live meter (it polls it); `go` switches the page to another section in place. */
|
||||
constructor(
|
||||
readonly srvId: string,
|
||||
private meter: LiveMeter,
|
||||
private go?: (section: string, filter?: string) => void,
|
||||
) {}
|
||||
|
||||
/** Build once; later calls to update() keep the map instance. */
|
||||
mount(st: Status): HTMLElement {
|
||||
this.st = scoped(st, this.srvId);
|
||||
for (const k of ['health', 'bento', 'map', 'side', 'activity']) this.parts[k] = E('div', {});
|
||||
dom.content(this.el, [
|
||||
this.parts.health,
|
||||
this.parts.bento,
|
||||
this.parts.map,
|
||||
E('div', { class: 'dl-grid2' }, [this.parts.activity, this.parts.side]),
|
||||
]);
|
||||
this.paint();
|
||||
void this.loadHealth();
|
||||
return this.el;
|
||||
}
|
||||
|
||||
/** New status; a `quiet` (periodic) update leaves alone a part that has the keyboard focus. */
|
||||
update(st: Status, quiet = false) {
|
||||
this.st = scoped(st, this.srvId);
|
||||
this.paint(quiet);
|
||||
// Health checks cost more than a status call: once a minute is plenty.
|
||||
if (Date.now() - this.healthAt > 60_000) void this.loadHealth();
|
||||
}
|
||||
|
||||
/** Notices above the bento for the checks that failed (with their fix), only while Health has any. */
|
||||
async loadHealth() {
|
||||
this.healthAt = Date.now();
|
||||
const r = await api.health().catch(() => null);
|
||||
if (!r) return;
|
||||
const again = () => void this.loadHealth();
|
||||
const run = async (fix: string) => {
|
||||
if (!(await runFix(fix))) return;
|
||||
again();
|
||||
// The network restarts a second after the answer: look again once it is back.
|
||||
if (fix === 'netrestart') setTimeout(again, 5000);
|
||||
};
|
||||
repaint(
|
||||
this.parts.health,
|
||||
healthNotices(r.checks, (fix) => void run(fix), again),
|
||||
true,
|
||||
);
|
||||
}
|
||||
|
||||
mapData() {
|
||||
return { geo: this.st.geo, people: this.st.people, now: this.st.now };
|
||||
}
|
||||
|
||||
/**
|
||||
* The map keeps its instance between updates. Its card is made again only
|
||||
* when locations were turned on or off, or when the map was freed: leaving
|
||||
* the page frees it, and Outline brings this same overview back on return.
|
||||
*/
|
||||
paintMap() {
|
||||
const on = this.st.geo.enabled;
|
||||
if (on === this.mapOn && (!on || this.map)) {
|
||||
this.map?.update(this.mapData());
|
||||
return;
|
||||
}
|
||||
this.mapOn = on;
|
||||
dom.content(this.parts.map, this.mapCard());
|
||||
}
|
||||
|
||||
mapCard(): HTMLElement {
|
||||
const st = this.st;
|
||||
const head = E('div', { class: 'dl-panel-head pad' }, [
|
||||
E('div', { class: 'dl-stack' }, [
|
||||
E('h3', {}, _('Where people connect from')),
|
||||
E('span', { class: 'dl-sub' }, _('City-level, from the client IP · locations cached on the router')),
|
||||
]),
|
||||
E('span', { class: 'dl-spacer' }),
|
||||
rangeControl(this.range, (r) => {
|
||||
this.range = r;
|
||||
this.map?.setRange(r);
|
||||
}),
|
||||
]);
|
||||
this.map?.destroy();
|
||||
this.map = null;
|
||||
if (!st.geo.enabled)
|
||||
return E('div', { class: 'dl-panel flush' }, [
|
||||
head,
|
||||
E(
|
||||
'div',
|
||||
{ class: 'dl-map-off' },
|
||||
fill(_('Locations are off. %s.'), E('a', { href: L.url('admin/services/dawnline/settings') }, _('Turn them on in Settings'))),
|
||||
),
|
||||
]);
|
||||
const map = (this.map = new ConnectionMap(
|
||||
{
|
||||
openPerson: (id) => (location.href = personUrl(id)),
|
||||
openDevice: (id, dev) => (location.href = personUrl(id, dev)),
|
||||
},
|
||||
this.range,
|
||||
));
|
||||
// A WebGL map outlives the page's DOM unless it is told: free it when
|
||||
// Outline navigates away. The page object is reused on return, and its
|
||||
// next update finds the map gone and makes the card again (paintMap).
|
||||
const offNav = onNavigate(() => {
|
||||
offNav();
|
||||
map.destroy();
|
||||
if (this.map === map) this.map = null;
|
||||
});
|
||||
const legend = E('div', { class: 'dl-map-legend' }, [
|
||||
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' }, [map.el, legend]);
|
||||
requestAnimationFrame(() => map.mount(this.mapData()));
|
||||
return E('div', { class: 'dl-panel flush' }, [head, wrap]);
|
||||
}
|
||||
|
||||
paint(quiet = false) {
|
||||
const st = this.st;
|
||||
const srv = st.servers[0];
|
||||
|
||||
this.paintMap();
|
||||
// The live speed tile moves into a new bento: one is made only when it is put on the page.
|
||||
if (quiet && focusInside(this.parts.bento)) this.paintSpeed();
|
||||
else
|
||||
dom.content(
|
||||
this.parts.bento,
|
||||
E('div', { class: 'dl-bento' }, [this.onlineTile(), this.speedTile(), coreOf(srv).overviewTile(srv), this.monthTile()]),
|
||||
);
|
||||
|
||||
const att = attention(st);
|
||||
repaint(
|
||||
this.parts.side,
|
||||
E('div', { class: 'dl-panel flush' }, [
|
||||
E('div', { class: 'dl-panel-head pad' }, [
|
||||
E('h3', {}, _('Needs attention')),
|
||||
E('span', { class: 'dl-spacer' }),
|
||||
E('a', { href: L.url('admin/services/dawnline/diagnostics') }, _('Health')),
|
||||
]),
|
||||
att.length
|
||||
? att
|
||||
.slice(0, 8)
|
||||
.map((a) =>
|
||||
E('div', { class: 'dl-attn-item dl-row' }, [
|
||||
E('span', { class: `dl-ev-dot ${a.tone}` }),
|
||||
E('span', {}, a.text),
|
||||
a.action ?? '',
|
||||
]),
|
||||
)
|
||||
: E('div', { class: 'dl-row dl-muted' }, [icon('check'), _('All good. Nothing needs you right now.')]),
|
||||
]),
|
||||
quiet,
|
||||
);
|
||||
|
||||
const events = [...st.events].reverse().slice(0, 8);
|
||||
repaint(
|
||||
this.parts.activity,
|
||||
E('div', { class: 'dl-panel flush' }, [
|
||||
E('div', { class: 'dl-panel-head pad' }, [
|
||||
E('h3', {}, _('Activity')),
|
||||
E('span', { class: 'dl-spacer' }),
|
||||
E('a', { href: `${L.url('admin/services/dawnline/diagnostics')}?tab=log` }, _('View all')),
|
||||
]),
|
||||
events.length
|
||||
? events.map((e) => eventRow(st, e))
|
||||
: E('div', { class: 'dl-row dl-muted' }, _('Nothing yet. Connections, new devices and pauses appear here.')),
|
||||
]),
|
||||
quiet,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Who is connected right now, and nothing else. One or two people: avatar,
|
||||
* name, device icons and city; three or more: a grid of avatars (two rows,
|
||||
* then +N). The device badge is the main device, or a count. Hover: a live
|
||||
* card with speed, devices and today's traffic. Nobody: when someone was last seen.
|
||||
*/
|
||||
onlineTile(): HTMLElement {
|
||||
const st = this.st;
|
||||
const off = st.servers[0] ? !st.servers[0].enabled : false;
|
||||
const CAP = 12;
|
||||
const today = (d: Device) => {
|
||||
const [rx, tx] = d.spark[d.spark.length - 1] ?? [0, 0];
|
||||
return rx + tx;
|
||||
};
|
||||
// The address it is connected from now, else the newest one (the points come oldest first).
|
||||
const cityOf = (d: Device) => {
|
||||
const pts = st.geo.points.filter((g) => g.device === d.id && g.city);
|
||||
return (pts.find((g) => g.online) ?? pts.reduce<GeoPoint | undefined>((a, g) => (a && a.ts >= g.ts ? a : g), undefined))?.city;
|
||||
};
|
||||
const home = (d: Device) => /^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/.test(d.endpoint ?? '');
|
||||
// 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)) }))
|
||||
.filter((x) => x.devs.length)
|
||||
.sort((a, b) => b.devs.reduce((n, d) => n + today(d), 0) - a.devs.reduce((n, d) => n + today(d), 0));
|
||||
const big = on.length <= 2;
|
||||
|
||||
const card = ({ p, devs }: { p: Person; devs: Device[] }): Node[] => {
|
||||
const starts = devs.map(connectedAt).filter(Boolean);
|
||||
const since = starts.length ? Math.min(...starts) : 0;
|
||||
// The live meter's last 2 minutes of their devices while it has them (the card is drawn again each
|
||||
// second it shows, paintSpeed), else their last 15 minutes.
|
||||
const ls = this.meter.speed(
|
||||
p.server,
|
||||
Date.now(),
|
||||
p.devices.map((d) => d.id),
|
||||
);
|
||||
const live = ls.pts.length > 1;
|
||||
const pts = live ? ls.pts : (p.rate ?? []).slice(-15);
|
||||
const xs = live ? ls.xs : pts.map((_x, i) => (pts.length > 1 ? i / (pts.length - 1) : 1));
|
||||
const last = pts[pts.length - 1];
|
||||
const fresh = live ? ([0, ls.rx, ls.tx] as const) : last && st.now - last[0] < 180 ? last : null;
|
||||
// The card's speed box is 228 px inside (280, less the card's and the box's padding).
|
||||
const lines = pts.length > 1 ? new SpeedLines(30, true, 228) : null;
|
||||
lines?.set(pts, xs);
|
||||
const chart = lines?.el ?? '';
|
||||
const idle = !fresh || (fresh[1] < 64 && fresh[2] < 64);
|
||||
const reach = p.access === 'both' ? ['home', 'globe'] : p.access === 'lan' ? ['home'] : ['globe'];
|
||||
return [
|
||||
E('div', { class: 'dl-hc' }, [
|
||||
E('div', { class: 'dl-hc-head' }, [
|
||||
E('span', { class: 'dl-onl-av sm' }, initials(p.name)),
|
||||
E('span', { class: 'dl-stack' }, [
|
||||
E('b', {}, p.name),
|
||||
E('span', { class: 'dl-hc-since' }, since ? fmt(_('online for %s'), duration(Math.max(60, st.now - since))) : _('online')),
|
||||
]),
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-hc-reach' },
|
||||
reach.map((r) => E('span', { class: `dl-ibadge ${r === 'home' ? 'lan' : 'inet'}` }, icon(r))),
|
||||
),
|
||||
]),
|
||||
E('div', { class: 'dl-hc-speed' }, [
|
||||
E(
|
||||
'div',
|
||||
{ class: 'dl-hc-speed-row' },
|
||||
idle
|
||||
? [E('span', { class: 'dl-faint' }, _('Idle right now'))]
|
||||
: [
|
||||
E('span', {}, [E('span', { class: 'dl-dn' }, '↓'), ` ${bits(fresh![2])}`]),
|
||||
E('span', {}, [E('span', { class: 'dl-up' }, '↑'), ` ${bits(fresh![1])}`]),
|
||||
E('span', { class: 'dl-spacer' }),
|
||||
E('span', { class: 'dl-faint' }, live ? _('2 min') : _('15 min')),
|
||||
],
|
||||
),
|
||||
chart,
|
||||
]),
|
||||
E(
|
||||
'div',
|
||||
{ class: 'dl-hc-devs' },
|
||||
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(
|
||||
'span',
|
||||
{ class: 'dl-faint' },
|
||||
`${fmt(_('%s today'), bytes(devs.reduce((n, d) => n + today(d), 0)))} · ${fmt(_('%s this month'), bytes(p.month[0] + p.month[1]))}`,
|
||||
),
|
||||
]),
|
||||
]),
|
||||
];
|
||||
};
|
||||
|
||||
const person = (x: { p: Person; devs: Device[] }) => {
|
||||
const { p, devs } = x;
|
||||
const badge = E('span', { class: 'dl-onl-dev' }, devs.length > 1 ? String(devs.length) : icon(devs[0].kind));
|
||||
// Every place their devices are, once, the busiest device's first: "Krasnodar · Moscow", or
|
||||
// "Krasnodar +1" when two do not fit under the avatar, "3 cities" from three on (the card names each).
|
||||
const places = [...new Set(devs.map((d) => where(d)).filter(Boolean))];
|
||||
const full = places.length > 2 ? plural(places.length, '%s city', '%s cities') : places.join(' · ');
|
||||
const place = E('span', {}, full ? [' · ', full] : '');
|
||||
const meta = big
|
||||
? E('span', { class: 'dl-onl-meta' }, [
|
||||
...devs.slice(0, 3).map((d) => icon(d.kind)),
|
||||
devs.length > 3 ? `+${devs.length - 3}` : '',
|
||||
place,
|
||||
])
|
||||
: '';
|
||||
const el = E('a', { class: `dl-onl-p${big ? '' : ' sm'}`, href: personUrl(p.id), 'aria-label': fmt(_('%s, online'), p.name) }, [
|
||||
E('span', { class: 'dl-onl-av' }, [initials(p.name), badge]),
|
||||
big ? E('span', { class: 'dl-onl-name' }, p.name) : '',
|
||||
meta,
|
||||
]);
|
||||
if (meta && places.length === 2) {
|
||||
// Measured where it stands (the person is a fixed width, so swapping the words never resizes what is observed).
|
||||
const fit = new ResizeObserver(() => {
|
||||
if (!el.isConnected) return fit.disconnect();
|
||||
place.textContent = ` · ${full}`;
|
||||
if (meta.scrollWidth > meta.clientWidth) place.textContent = ` · ${places[0]} +1`;
|
||||
});
|
||||
fit.observe(el);
|
||||
}
|
||||
attachTip(el, () => card(x));
|
||||
return el;
|
||||
};
|
||||
|
||||
const count = E('b', { class: `dl-onl-count${on.length ? '' : ' none'}` }, String(on.length));
|
||||
const ndev = on.reduce((n, x) => n + x.devs.length, 0);
|
||||
if (on.length) attachTip(count, () => [`${plural(on.length, '%s person', '%s people')} · ${plural(ndev, '%s device', '%s devices')}`]);
|
||||
const shown = on.length > CAP ? on.slice(0, CAP - 1) : on;
|
||||
const last = st.people
|
||||
.flatMap((p) => p.devices.map((d) => ({ p, d })))
|
||||
.filter((x) => x.d.handshake)
|
||||
.sort((a, b) => b.d.handshake - a.d.handshake)[0];
|
||||
return E('div', { class: 'dl-bento-tile online' }, [
|
||||
E('div', { class: 'dl-bento-head' }, [E('span', { class: 'dl-metric-label' }, _('Online')), count]),
|
||||
on.length
|
||||
? E('div', { class: `dl-onl-row${big ? '' : ' grid'}` }, [
|
||||
...shown.map(person),
|
||||
on.length > CAP
|
||||
? E(
|
||||
'a',
|
||||
{
|
||||
class: 'dl-onl-p sm more',
|
||||
href: `${L.url('admin/services/dawnline/server')}?server=${encodeURIComponent(this.srvId)}§ion=people&filter=online`,
|
||||
title: _('Everyone online'),
|
||||
click: (ev: Event) => {
|
||||
if (this.go) {
|
||||
ev.preventDefault();
|
||||
this.go('people', 'online');
|
||||
}
|
||||
},
|
||||
},
|
||||
[E('span', { class: 'dl-onl-av' }, `+${on.length - shown.length}`)],
|
||||
)
|
||||
: '',
|
||||
])
|
||||
: E('div', { class: 'dl-onl-empty' }, [
|
||||
// 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' }, fmt(_('Last: %s, %s'), last.p.name, ago(last.d.handshake, st.now)))
|
||||
: E('span', { class: 'dl-sub' }, off ? _('Devices connect once it is on') : _('No device has connected yet')),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Throughput right now (the live meter, one point a second): download and
|
||||
* upload side by side, the last 2 minutes as a small chart, today's total.
|
||||
*/
|
||||
speedTile(): HTMLElement {
|
||||
this.paintSpeed();
|
||||
return this.speed.el;
|
||||
}
|
||||
|
||||
/** The speed tile from the meter as it stands (the Servers page calls this with each answer). */
|
||||
paintSpeed() {
|
||||
if (!this.st) return;
|
||||
const srv = this.st.servers[0];
|
||||
this.speed.update(this.meter.speed(this.srvId, Date.now()), this.st.totals.today, srv ? !srv.enabled : false);
|
||||
// A person's card under the pointer follows the same second.
|
||||
refreshTip();
|
||||
}
|
||||
|
||||
/** The last 30 days, today on the right, with the peak. */
|
||||
monthTile(): HTMLElement {
|
||||
// Who used the most this month (the People sort has it too, a click away).
|
||||
const top = [...this.st.people]
|
||||
.map((p) => [p, p.month[0] + p.month[1]] as const)
|
||||
.filter(([, n]) => n > 0)
|
||||
.sort((a, b) => b[1] - a[1])
|
||||
.slice(0, 2);
|
||||
return daysTile(this.st.series, top.length ? fmt(_('Most: %s'), top.map(([p, n]) => `${p.name} ${bytes(n)}`).join(' · ')) : '');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
// What Overview's parts read: the router's answer, the Health checks (null
|
||||
// until the first run comes back), the service log with the watchdog, the
|
||||
// router's clock, and what they may ask of the page (read again, run the
|
||||
// checks again, run a check's own fix). Built by index.ts on every answer.
|
||||
|
||||
import type { HealthCheck, Status } from '../../../shared/types';
|
||||
import type { ServiceLog } from '../../api';
|
||||
import type { Today } from '../../people/lines';
|
||||
|
||||
export interface OverviewCtx {
|
||||
st: Status;
|
||||
/** The Health checks (null: not read yet, or this login could not). */
|
||||
checks: HealthCheck[] | null;
|
||||
/** The last run of the checks failed (the router did not answer it). */
|
||||
checksFailed: boolean;
|
||||
/** The service log and the watchdog (null: could not be read). */
|
||||
sl: ServiceLog | null;
|
||||
/** This login may change things (shell/role.ts). */
|
||||
write: boolean;
|
||||
/** The router's clock now (seconds). */
|
||||
now(): number;
|
||||
/** A server's speed to its devices as the live meter has it (bytes/s); null before it answered for it. */
|
||||
speedOf(id: string): number | null;
|
||||
/** The router's day and clock, for what is said about people. */
|
||||
today(): Today;
|
||||
/** Read the router again now (after a change made here). */
|
||||
reload(): Promise<void>;
|
||||
/** Run the Health checks again now and draw what they found. */
|
||||
recheck(): Promise<void>;
|
||||
/** Run a check's own fix (overview/model.ts ownFix); the checks come back with it. */
|
||||
fix(fix: string): Promise<void>;
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
// Overview's head: the router's glass and name; after it the router's state
|
||||
// in one phrase that counts the checks («2 warnings») and leads down to their
|
||||
// list on this page (health.ts), then Dawnline's version, its servers and
|
||||
// devices, «View only» for a read-only login. The notice and the watchdog's
|
||||
// news are the list's, not the head's.
|
||||
|
||||
import { h } from '../../../portal/dom';
|
||||
import { plural } from '../../../shared/i18n';
|
||||
import { glass } from '../../ui/glass';
|
||||
import { ic } from '../../ui/icons';
|
||||
import { fact, pageHead } from '../../ui/page-head';
|
||||
import { healthUrl } from '../../shell/routes';
|
||||
import { stateLine } from '../../overview/model';
|
||||
import type { OverviewCtx } from './ctx';
|
||||
|
||||
/** `toHealth`: bring the checks into view (a plain click stays on the page; the address is for a new tab). */
|
||||
export function overviewHead(c: OverviewCtx, toHealth: () => void): HTMLElement {
|
||||
const st = c.st;
|
||||
const line = stateLine(c.checks, c.checksFailed);
|
||||
const state = h('a', { class: `ph-state ov-state${line.tone ? ` ${line.tone}-t` : ''}`, href: healthUrl() }, line.text);
|
||||
state.addEventListener('click', (e) => {
|
||||
if (e.button || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
|
||||
e.preventDefault();
|
||||
toHealth();
|
||||
});
|
||||
const devices = st.people.reduce((n, p) => n + p.devices.length, 0);
|
||||
const head = pageHead({ icon: glass('router', 'grey'), title: st.hostname || 'OpenWrt' });
|
||||
head
|
||||
.querySelector('.ph-sub')
|
||||
?.replaceChildren(
|
||||
...[
|
||||
fact(state),
|
||||
fact(`Dawnline ${st.version}`),
|
||||
fact(plural(st.servers.length, '%s server', '%s servers')),
|
||||
fact(plural(devices, '%s device', '%s devices')),
|
||||
c.write ? null : fact([ic('eye'), _('View only')]),
|
||||
].filter((f): f is HTMLElement => !!f),
|
||||
);
|
||||
return head;
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
// Overview › Health (the anchor `health`, where the head's phrase and the old
|
||||
// Health address lead): the router's checks as a visible list, nothing folded.
|
||||
// The most pressing check that did not pass is the page's one notice, the
|
||||
// other failing ones are rows under it, and every check that passed stays on
|
||||
// the page by what it is about: a row for the router, one a server, one for
|
||||
// the portal, each naming its checks in one quiet line (a skipped one
|
||||
// fainter, why in its title) and counting them at its end. A cloud of two
|
||||
// dozen ticked phrases that repeat the core's and the server's name told
|
||||
// nothing apart (the owner, 2026-11-11). A failing
|
||||
// check that a Settings section is about is a signal: the whole notice or row
|
||||
// leads to that section, where its fix is (overview/model.ts fixPlace); only
|
||||
// a check nothing in Settings is about keeps its fix here as a button, or its
|
||||
// advice as its words (ownFix; flows/health-fix.ts runs it). The foot: the
|
||||
// watchdog in one line (its repair today, the agent gone quiet, or that it
|
||||
// had nothing to do) with its switch, and «Check again», which stays one button for the page's life, so its
|
||||
// busy orb and the focus hold through the repaint its answer brings.
|
||||
// A read-only login gets no fix buttons; the links and «Check again» stay.
|
||||
|
||||
import { refill } from '../../ui/reshape';
|
||||
import { flipping } from '../../ui/edit-rows';
|
||||
import type { HealthCheck } from '../../../shared/types';
|
||||
import { api } from '../../api';
|
||||
import { h } from '../../../portal/dom';
|
||||
import { once } from '../../../portal/ui/feedback';
|
||||
import { fmt, num, plural } from '../../../shared/i18n';
|
||||
import { glass } from '../../ui/glass';
|
||||
import { ic } from '../../ui/icons';
|
||||
import { secHead } from '../../ui/page-head';
|
||||
import { errorText, notify } from '../../ui/toast';
|
||||
import { whenAt } from '../../events/clock';
|
||||
import { fixLabel } from '../../servers/fixes';
|
||||
import { focusInside } from '../../state/poller';
|
||||
import { compRow } from '../../ui/comp-row';
|
||||
import { checkGroups, checkList, fixPlace, ownFix, systemNews, type CheckGroup } from '../../overview/model';
|
||||
import type { OverviewCtx } from './ctx';
|
||||
import { flippedNow } from '../../../portal/ui/carry';
|
||||
|
||||
export interface HealthSection {
|
||||
el: HTMLElement;
|
||||
/** Draw the checks as they stand; a `quiet` (background) repaint leaves the list alone while the focus is in it. */
|
||||
/** Draw the checks; false: left as it was, a background repaint under the keyboard focus. */
|
||||
update(c: OverviewCtx, quiet: boolean): void | boolean;
|
||||
}
|
||||
|
||||
const bad = (k: HealthCheck) => k.status === 'error';
|
||||
const words = (k: HealthCheck) => [h('b', {}, k.problem ?? k.title), k.detail ? h('span', {}, k.detail) : null];
|
||||
|
||||
/** The way to where a check is fixed, said at its notice's or row's end (a phone: the chevron alone). */
|
||||
const toFix = (): HTMLElement => h('span', { class: 'ov-fix' }, h('span', {}, _('Fix in Settings')), ic('chevron'));
|
||||
|
||||
/** A check's own fix as its button; null: none, or a read-only login. */
|
||||
function fixButton(c: OverviewCtx, k: HealthCheck, servers: string[]): HTMLButtonElement | null {
|
||||
const fix = ownFix(k, servers);
|
||||
if (!c.write || !fix) return null;
|
||||
const b = h('button', { type: 'button', class: `btn ${bad(k) ? 'tint' : 'soft'} sm` }, h('span', {}, fixLabel(fix))) as HTMLButtonElement;
|
||||
b.addEventListener('click', () => void once(b, () => c.fix(fix)));
|
||||
return b;
|
||||
}
|
||||
|
||||
/** The one notice: a link as a whole to the check's Settings section, or (nothing there is about it) its own fix. */
|
||||
function notice(c: OverviewCtx, k: HealthCheck, servers: string[]): HTMLElement {
|
||||
const to = fixPlace(k, servers);
|
||||
const box = h(
|
||||
'div',
|
||||
{ class: `notice ${bad(k) ? 'bad' : 'warn'}` },
|
||||
glass('pulse', bad(k) ? 'red' : 'orange'),
|
||||
// its own fix stands under its words: beside them it would squeeze them in the column
|
||||
h('div', { class: 't' }, ...words(k), to ? null : fixButton(c, k, servers)),
|
||||
to ? toFix() : null,
|
||||
);
|
||||
return to ? h('a', { class: 'notice-a', href: to }, box) : box;
|
||||
}
|
||||
|
||||
/** A failing check as a row: the same, in the list. */
|
||||
function row(c: OverviewCtx, k: HealthCheck, servers: string[]): HTMLElement {
|
||||
const to = fixPlace(k, servers);
|
||||
const kids = [h('span', { class: 'dg-m' }, ic(bad(k) ? 'x' : 'alert')), h('span', { class: 'chk-t' }, ...words(k))];
|
||||
return to
|
||||
? h('a', { class: `chk ${k.status} ov-chk`, href: to }, ...kids, toFix())
|
||||
: h('div', { class: `chk ${k.status}` }, ...kids, fixButton(c, k, servers));
|
||||
}
|
||||
|
||||
const GROUP_ICON = { router: 'router', server: 'server', portal: 'portal' } as const;
|
||||
const GROUP_TONE = { ok: 'green', warn: 'orange', bad: 'red', off: 'grey' } as const;
|
||||
|
||||
/** What a group is about, as its row: its checks that passed named in one line, counted at the row's end. */
|
||||
function groupRow(g: CheckGroup): HTMLElement {
|
||||
const title = g.kind === 'router' ? _('Router') : g.kind === 'portal' ? _('Personal portal') : (g.name ?? '');
|
||||
const names = g.passed.flatMap(({ check, title: t }, i) => [
|
||||
i ? ' · ' : '',
|
||||
// not the status as a class: `.skip` is the page's skip link (page.css)
|
||||
h('span', { class: check.status === 'skip' ? 'ov-idle' : null, title: check.detail || null }, t),
|
||||
]);
|
||||
const count =
|
||||
g.tone === 'off'
|
||||
? h('span', { class: 'ov-gn' }, _('off', 'server'))
|
||||
: h(
|
||||
'span',
|
||||
{
|
||||
class: `ov-gn num ${g.tone}-t`,
|
||||
title: plural(g.ok, '%s check passed', '%s checks passed'),
|
||||
},
|
||||
ic(g.tone === 'ok' ? 'check' : 'alert'),
|
||||
fmt(_('%s of %s'), num(g.ok), num(g.of)),
|
||||
);
|
||||
return compRow({
|
||||
icon: GROUP_ICON[g.kind],
|
||||
tone: GROUP_TONE[g.tone],
|
||||
title,
|
||||
// a server turned off: «off» at the row's end says why nothing of it ran
|
||||
line: names.length && g.tone !== 'off' ? names : undefined,
|
||||
acts: [count],
|
||||
cls: 'ov-grp',
|
||||
});
|
||||
}
|
||||
|
||||
/** What passed, all of it on the page: a row for each thing the checks are about. */
|
||||
function groups(c: OverviewCtx): HTMLElement | null {
|
||||
const gs = checkGroups(c.checks ?? [], c.st.servers);
|
||||
return gs.length ? h('div', { class: 'checks ov-groups' }, ...gs.map(groupRow)) : null;
|
||||
}
|
||||
|
||||
/** The watchdog in one line; null: its state could not be read. */
|
||||
function watchdogLine(c: OverviewCtx): HTMLElement | null {
|
||||
const wd = c.sl?.watchdog;
|
||||
if (!wd) return null;
|
||||
const news = systemNews(c.sl);
|
||||
const quiet = news?.kind === 'quiet';
|
||||
const text = quiet
|
||||
? fmt(_('The agent has not checked in for %s min; cron restarts it after 5.'), num(news.minutes))
|
||||
: news
|
||||
? fmt(_('The watchdog repaired %s %s.'), news.name, whenAt(news.ts, c.now(), c.st.tz))
|
||||
: wd.enabled
|
||||
? _('The watchdog is on: nothing needed a repair today.')
|
||||
: _('The watchdog is off.');
|
||||
const kids = [
|
||||
quiet ? glass('pulse', 'orange') : glass('refresh', wd.enabled ? 'green' : 'grey'),
|
||||
h('span', { class: quiet ? 'warn-t' : null }, text),
|
||||
];
|
||||
if (!c.write) return h('span', { class: 'ov-wd' }, ...kids);
|
||||
// its switch: this line is the watchdog's one home
|
||||
const sw = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
class: `swrow ov-wd ov-wd-sw${wd.enabled ? ' on' : ''}`,
|
||||
role: 'switch',
|
||||
'aria-checked': String(wd.enabled),
|
||||
'aria-label': _('Watchdog'),
|
||||
title: _('Looks every minute and repairs the tunnels and services it can. It never reboots the router.'),
|
||||
},
|
||||
...kids,
|
||||
h('span', { class: 'sw' }),
|
||||
) as HTMLButtonElement;
|
||||
sw.addEventListener('click', () => {
|
||||
if (sw.classList.contains('wait')) return;
|
||||
const on = !wd.enabled;
|
||||
sw.classList.toggle('on', on);
|
||||
sw.setAttribute('aria-checked', String(on));
|
||||
flippedNow(sw);
|
||||
void flipping(sw, () =>
|
||||
api
|
||||
.settingsUpdate({ watchdog: on ? '1' : '0' })
|
||||
.then(() => c.reload())
|
||||
.then(
|
||||
() => true,
|
||||
(e) => {
|
||||
notify(errorText(e), 'error', 10000);
|
||||
return false;
|
||||
},
|
||||
),
|
||||
).then((ok) => {
|
||||
if (ok) return;
|
||||
sw.classList.toggle('on', !on);
|
||||
sw.setAttribute('aria-checked', String(!on));
|
||||
});
|
||||
});
|
||||
return sw;
|
||||
}
|
||||
|
||||
/** The checks still running, or the run the router did not answer. */
|
||||
const running = (failed: boolean): HTMLElement =>
|
||||
h(
|
||||
'div',
|
||||
{ class: 'checks' },
|
||||
h(
|
||||
'div',
|
||||
{ class: 'chk run' },
|
||||
h('span', { class: 'dg-m' }, ic(failed ? 'alert' : 'clock')),
|
||||
h(
|
||||
'span',
|
||||
{ class: 'chk-t' },
|
||||
h('b', {}, failed ? _('The checks did not run') : _('Running checks…')),
|
||||
h(
|
||||
'span',
|
||||
{},
|
||||
failed ? _('The router did not answer. Check again in a moment.') : _('DNS, ports, certificates: it takes a moment.'),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
function body(c: OverviewCtx, again: HTMLElement): HTMLElement[] {
|
||||
const foot = (first: HTMLElement | null) => h('div', { class: 'ov-hfoot' }, first, again);
|
||||
if (!c.checks)
|
||||
return [
|
||||
secHead(_('Health')),
|
||||
// nothing to press while the first run is on its way
|
||||
h('div', { class: 'card ov-checks' }, running(c.checksFailed), c.checksFailed ? foot(null) : null),
|
||||
];
|
||||
const servers = c.st.servers.map((s) => s.id);
|
||||
const l = checkList(c.checks);
|
||||
const rows = l.failing.map((k) => row(c, k, servers));
|
||||
return [
|
||||
secHead(_('Health'), fmt(_('%s of %s passed'), num(l.ok), num(l.of))),
|
||||
...(l.top ? [notice(c, l.top, servers)] : []),
|
||||
h('div', { class: 'card ov-checks' }, rows.length ? h('div', { class: 'checks' }, ...rows) : null, groups(c), foot(watchdogLine(c))),
|
||||
];
|
||||
}
|
||||
|
||||
export function healthSection(): HealthSection {
|
||||
const el = h('section', { class: 'ov-health', id: 'health' });
|
||||
let cur: OverviewCtx | null = null;
|
||||
const again = h(
|
||||
'button',
|
||||
{ type: 'button', class: 'pill-link ov-again' },
|
||||
ic('refresh'),
|
||||
h('span', {}, _('Check again')),
|
||||
) as HTMLButtonElement;
|
||||
const root = () => el.getRootNode() as Document | ShadowRoot;
|
||||
again.addEventListener(
|
||||
'click',
|
||||
() =>
|
||||
void once(again, async () => {
|
||||
await cur?.recheck();
|
||||
}).then(() => {
|
||||
// busy, the button could not hold the focus, and the repaint took it out and put it back: once it can be
|
||||
// pressed again the focus is on it, unless it went elsewhere meanwhile
|
||||
const a = root().activeElement;
|
||||
if (again.isConnected && (!a || a === document.body)) again.focus({ preventScroll: true });
|
||||
}),
|
||||
);
|
||||
return {
|
||||
el,
|
||||
update(c, quiet) {
|
||||
cur = c;
|
||||
const held = focusInside(again);
|
||||
// left as it is under the focus: the page draws it once the focus leaves (state/regions.ts drawn)
|
||||
if (quiet && !held && focusInside(el)) return false;
|
||||
// checks coming, going or changing their state unfold, fold and morph (ui/reshape.ts)
|
||||
refill(
|
||||
el,
|
||||
body(c, again).filter((x): x is HTMLElement => !!x),
|
||||
);
|
||||
if (held && again.isConnected) again.focus({ preventScroll: true });
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,312 @@
|
||||
// Overview: does everything work now. The section row; the head with the
|
||||
// router's state in one phrase that counts the checks and leads down to them
|
||||
// (head.ts); "now" in numbers over the 30-day line (now.ts); the servers as
|
||||
// cards, each the door to its people, places and settings, with who waits
|
||||
// for a decision on it and its rollout in short (servers.ts); Health: the
|
||||
// checks as a visible list, the one notice among them (health.ts; the
|
||||
// address `?s=health`, and the old `?at=health`, brings it into view). Who
|
||||
// waits for a decision is listed on their server's own Overview
|
||||
// (pages/server). No server yet: the first run (first.ts). The map is
|
||||
// People's, the log's excerpt the Log's.
|
||||
//
|
||||
// Live: the status (60 days: the line and the 30 before it) and the service log
|
||||
// on the live revision, 30 s as the fallback; the Health checks in the
|
||||
// background once the page is drawn and at most every 2 minutes after, never
|
||||
// on the revision; the meter once a second only while the speed tile is on
|
||||
// screen and a server runs (before its first answer the tile says the router's
|
||||
// last minute).
|
||||
//
|
||||
// Drawing: the page is built once. Every answer is laid over the last one field by field
|
||||
// (shared/live/doc.ts), and each region is an effect that reads what it shows (state/regions.ts): it is
|
||||
// drawn again only when a field it read changed, a server's card only when that server or what its card
|
||||
// read did. A region or a card holding the focus is left alone by a background repaint; the chart is drawn
|
||||
// once and follows in place.
|
||||
//
|
||||
// Opening: every opening asks the router, and the page comes in when the status has come (shell/waiting.ts:
|
||||
// the section row stands meanwhile). Health is drawn saying its checks are being read, and fills in place
|
||||
// when they have come (they are asked after the status and take about as long again).
|
||||
|
||||
import type { HealthCheck, Status } from '../../../shared/types';
|
||||
import { LiveDoc } from '../../../shared/live/doc';
|
||||
import { signal } from '../../../shared/live/signal';
|
||||
import { share } from '../../../shared/live/share';
|
||||
import { drawn, fill, live, ownPaint, paintNow } from '../../state/regions';
|
||||
import { api, type Health, type ServiceLog, type SetupDefaults } from '../../api';
|
||||
import { h } from '../../../portal/dom';
|
||||
import { calm } from '../../../portal/motion';
|
||||
import { rateOf, todayOf } from '../../../shared/format';
|
||||
import { morphText, textOf } from '../../../portal/ui/morph';
|
||||
import { createPoller } from '../../state/poller';
|
||||
import { LiveMeter } from '../../state/meter';
|
||||
import { pollMeter } from '../../state/meterpoll';
|
||||
import { routerDay } from '../../events/clock';
|
||||
import { canWrite } from '../../shell/role';
|
||||
import { navRow } from '../../shell/nav';
|
||||
import { RATE_FRESH } from '../../overview/model';
|
||||
import { firstRun } from '../settings/first';
|
||||
import type { OverviewCtx } from './ctx';
|
||||
import { runFix } from '../../flows/health-fix';
|
||||
import { overviewHead } from './head';
|
||||
import { healthSection } from './health';
|
||||
import { DAYS, nowCard, type NowCard, type Speed } from './now';
|
||||
import { NOW_KEY, serversSection } from './servers';
|
||||
import { putChildren } from '../../../portal/ui/put';
|
||||
|
||||
/** Health checks cost more than a status: at most this often (ms). */
|
||||
const HEALTH_EVERY = 120_000;
|
||||
export interface OverviewData {
|
||||
st: Status;
|
||||
/** No server yet: what a new one would get (null for a login that cannot read it). */
|
||||
setup: SetupDefaults | null;
|
||||
sl: ServiceLog | null;
|
||||
}
|
||||
|
||||
export class OverviewPage {
|
||||
/** The router's answer, followed field by field: what the regions read. */
|
||||
private doc = new LiveDoc<Status>();
|
||||
private st = this.doc.view;
|
||||
private sl = signal<ServiceLog | null>(null);
|
||||
private checks = signal<HealthCheck[] | null>(null);
|
||||
private checksFailed = signal(false);
|
||||
private healthAt = 0;
|
||||
private skew = 0;
|
||||
private write = canWrite();
|
||||
private headBox = h('div');
|
||||
private health = healthSection();
|
||||
private srvBox = h('section', { class: 'ov-srv' });
|
||||
private body = h('div', { class: 'ov-body' });
|
||||
private now!: NowCard;
|
||||
private meter = new LiveMeter();
|
||||
private seen = false;
|
||||
private metered = false;
|
||||
/** Each server's speed as the meter last said it (bytes/s to its devices). */
|
||||
private srvNow = new Map<string, number>();
|
||||
private page = h('div', { class: 'page overview ov' }, navRow());
|
||||
|
||||
async load(): Promise<OverviewData> {
|
||||
const [st, sl, meter] = await Promise.all([
|
||||
api.status(2 * DAYS),
|
||||
api.serviceLog().catch(() => null),
|
||||
// the stream carries the meter's two minutes always: the live line is drawn with the page and comes in with
|
||||
// it, not a second later at the poller's first answer
|
||||
api.meter(0).catch(() => null),
|
||||
]);
|
||||
if (meter?.points.length) {
|
||||
this.meter.take({ meter }, Date.now());
|
||||
this.metered = true;
|
||||
}
|
||||
return { st, sl, setup: st.servers.length ? null : await api.setupDefaults().catch(() => null) };
|
||||
}
|
||||
|
||||
render(d: OverviewData): HTMLElement {
|
||||
const page = this.page;
|
||||
if (!d.st.servers.length) {
|
||||
this.firstRun(d.setup);
|
||||
return page;
|
||||
}
|
||||
this.take(d.st, d.sl);
|
||||
const c = this.ctx();
|
||||
this.now = nowCard(c);
|
||||
// «now» in numbers, then the servers (each the door to its people, places and settings), then Health (the
|
||||
// owner's order, 2026-11-11)
|
||||
this.body.append(h('div', { class: 'ov-now' }, this.now.el), this.srvBox, this.health.el);
|
||||
page.append(this.headBox, this.body);
|
||||
// each region follows what it reads
|
||||
fill(this.headBox, () => overviewHead(c, () => this.toHealth()));
|
||||
drawn(this.health.el, () => this.health.update(c, !ownPaint()));
|
||||
live(() => this.now.update(c));
|
||||
serversSection(c, this.srvBox);
|
||||
this.speed(true);
|
||||
// drawn whole before it comes in
|
||||
paintNow();
|
||||
createPoller({
|
||||
fetch: () => this.fetch(),
|
||||
every: 30,
|
||||
live: true,
|
||||
active: () => page.isConnected,
|
||||
apply: ([st, sl], quiet) => this.land(st, sl, quiet),
|
||||
});
|
||||
// the Health checks after the page is drawn: they take a moment on the router
|
||||
void this.runHealth(true);
|
||||
// the meter is read while a speed is on screen: the tile's, or a server's «Now» on its card
|
||||
const inView = new Set<Element>();
|
||||
const watch = new IntersectionObserver((es) => {
|
||||
for (const e of es) inView[e.isIntersecting ? 'add' : 'delete'](e.target);
|
||||
this.seen = inView.size > 0;
|
||||
});
|
||||
watch.observe(this.now.tile);
|
||||
watch.observe(this.srvBox);
|
||||
pollMeter(
|
||||
this.meter,
|
||||
() => page.isConnected && this.seen && this.st.servers.some((s) => s.enabled && s.up),
|
||||
() => {
|
||||
this.metered = true;
|
||||
this.speed();
|
||||
},
|
||||
);
|
||||
const q = new URLSearchParams(location.search);
|
||||
if (q.get('s') === 'health' || q.get('at') === 'health') requestAnimationFrame(() => this.health.el.scrollIntoView({ block: 'start' }));
|
||||
return page;
|
||||
}
|
||||
|
||||
private async fetch(): Promise<[Status, ServiceLog | null]> {
|
||||
const [st, sl] = await Promise.all([api.status(2 * DAYS), api.serviceLog().catch(() => this.sl.peek())]);
|
||||
if (Date.now() - this.healthAt > HEALTH_EVERY) void this.runHealth(true);
|
||||
return [st, sl];
|
||||
}
|
||||
|
||||
/** No server on the router (yet): the first run's page in this one's place. */
|
||||
private firstRun(setup: SetupDefaults | null) {
|
||||
this.page.classList.remove('ov');
|
||||
putChildren(this.page, [navRow(), firstRun(setup, this.write)]);
|
||||
}
|
||||
|
||||
/** A status from the router: drawn in place. */
|
||||
private land(st: Status, sl: ServiceLog | null, quiet: boolean) {
|
||||
// the last server was removed: the page as it is now (the first run's)
|
||||
if (!st.servers.length) return void (location.href = location.pathname);
|
||||
this.take(st, sl);
|
||||
paintNow(!quiet);
|
||||
}
|
||||
|
||||
/** Run the Health checks and say what they found; `quiet`: in the background (asked for here: at once). */
|
||||
private async runHealth(quiet: boolean) {
|
||||
this.healthAt = Date.now();
|
||||
const r = await api.health().catch(() => null);
|
||||
this.checksFailed.set(!r);
|
||||
if (r) this.tookHealth(r, quiet);
|
||||
else paintNow(!quiet);
|
||||
}
|
||||
|
||||
/** The checks' answer (a run, or a fix): it brings the watchdog and the service log too. */
|
||||
private tookHealth(r: Health, quiet: boolean) {
|
||||
this.checks.set(share(this.checks.peek(), r.checks));
|
||||
this.checksFailed.set(false);
|
||||
this.healthAt = Date.now();
|
||||
this.sl.set(share(this.sl.peek(), { watchdog: r.watchdog, log: r.log }));
|
||||
paintNow(!quiet);
|
||||
}
|
||||
|
||||
private async reload() {
|
||||
const r = await this.fetch().catch(() => null);
|
||||
if (!r) return;
|
||||
this.take(...r);
|
||||
paintNow(true);
|
||||
}
|
||||
|
||||
/** An answer from the router: laid over the last one, so only what changed tells its readers. */
|
||||
private take(st: Status, sl: ServiceLog | null) {
|
||||
this.doc.feed(st);
|
||||
// the same lines again are the same object: nobody who read them is told
|
||||
this.sl.set(share(this.sl.peek(), sl));
|
||||
this.skew = st.now - Date.now() / 1000;
|
||||
}
|
||||
|
||||
/** What the parts read, made once: its fields are the page's signals, read as plain values. */
|
||||
private ctx(): OverviewCtx {
|
||||
const { st, checks, checksFailed, sl } = this;
|
||||
const now = () => Date.now() / 1000 + this.skew;
|
||||
return {
|
||||
st,
|
||||
get checks() {
|
||||
return checks();
|
||||
},
|
||||
get checksFailed() {
|
||||
return checksFailed();
|
||||
},
|
||||
get sl() {
|
||||
return sl();
|
||||
},
|
||||
write: this.write,
|
||||
now,
|
||||
speedOf: (id) => this.srvNow.get(id) ?? null,
|
||||
today: () => ({ now: now(), today: todayOf(st.series) || routerDay(now(), st.tz) }),
|
||||
reload: () => this.reload(),
|
||||
recheck: () => this.runHealth(false),
|
||||
fix: (fix) =>
|
||||
runFix(fix, {
|
||||
took: (r) => this.tookHealth(r, false),
|
||||
again: () => {
|
||||
void this.runHealth(false);
|
||||
void this.reload();
|
||||
},
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/** Bring the checks into view (the head's phrase). */
|
||||
private toHealth() {
|
||||
this.health.el.scrollIntoView({ block: 'start', behavior: calm() ? 'auto' : 'smooth' });
|
||||
}
|
||||
|
||||
/** The speed tile: the meter's once it answers, before that the router's last minute (status), else why none. */
|
||||
private speed(atOnce = false) {
|
||||
const st = this.st;
|
||||
const running = st.servers.filter((s) => s.enabled && s.up);
|
||||
const ms = Date.now();
|
||||
const on = st.people.filter((p) => p.online > 0);
|
||||
let s: Speed;
|
||||
if (!running.length) s = { down: 0, up: 0, top: [], line: [], why: _('No server is running') };
|
||||
else if (this.metered) {
|
||||
const all = this.meter.speed(null, ms);
|
||||
const top = on
|
||||
.map((p) => {
|
||||
const v = this.meter.speed(
|
||||
null,
|
||||
ms,
|
||||
p.devices.map((d) => d.id),
|
||||
);
|
||||
return { p, v: v.rx + v.tx };
|
||||
})
|
||||
.filter((x) => x.v > 0)
|
||||
.sort((a, b) => b.v - a.v)
|
||||
.slice(0, 2);
|
||||
s = all.error
|
||||
? { down: 0, up: 0, top: [], line: [], why: all.error }
|
||||
: { down: all.tx, up: all.rx, top, line: all.pts.map((p) => p[2]) };
|
||||
} else {
|
||||
// the last minute the agent measured, per server and per person
|
||||
const last = (r: [number, number, number][] | undefined) => {
|
||||
const p = r?.[r.length - 1];
|
||||
return p && st.now - p[0] < RATE_FRESH ? p : null;
|
||||
};
|
||||
let down = 0;
|
||||
let up = 0;
|
||||
for (const srv of running) {
|
||||
const p = last(srv.rate);
|
||||
if (p) {
|
||||
up += p[1];
|
||||
down += p[2];
|
||||
}
|
||||
}
|
||||
const top = on
|
||||
.map((p) => {
|
||||
const r = last(p.rate);
|
||||
return { p, v: r ? r[1] + r[2] : 0 };
|
||||
})
|
||||
.filter((x) => x.v > 0)
|
||||
.sort((a, b) => b.v - a.v)
|
||||
.slice(0, 2);
|
||||
s = { down, up, top, line: [] };
|
||||
}
|
||||
if (this.now.speed(s, atOnce) && this.metered) this.serverSpeeds(running, ms);
|
||||
}
|
||||
|
||||
/**
|
||||
* Each running server's «Now» on its card, as the meter reads it: its words change with the tile's (the same
|
||||
* second, every third: they are the mean of those three, so one server's says what the tile says), and morph
|
||||
* where they stand. A card drawn again says the same.
|
||||
*/
|
||||
private serverSpeeds(running: Status['servers'], ms: number) {
|
||||
for (const srv of running) {
|
||||
const v = this.meter.speed(srv.id, ms);
|
||||
if (v.pts.length && !v.error) this.srvNow.set(srv.id, v.tx);
|
||||
}
|
||||
for (const el of this.srvBox.querySelectorAll<HTMLElement>(`[data-t^="${NOW_KEY}"]`)) {
|
||||
const v = this.srvNow.get(el.dataset.t!.slice(NOW_KEY.length));
|
||||
if (v == null) continue;
|
||||
const text = `↓ ${rateOf(v)}`;
|
||||
if (textOf(el) !== text) morphText(el, text);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
// Overview's "now" card (the concept's card.now): three tiles over the 30-day
|
||||
// line. Online: the devices online and how many people they are, their faces
|
||||
// (the map markers' initials) leading to People. Speed now: the router's speed
|
||||
// to the devices and from them, who moves most this second (the two biggest,
|
||||
// links to their pages), and the live line of the last two minutes. Today:
|
||||
// what moved since midnight, this month's total, and today by the router's
|
||||
// hour as bars (the hours to come empty). Then the last 30 days as a line, the
|
||||
// 30 before dashed under it; a day read under the pointer, a tap or the arrows
|
||||
// is said at the foot, where at rest stand who moved most this month.
|
||||
//
|
||||
// Motion: the speed's words are put in place at once the first time (nothing
|
||||
// blinks on load), then morph every third second (a morph each second keeps
|
||||
// the letters moving most of the time); the line slides each second. A read
|
||||
// day swaps at once (a readout never morphs). The chart's entrance plays once:
|
||||
// the page draws it again only when its days change.
|
||||
|
||||
import { tip } from '../../../portal/ui/tip';
|
||||
import type { DayUsage, Person } from '../../../shared/types';
|
||||
import { h } from '../../../portal/dom';
|
||||
import { morphText, setText, textOf } from '../../../portal/ui/morph';
|
||||
import { refill } from '../../ui/reshape';
|
||||
import { rateOf, bytes, initials } from '../../../shared/format';
|
||||
import { fmt, plural } from '../../../shared/i18n';
|
||||
import { peopleUrl, personUrl } from '../../shell/routes';
|
||||
import { drawChart, lineChart } from '../../widgets/line-chart';
|
||||
import { liveLine } from '../../widgets/live-line';
|
||||
import { shortDay } from '../../people/lines';
|
||||
import { hourBars, topMonth } from '../../overview/model';
|
||||
import type { OverviewCtx } from './ctx';
|
||||
import { putChildren } from '../../../portal/ui/put';
|
||||
|
||||
/** Days on the line; the status brings twice as many, the period before drawn under it. */
|
||||
export const DAYS = 30;
|
||||
/** Faces in the Online tile before "+N". */
|
||||
const FACES = 6;
|
||||
|
||||
const sum = (d: DayUsage) => d.rx + d.tx;
|
||||
const first = (p: Person) => p.name.trim().split(/\s+/)[0] ?? p.name;
|
||||
|
||||
/** The speed as the tile says it: down to the devices, up from them, the busiest people now, the last two minutes. */
|
||||
export interface Speed {
|
||||
down: number;
|
||||
up: number;
|
||||
top: { p: Person; v: number }[];
|
||||
/** Bytes/s to the devices, a second each, oldest first (empty: none yet). */
|
||||
line: number[];
|
||||
/** Why there is no speed (the meter failing, nothing running), said in the tile instead. */
|
||||
why?: string;
|
||||
}
|
||||
|
||||
export interface NowCard {
|
||||
el: HTMLElement;
|
||||
/** The speed tile: the meter runs only while it is on screen. */
|
||||
tile: HTMLElement;
|
||||
/** A fresh status: the counts, faces and today's bars in place; the chart again when its days changed. */
|
||||
update(c: OverviewCtx): void;
|
||||
/**
|
||||
* `atOnce`: say it now, not at the words' next turn (they change every third second). True when the speed's
|
||||
* words were said this time: what else says a speed of the same meter (a server's «Now») changes with them.
|
||||
*/
|
||||
speed(s: Speed, atOnce?: boolean): boolean;
|
||||
}
|
||||
|
||||
function onlineTile(c: OverviewCtx): (HTMLElement | null)[] {
|
||||
const on = c.st.people.filter((p) => p.online > 0);
|
||||
const devices = c.st.people.reduce((n, p) => n + p.online, 0);
|
||||
const faces = on.length
|
||||
? h(
|
||||
'a',
|
||||
{ class: 'st-faces', href: peopleUrl(), 'aria-label': fmt(_('Online now: %s'), on.map((p) => p.name).join(', ')) },
|
||||
...on.slice(0, FACES).map((p) => h('span', { class: 'pav on', title: p.name }, initials(p.name))),
|
||||
on.length > FACES ? h('span', { class: 'pav more num' }, `+${on.length - FACES}`) : null,
|
||||
)
|
||||
: null;
|
||||
return [
|
||||
h('span', { class: 'use-lbl' }, _('Online')),
|
||||
h('b', { class: 'num' }, plural(devices, '%s device', '%s devices')),
|
||||
h('span', { class: 'stat-sub' }, on.length ? plural(on.length, 'across %s person', 'across %s people') : _('nobody is connected')),
|
||||
faces,
|
||||
];
|
||||
}
|
||||
|
||||
function todayTile(c: OverviewCtx): (HTMLElement | null)[] {
|
||||
const t = c.st.totals;
|
||||
const hours = c.st.hours;
|
||||
// the router's hour now: the last bar's; the others count back from it
|
||||
const hourNow = Math.floor(((((c.now() + (c.st.tz ?? 0) * 60) % 86400) + 86400) % 86400) / 3600);
|
||||
const bars = hours?.length
|
||||
? h(
|
||||
'div',
|
||||
{ class: 'hbars', role: 'img', 'aria-label': _('The last 24 hours by the hour') },
|
||||
...hourBars(hours).map((b, i) => {
|
||||
const hour = (((hourNow - (hours.length - 1 - i)) % 24) + 24) % 24;
|
||||
const bar = h('i', { class: b.share === null ? 'later' : i === hours.length - 1 ? 'now' : '' });
|
||||
bar.style.height = `${b.share === null ? 3 : Math.max(3, Math.round(b.share * 26))}px`;
|
||||
// the hour's whole column answers the pointer, not the bar alone: a quiet hour's bar is three px tall
|
||||
const col = h('span', { class: 'hb' }, bar);
|
||||
if (b.share !== null) tip(col, () => `${String(hour).padStart(2, '0')}:00 · ${bytes(b.bytes)}`);
|
||||
return col;
|
||||
}),
|
||||
)
|
||||
: null;
|
||||
return [
|
||||
// what the bars add up to: the last 24 hours, not the day since midnight (two bars at one in the morning)
|
||||
h('span', { class: 'use-lbl' }, _('Last 24 hours')),
|
||||
h('b', { class: 'num' }, bytes(hours?.length ? hours.reduce((n, v) => n + v[0] + v[1], 0) : t.today[0] + t.today[1])),
|
||||
h('span', { class: 'stat-sub' }, fmt(_('%s in 30 days'), bytes(t.month[0] + t.month[1]))),
|
||||
bars,
|
||||
];
|
||||
}
|
||||
|
||||
/** Who moved most in the last 30 days, at the chart's foot while no day is read. */
|
||||
function topLine(c: OverviewCtx): HTMLElement | null {
|
||||
const top = topMonth(c.st.people);
|
||||
if (!top.length) return null;
|
||||
return h(
|
||||
'span',
|
||||
{ class: 'now-top' },
|
||||
_('Most in 30 days:'),
|
||||
' ',
|
||||
...top.flatMap((x, i) => [
|
||||
i ? ', ' : '',
|
||||
h('span', { class: 'nb' }, h('a', { href: personUrl(x.p.id), title: x.p.name }, first(x.p)), ` ${bytes(x.bytes)}`),
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
function chart(c: OverviewCtx, readout: HTMLElement): HTMLElement | null {
|
||||
const all = c.st.series;
|
||||
const days = all.slice(-DAYS);
|
||||
if (days.length < 2) return null;
|
||||
const before = all.slice(-2 * DAYS, -DAYS);
|
||||
const past = before.length === days.length && before.some((d) => sum(d) > 0) ? before.map(sum) : null;
|
||||
const el = lineChart(
|
||||
days.map(sum),
|
||||
120,
|
||||
[shortDay(days[0].day), _('today')],
|
||||
_('Traffic by day: the arrows pick a day'),
|
||||
(i) => {
|
||||
const d = days[i];
|
||||
// the day read stands where who moved most this month stood (overview.css)
|
||||
readout.textContent = i < 0 || !d ? '' : `${shortDay(d.day)} · ${bytes(sum(d))}${i === days.length - 1 ? ` · ${_('today')}` : ''}`;
|
||||
},
|
||||
past,
|
||||
);
|
||||
el.dataset.past = past ? '1' : '';
|
||||
return el;
|
||||
}
|
||||
|
||||
export function nowCard(c0: OverviewCtx): NowCard {
|
||||
const online = h('div', { class: 'stat' });
|
||||
const today = h('div', { class: 'stat' });
|
||||
const down = h('b', { class: 'num' }, '—');
|
||||
const up = h('span', { class: 'stat-sub' }, ' ');
|
||||
const line = liveLine(36);
|
||||
const tile = h(
|
||||
'div',
|
||||
{ class: 'stat has-extra' },
|
||||
h('span', { class: 'use-lbl' }, _('Speed now')),
|
||||
down,
|
||||
up,
|
||||
h('div', { class: 'll-wrap' }, line.el),
|
||||
);
|
||||
const chartBox = h('div', { class: 'now-chart' });
|
||||
const readout = h('span', { class: 'lc-read num' });
|
||||
const keys = h('span', { class: 'now-keys' });
|
||||
const topBox = h('span', { class: 'now-topbox' });
|
||||
const foot = h('div', { class: 'now-foot' }, keys, readout, topBox);
|
||||
const el = h('section', { class: 'card now' }, h('div', { class: 'stats' }, online, tile, today), chartBox, foot);
|
||||
let dayKey = '';
|
||||
let beat = 0;
|
||||
let said = '';
|
||||
const update = (c: OverviewCtx) => {
|
||||
// their parts change in place (ui/reshape.ts)
|
||||
refill(
|
||||
online,
|
||||
onlineTile(c).filter((x): x is HTMLElement => !!x),
|
||||
);
|
||||
refill(
|
||||
today,
|
||||
todayTile(c).filter((x): x is HTMLElement => !!x),
|
||||
);
|
||||
online.classList.toggle('has-extra', !!online.querySelector('.st-faces'));
|
||||
today.classList.toggle('has-extra', !!today.querySelector('.hbars'));
|
||||
refill(
|
||||
topBox,
|
||||
[topLine(c)].filter((x): x is HTMLElement => !!x),
|
||||
);
|
||||
const k = JSON.stringify(c.st.series.slice(-2 * DAYS));
|
||||
if (k === dayKey) return;
|
||||
dayKey = k;
|
||||
readout.textContent = '';
|
||||
const ch = chart(c, readout);
|
||||
// put in whole and drawn at once, never morphed: a morph keeps the old plot's node, which has the new markup
|
||||
// (no drawing yet) and its old width, so nothing ever drew in it again until the window was resized
|
||||
putChildren(chartBox, ch ? [ch] : []);
|
||||
if (ch) drawChart(ch);
|
||||
|
||||
foot.hidden = !ch;
|
||||
refill(keys, [
|
||||
h('span', { class: 'lc-key' }, h('i', { class: 'lg live' }), fmt(_('%s days'), DAYS)),
|
||||
...(ch?.dataset.past ? [h('span', { class: 'lc-key' }, h('i', { class: 'lg past' }), fmt(_('Previous %s'), DAYS))] : []),
|
||||
]);
|
||||
};
|
||||
update(c0);
|
||||
return {
|
||||
el,
|
||||
tile,
|
||||
update,
|
||||
speed(s, atOnce = false) {
|
||||
if (s.line.length > 1) line.push(s.line);
|
||||
// said plainly the first time, then every change morphs (the speed's words, the reason there is none)
|
||||
const put = ++beat === 1 ? setText : (el: HTMLElement, t: string) => textOf(el) !== t && morphText(el, t);
|
||||
if (s.why) {
|
||||
put(down, '—');
|
||||
put(up, s.why);
|
||||
said = 'why';
|
||||
return false;
|
||||
}
|
||||
// the words every third second (and at once when they first come)
|
||||
if (!atOnce && beat % 3 !== 1 && said === 'speed') return false;
|
||||
put(down, `↓ ${rateOf(s.down)}`);
|
||||
put(up, fmt(_('↑ %s from devices'), rateOf(s.up)));
|
||||
said = 'speed';
|
||||
return true;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
// Overview › Servers: a card a server, the door to its page. Its row: the
|
||||
// server as its page's head names it (its name; whether it runs,
|
||||
// servers/state.ts, and the address devices connect to in one line under
|
||||
// it), then its figures as named cells that stand in the same columns on
|
||||
// every card: People, who of them waits for a decision (only while someone
|
||||
// on some server does), the speed to the devices now and what moved today
|
||||
// (overview/model.ts serverNumbers). One that is off has «Turn on» beside
|
||||
// them: done at once and said in a toast with Undo.
|
||||
// Under a server whose devices wait for a new configuration, its rollout in
|
||||
// short: the count, the change it follows, a cell a device (widgets/rollout.ts
|
||||
// rolloutCells), the first who still wait as chips that lead to their
|
||||
// devices' panels, and the rest in People filtered to them. The whole rollout,
|
||||
// with the portal-link knobs, is in Settings. A read-only login gets no
|
||||
// «Turn on».
|
||||
|
||||
import type { Server } from '../../../shared/types';
|
||||
import { h } from '../../../portal/dom';
|
||||
import { once } from '../../../portal/ui/feedback';
|
||||
import { rateOf, bytes } from '../../../shared/format';
|
||||
import { fmt, num, plural } from '../../../shared/i18n';
|
||||
import { api } from '../../api';
|
||||
import { glass } from '../../ui/glass';
|
||||
import { ic } from '../../ui/icons';
|
||||
import { secHead } from '../../ui/page-head';
|
||||
import { fill, rows } from '../../state/regions';
|
||||
import { errorText, notify } from '../../ui/toast';
|
||||
import { say } from '../../shell/toast';
|
||||
import { deviceUrl, peopleUrl, serverUrl } from '../../shell/routes';
|
||||
import { movePerson } from '../../flows/move-person';
|
||||
import { compList, compRow } from '../../ui/comp-row';
|
||||
import { newServer } from '../../flows/new-server';
|
||||
import { serverState } from '../../servers/state';
|
||||
import { changeLine, rollout, rolloutItems } from '../../servers/rollout';
|
||||
import { rolloutCells } from '../../widgets/rollout';
|
||||
import { serverNumbers, stillWaiting, waiting } from '../../overview/model';
|
||||
import type { OverviewCtx } from './ctx';
|
||||
import { putChildren } from '../../../portal/ui/put';
|
||||
|
||||
const first = (name: string) => name.trim().split(/\s+/)[0] ?? name;
|
||||
|
||||
/** Turn a server on or off; false when the router refused (said in a toast). */
|
||||
async function setEnabled(s: Server, on: boolean): Promise<boolean> {
|
||||
try {
|
||||
await api.serverUpdate(s.id, { enabled: on ? '1' : '0' });
|
||||
return true;
|
||||
} catch (e) {
|
||||
notify(errorText(e), 'error', 10000);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** «Turn on» for a server that is off: one tap, undone from its toast (nothing is cut off by turning it on). */
|
||||
function turnOn(c: OverviewCtx, s: Server): HTMLElement {
|
||||
const b = h('button', { type: 'button', class: 'btn tint sm' }, ic('play'), h('span', {}, _('Turn on'))) as HTMLButtonElement;
|
||||
b.addEventListener('click', () =>
|
||||
once(b, async () => {
|
||||
if (!(await setEnabled(s, true))) return;
|
||||
say(fmt(_('Server %s turned on'), s.name), {
|
||||
undo: () => void setEnabled(s, false).then((ok) => void (ok && c.reload())),
|
||||
undone: fmt(_('Server %s turned off again'), s.name),
|
||||
});
|
||||
await c.reload();
|
||||
}),
|
||||
);
|
||||
return b;
|
||||
}
|
||||
|
||||
/** The rollout in short, under the server's row; null: none of its devices waits. */
|
||||
function rolloutShort(c: OverviewCtx, s: Server): HTMLElement | null {
|
||||
const st = c.st;
|
||||
const r = rollout(st.people, s.id);
|
||||
if (!r) return null;
|
||||
const all = rolloutItems(st.people, s.id);
|
||||
const w = stillWaiting(all);
|
||||
const change = changeLine(c.sl?.log ?? [], s, c.now(), st.tz);
|
||||
return h(
|
||||
'div',
|
||||
{ class: 'ov-roll' },
|
||||
h(
|
||||
'div',
|
||||
{ class: 'ov-roll-h' },
|
||||
ic('refresh'),
|
||||
h('b', { class: 'num' }, fmt(_('New configuration: %s of %s'), r.done, r.of)),
|
||||
change ? h('span', { class: 'ov-roll-ch' }, change) : null,
|
||||
),
|
||||
rolloutCells(all),
|
||||
h(
|
||||
'div',
|
||||
{ class: 'ov-roll-f' },
|
||||
h(
|
||||
'div',
|
||||
{ class: 'ov-waiters' },
|
||||
h('span', { class: 'ov-lbl' }, _('Waiting:')),
|
||||
...w.named.map((x) =>
|
||||
h(
|
||||
'a',
|
||||
{ class: 'kt-chip', href: deviceUrl(x.d.id), title: `${x.d.name} · ${x.p.name}` },
|
||||
ic(x.d.kind),
|
||||
h('span', {}, `${x.d.name} · ${first(x.p.name)}`),
|
||||
),
|
||||
),
|
||||
w.more
|
||||
? h(
|
||||
'a',
|
||||
{ class: 'kt-chip more', href: peopleUrl(s.id, 'config') },
|
||||
h('span', {}, fmt(_('and %s more'), num(w.more))),
|
||||
ic('chevron'),
|
||||
)
|
||||
: null,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/** A figure of the row: its name over it (`tone`: the value's, when it asks for attention). */
|
||||
const fig = (label: string, value: string | null, tone = '', key?: string): HTMLElement =>
|
||||
h(
|
||||
'span',
|
||||
{ class: 'ov-fig' },
|
||||
h('span', { class: 'ov-fig-l' }, label),
|
||||
value === null
|
||||
? h('b', { class: 'ov-none', 'aria-label': _('none') }, '—')
|
||||
: h('b', { class: `num${tone ? ` ${tone}-t` : ''}`, 'data-t': key ?? null }, value),
|
||||
);
|
||||
|
||||
/** The key of a server's «Now» on its card: the page says its speed there as the meter reads it (index.ts). */
|
||||
export const NOW_KEY = 'now:';
|
||||
|
||||
/** How many people of a server wait for a decision. */
|
||||
const waitingOn = (c: OverviewCtx, s: Server): number =>
|
||||
waiting(
|
||||
c.st.people.filter((x) => x.server === s.id),
|
||||
c.today(),
|
||||
).length;
|
||||
|
||||
function serverCard(c: OverviewCtx, s: Server): HTMLElement {
|
||||
const st = c.st;
|
||||
// the cells stand in the same columns on every card: «Waiting» has its column while anyone on any server waits
|
||||
const anyWait = st.servers.some((x) => waitingOn(c, x) > 0);
|
||||
const line = serverState(s);
|
||||
const n = serverNumbers(s, st, c.today().today);
|
||||
// its speed as the meter has it this moment, once it answers; before that the router's last minute
|
||||
const live = s.enabled && s.up ? c.speedOf(s.id) : null;
|
||||
const down = live ?? n.down;
|
||||
// the card is the door to the server's own page: its Overview, people, places and settings
|
||||
const to = serverUrl(s.id);
|
||||
// who on it waits for a decision: counted here, listed on its page
|
||||
const wait = waitingOn(c, s);
|
||||
const row = h(
|
||||
'div',
|
||||
{ class: 'orow ov-srow' },
|
||||
h(
|
||||
'a',
|
||||
{ class: 'orow-a', href: to },
|
||||
glass('server', s.enabled && s.up ? 'blue' : 'grey'),
|
||||
h(
|
||||
'span',
|
||||
{ class: 'orow-t' },
|
||||
h('b', { title: s.name }, s.name),
|
||||
// as the server's page head says it: its state, then where devices connect
|
||||
h(
|
||||
'span',
|
||||
{ class: 'orow-l ov-sline' },
|
||||
h('span', { class: `${line.tone}-t`, 'data-live': '' }, line.text),
|
||||
h('span', { class: 'ov-addr mono', title: _('Address for devices') }, `${s.endpoint || _('no address')}:${s.port}`),
|
||||
),
|
||||
),
|
||||
),
|
||||
// «Turn on» stands between the name and the figures, so the figures keep their columns on every card
|
||||
c.write && !s.enabled ? h('span', { class: 'act-slot ov-on' }, turnOn(c, s)) : null,
|
||||
// the figures lead to the server as the name does (the keyboard has the name's link)
|
||||
h(
|
||||
'a',
|
||||
{ class: 'ov-figs', href: to, tabindex: '-1' },
|
||||
fig(_('People'), num(n.people)),
|
||||
anyWait ? fig(_('Waiting for a decision'), wait ? num(wait) : null, 'warn') : null,
|
||||
fig(_('Now', 'speed'), down === null ? null : `↓ ${rateOf(down)}`, '', NOW_KEY + s.id),
|
||||
fig(_('Today'), n.today === null ? null : bytes(n.today)),
|
||||
),
|
||||
h('a', { class: 'orow-go', href: to, tabindex: '-1', 'aria-hidden': 'true' }, ic('chevron')),
|
||||
);
|
||||
return h('div', { class: 'ov-server' }, row, rolloutShort(c, s));
|
||||
}
|
||||
|
||||
/**
|
||||
* The section's head (with the way to add a server) and a card a server; under them the people no server holds
|
||||
* (theirs was removed): the one thing of people Overview keeps, each with the way to choose them a server.
|
||||
* Put into `box` once; each part then follows what it reads (state/regions.ts): the head the servers' count,
|
||||
* a card its own server and what it counts of its people.
|
||||
*/
|
||||
export function serversSection(c: OverviewCtx, box: HTMLElement): void {
|
||||
const head = h('div', { class: 'ov-srv-h' });
|
||||
const cards = h('div', { class: 'ov-servers' });
|
||||
const lost = h('div', { class: 'ov-srv-lost' });
|
||||
putChildren(box, [head, cards, lost]);
|
||||
const add = c.write
|
||||
? h(
|
||||
'button',
|
||||
{ type: 'button', class: 'btn soft sm', onclick: () => newServer(() => api.setupDefaults(), true) },
|
||||
ic('plus'),
|
||||
h('span', {}, _('Add server')),
|
||||
)
|
||||
: null;
|
||||
fill(head, () => secHead(_('Servers'), num(c.st.servers.length), add));
|
||||
rows(
|
||||
cards,
|
||||
() => c.st.servers,
|
||||
(s) => s.id,
|
||||
(s) => serverCard(c, s),
|
||||
);
|
||||
// people no server holds (theirs was removed): the one thing of people Overview keeps
|
||||
fill(lost, () => {
|
||||
const servers = c.st.servers;
|
||||
const none = c.st.people.filter((x) => !servers.some((s) => s.id === x.server));
|
||||
return none.length
|
||||
? h(
|
||||
'div',
|
||||
{ class: 'ov-lost' },
|
||||
secHead(_('No server'), num(none.length)),
|
||||
compList(
|
||||
...none.map((x) =>
|
||||
compRow({
|
||||
icon: 'person',
|
||||
tone: 'red',
|
||||
title: x.name,
|
||||
line: fmt(_('%s: no server, no access'), plural(x.devices.length, '%s device', '%s devices')),
|
||||
lineTone: 'bad',
|
||||
acts: [
|
||||
c.write
|
||||
? h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
class: 'btn tint sm',
|
||||
onclick: () => movePerson({ person: x, st: c.st, moved: () => void c.reload() }),
|
||||
},
|
||||
ic('terminal'),
|
||||
h('span', {}, _('Choose a server')),
|
||||
)
|
||||
: null,
|
||||
],
|
||||
}),
|
||||
),
|
||||
),
|
||||
)
|
||||
: null;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
// Overview › Waiting for a decision: the first people of People's «Needs a
|
||||
// decision» group (overview/model.ts waitRows: the same people in the same
|
||||
// order, five rows, three on a phone), each a row: the face in the state's
|
||||
// tone, the name, their card's state line, and beside the link their card's
|
||||
// one action (people/card.ts; flows/person-acts.ts: done at once and said in
|
||||
// a toast with Undo, or its sheet). The head counts everyone who waits; «N more» leads to People
|
||||
// filtered to them. Nobody waits: the empty state says so. A read-only login
|
||||
// gets the rows without the actions.
|
||||
|
||||
import type { Person } from '../../../shared/types';
|
||||
import { h } from '../../../portal/dom';
|
||||
import { once } from '../../../portal/ui/feedback';
|
||||
import { fmt, num } from '../../../shared/i18n';
|
||||
import { ic } from '../../ui/icons';
|
||||
import { face } from '../../ui/face';
|
||||
import { emptyState } from '../../ui/empty';
|
||||
import { secHead } from '../../ui/page-head';
|
||||
import { peopleAt, personUrl } from '../../shell/routes';
|
||||
import { cardParts } from '../../people/card';
|
||||
import { actButton, runAct } from '../../flows/person-acts';
|
||||
import { waitRows } from '../../overview/model';
|
||||
import type { OverviewCtx } from './ctx';
|
||||
|
||||
/** Their card's parts (the server's name is in its words). */
|
||||
const partsOf = (c: OverviewCtx, p: Person) =>
|
||||
cardParts(
|
||||
p,
|
||||
c.st.servers.find((s) => s.id === p.server),
|
||||
c.today(),
|
||||
);
|
||||
|
||||
function row(c: OverviewCtx, p: Person): HTMLElement {
|
||||
const parts = partsOf(c, p);
|
||||
const text = parts.line ?? '';
|
||||
return h(
|
||||
'div',
|
||||
{ class: 'orow', 'data-id': p.id },
|
||||
h(
|
||||
'a',
|
||||
{ class: 'orow-a', href: personUrl(p.id), 'aria-label': `${p.name}: ${text}` },
|
||||
face(p.name, parts.tone),
|
||||
h(
|
||||
'span',
|
||||
{ class: 'orow-t' },
|
||||
h('b', { title: p.name }, p.name),
|
||||
h('span', { class: `orow-l${parts.tone ? ` ${parts.tone}-t` : ''}`, title: parts.title || null }, text),
|
||||
),
|
||||
),
|
||||
h('span', { class: 'act-slot' }, c.write && parts.action ? actButton(parts.action) : null),
|
||||
);
|
||||
}
|
||||
|
||||
/** The section's head and its rows; `narrow`: the page is a phone's width. */
|
||||
export function waitList(c: OverviewCtx, narrow: boolean): HTMLElement[] {
|
||||
const w = waitRows(c.st.people, c.today(), narrow);
|
||||
if (!w.total)
|
||||
return [
|
||||
secHead(_('Waiting for a decision')),
|
||||
emptyState({
|
||||
icon: 'people',
|
||||
title: _('Nobody waits for a decision'),
|
||||
text: _('Everyone’s terms, limits and connections are in order.'),
|
||||
}),
|
||||
];
|
||||
return [
|
||||
secHead(
|
||||
_('Waiting for a decision'),
|
||||
num(w.total),
|
||||
w.more > 0
|
||||
? h('a', { class: 'pill-link', href: peopleAt({ group: 'need' }) }, fmt(_('%s more'), num(w.more)), ic('chevron'))
|
||||
: undefined,
|
||||
),
|
||||
h('div', { class: 'olist ov-waitlist' }, ...w.rows.map((p) => row(c, p))),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* A person's one action, from any row of `box` (a button beside the row's link), as the People table runs it;
|
||||
* `ctx`: the page's newest answer.
|
||||
*/
|
||||
export function waitActions(box: HTMLElement, ctx: () => OverviewCtx) {
|
||||
box.addEventListener('click', (e) => {
|
||||
const b = (e.target as HTMLElement).closest<HTMLButtonElement>('.act-slot .btn[data-act]');
|
||||
const c = ctx();
|
||||
const p = c.st.people.find((x) => x.id === b?.closest<HTMLElement>('.orow')?.dataset.id);
|
||||
if (!b || !p) return;
|
||||
const act = partsOf(c, p).action;
|
||||
if (act)
|
||||
void once(b, () =>
|
||||
runAct(act, p, { st: () => ctx().st, today: () => ctx().today().today, now: () => ctx().now(), reload: () => ctx().reload() }),
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -1,913 +0,0 @@
|
||||
// People: one card per person, built from the status (the config itself,
|
||||
// with keys, is never read by the browser). Creating, editing, pausing and
|
||||
// device actions take effect immediately through RPC.
|
||||
|
||||
import type { Person, Status } from '../../shared/types';
|
||||
import { E } from '../e';
|
||||
import { api } from '../api';
|
||||
import { button, iconButton } from '../ui/button';
|
||||
import { cancelButton, closeModal, confirmDialog, modal } from '../ui/modal';
|
||||
import { copyText } from '../ui/files';
|
||||
import { dropdown, type MenuItem } from '../ui/menu';
|
||||
import { attempt, notify } from '../ui/toast';
|
||||
import { pointTip } from '../ui/glide';
|
||||
import { limitMeter, splitMeter } from '../widgets/meter';
|
||||
import { paceOf, paceWords, weekAhead } from '../../shared/pace';
|
||||
import { accessBadge } from '../ui/badges';
|
||||
import { addDevice, openDevice, type DeviceOpts } from '../device';
|
||||
import { copyPersonLink, inviteCard } from '../invite';
|
||||
import { personUrl } from '../urls';
|
||||
import { scoped } from '../state/scope';
|
||||
import { createPoller, focusInside, type Poller } from '../state/poller';
|
||||
import type { LiveMeter, Rate } from '../state/meter';
|
||||
import { onNavigate } from '../ui/nav';
|
||||
import { accessPicker } from '../widgets/access-picker';
|
||||
import { firstBad, liveField } from '../ui/layout';
|
||||
import { expiresHelp, limitHelp, nameHelp, quotaHelp } from '../netcheck';
|
||||
import { coreFor } from '../cores';
|
||||
import { icon } from '../../shared/icons';
|
||||
import {
|
||||
kindLabel,
|
||||
addMonthsClamped,
|
||||
ago,
|
||||
bits,
|
||||
byDeviceState,
|
||||
bytes,
|
||||
date,
|
||||
dayDiff,
|
||||
daysLeft,
|
||||
endsIn,
|
||||
endsSoon,
|
||||
initials,
|
||||
todayOf,
|
||||
} from '../../shared/format';
|
||||
import { fill, fmt, num, plural } from '../../shared/i18n';
|
||||
|
||||
type Sid = string;
|
||||
|
||||
/** Per-browser conveniences (a tab, a sort): storage may be absent or refuse. */
|
||||
function remembered(key: string): string | null {
|
||||
try {
|
||||
return localStorage.getItem(key);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
function remember(key: string, value: string) {
|
||||
try {
|
||||
localStorage.setItem(key, value);
|
||||
} catch {
|
||||
/* no storage */
|
||||
}
|
||||
}
|
||||
|
||||
/** Device slots as a row of segments (one per allowed device, used ones lit) and "2 of 10". */
|
||||
function slotBar(p: Person): HTMLElement {
|
||||
const used = p.devices.length;
|
||||
// Devices added over the limit get their own (soft orange) segments after the allowed ones.
|
||||
const n = Math.max(1, p.device_limit, used);
|
||||
// 22px a segment until the bar is 160px long; past that the segments get thinner, so the count stays close.
|
||||
const width = Math.min(160, n * 22 + (n - 1) * 3);
|
||||
return E('div', { class: 'dl-slotbar', title: fmt(N_(p.device_limit, '%s of %s device', '%s of %s devices'), used, p.device_limit) }, [
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-slotbar-segs', style: `width: ${width}px` },
|
||||
Array.from({ length: n }, (_x, i) => E('i', { class: i >= p.device_limit ? 'over' : i < used ? 'used' : '' })),
|
||||
),
|
||||
E('span', { class: 'dl-slotbar-text' }, fmt(_('%s of %s'), used, p.device_limit)),
|
||||
]);
|
||||
}
|
||||
|
||||
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 p.state === 'quota' || p.state === 'expired' || endsSoon(p, left) || (!!p.quota_limit && p.quota_used >= p.quota_limit * 0.9);
|
||||
}
|
||||
|
||||
/** A month more, from the end date or from today once it has passed. */
|
||||
function addMonth(end: string, today: string): string {
|
||||
return addMonthsClamped(end && dayDiff(end, today) >= 0 ? end : today, 1);
|
||||
}
|
||||
|
||||
const ids = (st: Status) =>
|
||||
st.people
|
||||
.map((p) => p.id)
|
||||
.sort()
|
||||
.join(' ');
|
||||
|
||||
let addOpened = false;
|
||||
|
||||
export class PeoplePage {
|
||||
st!: Status;
|
||||
/** The cards, one per person, in the current sort order. */
|
||||
private list: HTMLElement = E('div', { class: 'dl-plist', role: 'list' });
|
||||
// `?filter=online` (from Overview) preselects a tab.
|
||||
// The tab and the sort are remembered in this browser; ?filter= (from Overview) wins for the tab.
|
||||
filter: Filter =
|
||||
(['all', 'online', 'attention', 'paused'] as Filter[]).find(
|
||||
(f) => f === (new URLSearchParams(location.search).get('filter') ?? remembered('dl.people.filter')),
|
||||
) ?? 'all';
|
||||
sort: SortBy = (['seen', 'name', 'usage'] as SortBy[]).find((x) => x === remembered('dl.people.sort')) ?? 'seen';
|
||||
/** What the admin typed into Find (name, note, device, address). */
|
||||
query = '';
|
||||
noFooter = true;
|
||||
/** Set when shown as a server's People section: only that server's people. */
|
||||
serverId: string | null = null;
|
||||
el: HTMLElement | null = null;
|
||||
poller?: Poller<Status>;
|
||||
/** Each online person's speed in their card, put in place each second from the meter (a server's People list). */
|
||||
private speedEls = new Map<string, { p: Person; down: HTMLElement; up: HTMLElement }>();
|
||||
|
||||
/** `meter`: the Servers page's live meter, which it polls while this list shows (none on its own page). */
|
||||
constructor(private meter?: LiveMeter) {}
|
||||
|
||||
async load(): Promise<Status> {
|
||||
return api.status(30);
|
||||
}
|
||||
|
||||
/** The status limited to this page's server (or everything). */
|
||||
scope(st: Status): Status {
|
||||
return this.serverId ? scoped(st, this.serverId) : st;
|
||||
}
|
||||
|
||||
/** Render as a section of the Servers page. */
|
||||
embed(st: Status, serverId: string): Promise<Node> {
|
||||
this.serverId = serverId;
|
||||
return this.render(st);
|
||||
}
|
||||
|
||||
person(sid: Sid): Person | undefined {
|
||||
return this.st.people.find((p) => p.id === sid);
|
||||
}
|
||||
|
||||
get today(): string {
|
||||
return todayOf(this.st.series);
|
||||
}
|
||||
|
||||
/** What a device drawer opened from here gets. */
|
||||
deviceOpts(p: Person): DeviceOpts {
|
||||
return {
|
||||
refresh: () => this.refresh(),
|
||||
geo: this.st.geo,
|
||||
now: this.st.now,
|
||||
today: this.today,
|
||||
core: coreFor(this.st.servers, p.server),
|
||||
server: this.st.servers.find((s) => s.id === p.server),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* A new status (newest answer wins, see the poller). People added or removed
|
||||
* elsewhere re-render the list; otherwise the cards repaint in place.
|
||||
*/
|
||||
take(stAll: Status, quiet: boolean) {
|
||||
const st = this.scope(stAll);
|
||||
const changed = ids(st) !== ids(this.st);
|
||||
this.st = st;
|
||||
if (changed) this.rebuild();
|
||||
else {
|
||||
this.paintCards(quiet);
|
||||
this.decorate(quiet);
|
||||
}
|
||||
}
|
||||
|
||||
/** Repaint the cards from a fresh status (after a change made here). */
|
||||
async update() {
|
||||
await this.poller?.refresh();
|
||||
}
|
||||
|
||||
/** Everything again, the form's sections too (after adding or removing someone). */
|
||||
async refresh() {
|
||||
this.poller?.claim();
|
||||
const st = await api.status(30).catch(() => null);
|
||||
if (!st) return;
|
||||
this.st = this.scope(st);
|
||||
this.rebuild();
|
||||
}
|
||||
|
||||
/** One card per person (cards already shown are kept and repainted), or the empty state. */
|
||||
rebuild() {
|
||||
const old = new Map<string, HTMLElement>();
|
||||
for (const el of Array.from(this.list.children) as HTMLElement[]) if (el.dataset.sid) old.set(el.dataset.sid, el);
|
||||
const cards = this.st.people.map((p) => {
|
||||
const card = old.get(p.id) ?? E('div', { class: 'dl-card', role: 'listitem', 'data-sid': p.id });
|
||||
return this.renderCard(card, p.id);
|
||||
});
|
||||
dom.content(
|
||||
this.list,
|
||||
cards.length
|
||||
? cards
|
||||
: E(
|
||||
'div',
|
||||
{ class: 'dl-plist-none' },
|
||||
this.st.servers.length
|
||||
? _('No people yet. Add someone and send them their personal link.')
|
||||
: _('Set up the server first, then add people.'),
|
||||
),
|
||||
);
|
||||
this.decorate();
|
||||
}
|
||||
|
||||
/** `quiet` (a periodic repaint) leaves alone a card that has the keyboard focus. */
|
||||
paintCards(quiet = false) {
|
||||
for (const p of this.st.people) {
|
||||
const card = this.card(p.id);
|
||||
if (card && !(quiet && focusInside(card))) this.renderCard(card, p.id);
|
||||
}
|
||||
}
|
||||
|
||||
/** This page's card for a person (a server's People section has its own list). */
|
||||
card(sid: Sid): HTMLElement | null {
|
||||
return this.list.querySelector<HTMLElement>(`[data-sid="${CSS.escape(sid)}"]`);
|
||||
}
|
||||
|
||||
render(stAll: Status): Promise<Node> {
|
||||
const st = this.scope(stAll);
|
||||
this.st = st;
|
||||
const sort = E(
|
||||
'select',
|
||||
{
|
||||
class: 'dl-select',
|
||||
'aria-label': _('Sort'),
|
||||
change: (ev: Event) => {
|
||||
this.sort = (ev.target as HTMLSelectElement).value as SortBy;
|
||||
remember('dl.people.sort', this.sort);
|
||||
this.decorate();
|
||||
},
|
||||
},
|
||||
[
|
||||
E('option', { value: 'seen', selected: this.sort === 'seen' ? 'selected' : null }, _('Last seen', 'sort')),
|
||||
E('option', { value: 'name', selected: this.sort === 'name' ? 'selected' : null }, _('Name', 'sort')),
|
||||
E('option', { value: 'usage', selected: this.sort === 'usage' ? 'selected' : null }, _('Usage', 'sort')),
|
||||
],
|
||||
);
|
||||
// Find, once the list is long enough to need it; "/" focuses it.
|
||||
const find = E('input', {
|
||||
type: 'search',
|
||||
class: 'cbi-input-text dl-people-find',
|
||||
placeholder: _('Find…'),
|
||||
'aria-label': _('Find a person or device'),
|
||||
hidden: st.people.length > 8 ? null : 'hidden',
|
||||
input: (ev: Event) => {
|
||||
this.query = (ev.target as HTMLInputElement).value.trim().toLowerCase();
|
||||
this.decorate();
|
||||
},
|
||||
}) as HTMLInputElement;
|
||||
const onSlash = (ev: KeyboardEvent) => {
|
||||
const t = ev.target as HTMLElement;
|
||||
if (ev.key === '/' && !find.hidden && !['INPUT', 'TEXTAREA', 'SELECT'].includes(t?.tagName) && !t?.isContentEditable) {
|
||||
ev.preventDefault();
|
||||
find.focus();
|
||||
}
|
||||
};
|
||||
document.addEventListener('keydown', onSlash);
|
||||
onNavigate(() => document.removeEventListener('keydown', onSlash));
|
||||
const wrap = E('div', { class: 'dl-root' }, [
|
||||
this.serverId
|
||||
? ''
|
||||
: E('div', { class: 'dl-pagehead' }, [
|
||||
E('div', { class: 'dl-stack' }, [
|
||||
E('h2', { class: 'dl-h1' }, _('People')),
|
||||
E('span', { class: 'dl-muted dl-people-count' }, this.countText()),
|
||||
]),
|
||||
st.servers.length ? button([icon('plus'), ` ${_('Add person')}`], () => this.openCreate(), 'add') : '',
|
||||
]),
|
||||
st.servers.length
|
||||
? ''
|
||||
: E(
|
||||
'div',
|
||||
{ class: 'alert-message warning' },
|
||||
fill(
|
||||
_('No server yet. %s before adding people.'),
|
||||
E('a', { href: L.url('admin/services/dawnline/server') }, _('Run the setup wizard')),
|
||||
),
|
||||
),
|
||||
E('div', { class: 'dl-toolbar' }, [
|
||||
E('div', { class: 'dl-seg dl-people-tabs', role: 'tablist' }),
|
||||
// Sort and add stay together on the right, wrapping as one group.
|
||||
E('div', { class: 'dl-toolbar-end' }, [
|
||||
find,
|
||||
sort,
|
||||
this.serverId ? button([icon('plus'), ` ${_('Add person')}`], () => this.openCreate(), 'add') : '',
|
||||
]),
|
||||
]),
|
||||
this.list,
|
||||
]);
|
||||
this.el = wrap;
|
||||
this.rebuild();
|
||||
// Only while visible (a server section may be swapped out).
|
||||
this.poller ??= createPoller({
|
||||
fetch: () => api.status(30),
|
||||
every: 30,
|
||||
live: true,
|
||||
active: () => !!this.el?.isConnected,
|
||||
apply: (st, quiet) => this.take(st, quiet),
|
||||
});
|
||||
// ?add=1 opens Add person once, not again on every server's People tab.
|
||||
if (!addOpened && new URLSearchParams(location.search).get('add')) {
|
||||
addOpened = true;
|
||||
setTimeout(() => this.openCreate(), 100);
|
||||
}
|
||||
return Promise.resolve(wrap);
|
||||
}
|
||||
|
||||
countText(): string {
|
||||
const t = this.st.totals;
|
||||
return [
|
||||
plural(t.people, '%s person', '%s people'),
|
||||
plural(t.devices, '%s device', '%s devices'),
|
||||
fmt(_('%s online'), num(t.online)),
|
||||
].join(' · ');
|
||||
}
|
||||
|
||||
/** Row classes, counters, filter tabs and sort order; a `quiet` repaint keeps focused tabs. */
|
||||
decorate(quiet = false) {
|
||||
const c = this.el?.querySelector('.dl-people-count');
|
||||
if (c) c.textContent = this.countText();
|
||||
const people = this.st.people;
|
||||
const today = this.today;
|
||||
const attn = (p: Person) => needsAttention(p, today);
|
||||
const counts: Record<Filter, number> = {
|
||||
all: people.length,
|
||||
online: people.filter((p) => p.online > 0).length,
|
||||
attention: people.filter(attn).length,
|
||||
paused: people.filter((p) => paused(p)).length,
|
||||
};
|
||||
const tabs = this.el?.querySelector<HTMLElement>('.dl-people-tabs');
|
||||
if (tabs && !(quiet && focusInside(tabs))) {
|
||||
const label: Record<Filter, string> = { all: _('All'), online: _('Online'), attention: _('Needs attention'), paused: _('Paused') };
|
||||
dom.content(
|
||||
tabs,
|
||||
(Object.keys(label) as Filter[]).map((f) =>
|
||||
E(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
role: 'tab',
|
||||
class: f === this.filter ? 'on' : '',
|
||||
click: () => {
|
||||
this.filter = f;
|
||||
remember('dl.people.filter', f);
|
||||
this.decorate();
|
||||
},
|
||||
},
|
||||
[label[f], E('b', { class: f === 'attention' && counts[f] ? 'warn' : '' }, String(counts[f]))],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
const q = this.query;
|
||||
const hay = (p: Person) =>
|
||||
[p.name, p.note ?? '', ...p.devices.flatMap((d) => [d.name, d.address, d.hostname, d.endpoint])].join(' ').toLowerCase();
|
||||
const match = (p: Person) => {
|
||||
if (this.filter === 'online' && !p.online) return false;
|
||||
if (this.filter === 'attention' && !attn(p)) return false;
|
||||
if (this.filter === 'paused' && !paused(p)) return false;
|
||||
if (q && !hay(p).includes(q)) return false;
|
||||
return true;
|
||||
};
|
||||
// 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', stopped(p));
|
||||
const hit = match(p);
|
||||
card.classList.toggle('dl-filtered', !hit);
|
||||
if (hit) shown++;
|
||||
}
|
||||
// Say so when the filter leaves nobody.
|
||||
let none = this.el?.querySelector<HTMLElement>('.dl-people-none') ?? null;
|
||||
if (people.length && !shown) {
|
||||
none ??= E('div', { class: 'dl-empty dl-people-none' }, E('p', {}, _('No one here right now.')));
|
||||
if (none.previousElementSibling !== this.list) this.list.after(none);
|
||||
} else none?.remove();
|
||||
}
|
||||
|
||||
async quick(p: Person, patch: Parameters<typeof api.personUpdate>[1], ok: string) {
|
||||
if (await attempt(() => api.personUpdate(p.id, patch), ok)) await this.update();
|
||||
}
|
||||
|
||||
renderCard(node: HTMLElement, sid: Sid): HTMLElement {
|
||||
const p = this.person(sid);
|
||||
if (!p) {
|
||||
dom.content(node, E('em', {}, _('This person was just removed.')));
|
||||
return node;
|
||||
}
|
||||
const today = this.today;
|
||||
const left = daysLeft(p.expires, today);
|
||||
const free = Math.max(0, p.device_limit - p.devices.length);
|
||||
// The link itself is not in the status (person_links asks for it).
|
||||
const portal = p.has_link ?? this.st.settings.portal_enabled;
|
||||
|
||||
// Term and hours sit by the name; online/last seen lives in the strip below.
|
||||
const pills: Node[] = [];
|
||||
const why = stopReason(p);
|
||||
if (p.expires && why !== 'expired') {
|
||||
const soon = endsSoon(p, left);
|
||||
const over = left != null && left < 0;
|
||||
pills.push(
|
||||
E('span', { class: `dl-pill-ic${over ? ' bad' : soon ? ' warn' : ''}`, title: fmt(_('Access ends %s'), date(p.expires)) }, [
|
||||
icon('calendar'),
|
||||
over ? fmt(_('ended %s'), date(p.expires)) : soon ? endsIn(left as number) : fmt(_('until %s'), date(p.expires)),
|
||||
]),
|
||||
);
|
||||
}
|
||||
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(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
class: `dl-chip${d.disabled ? ' disabled' : ''}${d.online ? ' live' : ''}`,
|
||||
title: [
|
||||
kindLabel(d.kind),
|
||||
d.address,
|
||||
d.online ? fmt(_('online from %s'), d.endpoint) : d.handshake ? fmt(_('seen %s'), ago(d.handshake, this.st.now)) : '',
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' · '),
|
||||
click: (ev: Event) => {
|
||||
ev.preventDefault();
|
||||
void openDevice(p, d, this.deviceOpts(p));
|
||||
},
|
||||
},
|
||||
[
|
||||
icon(d.kind),
|
||||
E('span', { class: 'dl-chip-name' }, d.name),
|
||||
!d.handshake && !d.disabled ? E('span', { class: 'dl-chip-tag' }, _('not set up')) : '',
|
||||
// Online shows as the green chip (.dl-chip.live); no dots.
|
||||
],
|
||||
);
|
||||
});
|
||||
// Always there: over the limit the admin can still add one (the slot bar turns orange).
|
||||
chips.push(
|
||||
E(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
class: 'dl-chip add',
|
||||
title: free > 0 ? _('Add device') : _('Over the limit: admins can still add'),
|
||||
click: (ev: Event) => {
|
||||
ev.preventDefault();
|
||||
addDevice(p, this.deviceOpts(p));
|
||||
},
|
||||
},
|
||||
[icon('plus'), _('Add device')],
|
||||
),
|
||||
);
|
||||
|
||||
// Ending soon (the strip below handles an end that has passed).
|
||||
const fixes: Node[] = [];
|
||||
if (p.expires && endsSoon(p, left) && why !== 'expired')
|
||||
fixes.push(
|
||||
E(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
class: 'dl-fix',
|
||||
click: () => this.quick(p, { expires: addMonth(p.expires, today) }, _('Extended by 1 month')),
|
||||
},
|
||||
_('Extend 1 month'),
|
||||
),
|
||||
);
|
||||
|
||||
const more = iconButton(
|
||||
'more',
|
||||
_('More'),
|
||||
(ev: MouseEvent) =>
|
||||
dropdown(
|
||||
ev.currentTarget as HTMLElement,
|
||||
[
|
||||
{
|
||||
label: _('Open'),
|
||||
icon: icon('open'),
|
||||
run: () => {
|
||||
location.href = personUrl(p.id);
|
||||
},
|
||||
},
|
||||
portal
|
||||
? {
|
||||
label: _('Invite card'),
|
||||
icon: icon('qr'),
|
||||
run: () => inviteCard(p, this.st.servers.find((s) => s.id === p.server)?.name ?? _('Home')),
|
||||
}
|
||||
: null,
|
||||
free > 0 ? { label: _('Add device'), icon: icon('plus'), run: () => addDevice(p, this.deviceOpts(p)) } : null,
|
||||
null,
|
||||
{
|
||||
label: p.paused ? _('Resume') : _('Pause'),
|
||||
icon: icon(p.paused ? 'play' : 'pause'),
|
||||
warn: !p.paused,
|
||||
run: () => this.togglePause(p),
|
||||
},
|
||||
{ label: _('Delete'), icon: icon('trash'), danger: true, run: () => this.remove(p.id) },
|
||||
].filter((x, i, a) => x || (i > 0 && a[i - 1])) as MenuItem[],
|
||||
),
|
||||
'neutral',
|
||||
'dl-icon-only',
|
||||
);
|
||||
const actions = E('div', { class: 'dl-pcard-actions' }, [
|
||||
portal ? iconButton('link', _('Copy link'), () => copyPersonLink(p.id), 'neutral', 'dl-icon-only') : '',
|
||||
more,
|
||||
]);
|
||||
|
||||
dom.content(
|
||||
node,
|
||||
E('div', { class: 'dl-pcard' }, [
|
||||
E('div', { class: 'dl-pcard-main' }, [
|
||||
// The avatar is centred on the name and the slots; devices follow under the name.
|
||||
E('div', { class: 'dl-pcard-top' }, [
|
||||
E('span', { class: `dl-avatar${p.online ? ' online' : ''}` }, initials(p.name)),
|
||||
E('div', { class: 'dl-pcard-who' }, [
|
||||
E('div', { class: 'dl-card-head' }, [
|
||||
E('a', { class: 'dl-card-name', href: personUrl(p.id) }, p.name),
|
||||
accessBadge(p),
|
||||
...pills,
|
||||
]),
|
||||
slotBar(p),
|
||||
]),
|
||||
]),
|
||||
E('div', { class: 'dl-chips' }, chips),
|
||||
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'),
|
||||
fmt(_('Paused until it resets on %s'), 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',
|
||||
fmt(_('Access ended %s'), 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'), fmt(_('Access %s (router time)'), p.hours.replace('-', '–')), 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];
|
||||
const pct = p.quota_limit ? Math.min(100, (p.quota_used / p.quota_limit) * 100) : 0;
|
||||
const today = p.devices.reduce((a, d) => a + (d.spark[d.spark.length - 1] ?? [0, 0]).reduce((x, y) => x + y), 0);
|
||||
const r = p.online ? this.speedOf(p) : null;
|
||||
const live = !!r;
|
||||
|
||||
// The pace lately: their devices' days added up (each device's last 7, today last).
|
||||
const week = Array.from({ length: 7 }, (_x, k) => p.devices.reduce((a, d) => a + (d.spark[k]?.[0] ?? 0) + (d.spark[k]?.[1] ?? 0), 0));
|
||||
const pace = paceOf(week);
|
||||
const paceText = paceWords(used, p.quota_limit, pace, p.quota_period === 'month', this.today);
|
||||
let bar: HTMLElement;
|
||||
if (p.quota_limit) {
|
||||
bar = limitMeter(pct, weekAhead(p.quota_used, p.quota_limit, pace));
|
||||
// Above where the fill ends: the value's own place.
|
||||
pointTip(
|
||||
bar,
|
||||
() => [
|
||||
E('div', { class: 'dl-glide-head' }, [
|
||||
E('b', {}, fmt(_('%s%% used'), num(pct, 1))),
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-faint' },
|
||||
p.quota_period === 'total'
|
||||
? _('In total')
|
||||
: [_('This month'), p.bonus_gb ? fmt(_('includes +%s GB extra'), num(p.bonus_gb)) : ''].filter(Boolean).join(' · '),
|
||||
),
|
||||
]),
|
||||
E(
|
||||
'div',
|
||||
{ class: 'dl-muted' },
|
||||
`${fmt(_('%s of %s'), bytes(p.quota_used), bytes(p.quota_limit))} · ${fmt(_('%s left'), bytes(Math.max(0, p.quota_limit - p.quota_used)))}`,
|
||||
),
|
||||
pct < 100 && paceText ? E('div', { class: 'dl-glide-note' }, paceText) : '',
|
||||
],
|
||||
() => {
|
||||
const r = bar.getBoundingClientRect();
|
||||
return [r.left + (r.width * pct) / 100, r.top];
|
||||
},
|
||||
);
|
||||
} else {
|
||||
const devs = p.devices
|
||||
.map((d) => ({ d, v: d.month[0] + d.month[1] }))
|
||||
.filter((x) => x.v > 0)
|
||||
.sort((a, b) => b.v - a.v);
|
||||
bar = splitMeter(devs.map((x) => x.v));
|
||||
if (devs.length)
|
||||
pointTip(bar, () => [
|
||||
E('div', { class: 'dl-glide-head' }, [E('b', {}, _('This month by device')), E('span', { class: 'dl-faint' }, bytes(used))]),
|
||||
...devs.map((x, i) =>
|
||||
E('div', { class: 'dl-tip-row' }, [
|
||||
E('span', { class: `dl-swatch c${Math.min(i, 4)}` }),
|
||||
E('span', {}, x.d.name),
|
||||
E('span', { class: 'dl-faint' }, `${num(Math.round((x.v / Math.max(1, used)) * 100))}%`),
|
||||
E('b', {}, bytes(x.v)),
|
||||
]),
|
||||
),
|
||||
paceText ? E('div', { class: 'dl-glide-note' }, paceText) : '',
|
||||
]);
|
||||
}
|
||||
|
||||
const limitText = p.quota_limit ? fmt(_('%s left'), bytes(Math.max(0, p.quota_limit - p.quota_used))) : _('no limit');
|
||||
return E('div', { class: 'dl-pside' }, [
|
||||
E('div', { class: 'dl-pside-top' }, [
|
||||
live
|
||||
? E('span', { class: 'dl-pside-state live' }, _('Online'))
|
||||
: E('span', { class: 'dl-pside-state' }, p.online ? _('Online') : p.last_seen ? _('Offline') : _('Never connected')),
|
||||
actions,
|
||||
]),
|
||||
E('div', { class: 'dl-use-num' }, [
|
||||
E('b', { class: used ? '' : 'dl-faint' }, bytes(used)),
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-faint' },
|
||||
p.quota_limit
|
||||
? fmt(_('of %s'), bytes(p.quota_limit))
|
||||
: p.quota_period === 'total' && p.quota_gb
|
||||
? _('in total')
|
||||
: _('this month'),
|
||||
),
|
||||
]),
|
||||
bar,
|
||||
r
|
||||
? this.speedRow(p, r)
|
||||
: E('div', { class: 'dl-faint dl-pside-foot' }, today ? `${fmt(_('today %s'), bytes(today))} · ${limitText}` : limitText),
|
||||
]);
|
||||
}
|
||||
|
||||
/** Their speed now ([ts, rx, tx]): the live meter's while it has points, else their newest minute while it is recent. */
|
||||
private speedOf(p: Person): Rate | null {
|
||||
const s = this.meter?.speed(
|
||||
p.server,
|
||||
Date.now(),
|
||||
p.devices.map((d) => d.id),
|
||||
);
|
||||
if (s?.pts.length) return [0, s.rx, s.tx];
|
||||
const r = p.rate?.[p.rate.length - 1];
|
||||
return r && this.st.now - r[0] < 180 ? r : null;
|
||||
}
|
||||
|
||||
private speedRow(p: Person, r: Rate): HTMLElement {
|
||||
const down = E('span', {}, `↓ ${bits(r[2])}`);
|
||||
const up = E('span', { class: 'dl-faint' }, `↑ ${bits(r[1])}`);
|
||||
this.speedEls.set(p.id, { p, down, up });
|
||||
return E('div', { class: 'dl-use-live', title: _('Right now') }, [down, up]);
|
||||
}
|
||||
|
||||
/** Each second's meter answer: the speeds in the cards on screen (whether someone is online waits for the status). */
|
||||
paintSpeed() {
|
||||
for (const { p, down, up } of this.speedEls.values()) {
|
||||
if (!down.isConnected) continue;
|
||||
const r = this.speedOf(p);
|
||||
if (!r) continue;
|
||||
down.textContent = `↓ ${bits(r[2])}`;
|
||||
up.textContent = `↑ ${bits(r[1])}`;
|
||||
}
|
||||
}
|
||||
|
||||
async togglePause(p: Person) {
|
||||
if (await attempt(() => api.personPause(p.id, !p.paused), fmt(p.paused ? _('%s resumed') : _('%s paused'), p.name)))
|
||||
await this.refresh();
|
||||
}
|
||||
|
||||
async remove(sid: Sid) {
|
||||
const p = this.person(sid);
|
||||
const ok = await confirmDialog(
|
||||
fmt(_('Remove %s?'), p?.name ?? sid),
|
||||
plural(
|
||||
p?.devices.length ?? 0,
|
||||
'%s device is disconnected immediately and the personal link stops working. Usage history is kept in backups.',
|
||||
'All %s devices are disconnected immediately and the personal link stops working. Usage history is kept in backups.',
|
||||
),
|
||||
_('Remove'),
|
||||
true,
|
||||
);
|
||||
if (ok && (await attempt(() => api.personDelete(sid), _('Person removed')))) await this.refresh();
|
||||
}
|
||||
|
||||
openCreate() {
|
||||
const st = this.st;
|
||||
if (!st.servers.length) {
|
||||
notify(_('Set up the server first.'), 'warning');
|
||||
return;
|
||||
}
|
||||
const name = E('input', { type: 'text', class: 'cbi-input-text', placeholder: _('e.g. Myata'), maxlength: 48 }) as HTMLInputElement;
|
||||
// The last person's access and data limit come back pre-filled (most are alike).
|
||||
const last = (() => {
|
||||
try {
|
||||
return JSON.parse(remembered('dl.person.last') ?? '{}') as { access?: Person['access']; quota?: string };
|
||||
} catch {
|
||||
return {} as { access?: Person['access']; quota?: string };
|
||||
}
|
||||
})();
|
||||
const access = accessPicker(last.access ?? 'internet');
|
||||
const limit = E('input', {
|
||||
type: 'number',
|
||||
class: 'cbi-input-text',
|
||||
min: 1,
|
||||
max: 32,
|
||||
value: st.settings.default_device_limit,
|
||||
}) as HTMLInputElement;
|
||||
const expires = E('input', { type: 'date', class: 'cbi-input-text' }) as HTMLInputElement;
|
||||
const quota = E('input', {
|
||||
type: 'number',
|
||||
class: 'cbi-input-text',
|
||||
min: 0,
|
||||
step: 'any',
|
||||
placeholder: _('Unlimited'),
|
||||
value: last.quota ?? '',
|
||||
}) as HTMLInputElement;
|
||||
const quick = (label: string, months: number) =>
|
||||
E(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
class: 'cbi-button cbi-button-neutral',
|
||||
click: () => {
|
||||
expires.value = months ? addMonthsClamped(todayOf(st.series), months) : '';
|
||||
expires.dispatchEvent(new Event('change'));
|
||||
},
|
||||
},
|
||||
label,
|
||||
);
|
||||
const srv = st.servers[0];
|
||||
const server =
|
||||
!this.serverId && st.servers.length > 1
|
||||
? (E(
|
||||
'select',
|
||||
{ class: 'cbi-input-select' },
|
||||
st.servers.map((s) => E('option', { value: s.id }, s.name)),
|
||||
) as HTMLSelectElement)
|
||||
: null;
|
||||
|
||||
const row = (label: string, w: Node, help?: string) =>
|
||||
E('div', { class: 'cbi-value' }, [
|
||||
E('label', { class: 'cbi-value-title' }, label),
|
||||
E('div', { class: 'cbi-value-field' }, [w, help ? E('div', { class: 'cbi-value-description' }, help) : '']),
|
||||
]);
|
||||
// Each field says what its value means, or what is wrong, as it is typed; Create refuses what the router would.
|
||||
const today = todayOf(st.series);
|
||||
const nameRow = liveField(_('Name', 'person'), name, () => nameHelp(name.value, [], _('Shown in their portal and apps.')));
|
||||
const limitRow = liveField(_('Devices'), limit, () => limitHelp(limit.value));
|
||||
const expRow = liveField(
|
||||
_('End date'),
|
||||
expires,
|
||||
() => expiresHelp(expires.value, today, daysLeft, date),
|
||||
E('div', { class: 'dl-actions' }, [
|
||||
expires,
|
||||
quick(_('1 month'), 1),
|
||||
quick(_('3 months'), 3),
|
||||
quick(_('1 year'), 12),
|
||||
quick(_('None', 'end date'), 0),
|
||||
]),
|
||||
);
|
||||
const quotaRow = liveField(_('Monthly data (GB)'), quota, () => quotaHelp(quota.value));
|
||||
// The quick buttons set the date without an input event.
|
||||
expires.addEventListener('change', () => expRow.refresh());
|
||||
const portalOn = st.settings.portal_enabled;
|
||||
|
||||
modal(
|
||||
_('Add person'),
|
||||
[
|
||||
nameRow,
|
||||
server ? row(_('Server'), server) : '',
|
||||
E('div', { class: 'cbi-value dl-block' }, [
|
||||
E('label', { class: 'cbi-value-title' }, _('Access')),
|
||||
E('div', { class: 'cbi-value-field' }, access.el),
|
||||
]),
|
||||
limitRow,
|
||||
expRow,
|
||||
quotaRow,
|
||||
],
|
||||
[
|
||||
cancelButton(),
|
||||
' ',
|
||||
button(
|
||||
// Without the portal there is no link to copy.
|
||||
portalOn ? _('Create and copy link') : _('Create'),
|
||||
async () => {
|
||||
const bad = firstBad([nameRow, limitRow, expRow, quotaRow]);
|
||||
if (bad) {
|
||||
notify(bad, 'warning');
|
||||
return;
|
||||
}
|
||||
const r = await attempt(() =>
|
||||
api.personCreate(
|
||||
name.value.trim(),
|
||||
'',
|
||||
server?.value ?? srv.id,
|
||||
access.get(),
|
||||
limit.value.trim(),
|
||||
expires.value,
|
||||
quota.value.trim(),
|
||||
'month',
|
||||
),
|
||||
);
|
||||
if (!r) return;
|
||||
remember('dl.person.last', JSON.stringify({ access: access.get(), quota: quota.value.trim() }));
|
||||
// After the await some browsers refuse the clipboard: the card has its own Copy.
|
||||
if (r.link) await copyText(r.link, _('Personal link copied'), true);
|
||||
this.showCreated(r.id, name.value.trim(), r.link, st.servers.find((x) => x.id === (server?.value ?? srv.id))?.name ?? srv.name);
|
||||
await this.refresh();
|
||||
},
|
||||
'positive',
|
||||
),
|
||||
],
|
||||
);
|
||||
setTimeout(() => name.focus(), 50);
|
||||
}
|
||||
|
||||
showCreated(id: string, name: string, link: string | null, server: string) {
|
||||
if (link) {
|
||||
inviteCard({ id, name, link }, server, {
|
||||
title: fmt(_('%s is ready'), name),
|
||||
lead: fmt(_('Send %s the card or the link. They open it, add their devices and connect - no account needed.'), name),
|
||||
});
|
||||
return;
|
||||
}
|
||||
// No portal, no link: the two ways on from here, as buttons.
|
||||
const p = this.person(id);
|
||||
modal(
|
||||
fmt(_('%s is ready'), name),
|
||||
[E('p', {}, _('Created. Turn on the personal portal in Settings to get a link, or add devices for them here.'))],
|
||||
[
|
||||
E('button', { class: 'cbi-button cbi-button-neutral', click: closeModal }, _('Done')),
|
||||
' ',
|
||||
E(
|
||||
'a',
|
||||
{ class: 'cbi-button cbi-button-neutral', href: `${L.url('admin/services/dawnline/settings')}?section=portal` },
|
||||
_('Open Settings'),
|
||||
),
|
||||
' ',
|
||||
p
|
||||
? button(
|
||||
_('Add device'),
|
||||
() => {
|
||||
closeModal();
|
||||
addDevice(p, this.deviceOpts(p));
|
||||
},
|
||||
'positive',
|
||||
)
|
||||
: '',
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,359 @@
|
||||
// A person's card in the People list: the portal's device card (.dev, raised, radius 28, padding 8; a top row and
|
||||
// field blocks of radius 20) with the parts people/card.ts gives this person's state, nothing else. The head: the
|
||||
// face (blue ring while online; a decision's tone in «Needs a decision»), the name (a link to their page, its hit
|
||||
// area stretched over the card), up to three device tiles and «+N» (a dot on those online, warn on a fault or a
|
||||
// configuration to fetch; each tile names its device in the tooltip and leads to it), ⋯. Under the name the one state
|
||||
// line in its tone with «· N more», and what the search found them by. Then presence (for how long, the week's hours,
|
||||
// the live speed with its line while online), traffic (the week and the month beside the week's bars, read a day
|
||||
// at a time; the limit's bar from 50 %), and the one action as the card's block button. A read-only login: no
|
||||
// action, no ⋯.
|
||||
|
||||
import type { Device, GeoPoint, Pair, Person, Status } from '../../../shared/types';
|
||||
import { h, type Kid } from '../../../portal/dom';
|
||||
import { openMenu, type MenuItem } from '../../../portal/ui/menu';
|
||||
import { once } from '../../../portal/ui/feedback';
|
||||
import { bars, readBars } from '../../../portal/ui/bars';
|
||||
import { setText } from '../../../portal/ui/morph';
|
||||
import { bytes } from '../../../shared/format';
|
||||
import { fmt, locale, plural } from '../../../shared/i18n';
|
||||
import { ic } from '../../ui/icons';
|
||||
import { face } from '../../ui/face';
|
||||
import { meter } from '../../ui/meter';
|
||||
import { tip } from '../../../portal/ui/tip';
|
||||
import { liveLine, type LiveLine } from '../../widgets/live-line';
|
||||
import { deviceUrl, personUrl } from '../../shell/routes';
|
||||
import { visit } from '../../shell/visit';
|
||||
import { routerDay, routerTime } from '../../events/clock';
|
||||
import { ofLimit, type CardParts } from '../../people/card';
|
||||
import { deviceLine } from '../../people/diagnosis';
|
||||
import { litAt, type Match } from '../../people/find';
|
||||
import type { Presence } from '../../people/presence';
|
||||
import type { ActCtx } from '../../people/ctx';
|
||||
import { actButton, pause, runAct } from '../../flows/person-acts';
|
||||
import { showSetup } from '../../flows/setup';
|
||||
import { openInvite } from '../../flows/invite';
|
||||
import { addDevice } from '../../flows/add-device';
|
||||
|
||||
const DAY = 86400;
|
||||
const H = 3600;
|
||||
const MAX_TILES = 3;
|
||||
|
||||
/** What a card is drawn from. */
|
||||
export interface CardData {
|
||||
p: Person;
|
||||
parts: CardParts;
|
||||
/** Their presence from the log; null while it is read. */
|
||||
pres: Presence | null;
|
||||
place: GeoPoint | null;
|
||||
match: Match | null;
|
||||
words: string[];
|
||||
/** The card's width (px): how many tiles leave the name its room. */
|
||||
width: number;
|
||||
}
|
||||
|
||||
/** What the cards read of the page. */
|
||||
export interface CardsCtx {
|
||||
st(): Status;
|
||||
now(): number;
|
||||
write: boolean;
|
||||
acts: ActCtx;
|
||||
}
|
||||
|
||||
/** A card's live speed: its devices online, where the number and the line go. */
|
||||
export interface Live {
|
||||
ids: string[];
|
||||
speed: HTMLElement;
|
||||
line: LiveLine;
|
||||
}
|
||||
|
||||
/** `text` with the searched word lit. */
|
||||
function lit(text: string, ws: string[]): Kid[] {
|
||||
const at = litAt(text, ws);
|
||||
return at ? [text.slice(0, at[0]), h('mark', { class: 'kt-hl' }, text.slice(at[0], at[0] + at[1])), text.slice(at[0] + at[1])] : [text];
|
||||
}
|
||||
|
||||
/** What a found value is, after it. */
|
||||
const whatLabel = (w: Match['what']): string =>
|
||||
({ name: _('device'), address: _('address in the tunnel'), hostname: _('name in the network'), ip: _('client IP') })[w];
|
||||
|
||||
/** What the search found them by: the device and the value (never cut: the device's name gives way), a link to it. */
|
||||
function foundLine(m: Match | null, ws: string[]): HTMLElement | null {
|
||||
if (!m) return null;
|
||||
return h(
|
||||
'a',
|
||||
{
|
||||
class: 'pp-found',
|
||||
href: deviceUrl(m.device.id),
|
||||
title: `${fmt(_('Open the device %s'), m.device.name)} · ${m.value} · ${whatLabel(m.what)}`,
|
||||
},
|
||||
ic('search'),
|
||||
...(m.what === 'name'
|
||||
? [h('span', {}, ...lit(m.device.name, ws))]
|
||||
: [h('span', { class: 'mono pp-found-v' }, ...lit(m.value, ws)), h('span', {}, m.device.name)]),
|
||||
h('span', { class: 'pp-found-w' }, whatLabel(m.what)),
|
||||
);
|
||||
}
|
||||
|
||||
/** «06:59» today, else «Tue 21:10» (router time). */
|
||||
function when(ts: number, now: number, tz?: number): string {
|
||||
const day = routerDay(ts, tz);
|
||||
if (day === routerDay(now, tz)) return routerTime(ts, tz);
|
||||
const wd = new Date(Date.parse(`${day}T12:00:00Z`)).toLocaleDateString(locale(), { weekday: 'short', timeZone: 'UTC' });
|
||||
return `${wd} ${routerTime(ts, tz)}`;
|
||||
}
|
||||
|
||||
/** How long, short: «12 min», «3 h», «10 days». */
|
||||
function howLong(sec: number): string {
|
||||
// one unit, short: the line stands beside the speed in half a card and must not wrap
|
||||
if (sec >= DAY) return fmt(_('%sd'), Math.floor(sec / DAY));
|
||||
if (sec >= H) return fmt(_('%sh'), Math.floor(sec / H));
|
||||
return fmt(_('%sm'), Math.max(1, Math.floor(sec / 60)));
|
||||
}
|
||||
|
||||
/** A weekday's short name in the router's time. */
|
||||
const weekday = (ts: number, tz?: number): string =>
|
||||
new Date(Date.parse(`${routerDay(ts, tz)}T12:00:00Z`)).toLocaleDateString(locale(), { weekday: 'short', timeZone: 'UTC' });
|
||||
|
||||
/** The devices with a fault or a configuration to fetch first, then the rest: «+N» never hides a warn tile. */
|
||||
function tileOrder(p: Person, pres: Presence | null): Device[] {
|
||||
const list = pres
|
||||
? pres.devices.map((x) => x.d)
|
||||
: [...p.devices].sort((a, b) => Number(b.online) - Number(a.online) || b.handshake - a.handshake);
|
||||
const warn = (d: Device) => !d.disabled && (!!d.link || (d.config_stale && !!d.handshake));
|
||||
return [...list.filter(warn), ...list.filter((d) => !warn(d))];
|
||||
}
|
||||
|
||||
/** The tiles that leave the name about 96 px of a card `width` wide (a write login has ⋯ too), at most three. */
|
||||
function tileCount(name: string, width: number, write: boolean): number {
|
||||
const nameW = Math.min(112, 16 + name.length * 8.6);
|
||||
return Math.max(1, Math.min(MAX_TILES, Math.floor((width - 88 - (write ? 44 : 0) - nameW - 26) / 29)));
|
||||
}
|
||||
|
||||
function tiles(c: CardsCtx, d: CardData): HTMLElement {
|
||||
const { p } = d;
|
||||
const list = tileOrder(p, d.pres);
|
||||
const n = tileCount(p.name, d.width, c.write);
|
||||
const shown = list.slice(0, list.length > n ? n : list.length);
|
||||
const rest = list.slice(shown.length);
|
||||
const st = c.st();
|
||||
const words = (x: Device) => `${x.name} · ${deviceLine(x, p, { now: c.now(), today: routerDay(c.now(), st.tz), tz: st.tz }).text}`;
|
||||
const box = h('span', { class: 'pp-tiles' });
|
||||
for (const x of shown) {
|
||||
const warn = !x.disabled && (!!x.link || (x.config_stale && !!x.handshake));
|
||||
const t = h(
|
||||
'a',
|
||||
{
|
||||
class: `pp-tile${x.online ? ' on' : ''}${x.disabled ? ' off' : ''}${warn ? ' warn' : ''}`,
|
||||
href: deviceUrl(x.id),
|
||||
'aria-label': words(x),
|
||||
},
|
||||
ic(x.kind),
|
||||
);
|
||||
tip(t, () => words(x));
|
||||
box.append(t);
|
||||
}
|
||||
if (rest.length) {
|
||||
const more = h(
|
||||
'button',
|
||||
{ type: 'button', class: 'pp-tile more num', 'aria-label': rest.map((x) => x.name).join(', ') },
|
||||
`+${rest.length}`,
|
||||
);
|
||||
tip(more, () => `${rest.map((x) => x.name).join(', ')} · ${fmt(_('%s online'), rest.filter((x) => x.online).length)}`);
|
||||
box.append(more);
|
||||
}
|
||||
return box;
|
||||
}
|
||||
|
||||
/** ⋯: open, the set-up of a device that waits for it, their link, a device, pause or resume. */
|
||||
function menu(c: CardsCtx, p: Person, from: HTMLElement) {
|
||||
const st = c.st();
|
||||
const srv = st.servers.find((s) => s.id === p.server);
|
||||
const reload = () => void c.acts.reload();
|
||||
const mid: MenuItem[] = p.devices
|
||||
.filter((x) => x.config_stale && x.handshake && !x.disabled)
|
||||
.slice(0, 2)
|
||||
.map((x) => ({
|
||||
label: fmt(_('Show set-up · %s'), x.name),
|
||||
icon: 'qr',
|
||||
run: () => void showSetup({ person: p, device: x, now: c.now, done: reload }).then(reload),
|
||||
}));
|
||||
if (p.has_link)
|
||||
mid.push({
|
||||
label: p.devices.length ? _('Link') : _('Invite'),
|
||||
icon: 'link',
|
||||
run: () => void openInvite({ person: p, server: srv?.name ?? '', changed: reload }),
|
||||
});
|
||||
if (srv)
|
||||
mid.push({
|
||||
label: _('Add device'),
|
||||
icon: 'plus',
|
||||
run: () => addDevice({ person: p, server: srv, now: c.now, added: reload, people: st.people, servers: st.servers }),
|
||||
});
|
||||
openMenu(
|
||||
from,
|
||||
[
|
||||
{ label: _('Open'), icon: 'open', run: () => visit(personUrl(p.id)) },
|
||||
...(mid.length ? [null, ...mid] : []),
|
||||
null,
|
||||
p.paused
|
||||
? { label: _('Resume'), icon: 'play', run: () => void pause(c.acts, p, false) }
|
||||
: { label: _('Pause'), icon: 'pause', tone: 'warn', run: () => void pause(c.acts, p, true) },
|
||||
],
|
||||
p.name,
|
||||
);
|
||||
}
|
||||
|
||||
/** Presence: since when (or how long not) and from where, the week's hours under it, the speed while online. */
|
||||
function presenceBlock(c: CardsCtx, d: CardData, lives: Live[]): HTMLElement {
|
||||
const { p, pres, parts } = d;
|
||||
const now = c.now();
|
||||
const tz = c.st().tz;
|
||||
const city = d.place ? d.place.city || d.place.country || '' : '';
|
||||
let speed: HTMLElement | null = null;
|
||||
const on = parts.presence === 'online';
|
||||
if (on) {
|
||||
const n = h('b', { class: 'pp-spd num' });
|
||||
const line = liveLine(22);
|
||||
speed = h('span', { class: 'pp-speed' }, n, line.el);
|
||||
lives.push({ ids: p.devices.filter((x) => x.online).map((x) => x.id), speed: n, line });
|
||||
}
|
||||
const place = d.place ? [city, d.place.org].filter(Boolean).join(' · ') : '';
|
||||
// for how long, as «Offline for …» beside it says (the owner, 2026-11-11: «Online since Tue 07:01» took two
|
||||
// lines); since when exactly is the line's title
|
||||
const since = on && pres?.since ? fmt(_('Online since %s'), when(pres.since, now, tz)) : '';
|
||||
const value = on
|
||||
? h(
|
||||
'span',
|
||||
{ class: 'use-val pp-nowv ok-t', title: [since, place].filter(Boolean).join(' · ') || null },
|
||||
pres?.since ? fmt(_('Online for %s'), howLong(now - pres.since)) : _('Online'),
|
||||
)
|
||||
: h(
|
||||
'span',
|
||||
{ class: 'use-val pp-nowv pp-two', title: place || null },
|
||||
h('span', {}, fmt(_('Offline for %s'), howLong(now - p.last_seen))),
|
||||
city ? h('span', { class: 'pp-city' }, ` · ${city}`) : null,
|
||||
);
|
||||
const week = pres ? weekWords(pres.week) : ' ';
|
||||
return h('div', { class: 'dev-use pp-now' }, h('div', { class: 'use-txt' }, value, h('span', { class: 'use-lbl pp-sub' }, week)), speed);
|
||||
}
|
||||
|
||||
/** «64 hours in 7 days» (online, under «Online for»). */
|
||||
function weekWords(sec: number): string {
|
||||
if (sec >= H) return plural(Math.round(sec / H), '%s hour in 7 days', '%s hours in 7 days');
|
||||
return sec > 0 ? _('under an hour in 7 days') : _('not online in 7 days');
|
||||
}
|
||||
|
||||
/** Traffic: the week and the month beside the week's bars (a day read at a time); the limit's bar from 50 %. */
|
||||
function trafficBlock(c: CardsCtx, d: CardData): HTMLElement {
|
||||
const { p } = d;
|
||||
const now = c.now();
|
||||
const tz = c.st().tz;
|
||||
const week: Pair[] = Array.from({ length: 7 }, (_x, i) =>
|
||||
p.devices.reduce<Pair>((a, x) => [a[0] + (x.spark[i]?.[0] ?? 0), a[1] + (x.spark[i]?.[1] ?? 0)], [0, 0]),
|
||||
);
|
||||
const sum = week.reduce((n, x) => n + x[0] + x[1], 0);
|
||||
const lbl = h('span', { class: 'use-lbl' }, _('Last 7 days'));
|
||||
const val = h('span', { class: 'use-val num' }, bytes(sum));
|
||||
const chart = bars(week, 'bars-week', 34);
|
||||
readBars(chart, fmt(_('%s: traffic in the last 7 days'), p.name), (i) => {
|
||||
const day = i < 0 ? null : week[i];
|
||||
setText(lbl, !day ? _('Last 7 days') : i === week.length - 1 ? _('Today') : weekday(now - (week.length - 1 - i) * DAY, tz));
|
||||
setText(val, bytes(day ? day[0] + day[1] : sum));
|
||||
});
|
||||
// beside the week: what is used of the limit (their limit month, or all time) when it is said here, else the
|
||||
// last 30 days
|
||||
const of = d.parts.meter === 'of' ? fmt(_('of %s'), bytes(p.quota_limit)) : '';
|
||||
const month = of ? p.quota_used : p.month[0] + p.month[1];
|
||||
return h(
|
||||
'div',
|
||||
{ class: 'dev-use pp-use' },
|
||||
h(
|
||||
'div',
|
||||
{ class: 'pp-use-row' },
|
||||
h('div', { class: 'use-txt' }, lbl, val),
|
||||
h(
|
||||
'div',
|
||||
{ class: 'use-txt pp-month' },
|
||||
h('span', { class: 'use-lbl' }, of ? _('Of the limit') : _('30 days')),
|
||||
h(
|
||||
'span',
|
||||
{ class: 'use-val num', title: of ? `${bytes(month)} ${of}` : null },
|
||||
bytes(month),
|
||||
of ? h('span', { class: 'pp-of' }, ` ${of}`) : null,
|
||||
),
|
||||
),
|
||||
chart.el,
|
||||
),
|
||||
d.parts.meter === 'bar'
|
||||
? h(
|
||||
'div',
|
||||
{ class: 'pp-lim' },
|
||||
h(
|
||||
'span',
|
||||
{ class: 'pp-lim-t num' },
|
||||
h('b', {}, ofLimit(p.quota_used, p.quota_limit)),
|
||||
h('span', {}, p.quota_period === 'month' ? _('limit for the month') : _('limit for the whole term')),
|
||||
),
|
||||
meter(p.quota_limit ? p.quota_used / p.quota_limit : 0),
|
||||
)
|
||||
: null,
|
||||
);
|
||||
}
|
||||
|
||||
/** The card; its live speed, if any, is put in `lives`. */
|
||||
export function personCard(c: CardsCtx, d: CardData, lives: Live[]): HTMLElement {
|
||||
const { p, parts } = d;
|
||||
const stat = parts.line
|
||||
? h(
|
||||
'span',
|
||||
{ class: `dev-stat pp-line${parts.tone ? ` ${parts.tone}-t` : ''}`, id: `pp-st-${p.id}`, title: parts.title || parts.line },
|
||||
h('span', { class: 'pp-line-t' }, parts.line),
|
||||
parts.more.length ? h('span', { class: 'pp-more' }, ` · ${fmt(_('%s more', 'problems'), parts.more.length)}`) : null,
|
||||
)
|
||||
: null;
|
||||
const more = c.write
|
||||
? (h(
|
||||
'button',
|
||||
{ type: 'button', class: 'knob more', 'aria-label': fmt(_('%s: open, link, device, pause'), p.name), 'aria-haspopup': 'menu' },
|
||||
ic('more'),
|
||||
) as HTMLButtonElement)
|
||||
: null;
|
||||
more?.addEventListener('click', () => menu(c, p, more));
|
||||
let act: HTMLButtonElement | null = null;
|
||||
if (parts.action && c.write) {
|
||||
const a = parts.action;
|
||||
act = actButton(a, parts.quiet ? 'soft block pp-act' : 'tint block pp-act');
|
||||
const b = act;
|
||||
b.addEventListener('click', () => void once(b, () => runAct(a, p, c.acts)));
|
||||
}
|
||||
// the face's ring: blue while online; a decision's tone only in «Needs a decision» (a rollout is no one's alarm)
|
||||
const tone = p.online > 0 ? 'ok' : parts.group === 'need' ? parts.tone : '';
|
||||
return h(
|
||||
'article',
|
||||
{
|
||||
class: `dev as-link pp-card st-${parts.state} g-${parts.group}${p.state === 'paused' ? ' off' : ''}`,
|
||||
'data-id': p.id,
|
||||
},
|
||||
h(
|
||||
'div',
|
||||
{ class: `dev-top${stat || d.match ? '' : ' one'}` },
|
||||
h('span', { class: 'pp-face' }, face(p.name, tone), h('span', { class: 'pk-ck', 'aria-hidden': 'true' }, ic('check'))),
|
||||
h(
|
||||
'div',
|
||||
{ class: 'dev-id' },
|
||||
h(
|
||||
'a',
|
||||
{ class: 'dev-name dev-a', href: personUrl(p.id), title: p.name, 'aria-describedby': stat ? stat.id : null },
|
||||
...lit(p.name, d.words),
|
||||
),
|
||||
parts.tiles ? tiles(c, d) : null,
|
||||
stat,
|
||||
foundLine(d.match, d.words),
|
||||
),
|
||||
more,
|
||||
),
|
||||
parts.presence ? h('div', { class: 'pp-r' }, presenceBlock(c, d, lives)) : null,
|
||||
parts.traffic ? h('div', { class: 'pp-r' }, trafficBlock(c, d)) : null,
|
||||
act ? h('div', { class: 'pp-r foot' }, act) : null,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,412 @@
|
||||
// The People list as cards (card.ts): the notices over it (notices.ts), then from seven people the groups by the
|
||||
// cards' own matrix (people/card.ts: needs a decision, online, everyone else, paused), each in its order; fewer
|
||||
// people, or an order picked from the chip, are one stack. A grid of cards 264 px or wider, three across in LuCI's
|
||||
// column, one on a phone; in «Needs a decision» the cards of a row are one height and their buttons stand on one
|
||||
// line, elsewhere each card is its own height. A fresh answer draws the cards again only when something they say
|
||||
// changed, never from under someone picking them or holding the keyboard's focus in them; cards that stay glide
|
||||
// to their new places. The live speed of those online is the meter's, read once a second while one of their
|
||||
// speeds is on screen. Nothing found, or nobody yet: the empty state names the reason and the way out.
|
||||
|
||||
import { morphValues, same, valuesOf } from '../../ui/reshape';
|
||||
import type { LogEvent, Person } from '../../../shared/types';
|
||||
import { h } from '../../../portal/dom';
|
||||
import { SMOOTH, frozen, still, play } from '../../../portal/motion';
|
||||
import { appear, fadeAway, look, morphInto, morphText, setText } from '../../../portal/ui/morph';
|
||||
import { rateOf } from '../../../shared/format';
|
||||
import { fmt, num } from '../../../shared/i18n';
|
||||
import { glass } from '../../ui/glass';
|
||||
import { secHead } from '../../ui/page-head';
|
||||
import { emptyState } from '../../ui/empty';
|
||||
import { focusInside, type Poller } from '../../state/poller';
|
||||
import { LiveMeter } from '../../state/meter';
|
||||
import { pollMeter } from '../../state/meterpoll';
|
||||
import { routerDay } from '../../events/clock';
|
||||
import { byAttention, cardParts, GROUPS, groupTitle, type Group, type Ranked } from '../../people/card';
|
||||
import { byPerson, presence, type Presence } from '../../people/presence';
|
||||
import { lastPlace, onlineAbove, sortOf, sortPeople } from '../../people/roster';
|
||||
import type { Match } from '../../people/find';
|
||||
import type { ActCtx } from '../../people/ctx';
|
||||
import type { PeopleHost } from './host';
|
||||
import { personCard, type CardsCtx, type Live } from './card';
|
||||
import { paintNotices } from './notices';
|
||||
import { keepPlace, putChildren } from '../../../portal/ui/put';
|
||||
|
||||
/** From this many people the list stands in groups; fewer are one stack in the order of attention. */
|
||||
const GROUP_FROM = 7;
|
||||
|
||||
export interface CardsOpts {
|
||||
/** Someone is picking cards (pick.ts): they stay as they are. */
|
||||
picking(): boolean;
|
||||
/** Cards can be picked: each group's head offers «Select all». */
|
||||
pickable: boolean;
|
||||
reset(): void;
|
||||
add(): void;
|
||||
/** Narrow the list to the people a rollout waits on. */
|
||||
waiting(): void;
|
||||
acts: ActCtx;
|
||||
}
|
||||
|
||||
/** What the list shows now. */
|
||||
export interface CardsData {
|
||||
/** The people the filters and the search leave. */
|
||||
people: Person[];
|
||||
found: Map<string, Match | null>;
|
||||
words: string[];
|
||||
/** What was typed in the search. */
|
||||
query: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The list drawn again without a blink (DESIGN.md › Repaint choreography); over 40 cards, at once. A card that stays
|
||||
* changes in place (portal morphInto, deep: its words morph, a part that came blurs in, one that went fades, its
|
||||
* height glides) and glides to its new place, width and opacity (FLIP on SMOOTH, both axes, across groups too); a group's head changes
|
||||
* in place the same way; a new card blurs in (`in, s.9, b6`, SMOOTH / 60, to its own opacity); a card no longer there fades where it
|
||||
* stood (out, b4, 180 EASE_IN).
|
||||
*/
|
||||
function flip(box: HTMLElement, change: () => void) {
|
||||
const items = () => [...box.querySelectorAll<HTMLElement>('.pp-card[data-id]')];
|
||||
const heads = () => [...box.querySelectorAll<HTMLElement>('.grp[data-g] > :first-child')];
|
||||
const box0 = box.getBoundingClientRect();
|
||||
const before = new Map(items().map((r) => [r.dataset.id!, [r, r.getBoundingClientRect(), look(r)] as const]));
|
||||
const heads0 = new Map(heads().map((x) => [x.parentElement!.dataset.g!, x]));
|
||||
change();
|
||||
const after = items();
|
||||
if (frozen()) {
|
||||
// the page stands still: a card built again is put where it stood, and only its values that changed morph
|
||||
for (const r of after) {
|
||||
const old = before.get(r.dataset.id!)?.[0];
|
||||
if (old && old !== r) morphValues(valuesOf(old), r);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (still() || !before.size || after.length > 40) return;
|
||||
// in place first (each measured where it stands now), then the places
|
||||
const refill = (old: HTMLElement, el: HTMLElement) => {
|
||||
// a card that says the same: only its place moves (no walk over its pieces)
|
||||
// (its live speed and line left out: the meter fills the new one at once)
|
||||
const said = (e: HTMLElement) => {
|
||||
const c = e.cloneNode(true) as HTMLElement;
|
||||
c.querySelectorAll('.pp-speed').forEach((x) => x.remove());
|
||||
return c.innerHTML;
|
||||
};
|
||||
if (same(said(old), said(el))) return;
|
||||
const kids = [...el.childNodes];
|
||||
putChildren(el, Array.from(old.childNodes));
|
||||
morphInto(el, kids, { deep: true });
|
||||
};
|
||||
for (const x of heads()) {
|
||||
const old = heads0.get(x.parentElement!.dataset.g!);
|
||||
if (old && old.className === x.className && old.textContent !== x.textContent) refill(old, x);
|
||||
}
|
||||
for (const r of after) {
|
||||
const was = before.get(r.dataset.id!);
|
||||
if (was) refill(was[0], r);
|
||||
}
|
||||
for (const r of after) {
|
||||
const was = before.get(r.dataset.id!);
|
||||
if (!was) {
|
||||
play(
|
||||
r,
|
||||
[
|
||||
{ opacity: 0, transform: 'scale(.9)', filter: 'blur(6px)' },
|
||||
{ opacity: getComputedStyle(r).opacity, transform: 'none', filter: 'blur(0px)' },
|
||||
],
|
||||
{ duration: SMOOTH.duration, delay: 60, easing: SMOOTH.easing, fill: 'backwards' },
|
||||
);
|
||||
continue;
|
||||
}
|
||||
before.delete(r.dataset.id!);
|
||||
const now = r.getBoundingClientRect();
|
||||
const dx = was[1].left - now.left;
|
||||
const dy = was[1].top - now.top;
|
||||
const o = +getComputedStyle(r).opacity;
|
||||
// its width (a group of another width) and its own opacity (into Paused, 50%) go with it
|
||||
const dw = Math.abs(was[1].width - now.width) > 0.5;
|
||||
const fades = Math.abs(was[2].opacity - o) > 0.01;
|
||||
if (Math.abs(dx) < 1 && Math.abs(dy) < 1 && !dw && !fades) continue;
|
||||
play(
|
||||
r,
|
||||
[
|
||||
{ transform: `translate(${dx}px, ${dy}px)`, ...(dw && { width: `${was[1].width}px` }), ...(fades && { opacity: was[2].opacity }) },
|
||||
{ transform: 'none', ...(dw && { width: `${now.width}px` }), ...(fades && { opacity: o }) },
|
||||
],
|
||||
{ duration: SMOOTH.duration, easing: SMOOTH.easing },
|
||||
);
|
||||
}
|
||||
for (const [el, at, shows] of before.values()) fadeAway(el, at, box, box0, shows);
|
||||
}
|
||||
|
||||
export class Cards {
|
||||
/** The notices and the groups. */
|
||||
readonly el: HTMLElement;
|
||||
/** The groups and their cards: what pick.ts picks over. */
|
||||
readonly groups = h('div', { class: 'groups' });
|
||||
private notices = h('div', { class: 'pp-notices' });
|
||||
/** Everyone's last 8 days of the log (presence, when paused); null until read. */
|
||||
private events: LogEvent[] | null = null;
|
||||
private layout = '';
|
||||
private lives: Live[] = [];
|
||||
/** The devices whose speed shows already (its first words blur in; a repaint carries them). */
|
||||
private said = new Set<string>();
|
||||
private seen = new Set<Element>();
|
||||
private watch: IntersectionObserver;
|
||||
private meter = new LiveMeter();
|
||||
private poll: Poller<unknown>;
|
||||
private beat = 0;
|
||||
/**
|
||||
* The cards as they stand, by person: one is built again only when its person is another object (the
|
||||
* page keeps who did not change the same object) or what else it shows moved; the others keep their nodes,
|
||||
* with their live speed and line as they are.
|
||||
*/
|
||||
private kept = new Map<string, { p: Person; key: string; el: HTMLElement; lives: Live[] }>();
|
||||
|
||||
constructor(
|
||||
private host: PeopleHost,
|
||||
private o: CardsOpts,
|
||||
) {
|
||||
this.el = h('div', { class: 'pp-list' }, this.notices, this.groups);
|
||||
this.watch = new IntersectionObserver((es) => {
|
||||
for (const e of es) {
|
||||
if (e.isIntersecting) this.seen.add(e.target);
|
||||
else this.seen.delete(e.target);
|
||||
}
|
||||
});
|
||||
// the meter only while a speed is on screen and the list is in the page
|
||||
this.poll = pollMeter(
|
||||
this.meter,
|
||||
() => this.el.isConnected && this.lives.length > 0 && this.seen.size > 0,
|
||||
() => this.tick(),
|
||||
);
|
||||
}
|
||||
|
||||
/** Stop reading the meter (LuCI left the page). */
|
||||
stop() {
|
||||
this.poll.stop();
|
||||
this.watch.disconnect();
|
||||
}
|
||||
|
||||
/** The log the cards read (everyone's, the last 8 days, oldest first). */
|
||||
take(events: LogEvent[]) {
|
||||
this.events = events;
|
||||
}
|
||||
|
||||
/** Draw again whatever is there (the view came back from the map, the log came in). */
|
||||
forget() {
|
||||
this.layout = '';
|
||||
}
|
||||
|
||||
/** The router's day a person was paused, from the log ('' when it is older than what was read). */
|
||||
private pausedAt(): Map<string, string> {
|
||||
const m = new Map<string, string>();
|
||||
for (const e of this.events ?? []) if (e.type === 'paused' && e.person) m.set(e.person, routerDay(e.ts, this.host.st().tz));
|
||||
return m;
|
||||
}
|
||||
|
||||
paint(d: CardsData, quiet: boolean) {
|
||||
const host = this.host;
|
||||
const r = host.route();
|
||||
const st = host.st();
|
||||
const now = host.now();
|
||||
const t = { now, today: host.today() };
|
||||
const paused = this.pausedAt();
|
||||
const mine = this.events ? byPerson(this.events) : null;
|
||||
const press = new Map<string, Presence>();
|
||||
const ranked: Ranked[] = d.people.map((p) => {
|
||||
const srv = st.servers.find((s) => s.id === p.server);
|
||||
const place = lastPlace(p, st.geo);
|
||||
const parts = cardParts(p, srv, t, { pausedAt: paused.get(p.id), city: place?.city || place?.country || '' });
|
||||
if (mine && parts.presence) press.set(p.id, presence(p, srv, mine.get(p.id) ?? [], now, st.tz));
|
||||
return {
|
||||
p,
|
||||
parts,
|
||||
speed: p.rate?.[p.rate.length - 1]?.[2] ?? 0,
|
||||
week: p.devices.reduce((n, x) => n + x.spark.reduce((a, s) => a + s[0] + s[1], 0), 0),
|
||||
pausedAt: paused.get(p.id) ?? '',
|
||||
};
|
||||
});
|
||||
const s = sortOf(r.sort);
|
||||
const list = s ? sortPeople(d.people, s).map((p) => ranked.find((x) => x.p === p)!) : byAttention(ranked, t.today);
|
||||
const groups = GROUPS.map((g) => [g, list.filter((x) => x.parts.group === g)] as [Group, Ranked[]]).filter(([, xs]) => xs.length);
|
||||
const sections: [Group | 'all', Ranked[]][] = !s && list.length >= GROUP_FROM && groups.length > 1 ? groups : [['all', list]];
|
||||
const width = this.groups.clientWidth || this.el.clientWidth;
|
||||
/** What a person's card says that is not the person themself: where it stands in time, and what was searched. */
|
||||
const says = (x: Ranked) => [
|
||||
x.p.id,
|
||||
x.p.name,
|
||||
x.parts,
|
||||
x.p.online,
|
||||
x.p.month,
|
||||
x.p.quota_used,
|
||||
x.p.has_link,
|
||||
x.p.devices.map((v) => [
|
||||
v.id,
|
||||
v.name,
|
||||
v.kind,
|
||||
v.online,
|
||||
v.disabled,
|
||||
v.spark,
|
||||
v.link?.state,
|
||||
v.config_stale,
|
||||
Math.floor(v.handshake / 60),
|
||||
]),
|
||||
press.get(x.p.id)?.since,
|
||||
Math.round((press.get(x.p.id)?.week ?? -1) / 3600),
|
||||
lastPlace(x.p, st.geo)?.city,
|
||||
// «Offline for 3 h» moves on with the clock
|
||||
x.p.online ? 0 : Math.floor((now - x.p.last_seen) / 3600),
|
||||
];
|
||||
const key = JSON.stringify([
|
||||
sections.map(([g, xs]) => [g, xs.map(says)]),
|
||||
d.words,
|
||||
[...d.found].map(([id, m]) => [id, m?.device.id, m?.value]),
|
||||
Math.round(width / 40),
|
||||
st.people.length,
|
||||
st.servers.map((v) => [v.id, v.name, v.enabled]),
|
||||
]);
|
||||
paintNotices(this.notices, st, { write: host.write, acts: this.o.acts, waiting: () => this.o.waiting() });
|
||||
// nothing to say anew; or someone is picking cards or has the keyboard in them: they stay as they are
|
||||
if (key === this.layout || (quiet && (this.o.picking() || focusInside(this.groups)))) return;
|
||||
const first = !this.layout;
|
||||
this.layout = key;
|
||||
const c: CardsCtx = { st: host.st, now: host.now, write: host.write, acts: this.o.acts };
|
||||
const all = () =>
|
||||
this.o.pickable
|
||||
? h('button', { type: 'button', class: 'pill-link pk-all', tabindex: '-1' }, h('span', {}, _('Select all')))
|
||||
: undefined;
|
||||
// «Online» and the page's «N online» count the same people: those online who stand in another group are above
|
||||
const above = onlineAbove(
|
||||
list.map((x) => x.p),
|
||||
t,
|
||||
);
|
||||
const count = (g: Group, n: number) => (g === 'online' && above ? fmt(_('%s · %s more above'), num(n), num(above)) : num(n));
|
||||
const next = new Map<string, { p: Person; key: string; el: HTMLElement; lives: Live[] }>();
|
||||
const card = (x: Ranked, cw: number): HTMLElement => {
|
||||
const srv = st.servers.find((v) => v.id === x.p.server);
|
||||
const k = JSON.stringify([says(x), d.words, d.found.get(x.p.id)?.device.id, d.found.get(x.p.id)?.value, cw, srv?.name, srv?.enabled]);
|
||||
let it = this.kept.get(x.p.id);
|
||||
if (!it || it.p !== x.p || it.key !== k) {
|
||||
const lives: Live[] = [];
|
||||
const el = personCard(
|
||||
c,
|
||||
{
|
||||
p: x.p,
|
||||
parts: x.parts,
|
||||
pres: press.get(x.p.id) ?? null,
|
||||
place: lastPlace(x.p, st.geo),
|
||||
match: d.found.get(x.p.id) ?? null,
|
||||
words: d.words,
|
||||
width: cw,
|
||||
},
|
||||
lives,
|
||||
);
|
||||
it = { p: x.p, key: k, el, lives };
|
||||
}
|
||||
next.set(x.p.id, it);
|
||||
this.lives.push(...it.lives);
|
||||
return it.el;
|
||||
};
|
||||
const draw = () => {
|
||||
for (const l of this.lives) this.watch.unobserve(l.speed);
|
||||
this.lives = [];
|
||||
this.seen.clear();
|
||||
next.clear();
|
||||
if (!list.length) {
|
||||
this.kept = next;
|
||||
return void putChildren(this.groups, [this.empty(d.query)]);
|
||||
}
|
||||
putChildren(
|
||||
this.groups,
|
||||
sections.map(([g, xs]) => {
|
||||
// a list of one or two: the card that adds the next person stands in the grid
|
||||
const adds = g === 'all' && host.write && st.people.length <= 2 && xs.length === st.people.length;
|
||||
const n = xs.length + (adds ? 1 : 0);
|
||||
const cw = cardWidth(width, n);
|
||||
return h(
|
||||
'section',
|
||||
{ class: 'grp', 'data-g': g },
|
||||
g === 'all' ? (all() ? h('div', { class: 'pp-allhead' }, all()!) : null) : secHead(groupTitle(g), count(g, xs.length), all()),
|
||||
h('div', { class: `pp-grid in-${g} n${Math.min(n, 4)}` }, ...xs.map((x) => card(x, cw)), adds ? this.addCard() : null),
|
||||
);
|
||||
}),
|
||||
);
|
||||
this.kept = next;
|
||||
for (const l of this.lives) this.watch.observe(l.speed);
|
||||
// devices that went offline: their speed blurs in again when they are back
|
||||
const on = new Set(this.lives.map((l) => l.ids.join()));
|
||||
for (const k of this.said) if (!on.has(k)) this.said.delete(k);
|
||||
this.beat = 0;
|
||||
this.tick();
|
||||
};
|
||||
// (the cards that stay are moved into the next groups as those are built: the page keeps its place over that)
|
||||
if (!first) return flip(this.groups, () => keepPlace(this.groups, draw));
|
||||
draw();
|
||||
}
|
||||
|
||||
/** A new second of the meter: the lines slide each second, the words change every third (at once the first time). */
|
||||
private tick() {
|
||||
const at = Date.now();
|
||||
const words = this.beat % 3 === 0;
|
||||
for (const l of this.lives) {
|
||||
const s = this.meter.speed(null, at, l.ids);
|
||||
if (s.pts.length > 1) l.line.push(s.pts.map((p) => p[2]));
|
||||
if (!s.pts.length) continue;
|
||||
const text = `↓ ${rateOf(s.tx)}`;
|
||||
if (!l.speed.textContent) {
|
||||
setText(l.speed, text);
|
||||
// the first time it is said for these devices it blurs in with its line (a repaint that keeps them on
|
||||
// carries it as it stood)
|
||||
const key = l.ids.join();
|
||||
if (!this.said.has(key)) appear(l.speed.parentElement ?? l.speed);
|
||||
this.said.add(key);
|
||||
} else if (words && text !== l.speed.textContent) morphText(l.speed, text);
|
||||
}
|
||||
this.beat++;
|
||||
}
|
||||
|
||||
private addCard(): HTMLElement {
|
||||
const b = h('button', { type: 'button', class: 'dev add pp-add' }, glass('plus', 'grey'), h('span', {}, _('Add person')));
|
||||
b.addEventListener('click', () => this.o.add());
|
||||
return b;
|
||||
}
|
||||
|
||||
/** Why the list is empty, and the one way out of it. */
|
||||
private empty(query: string): HTMLElement {
|
||||
const host = this.host;
|
||||
const r = host.route();
|
||||
const any = host.st().people.length > 0;
|
||||
const q = query.trim();
|
||||
const why = q
|
||||
? fmt(_('Nobody matches “%s”.'), q)
|
||||
: r.need
|
||||
? _('Nobody waits for a new configuration.')
|
||||
: r.group === 'need'
|
||||
? _('Nobody waits for a decision.')
|
||||
: r.group === 'paused'
|
||||
? _('Nobody is paused.')
|
||||
: r.group === 'online'
|
||||
? _('Nobody is online now.')
|
||||
: r.server && any
|
||||
? _('Nobody on this server yet.')
|
||||
: _('Add someone and send them their personal link: they add their devices themselves.');
|
||||
const b = h(
|
||||
'button',
|
||||
{ type: 'button', class: `btn ${any ? 'soft' : 'accent'} sm` },
|
||||
h('span', {}, any ? _('Reset the filters') : _('Add person')),
|
||||
);
|
||||
b.addEventListener('click', () => (any ? this.o.reset() : this.o.add()));
|
||||
return emptyState({
|
||||
icon: 'people',
|
||||
title: any ? _('Nothing found') : _('No people yet'),
|
||||
text: why,
|
||||
action: any || host.write ? b : null,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** A card's width in a grid of `n` in a list `w` wide (people.css .pp-grid: 264 px or more, 10 apart; a phone: one). */
|
||||
function cardWidth(w: number, n: number): number {
|
||||
const box = Math.min(w, n === 1 ? 440 : n === 2 ? 890 : w);
|
||||
if (w < 560) return box;
|
||||
const cols = Math.max(1, Math.min(n, Math.floor((box + 10) / 274)));
|
||||
return (box - 10 * (cols - 1)) / cols;
|
||||
}
|
||||
@@ -0,0 +1,532 @@
|
||||
// A device as a panel (people?device=; it takes its person's panel's place, the way back returns to them). First
|
||||
// what works and what does not, exactly as before: the Connection card (the portal's way between the device and the
|
||||
// router, the link timeline for 24 h / 7 days / 30 days, the brief diagnosis with its fix: link.ts,
|
||||
// widgets/timeline.ts) and the Traffic tiles (traffic.ts, with the live speed). Then its set-up as a card
|
||||
// (widgets/config-card.ts), its places as the close-up's rows with strips (the close-up itself one press away) and
|
||||
// its latest events. ?sheet=setup opens its set-up on arrival (a device just added elsewhere), ?sheet=places its
|
||||
// places' close-up.
|
||||
//
|
||||
// Live: the status comes from the page; its and its person's events (after the newest it has) and the service log
|
||||
// are read on opening, with every status the page takes and after a change made here; the meter once a second
|
||||
// only while it is online and the panel is in the page. A part holding the focus is left alone by a background
|
||||
// repaint.
|
||||
|
||||
import { grown } from '../../../../portal/ui/grown';
|
||||
import { refill } from '../../../ui/reshape';
|
||||
import type { ClientConfig, LogEvent } from '../../../../shared/types';
|
||||
import { api, type DeviceLinkPatch, type ServiceLogEntry } from '../../../api';
|
||||
import { h } from '../../../../portal/dom';
|
||||
import { openMenu } from '../../../../portal/ui/menu';
|
||||
import { go, openSheet, sheetOpen } from '../../../../portal/ui/sheet';
|
||||
import { DEVICE_NAME_MAX, kindLabel, todayOf } from '../../../../shared/format';
|
||||
import { fmt, locale } from '../../../../shared/i18n';
|
||||
import { deviceNameHelp } from '../../../netcheck';
|
||||
import { glass } from '../../../ui/glass';
|
||||
import { ic } from '../../../ui/icons';
|
||||
import { blockHead, fact, knob, pageHead } from '../../../ui/page-head';
|
||||
import { pageBar } from '../../../ui/subpage';
|
||||
import { copyText } from '../../../ui/files';
|
||||
import { errorText, notify } from '../../../ui/toast';
|
||||
import { focusInside, type Poller } from '../../../state/poller';
|
||||
import { LiveMeter } from '../../../state/meter';
|
||||
import { pollMeter } from '../../../state/meterpoll';
|
||||
import { briefDiagnosis, deviceLine, diagnose, otherNetAdvice, type Fix } from '../../../people/diagnosis';
|
||||
import { endpointHost } from '../../../people/find';
|
||||
import { listOf } from '../../../people/route';
|
||||
import type { DeviceCtx } from '../../../people/ctx';
|
||||
import { linkTimeline, type TimelineInput } from '../../../events/timeline';
|
||||
import { timelineWidget, type TimelineWidget } from '../../../widgets/timeline';
|
||||
import { configCard, setupHead } from '../../../widgets/config-card';
|
||||
import { devicePlaces, type DevicePlaces } from '../../../widgets/place-rows';
|
||||
import { feedShort, logLink } from '../../../widgets/feed';
|
||||
import { routerDay } from '../../../events/clock';
|
||||
import { say } from '../../../shell/toast';
|
||||
import { peopleAt, settingsUrl } from '../../../shell/routes';
|
||||
import { visit } from '../../../shell/visit';
|
||||
import { askView } from '../../../flows/ask';
|
||||
import { removeDevice, resetDeviceTraffic, toggleDevice, type DeviceActCtx } from '../../../flows/device-acts';
|
||||
import { setupView, showSetup, type SetupCtx } from '../../../flows/setup';
|
||||
import { addDevice } from '../../../flows/add-device';
|
||||
import { newKeys } from '../../../flows/new-keys';
|
||||
import { textSheet } from '../../../flows/text-sheet';
|
||||
import { openCloseUp } from '../../../flows/places-closeup';
|
||||
import type { PeopleHost } from '../host';
|
||||
import { diagnosisEl, wayEl } from './link';
|
||||
import { trafficCard, type TrafficCard } from './traffic';
|
||||
import { putChildren } from '../../../../portal/ui/put';
|
||||
|
||||
const LIMIT = 5000;
|
||||
/** For this long after it is made a panel settles: what lands meanwhile is not a repaint, the panel is still coming in (ms). */
|
||||
const SETTLES = 2500;
|
||||
const DAYS30 = 30 * 86400;
|
||||
|
||||
export class DevicePanel {
|
||||
readonly kind = 'device';
|
||||
el = h('article', { class: 'kt-panel pp-device' });
|
||||
private c!: DeviceCtx;
|
||||
private events: LogEvent[] = [];
|
||||
private system: ServiceLogEntry[] = [];
|
||||
private cfg: ClientConfig | null = null;
|
||||
private gone = false;
|
||||
/** Reading again after a change made here: the status that comes meanwhile is drawn with the events, once. */
|
||||
private batching = false;
|
||||
private okay: boolean;
|
||||
private headBox = h('div', { class: 'kt-phead' });
|
||||
private linkBox = h('div', { class: 'card link' });
|
||||
private trafficBox = h('div');
|
||||
private confBox = h('section', { class: 'kt-b b-conf' });
|
||||
private placesBox = h('section', { class: 'kt-b b-places' });
|
||||
private logBox = h('section', { class: 'kt-b b-log' });
|
||||
private wayKey = '';
|
||||
private tl: TimelineWidget | null = null;
|
||||
private traffic: TrafficCard | null = null;
|
||||
private places: DevicePlaces | null = null;
|
||||
/**
|
||||
* Its log, its configuration and its places' rows have been read: nothing more lands in it by itself. A dialog
|
||||
* waits for this to open whole (pages/server/device-dialog.ts).
|
||||
*/
|
||||
ready: Promise<void> = Promise.resolve();
|
||||
/** When the panel was made: it settles for a while after (paint). */
|
||||
private born = performance.now();
|
||||
private meter = new LiveMeter();
|
||||
private poll: Poller<unknown>;
|
||||
private open = new Set<string>();
|
||||
|
||||
constructor(
|
||||
readonly id: string,
|
||||
private host: PeopleHost,
|
||||
close: () => void,
|
||||
) {
|
||||
const ok = (this.okay = this.take());
|
||||
const p = this.c?.p;
|
||||
this.el.append(
|
||||
pageBar({ back: p?.name ?? _('People'), to: peopleAt({ ...listOf(host.route()), id: p?.id }), close }),
|
||||
this.headBox,
|
||||
h(
|
||||
'div',
|
||||
{ class: 'kt-blocks' },
|
||||
h('section', { class: 'kt-b b-link' }, blockHead(_('Connection', 'section')), this.linkBox),
|
||||
h('section', { class: 'kt-b b-traffic' }, blockHead(_('Traffic')), this.trafficBox),
|
||||
this.confBox,
|
||||
this.placesBox,
|
||||
this.logBox,
|
||||
),
|
||||
);
|
||||
if (ok) {
|
||||
this.paint(false);
|
||||
// read once, and the places' rows in: it can be shown whole then (a failure of either is no reason to wait on)
|
||||
this.ready = Promise.allSettled([this.load(false), this.places?.ready]).then(() => undefined);
|
||||
}
|
||||
this.poll = pollMeter(
|
||||
this.meter,
|
||||
() => ok && this.el.isConnected && !this.gone && this.c.d.online,
|
||||
() => this.paintSpeed(),
|
||||
);
|
||||
}
|
||||
|
||||
/** What the address asks to open on arrival: its set-up, its places' close-up. */
|
||||
arrive(_s?: string, sheet?: string) {
|
||||
if (!this.okay) return;
|
||||
if (sheet === 'setup' && this.c.write) void this.showSetup();
|
||||
else if (sheet === 'places') this.openPlaces();
|
||||
}
|
||||
|
||||
/** The person it belongs to (the list marks them). */
|
||||
get person(): string | undefined {
|
||||
return this.c?.p.id;
|
||||
}
|
||||
|
||||
destroy() {
|
||||
this.gone = true;
|
||||
this.poll.stop();
|
||||
}
|
||||
|
||||
private take(): boolean {
|
||||
const st = this.host.st();
|
||||
const p = st.people.find((x) => x.devices.some((d) => d.id === this.id));
|
||||
const d = p?.devices.find((x) => x.id === this.id);
|
||||
if (!p || !d) return false;
|
||||
this.c = {
|
||||
st,
|
||||
p,
|
||||
d,
|
||||
srv: st.servers.find((s) => s.id === p.server),
|
||||
events: this.events,
|
||||
system: this.system,
|
||||
cfg: this.cfg,
|
||||
write: this.host.write,
|
||||
now: this.host.now,
|
||||
refresh: () => this.reload(),
|
||||
};
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Its and its person's events (after the newest it has when `live`), the service log and, once, its configuration. */
|
||||
private async load(live: boolean) {
|
||||
const st = this.host.st();
|
||||
const p = this.c.p;
|
||||
const newest = this.events.length ? this.events[this.events.length - 1].ts : 0;
|
||||
const since = live && newest ? newest - 1 : st.now - DAYS30 - 1;
|
||||
const [a, b, sys, cfg] = await Promise.all([
|
||||
api.events(LIMIT, undefined, since, this.id).then(
|
||||
(r) => r.events,
|
||||
() => [] as LogEvent[],
|
||||
),
|
||||
api.events(LIMIT, p.id, since).then(
|
||||
(r) => r.events,
|
||||
() => [] as LogEvent[],
|
||||
),
|
||||
api.serviceLog().then(
|
||||
(s) => s.log,
|
||||
() => this.system,
|
||||
),
|
||||
this.host.write && !this.cfg ? api.deviceConfig(this.id).catch(() => null) : Promise.resolve(this.cfg),
|
||||
]);
|
||||
if (this.gone) return;
|
||||
const fresh = merge(a, b);
|
||||
this.events = (live && newest ? merge(this.events, fresh) : fresh).filter((e) => e.ts >= st.now - DAYS30);
|
||||
this.system = sys;
|
||||
this.cfg = cfg;
|
||||
if (!this.take()) return;
|
||||
this.paint(live);
|
||||
}
|
||||
|
||||
/** Read everything again now (after a change made here). */
|
||||
private async reload() {
|
||||
// one repaint for the change: the page's new status is taken in, drawn once its events are read too
|
||||
this.batching = true;
|
||||
try {
|
||||
await this.host.reload();
|
||||
} finally {
|
||||
this.batching = false;
|
||||
}
|
||||
if (this.okay) await this.load(false);
|
||||
}
|
||||
|
||||
/** A new status from the page; `quiet`: a periodic one (drawn once, with its new events). */
|
||||
fresh(quiet: boolean) {
|
||||
if (!this.okay || !this.take() || this.batching) return;
|
||||
if (quiet) void this.load(true);
|
||||
else this.paint(false);
|
||||
}
|
||||
|
||||
private clock() {
|
||||
const c = this.c;
|
||||
return { now: c.now(), today: todayOf(c.st.series) || routerDay(c.now(), c.st.tz), tz: c.st.tz };
|
||||
}
|
||||
|
||||
/**
|
||||
* Draw the panel. While it settles (its first seconds: its log, its configuration and the service log land one
|
||||
* after another, a moment after it stood) a block that is another height for what landed goes there from the
|
||||
* one it has (ui/reshape.ts grown), and a dialog follows: not a jump (the owner, 2026-11-12: «модалка все ещё
|
||||
* снапает»: it grew 148 px in one frame while still opening), no fade of blocks that stood there already, and
|
||||
* each landing takes the block on from where the last one left it. After that a reading is drawn in place.
|
||||
*/
|
||||
private paint(quiet: boolean) {
|
||||
if (performance.now() - this.born > SETTLES) return this.draw(quiet);
|
||||
const blocks = [this.confBox, this.logBox, this.placesBox];
|
||||
const was = blocks.map((b) => b.offsetHeight);
|
||||
this.draw(quiet);
|
||||
blocks.forEach((b, i) => grown(b, was[i]));
|
||||
}
|
||||
|
||||
private draw(quiet: boolean) {
|
||||
const c = this.c;
|
||||
const steps = diagnose(c.d, c.p, c.srv, this.clock());
|
||||
const brief = briefDiagnosis(steps);
|
||||
const fixShows = brief.some((s) => s.fix?.includes('show'));
|
||||
if (!quiet || !focusInside(this.headBox)) refill(this.headBox, [this.head(fixShows)]);
|
||||
this.el.setAttribute('aria-label', `${c.d.name} · ${c.p.name}`);
|
||||
this.paintLink(steps, brief, quiet);
|
||||
// the card stays across repaints: its numbers morph when they change
|
||||
if (this.traffic) this.traffic.set(c.d);
|
||||
else {
|
||||
this.traffic = trafficCard(c.d, `t:${c.d.id}`, c.d.name);
|
||||
putChildren(this.trafficBox, [this.traffic.el]);
|
||||
}
|
||||
this.paintSpeed();
|
||||
if (!quiet || !focusInside(this.confBox))
|
||||
refill(this.confBox, [
|
||||
setupHead(c),
|
||||
h('div', { class: 'card kt-confcard' }, configCard(c, { change: (w, v, p) => this.change(w, v, p) })),
|
||||
]);
|
||||
if (c.st.geo.enabled) {
|
||||
if (!this.places) {
|
||||
this.places = devicePlaces(c.st, c.p, c.d, this.events.length ? this.events.filter((e) => e.device === c.d.id) : null);
|
||||
putChildren(this.placesBox, [
|
||||
blockHead(_('Places'), undefined, this.places.range),
|
||||
h('div', { class: 'card pp-plcard' }, this.places.el),
|
||||
]);
|
||||
} else
|
||||
this.places.update(
|
||||
c.st,
|
||||
c.p,
|
||||
c.d,
|
||||
this.events.filter((e) => e.device === c.d.id),
|
||||
);
|
||||
}
|
||||
refill(this.logBox, [
|
||||
blockHead(_('Latest'), undefined, logLink({ device: c.d.id })),
|
||||
feedShort(c.st, c.events, { own: c.p.id, device: c.d.id, open: this.open, toggled: () => this.paint(false) }),
|
||||
]);
|
||||
}
|
||||
|
||||
/** pages/device/index.ts head(), in the panel. */
|
||||
private head(fixShows: boolean): HTMLElement {
|
||||
const { d, p } = this.c;
|
||||
const line = deviceLine(d, p, this.clock());
|
||||
const ip = endpointHost(d.endpoint);
|
||||
const added = new Date(d.created * 1000).toLocaleDateString(locale(), { day: 'numeric', month: 'short' });
|
||||
const acts: HTMLElement[] = [];
|
||||
if (this.c.write) {
|
||||
if (!fixShows)
|
||||
acts.push(
|
||||
h(
|
||||
'button',
|
||||
{ type: 'button', class: 'btn soft', onclick: () => void this.showSetup() },
|
||||
ic('qr'),
|
||||
h('span', {}, _('Show set-up')),
|
||||
),
|
||||
);
|
||||
const more = knob('more', _('Set-up, rename, turn off, reset traffic, new keys, remove'));
|
||||
more.setAttribute('aria-haspopup', 'menu');
|
||||
more.addEventListener('click', () => this.menu(more));
|
||||
acts.push(more);
|
||||
}
|
||||
const head = pageHead({ icon: glass(d.kind, d.online ? 'blue' : 'grey'), title: d.name, acts });
|
||||
const facts = [
|
||||
fact(h('span', { class: `ph-state ${line.tone ? `${line.tone}-t` : ''}`, title: line.why ?? null }, line.text)),
|
||||
fact(kindLabel(d.kind)),
|
||||
ip
|
||||
? fact(h('span', { class: 'mono' }, ip.length > 24 ? `${ip.slice(0, 10)}…${ip.slice(-10)}` : ip), {
|
||||
title: fmt(_('Client IP: where its last connection came from · %s'), ip),
|
||||
})
|
||||
: null,
|
||||
fact(d.created_by === 'portal' ? fmt(_('added on the portal %s'), added) : fmt(_('added by you %s'), added)),
|
||||
this.c.write ? null : fact([ic('eye'), _('View only')]),
|
||||
];
|
||||
head.querySelector('.ph-sub')?.replaceChildren(...facts.filter((f): f is HTMLElement => !!f));
|
||||
return head;
|
||||
}
|
||||
|
||||
private paintLink(steps: ReturnType<typeof diagnose>, brief: ReturnType<typeof briefDiagnosis>, quiet: boolean) {
|
||||
if (quiet && focusInside(this.linkBox)) return;
|
||||
const c = this.c;
|
||||
const input: TimelineInput = { device: c.d, person: c.p, server: c.srv, events: c.events, system: c.system, now: c.now(), tz: c.st.tz };
|
||||
const t = linkTimeline(input);
|
||||
const way = wayEl(c, steps);
|
||||
const key = way.outerHTML;
|
||||
const diag = brief.length ? diagnosisEl(c, brief, (f, from) => void this.fix(f, from)) : null;
|
||||
if (!this.tl) {
|
||||
this.tl = timelineWidget(input, t);
|
||||
putChildren(this.linkBox, [way, this.tl.el, ...(diag ? [diag] : [])]);
|
||||
} else {
|
||||
this.tl.update(input, t);
|
||||
// a new way, the diagnosis coming, going or changing: they change in place, the timeline kept as it is, and
|
||||
// the card glides to its new height (ui/reshape.ts)
|
||||
const old = this.linkBox.querySelector(':scope > .dg');
|
||||
if (key !== this.wayKey || old?.outerHTML !== diag?.outerHTML) refill(this.linkBox, [way, this.tl.el, ...(diag ? [diag] : [])]);
|
||||
}
|
||||
this.wayKey = key;
|
||||
}
|
||||
|
||||
private paintSpeed() {
|
||||
const c = this.c;
|
||||
if (!this.traffic) return;
|
||||
if (!c.d.online || !c.srv) return this.traffic.speed(null);
|
||||
const s = this.meter.speed(c.srv.id, Date.now(), [c.d.id]);
|
||||
this.traffic.speed(s.pts.length ? [s.rx, s.tx] : 'wait');
|
||||
}
|
||||
|
||||
/* ---------- actions (pages/device/index.ts) ---------- */
|
||||
|
||||
private setupCtx(): SetupCtx {
|
||||
return {
|
||||
person: this.c.p,
|
||||
device: this.c.d,
|
||||
now: this.c.now,
|
||||
fresh: (st) => this.host.take(st),
|
||||
done: () => void this.reload(),
|
||||
};
|
||||
}
|
||||
|
||||
async showSetup() {
|
||||
await showSetup(this.setupCtx());
|
||||
void this.reload();
|
||||
}
|
||||
|
||||
openPlaces() {
|
||||
if (this.c.st.geo.enabled) openCloseUp(this.id, this.c.st);
|
||||
}
|
||||
|
||||
private change(what: string, value: string, patch: DeviceLinkPatch): Promise<boolean> {
|
||||
const d = this.c.d;
|
||||
const save = () => api.deviceUpdate(this.id, undefined, undefined, patch);
|
||||
if (!d.handshake || d.disabled)
|
||||
return save().then(
|
||||
() => {
|
||||
say(fmt(_('%s: %s'), what, value));
|
||||
void this.reload();
|
||||
return true;
|
||||
},
|
||||
(e) => {
|
||||
notify(errorText(e), 'error', 10000);
|
||||
return false;
|
||||
},
|
||||
);
|
||||
return new Promise((res) => {
|
||||
let took = false;
|
||||
openSheet(() =>
|
||||
askView({
|
||||
icon: 'refresh',
|
||||
tone: 'orange',
|
||||
title: fmt(_('%s · %s: %s?'), d.name, what, value),
|
||||
text: [
|
||||
_('The device’s configuration changes. Until the new one is fetched on it, it works the old way. The new one opens next.'),
|
||||
],
|
||||
action: _('Change'),
|
||||
cls: 'warn',
|
||||
run: async () => {
|
||||
await save();
|
||||
took = true;
|
||||
res(true);
|
||||
const cfg = await api.deviceConfig(this.id);
|
||||
void this.reload();
|
||||
go(() => setupView(this.setupCtx(), cfg, 'top'));
|
||||
},
|
||||
}),
|
||||
);
|
||||
const watch = window.setInterval(() => {
|
||||
if (took) return clearInterval(watch);
|
||||
if (!sheetOpen()) {
|
||||
clearInterval(watch);
|
||||
res(false);
|
||||
}
|
||||
}, 300);
|
||||
});
|
||||
}
|
||||
|
||||
private async fix(f: Fix, from: HTMLButtonElement) {
|
||||
const { d, p } = this.c;
|
||||
switch (f) {
|
||||
case 'show':
|
||||
return this.showSetup();
|
||||
case 'resume':
|
||||
try {
|
||||
from.disabled = true;
|
||||
await api.personPause(p.id, false);
|
||||
say(fmt(_('%s: access resumed'), p.name));
|
||||
await this.reload();
|
||||
} catch (e) {
|
||||
notify(errorText(e), 'error', 10000);
|
||||
} finally {
|
||||
from.disabled = false;
|
||||
}
|
||||
return;
|
||||
case 'person':
|
||||
return this.host.go({ ...listOf(this.host.route()), id: p.id });
|
||||
case 'server':
|
||||
return visit(settingsUrl(undefined, p.server));
|
||||
case 'device-on':
|
||||
return toggleDevice(this.deviceActs(), false);
|
||||
case 'tell':
|
||||
void copyText(otherNetAdvice(d), _('Advice copied: send it to them'));
|
||||
return;
|
||||
case 'add-device':
|
||||
addDevice({
|
||||
person: p,
|
||||
server: this.c.srv,
|
||||
now: this.c.now,
|
||||
added: () => void this.reload(),
|
||||
people: this.c.st.people,
|
||||
servers: this.c.st.servers,
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private deviceActs(): DeviceActCtx {
|
||||
return {
|
||||
device: this.c.d,
|
||||
reload: () => void this.reload(),
|
||||
// its person's panel takes its place (the entry of a device that is no more is not kept)
|
||||
removed: () => {
|
||||
const id = this.c.p.id;
|
||||
void this.host.reload().then(() => this.host.go({ ...listOf(this.host.route()), id }, 'replace'));
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Its name, typed in a sheet (the router's rule for a device's name; one name once per person). */
|
||||
private rename() {
|
||||
const { d, p } = this.c;
|
||||
textSheet({
|
||||
title: _('Rename'),
|
||||
value: d.name,
|
||||
placeholder: _('Name'),
|
||||
max: DEVICE_NAME_MAX,
|
||||
refuse: (v) => {
|
||||
const r = deviceNameHelp(
|
||||
v,
|
||||
p.devices.filter((x) => x.id !== d.id).map((x) => x.name),
|
||||
);
|
||||
return r.bad ? r.text : null;
|
||||
},
|
||||
save: async (v) => {
|
||||
if (v === d.name) return;
|
||||
await api.deviceUpdate(this.id, v);
|
||||
say(fmt(_('Renamed: %s'), v));
|
||||
void this.reload();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private menu(anchor: HTMLElement) {
|
||||
const { d, p } = this.c;
|
||||
openMenu(
|
||||
anchor,
|
||||
[
|
||||
// calm to grave: what only shows it; its name; what resets something of it; what stops it: off in warn,
|
||||
// then Remove, last
|
||||
{ label: _('Show set-up'), icon: 'qr', run: () => void this.showSetup() },
|
||||
null,
|
||||
{ label: _('Rename'), icon: 'edit', run: () => this.rename() },
|
||||
null,
|
||||
{ label: _('Reset traffic'), icon: 'reset', run: () => resetDeviceTraffic(this.deviceActs()) },
|
||||
{
|
||||
label: _('New keys'),
|
||||
icon: 'key',
|
||||
run: () =>
|
||||
newKeys({
|
||||
person: p,
|
||||
device: d,
|
||||
server: this.c.srv,
|
||||
now: this.c.now,
|
||||
made: () => void this.reload(),
|
||||
setup: { done: () => void this.reload() },
|
||||
}),
|
||||
},
|
||||
null,
|
||||
d.disabled
|
||||
? { label: _('Turn on'), icon: 'play', run: () => void toggleDevice(this.deviceActs(), false) }
|
||||
: { label: _('Turn off'), icon: 'pause', tone: 'warn', run: () => void toggleDevice(this.deviceActs(), true) },
|
||||
{ label: _('Remove'), icon: 'trash', tone: 'bad', run: () => removeDevice(this.deviceActs()) },
|
||||
],
|
||||
d.name,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Two event lists as one, oldest first, without the ones both have. */
|
||||
function merge(a: LogEvent[], b: LogEvent[]): LogEvent[] {
|
||||
const key = (e: LogEvent) => `${e.ts}|${e.type}|${e.device ?? ''}|${e.person ?? ''}|${e.detail ?? ''}`;
|
||||
const seen = new Set<string>();
|
||||
return [...a, ...b]
|
||||
.filter((e) => {
|
||||
const k = key(e);
|
||||
if (seen.has(k)) return false;
|
||||
seen.add(k);
|
||||
return true;
|
||||
})
|
||||
.sort((x, y) => x.ts - y.ts);
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
// The device page's Connection card: the portal's way between the device and
|
||||
// the router (setup.css .way: its dots green from the device when it holds,
|
||||
// the knock while it cannot finish, grey when it is stopped), with the line
|
||||
// under it in the words of the first break; the link timeline
|
||||
// (widgets/timeline.ts); and the brief diagnosis (people/diagnosis.ts) with
|
||||
// the break's fix as a button. A way that holds is drawn filled and at rest:
|
||||
// its fill belongs to the moment it connects, not to every visit.
|
||||
|
||||
import { h } from '../../../../portal/dom';
|
||||
import { ago } from '../../../../shared/format';
|
||||
import { fmt } from '../../../../shared/i18n';
|
||||
import { plainOrg } from '../../../../shared/org';
|
||||
import { ic } from '../../../ui/icons';
|
||||
import { linkWords, type Fix, type Step } from '../../../people/diagnosis';
|
||||
import type { DeviceCtx } from '../../../people/ctx';
|
||||
|
||||
/** A fix as its button says it. */
|
||||
const fixLabel = (f: Fix, c: DeviceCtx): string =>
|
||||
({
|
||||
show: _('Show set-up'),
|
||||
resume: _('Resume access'),
|
||||
person: fmt(_('Open %s'), c.p.name),
|
||||
server: _('Open the server'),
|
||||
'device-on': _('Turn it on'),
|
||||
tell: _('Copy the advice'),
|
||||
'add-device': _('Add a second device'),
|
||||
})[f];
|
||||
|
||||
const FIX_ICON: Record<Fix, string> = {
|
||||
show: 'qr',
|
||||
resume: 'play',
|
||||
person: 'person',
|
||||
server: 'terminal',
|
||||
'device-on': 'play',
|
||||
tell: 'copy',
|
||||
'add-device': 'plus',
|
||||
};
|
||||
|
||||
/** The look of the way: holding, not holding, knocking, or connected without data. */
|
||||
type Look = 'done' | 'stopped' | 'trying' | 'nodata';
|
||||
|
||||
/** The way and its two lines, for the device as the router has it and its chain. */
|
||||
export function wayEl(c: DeviceCtx, steps: Step[]): HTMLElement {
|
||||
const { d } = c;
|
||||
const now = c.now();
|
||||
const broke = steps.find((s) => s.state === 'bad');
|
||||
const linkBad = broke?.id === 'connection' && !!d.link;
|
||||
const look: Look = !broke ? (d.online ? 'done' : 'stopped') : broke.id === 'traffic' ? 'nodata' : linkBad ? 'trying' : 'stopped';
|
||||
const since = d.handshake ? fmt(_('Last time %s'), ago(d.handshake, now)) : _('It has never connected');
|
||||
const handshake = fmt(_('handshake %s'), ago(d.handshake, now));
|
||||
const pt = c.st.geo.points.filter((x) => x.device === d.id).sort((a, b) => b.ts - a.ts)[0];
|
||||
let say: [string, string];
|
||||
if (broke && d.link?.state === 'trying' && linkBad) say = [linkWords(d).title, fmt(_('Last handshake %s'), ago(d.handshake, now))];
|
||||
else if (broke) say = [broke.line, ['access', 'server', 'device'].includes(broke.id) ? since : d.online ? handshake : since];
|
||||
else if (d.online)
|
||||
say = [
|
||||
_('Online'),
|
||||
[pt ? [pt.city, pt.org ? plainOrg(pt.org) : ''].filter(Boolean).join(', ') : '', handshake].filter(Boolean).join(' · '),
|
||||
];
|
||||
else say = [_('Not connected'), since];
|
||||
const way = h(
|
||||
'div',
|
||||
{ class: `way dway${look === 'done' ? ' done still' : ` ${look}`}`, role: 'status' },
|
||||
h(
|
||||
'div',
|
||||
{ class: 'way-row' },
|
||||
h('span', { class: 'way-end' }, ic(d.kind)),
|
||||
h(
|
||||
'span',
|
||||
{ class: 'way-track' },
|
||||
h('span', { class: 'way-glow' }, h('span', { class: 'run' }, h('i')), h('span', { class: 'knock' }, h('i'))),
|
||||
h('span', { class: 'way-fill' }),
|
||||
h('span', { class: 'way-break' }, h('i')),
|
||||
),
|
||||
h('span', { class: 'way-end home' }, ic('terminal')),
|
||||
),
|
||||
h('div', { class: 'way-text' }, h('span', { class: 't' }, h('b', {}, say[0]), h('span', { class: 'ws' }, say[1]))),
|
||||
);
|
||||
return way;
|
||||
}
|
||||
|
||||
/** The diagnosis: steps on a track, filled green as far as it holds; the first break with its fix (when this login may). */
|
||||
export function diagnosisEl(c: DeviceCtx, steps: Step[], act: (f: Fix, from: HTMLButtonElement) => void): HTMLElement {
|
||||
return h(
|
||||
'ol',
|
||||
{ class: 'dg' },
|
||||
...steps.map((s) =>
|
||||
h(
|
||||
'li',
|
||||
{ class: `dg-s ${s.state}` },
|
||||
h(
|
||||
'span',
|
||||
{ class: 'dg-m' },
|
||||
s.state === 'ok' ? ic('check') : s.state === 'bad' ? ic('x') : s.state === 'warn' ? ic('clock') : null,
|
||||
),
|
||||
h(
|
||||
'div',
|
||||
{ class: 'dg-t' },
|
||||
h('b', {}, s.title),
|
||||
h('span', {}, s.line),
|
||||
s.hint ? h('span', { class: 'dg-h' }, s.hint) : null,
|
||||
c.write && s.fix?.length
|
||||
? h(
|
||||
'div',
|
||||
{ class: 'dg-fix' },
|
||||
...s.fix.map((f, i) => {
|
||||
const b = h(
|
||||
'button',
|
||||
{ type: 'button', class: `btn ${i ? 'soft' : 'tint'} sm`, title: fixLabel(f, c) },
|
||||
ic(FIX_ICON[f]),
|
||||
h('span', {}, fixLabel(f, c)),
|
||||
) as HTMLButtonElement;
|
||||
b.addEventListener('click', () => act(f, b));
|
||||
return b;
|
||||
}),
|
||||
)
|
||||
: null,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
// The Traffic card of a device's page and of a person's (their devices summed):
|
||||
// the last 7 days read a day at a time (widgets/week-use.ts: the days as bars,
|
||||
// their sum down and up, a day under the pointer in the sum's place), then this
|
||||
// month and all time, and while online the speed now (the live meter, read only
|
||||
// while the card is on screen).
|
||||
|
||||
import { reshape } from '../../../ui/reshape';
|
||||
import { h } from '../../../../portal/dom';
|
||||
import { SMOOTH, play, still } from '../../../../portal/motion';
|
||||
import { appear, fadeAway, look, morphText, setText } from '../../../../portal/ui/morph';
|
||||
import { rateOf, bytes } from '../../../../shared/format';
|
||||
import type { Pair } from '../../../../shared/types';
|
||||
import { weekUse } from '../../../widgets/week-use';
|
||||
|
||||
export interface TrafficCard {
|
||||
el: HTMLElement;
|
||||
/** New numbers (a repaint): the values that changed morph, the bars are drawn again. */
|
||||
set(d: Use): void;
|
||||
/** The speed now ([rx, tx] in bytes/s, rx from the device); 'wait': online, the meter has no second yet (the
|
||||
* tile stays, with what it said or a dash); null: offline, it goes. Fed once a second, its words
|
||||
* change every third (at once when they come). */
|
||||
speed(v: [number, number] | 'wait' | null): void;
|
||||
}
|
||||
|
||||
/** A value that morphs when it changes, said plainly the first time. */
|
||||
function put(el: HTMLElement, text: string) {
|
||||
if (!el.textContent) setText(el, text);
|
||||
else if (text !== el.textContent) morphText(el, text);
|
||||
}
|
||||
|
||||
/** Its numbers: each of the last 7 days, the last 30 days and all time (each a Pair, the router's [rx, tx]). */
|
||||
export interface Use {
|
||||
spark: Pair[];
|
||||
month: Pair;
|
||||
total: Pair;
|
||||
}
|
||||
|
||||
/** A person's: their devices' days added up (the newest last, as each device's). */
|
||||
export function personUse(p: { devices: { spark: Pair[] }[]; month: Pair; total: Pair }): Use {
|
||||
const n = Math.max(0, ...p.devices.map((d) => d.spark.length));
|
||||
const spark = Array.from({ length: n }, (_x, k): Pair => {
|
||||
const s: Pair = [0, 0];
|
||||
for (const d of p.devices) {
|
||||
const v = d.spark[d.spark.length - n + k];
|
||||
if (v) {
|
||||
s[0] += v[0];
|
||||
s[1] += v[1];
|
||||
}
|
||||
}
|
||||
return s;
|
||||
});
|
||||
return { spark, month: p.month, total: p.total };
|
||||
}
|
||||
|
||||
/** `key`, `name`: whose traffic it is (its numbers' names for a repaint, its name for a screen reader). */
|
||||
export function trafficCard(d0: Use, key: string, name: string): TrafficCard {
|
||||
const val = () => h('b', { class: 'num' });
|
||||
const sub = () => h('span', { class: 'stat-sub' });
|
||||
const tile = (label: string, v: HTMLElement, s: HTMLElement) => h('div', { class: 'stat' }, h('span', { class: 'use-lbl' }, label), v, s);
|
||||
const week = weekUse(key, name, d0.spark);
|
||||
const [month, monthSub, total, totalSub, down, up] = [val(), sub(), val(), sub(), val(), sub()];
|
||||
const now = tile(_('Now', 'speed'), down, up);
|
||||
now.classList.add('live-speed');
|
||||
now.hidden = true;
|
||||
const stay = [tile(_('30 days'), month, monthSub), tile(_('Total'), total, totalSub)];
|
||||
const stats = h('div', { class: 'stats' }, ...stay, now);
|
||||
const el = h('div', { class: 'card traffic' }, week.el, stats);
|
||||
/**
|
||||
* «Now» comes or goes: the grid takes another column (or a phone's second row), and nothing jumps. The tiles that
|
||||
* stay glide from where they stand to their new place and width (SMOOTH, from a glide under way too), «Now» blurs
|
||||
* in at its place or fades where it stood, and the card glides to its new height.
|
||||
*/
|
||||
const toggle = (show: boolean) => {
|
||||
// a page that stands still: «Now» is there or it is not
|
||||
if (still()) return void (now.hidden = !show);
|
||||
const was = stay.map((t) => t.getBoundingClientRect());
|
||||
const at = now.getBoundingClientRect();
|
||||
const from = stats.getBoundingClientRect();
|
||||
const ghost = !show && now.getClientRects().length ? (now.cloneNode(true) as HTMLElement) : null;
|
||||
const shows = ghost ? look(now) : undefined;
|
||||
stay.forEach((t) => t.getAnimations().forEach((a) => a.cancel()));
|
||||
reshape(el, () => (now.hidden = !show));
|
||||
stay.forEach((t, i) => {
|
||||
const r = t.getBoundingClientRect();
|
||||
if (
|
||||
r.width &&
|
||||
was[i].width &&
|
||||
(Math.abs(r.left - was[i].left) > 0.5 || Math.abs(r.top - was[i].top) > 0.5 || Math.abs(r.width - was[i].width) > 0.5)
|
||||
)
|
||||
play(
|
||||
t,
|
||||
[
|
||||
{ transform: `translate(${was[i].left - r.left}px, ${was[i].top - r.top}px)`, width: `${was[i].width}px` },
|
||||
{ transform: 'none', width: `${r.width}px` },
|
||||
],
|
||||
{ duration: SMOOTH.duration, easing: SMOOTH.easing },
|
||||
);
|
||||
});
|
||||
if (show) appear(now);
|
||||
else if (ghost && el.isConnected) fadeAway(ghost, at, stats, from, shows);
|
||||
};
|
||||
let beat = 0;
|
||||
const set = (d: Use) => {
|
||||
week.set(d.spark);
|
||||
put(month, bytes(d.month[0] + d.month[1]));
|
||||
put(monthSub, `↓ ${bytes(d.month[1])} · ↑ ${bytes(d.month[0])}`);
|
||||
put(total, bytes(d.total[0] + d.total[1]));
|
||||
put(totalSub, `↓ ${bytes(d.total[1])} · ↑ ${bytes(d.total[0])}`);
|
||||
};
|
||||
set(d0);
|
||||
return {
|
||||
el,
|
||||
set,
|
||||
speed(v) {
|
||||
if (!v) {
|
||||
// gone: it fades where it stood, the tiles left glide to fill its place, the card folds (a phone's second row)
|
||||
if (!now.hidden) toggle(false);
|
||||
beat = 0;
|
||||
return;
|
||||
}
|
||||
if (v === 'wait') {
|
||||
// online but no reading this second (the meter's gap): the tile keeps its place and its last words
|
||||
if (now.hidden) {
|
||||
setText(down, '↓ —');
|
||||
setText(up, '↑ —');
|
||||
toggle(true);
|
||||
beat = 0;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (now.hidden) {
|
||||
// back in sight: said at once, plainly; the tile blurs in, the others make room, the card unfolds to it
|
||||
setText(down, `↓ ${rateOf(v[1])}`);
|
||||
setText(up, `↑ ${rateOf(v[0])}`);
|
||||
toggle(true);
|
||||
beat = 1;
|
||||
return;
|
||||
}
|
||||
if (beat++ % 3) return;
|
||||
put(down, `↓ ${rateOf(v[1])}`);
|
||||
put(up, `↑ ${rateOf(v[0])}`);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
// People's filters as chips of the filter bar (ui/filter-bar.ts), each kept in the address: who needs a decision,
|
||||
// who is online, who is paused (the count beside each is of the people the other filters leave; a chip that would
|
||||
// leave nobody is not offered), counted by the cards' own groups (people/card.ts); the server, with more than one;
|
||||
// «waiting for a new configuration», which a rollout's «Who waits» sends here; and the order. The map view keeps
|
||||
// the server alone: its period stands before the chips.
|
||||
|
||||
import type { Status } from '../../../shared/types';
|
||||
import { openMenu, type MenuItem } from '../../../portal/ui/menu';
|
||||
import { fmt } from '../../../shared/i18n';
|
||||
import { filterChip } from '../../ui/filter-bar';
|
||||
import type { Today } from '../../people/lines';
|
||||
import type { Filter, PeopleRoute } from '../../people/route';
|
||||
import { inFilter, scoped, sortBy, sortOf, SORTS, type SortKey } from '../../people/roster';
|
||||
|
||||
const filterLabel = (f: Filter): string => ({ need: _('Needs a decision'), online: _('Online'), paused: _('Paused') })[f];
|
||||
const FILTERS: Filter[] = ['need', 'online', 'paused'];
|
||||
const sortLabel = (k: SortKey): string =>
|
||||
({ name: _('Name'), devices: _('Devices'), traffic: _('Traffic'), term: _('Term'), seen: _('Last online') })[k];
|
||||
|
||||
/** The chips for where the page is; `go` moves it to the route with a filter changed. */
|
||||
export function filterChips(st: Status, r: PeopleRoute, t: Today, go: (patch: Partial<PeopleRoute>) => void): HTMLElement[] {
|
||||
const kids: HTMLElement[] = [];
|
||||
const list = r.view !== 'map';
|
||||
if (list) {
|
||||
// a chip's count is of the people the other filters leave
|
||||
const base = scoped(st.people, r, t, false);
|
||||
for (const f of FILTERS) {
|
||||
const n = base.filter((p) => inFilter(p, f, t)).length;
|
||||
// no «Needs a decision 0» on a quiet router
|
||||
if (!n && r.group !== f) continue;
|
||||
kids.push(filterChip({ label: filterLabel(f), n, on: r.group === f, press: () => go({ group: r.group === f ? undefined : f }) }));
|
||||
}
|
||||
}
|
||||
if (st.servers.length > 1) {
|
||||
const cur = st.servers.find((s) => s.id === r.server);
|
||||
kids.push(
|
||||
filterChip({
|
||||
label: cur ? fmt(_('Server: %s'), cur.name) : _('Server'),
|
||||
on: !!cur,
|
||||
menu: true,
|
||||
press: (from) =>
|
||||
openMenu(
|
||||
from,
|
||||
[
|
||||
{ label: _('All'), icon: cur ? 'terminal' : 'check', run: () => go({ server: undefined }) },
|
||||
null,
|
||||
...st.servers.map((s): MenuItem => ({
|
||||
label: s.name,
|
||||
icon: s.id === r.server ? 'check' : 'terminal',
|
||||
sub: s.enabled ? undefined : _('Turned off'),
|
||||
run: () => go({ server: s.id }),
|
||||
})),
|
||||
],
|
||||
_('Server'),
|
||||
),
|
||||
off: () => go({ server: undefined }),
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (r.need) kids.push(filterChip({ label: _('Waiting for a new configuration'), on: true, press: () => go({ need: undefined }) }));
|
||||
if (list) {
|
||||
const cur = sortOf(r.sort)?.key;
|
||||
kids.push(
|
||||
filterChip({
|
||||
label: cur ? fmt(_('Order: %s'), sortLabel(cur)) : _('Order'),
|
||||
on: !!cur,
|
||||
menu: true,
|
||||
press: (from) =>
|
||||
openMenu(
|
||||
from,
|
||||
[
|
||||
{ label: _('By attention, in groups'), icon: cur ? 'alert' : 'check', run: () => go({ sort: undefined }) },
|
||||
null,
|
||||
...(Object.keys(SORTS) as SortKey[]).map((k): MenuItem => ({
|
||||
label: sortLabel(k),
|
||||
icon: k === cur ? 'check' : 'arrow',
|
||||
run: () => go({ sort: sortBy(k) }),
|
||||
})),
|
||||
],
|
||||
_('Order'),
|
||||
),
|
||||
off: () => go({ sort: undefined }),
|
||||
}),
|
||||
);
|
||||
}
|
||||
return kids;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
// What the People page gives its parts (the list's rows, the map view, a person's and a device's panel): the
|
||||
// router's answer as it stands, the router's clock, whether this login writes, where the page is and how to move.
|
||||
|
||||
import type { Status } from '../../../shared/types';
|
||||
import type { PeopleRoute } from '../../people/route';
|
||||
|
||||
export interface PeopleHost {
|
||||
st(): Status;
|
||||
/** The router's clock now (seconds) and its day. */
|
||||
now(): number;
|
||||
today(): string;
|
||||
/** This login may change things (shell/role.ts). */
|
||||
write: boolean;
|
||||
route(): PeopleRoute;
|
||||
/** Move inside the page: a new history entry (a panel, the view), or the same one (filters, the order). */
|
||||
go(r: PeopleRoute, how?: 'push' | 'replace'): void;
|
||||
/** Read the router again now (after a change made here) and draw it. */
|
||||
reload(): Promise<void>;
|
||||
/** A status read elsewhere (a set-up sheet's own watch): taken and drawn. */
|
||||
take(st: Status): void;
|
||||
/** The panel is the whole page (a phone). */
|
||||
narrow(): boolean;
|
||||
}
|
||||
@@ -0,0 +1,455 @@
|
||||
// People: who connects and what they may do. The section row and the head (how many people and devices, how many
|
||||
// online; Add person). The filter bar (ui/filter-bar.ts): the page's search (name, note, device, address; a card
|
||||
// says what it was found by and leads to that device), the view (Cards · Map) and «Select» for several at once
|
||||
// (pick.ts and its dock); under them the filters as chips (filters.ts), each in the address. Then the list: the
|
||||
// cards (cards.ts) with the notices over them, or the map with its list (map-view.ts). A person (person/) and a
|
||||
// device (device/) are pages of their own inside this view (ui/subpage.ts): opening one gives it the whole column,
|
||||
// the list with the head and the bar waits under it, and the way back returns the list where it was, with the same
|
||||
// filters. Their addresses are this view's (people?id=, ?device=, ?view=map).
|
||||
//
|
||||
// Moving inside the page loads nothing (moves.ts): opening pushes a history entry, the way back steps back to it;
|
||||
// filters and the order replace the entry.
|
||||
//
|
||||
// Live: the status on the live revision, 30 s as the fallback; the log of the last 8 days for everyone in one request
|
||||
// (the cards' presence), then what came after it with each new status; a page reads what else it shows.
|
||||
|
||||
import type { LogEvent, Status } from '../../../shared/types';
|
||||
import { share } from '../../../shared/live/share';
|
||||
import { api } from '../../api';
|
||||
import { h, markup } from '../../../portal/dom';
|
||||
import { sheetOpen } from '../../../portal/ui/sheet';
|
||||
import { layer } from '../../../portal/ui/layer';
|
||||
import { todayOf } from '../../../shared/format';
|
||||
import { fmt, num, plural } from '../../../shared/i18n';
|
||||
import { createPoller } from '../../state/poller';
|
||||
import { routerDay } from '../../events/clock';
|
||||
import { glass } from '../../ui/glass';
|
||||
import { ic } from '../../ui/icons';
|
||||
import { pageHead, setFacts, fact } from '../../ui/page-head';
|
||||
import { tabs } from '../../ui/tabs';
|
||||
import { onNavigate } from '../../ui/nav';
|
||||
import { emptyState } from '../../ui/empty';
|
||||
import { filterBar, searchField, type FilterBar, type Search } from '../../ui/filter-bar';
|
||||
import { subpage, type Subpage } from '../../ui/subpage';
|
||||
import { canWrite } from '../../shell/role';
|
||||
import { navRow } from '../../shell/nav';
|
||||
import { href, logUrl } from '../../shell/routes';
|
||||
import { peopleOnline } from '../../people/lines';
|
||||
import { find, words, type Match } from '../../people/find';
|
||||
import { scoped } from '../../people/roster';
|
||||
import { listOf, parseRoute, type PeopleRoute } from '../../people/route';
|
||||
import type { ActCtx } from '../../people/ctx';
|
||||
import { addPerson } from '../../flows/add-person';
|
||||
import type { PeopleHost } from './host';
|
||||
import { pageMoves, type Moves } from './moves';
|
||||
import { pickPeople, type Pick } from './pick';
|
||||
import { filterChips } from './filters';
|
||||
import { Cards } from './cards';
|
||||
import { MapView } from './map-view';
|
||||
import { PersonPanel } from './person';
|
||||
import { DevicePanel } from './device';
|
||||
import { enter } from '../../ui/entrance';
|
||||
import { putChildren } from '../../../portal/ui/put';
|
||||
|
||||
export type PeopleData = Status;
|
||||
|
||||
/** The log the cards read: the last 8 days (the week's hours, since when someone is online, when paused). */
|
||||
const SPAN = 8 * 86400;
|
||||
const EVENTS = 5000;
|
||||
/** A phone: the page's column under this. */
|
||||
const NARROW = 560;
|
||||
|
||||
/** The view switch's icon for the cards: four tiles. */
|
||||
const cardsIcon = (): Element =>
|
||||
markup(
|
||||
'<svg class="i" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="4" y="4" width="7" height="7" rx="2"/><rect x="13" y="4" width="7" height="7" rx="2"/><rect x="4" y="13" width="7" height="7" rx="2"/><rect x="13" y="13" width="7" height="7" rx="2"/></svg>',
|
||||
);
|
||||
|
||||
export class PeoplePage implements PeopleHost {
|
||||
write = canWrite();
|
||||
protected status!: Status;
|
||||
/** The router's last answer, each new one laid over it: who did not change is the object they were (shared/live/share.ts). */
|
||||
private raw: Status | null = null;
|
||||
private keep(st: Status): Status {
|
||||
return (this.raw = share(this.raw, st));
|
||||
}
|
||||
private skew = 0;
|
||||
protected r: PeopleRoute = parseRoute(location.search.replace(/^\?/, ''));
|
||||
private page = h('div', { class: 'page people' });
|
||||
private head!: HTMLElement;
|
||||
private search: Search | null = null;
|
||||
private bar: FilterBar | null = null;
|
||||
private viewBox = h('div', { class: 'pp-viewbox' });
|
||||
private sub: Subpage = subpage(this.page);
|
||||
private cards: Cards | null = null;
|
||||
private map: MapView | null = null;
|
||||
private pick: Pick | null = null;
|
||||
private moves: Moves | null = null;
|
||||
private panel: PersonPanel | DevicePanel | null = null;
|
||||
/** The log the cards read; null until the first answer. */
|
||||
private events: LogEvent[] | null = null;
|
||||
/** What stands in the list's place: a page's object, or one that is not there (''. nothing). */
|
||||
private shown = '';
|
||||
|
||||
load(): Promise<PeopleData> {
|
||||
return api.status(1);
|
||||
}
|
||||
|
||||
/* ---------- what a page built on this one may change (a server's People, pages/server/people.ts) ---------- */
|
||||
|
||||
/** What of the router's answer the page reads (all of it). */
|
||||
protected scope(st: Status): Status {
|
||||
return st;
|
||||
}
|
||||
|
||||
/** The row over the page's head (the admin's sections), or none when the page stands inside another's frame. */
|
||||
protected chrome(): HTMLElement | null {
|
||||
return navRow();
|
||||
}
|
||||
|
||||
/* ---------- what the parts read (PeopleHost) ---------- */
|
||||
|
||||
st = (): Status => this.status;
|
||||
now = (): number => Date.now() / 1000 + this.skew;
|
||||
today = (): string => todayOf(this.status.series) || routerDay(this.now(), this.status.tz);
|
||||
route = (): PeopleRoute => this.r;
|
||||
narrow = (): boolean => (this.page.clientWidth || innerWidth) < NARROW;
|
||||
|
||||
/** What a one-tap action from the list needs. */
|
||||
private acts: ActCtx = { st: this.st, today: this.today, now: this.now, reload: () => this.reload() };
|
||||
|
||||
take(st: Status) {
|
||||
this.status = this.scope(this.keep(st));
|
||||
this.skew = st.now - Date.now() / 1000;
|
||||
this.fresh(true);
|
||||
}
|
||||
|
||||
async reload() {
|
||||
const st = await api.status(1).catch(() => null);
|
||||
if (!st) return;
|
||||
this.status = this.scope(this.keep(st));
|
||||
this.skew = st.now - Date.now() / 1000;
|
||||
this.fresh(false);
|
||||
}
|
||||
|
||||
go(r: PeopleRoute, how: 'push' | 'replace' = 'push') {
|
||||
this.moves?.go(r, how);
|
||||
}
|
||||
|
||||
/* ---------- the page ---------- */
|
||||
|
||||
render(st: PeopleData): HTMLElement {
|
||||
const page = this.page;
|
||||
this.status = this.scope(this.keep(st));
|
||||
this.skew = st.now - Date.now() / 1000;
|
||||
if (this.r.server && !st.servers.some((s) => s.id === this.r.server)) this.r = { ...this.r, server: undefined };
|
||||
const add =
|
||||
this.write && st.servers.length
|
||||
? h('button', { type: 'button', class: 'btn accent sm', onclick: () => this.add() }, ic('plus'), h('span', {}, _('Add person')))
|
||||
: null;
|
||||
this.head = pageHead({ icon: glass('people', 'grey'), title: _('People'), acts: add ? [add] : [] });
|
||||
const row = this.chrome();
|
||||
if (row) page.append(row);
|
||||
page.append(this.head);
|
||||
if (!st.servers.length) {
|
||||
setFacts(this.head, [this.write ? null : fact([ic('eye'), _('View only')])]);
|
||||
page.append(
|
||||
emptyState({
|
||||
icon: 'server',
|
||||
title: _('No server yet'),
|
||||
text: _('Set up the server first, then add people.'),
|
||||
action: h('a', { class: 'btn accent sm', href: href({ view: 'server' }) }, h('span', {}, _('Set up the server'))),
|
||||
}),
|
||||
);
|
||||
return page;
|
||||
}
|
||||
this.cards = new Cards(this, {
|
||||
picking: () => !!this.pick?.picking(),
|
||||
pickable: this.write && st.people.length > 1,
|
||||
reset: () => this.reset(),
|
||||
add: () => this.add(),
|
||||
waiting: () => this.go({ ...this.r, need: 'config', group: undefined }, 'replace'),
|
||||
acts: this.acts,
|
||||
});
|
||||
page.append(this.makeBar(), this.sub.el);
|
||||
this.moves = pageMoves(page, this.route, (r, how) => this.arrive(r, how));
|
||||
this.paint(false);
|
||||
this.sync('load');
|
||||
this.listen();
|
||||
void this.readLog();
|
||||
createPoller({
|
||||
fetch: () => api.status(1),
|
||||
every: 30,
|
||||
live: true,
|
||||
active: () => page.isConnected,
|
||||
apply: (d, quiet) => {
|
||||
this.status = this.scope(this.keep(d));
|
||||
this.skew = d.now - Date.now() / 1000;
|
||||
this.fresh(quiet);
|
||||
void this.readLog();
|
||||
},
|
||||
});
|
||||
if (this.r.sheet === 'add' && !this.r.id && this.write) requestAnimationFrame(() => this.add());
|
||||
return page;
|
||||
}
|
||||
|
||||
/** The log the cards read: the last 8 days at first, then what came after the newest it has. */
|
||||
private async readLog() {
|
||||
const now = this.status.now;
|
||||
const had = this.events;
|
||||
const newest = had?.length ? had[had.length - 1].ts : 0;
|
||||
const r = await api.events(EVENTS, undefined, newest ? newest - 1 : now - SPAN - 1).catch(() => null);
|
||||
if (!r || !this.cards) return;
|
||||
const key = (e: LogEvent) => `${e.ts}|${e.type}|${e.device ?? ''}|${e.person ?? ''}|${e.detail ?? ''}`;
|
||||
const seen = new Set((had ?? []).map(key));
|
||||
const fresh = r.events.filter((e) => !seen.has(key(e)));
|
||||
if (had && !fresh.length) return;
|
||||
this.events = [...(had ?? []), ...fresh].filter((e) => e.ts >= now - SPAN).sort((a, b) => a.ts - b.ts);
|
||||
this.cards.take(this.events);
|
||||
this.paint(true);
|
||||
}
|
||||
|
||||
/** What the page listens to outside its own tree, until LuCI leaves it. */
|
||||
private listen() {
|
||||
const lay = layer();
|
||||
// Escape takes a page back to the list at once (the keyboard never animates); a sheet, a menu or a pick over it
|
||||
// takes it first.
|
||||
const esc = (e: KeyboardEvent) => {
|
||||
if (e.key !== 'Escape' || e.defaultPrevented || !this.shown || sheetOpen() || this.pick?.picking()) return;
|
||||
if ((lay as ParentNode).querySelector('.drop, .menu')) return;
|
||||
const t = e.composedPath()[0] as HTMLElement | undefined;
|
||||
if (t && ['INPUT', 'TEXTAREA', 'SELECT'].includes(t.tagName)) return;
|
||||
this.keyed = true;
|
||||
this.close();
|
||||
};
|
||||
document.addEventListener('keydown', esc);
|
||||
const off = onNavigate(() => {
|
||||
off();
|
||||
document.removeEventListener('keydown', esc);
|
||||
this.panel?.destroy();
|
||||
this.cards?.stop();
|
||||
});
|
||||
}
|
||||
|
||||
/* ---------- the bar ---------- */
|
||||
|
||||
private makeBar(): HTMLElement {
|
||||
this.search = searchField({
|
||||
placeholder: _('Name, device, IP'),
|
||||
label: _('Find a person, a device or an address'),
|
||||
page: this.page,
|
||||
typed: () => this.paint(false),
|
||||
});
|
||||
this.paintView();
|
||||
const toggle =
|
||||
this.write && this.status.people.length > 1
|
||||
? (h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
class: 'btn soft sm pk-toggle',
|
||||
'aria-pressed': 'false',
|
||||
title: _('Select several: extend, pause, resume. Or hold a card.'),
|
||||
},
|
||||
h('span', {}, _('Select')),
|
||||
) as HTMLButtonElement)
|
||||
: null;
|
||||
if (toggle)
|
||||
this.pick = pickPeople(this.cards!.groups, toggle, {
|
||||
people: () => this.status.people,
|
||||
today: this.today,
|
||||
reload: () => this.reload(),
|
||||
});
|
||||
this.bar = filterBar({ top: [this.search.el, this.viewBox, toggle] });
|
||||
return this.bar.el;
|
||||
}
|
||||
|
||||
/** The view's track: Cards · Map (drawn again when the address changed the view under it: Back). */
|
||||
private paintView() {
|
||||
const on = this.r.view === 'map' ? 'map' : 'cards';
|
||||
if (this.viewBox.dataset.on === on) return;
|
||||
this.viewBox.dataset.on = on;
|
||||
putChildren(this.viewBox, [
|
||||
tabs<'cards' | 'map'>(
|
||||
[
|
||||
{ id: 'cards', label: _('Cards'), icon: 'cards' },
|
||||
{ id: 'map', label: _('Map'), icon: 'map' },
|
||||
],
|
||||
on,
|
||||
(v) => {
|
||||
this.viewBox.dataset.on = v;
|
||||
// the map has no order and no group chips; the cards have no period
|
||||
this.go({
|
||||
...this.r,
|
||||
view: v === 'map' ? 'map' : undefined,
|
||||
sort: undefined,
|
||||
group: undefined,
|
||||
range: undefined,
|
||||
s: undefined,
|
||||
sheet: undefined,
|
||||
});
|
||||
},
|
||||
{ cls: 'pp-view', label: _('View') },
|
||||
).el,
|
||||
]);
|
||||
this.viewBox.querySelector('.tab[data-id="cards"] .i')?.replaceWith(cardsIcon());
|
||||
}
|
||||
|
||||
private reset() {
|
||||
this.search?.clear();
|
||||
this.go({ view: this.r.view, id: this.r.id, device: this.r.device, range: this.r.range }, 'replace');
|
||||
}
|
||||
|
||||
private add() {
|
||||
addPerson({ st: this.status, today: this.today(), server: this.r.server ?? '', added: () => void this.reload() });
|
||||
}
|
||||
|
||||
/* ---------- the list ---------- */
|
||||
|
||||
private paint(quiet: boolean) {
|
||||
const r = this.r;
|
||||
const st = this.status;
|
||||
const t = { now: this.now(), today: this.today() };
|
||||
const all = scoped(st.people, r, t, false);
|
||||
setFacts(this.head, [
|
||||
fact(plural(all.length, '%s person', '%s people')),
|
||||
fact(
|
||||
plural(
|
||||
all.reduce((n, p) => n + p.devices.length, 0),
|
||||
'%s device',
|
||||
'%s devices',
|
||||
),
|
||||
),
|
||||
fact(fmt(_('%s online'), num(peopleOnline(all)))),
|
||||
this.write ? null : fact([ic('eye'), _('View only')]),
|
||||
]);
|
||||
if (!this.cards || !this.bar) return;
|
||||
const query = this.search?.value() ?? '';
|
||||
const ws = words(query);
|
||||
const found = new Map<string, Match | null>();
|
||||
const hit = scoped(st.people, r, t).filter((p) => {
|
||||
const f = find(p, ws);
|
||||
if (f.hit) found.set(p.id, f.match);
|
||||
return f.hit;
|
||||
});
|
||||
const narrowed = !!(r.group || r.server || r.need || r.sort || ws.length);
|
||||
// one person, or nobody: nothing to narrow or to order
|
||||
this.bar.chips(
|
||||
st.people.length > 1 ? filterChips(st, r, t, (patch) => this.go({ ...this.r, ...patch }, 'replace')) : [],
|
||||
narrowed ? () => this.reset() : null,
|
||||
);
|
||||
this.bar.count(hit.length, st.people.length, hit.length === st.people.length);
|
||||
const map = r.view === 'map';
|
||||
this.page.classList.toggle('map', map);
|
||||
const list = this.sub.list;
|
||||
// cards ↔ map: the view that goes is gone at once, the one that comes in comes in as a page does (ui/entrance.ts)
|
||||
const swap = list.firstElementChild && list.firstElementChild !== (map ? this.map?.el : this.cards.el) && !this.shown;
|
||||
if (map) {
|
||||
this.map ??= new MapView(this);
|
||||
if (this.map.el.parentElement !== list) putChildren(list, [this.map.el]);
|
||||
this.map.paint(r, hit);
|
||||
if (swap) enter(this.map.el);
|
||||
return;
|
||||
}
|
||||
if (this.cards.el.parentElement !== list) {
|
||||
putChildren(list, [this.cards.el]);
|
||||
this.cards.forget();
|
||||
}
|
||||
// under a person's or a device's page the list waits as it was: drawn again when it is back
|
||||
if (this.shown) return;
|
||||
this.cards.paint({ people: hit, found, words: ws, query }, quiet);
|
||||
this.pick?.adopt();
|
||||
if (swap) enter(this.cards.el);
|
||||
}
|
||||
|
||||
/* ---------- a person's or a device's page ---------- */
|
||||
|
||||
/** The page at another route: a pick, or a traversal (Back). */
|
||||
protected arrive(r: PeopleRoute, how: 'pick' | 'back') {
|
||||
this.r = r;
|
||||
this.paintView();
|
||||
this.sync(how);
|
||||
this.paint(false);
|
||||
}
|
||||
|
||||
/** Escape asked for the list: it comes back without motion. */
|
||||
private keyed = false;
|
||||
|
||||
/** The person a route is about (a device's owner). */
|
||||
protected owner(r: PeopleRoute): string | undefined {
|
||||
return r.device ? this.status.people.find((p) => p.devices.some((d) => d.id === r.device))?.id : r.id;
|
||||
}
|
||||
|
||||
/** The page the route asks for, opened, swapped or taken back to the list. */
|
||||
protected sync(how: 'load' | 'pick' | 'back') {
|
||||
const r = this.r;
|
||||
// the map view with a person or a device is their places on the map (map-view.ts scopes to them), not their page
|
||||
const want = r.view === 'map' ? '' : r.device ? `d:${r.device}` : r.id ? `p:${r.id}` : '';
|
||||
if (want === this.shown) {
|
||||
// the same page asked for a block or a sheet of its own
|
||||
if (how === 'pick') this.panel?.arrive(r.s, r.sheet);
|
||||
return;
|
||||
}
|
||||
this.panel?.destroy();
|
||||
this.panel = null;
|
||||
this.shown = want;
|
||||
// back by Escape: the list stands there at once, as it was left
|
||||
const keyed = this.keyed;
|
||||
this.keyed = false;
|
||||
if (!want) return this.sub.show(null, keyed ? 'load' : how);
|
||||
this.pick?.leave();
|
||||
const known = r.device
|
||||
? this.status.people.some((p) => p.devices.some((d) => d.id === r.device))
|
||||
: this.status.people.some((p) => p.id === r.id);
|
||||
if (!known) {
|
||||
const back = h('button', { type: 'button', class: 'btn soft sm' }, h('span', {}, _('To people')));
|
||||
back.addEventListener('click', () => this.close());
|
||||
this.sub.show(
|
||||
emptyState({
|
||||
icon: r.device ? 'phone' : 'person',
|
||||
title: r.device ? _('No such device') : _('No such person'),
|
||||
text: r.device
|
||||
? _('It was removed, or the link is out of date. Its events stay in the log for as long as the log keeps them.')
|
||||
: _('They were removed, or the link is out of date. Their devices’ events stay in the log for as long as the log keeps them.'),
|
||||
action: h(
|
||||
'div',
|
||||
{ class: 'pp-gone-acts' },
|
||||
back,
|
||||
h('a', { class: 'btn soft sm', href: logUrl(r.device ? { device: r.device } : {}) }, h('span', {}, _('Open the log'))),
|
||||
),
|
||||
}),
|
||||
how,
|
||||
);
|
||||
return;
|
||||
}
|
||||
const close = () => this.close();
|
||||
const panel = r.device ? new DevicePanel(r.device, this, close) : new PersonPanel(r.id!, this, close);
|
||||
this.panel = panel;
|
||||
this.sub.show(panel.el, how, this.owner(r));
|
||||
// what the address asks to open on arrival (a block, a sheet), once the page stands
|
||||
if (r.s || r.sheet) requestAnimationFrame(() => panel.arrive(r.s, r.sheet));
|
||||
}
|
||||
|
||||
/** Back to the list as it stands (a step back in history when that is where the page was opened from). */
|
||||
private close() {
|
||||
const go = () => this.moves?.back(listOf(this.r));
|
||||
// a person's page with changes waiting asks first
|
||||
if (this.panel instanceof PersonPanel) this.panel.leave(go);
|
||||
else go();
|
||||
}
|
||||
|
||||
/** A new answer from the router; `quiet`: a periodic one (what holds the focus is left alone). */
|
||||
protected fresh(quiet: boolean) {
|
||||
this.paint(quiet);
|
||||
if (this.panel) this.panel.fresh(quiet);
|
||||
// the page's object went away (removed here or elsewhere): it says so
|
||||
const r = this.r;
|
||||
const there = r.device
|
||||
? this.status.people.some((p) => p.devices.some((d) => d.id === r.device))
|
||||
: !r.id || this.status.people.some((p) => p.id === r.id);
|
||||
if (this.panel && !there) {
|
||||
this.shown = '';
|
||||
this.sync('back');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,416 @@
|
||||
// People › Map: where the people in the list connect from, as one stage (ui/split.ts): the admin's map (map.ts in
|
||||
// widgets/map-box.ts) and beside it an inspector as high as the map, that scrolls inside itself however many places
|
||||
// there are. The inspector's head counts the places and who is in one now, picks the period, and names the person
|
||||
// or device the view is narrowed to (× lets go). Its body has two levels in one place:
|
||||
// - the places: a row a city (who was there as faces, how many devices on which networks, now or how long ago, one
|
||||
// strip of when anyone was there over the period); a row under the pointer brings its city's markers forward;
|
||||
// - a city, opened from its row or its marker: the way back, its words, and its devices as place rows
|
||||
// (widgets/place-rows.ts: who and which, the operator, the strip, when), each the way to its device's page. The
|
||||
// camera eases to the city and holds there while it is open; back, it frames everyone again and the list stands
|
||||
// where it was left with the city's row in sight.
|
||||
// With a person or a device open (the route), the map and the list are their places alone. The list is the map's
|
||||
// text alternative and what shows when WebGL is missing; nothing in it folds. Without geolocation the view says
|
||||
// where it is turned on.
|
||||
|
||||
import type { Device, GeoPoint, LogEvent, Person } from '../../../shared/types';
|
||||
import { api } from '../../api';
|
||||
import { h } from '../../../portal/dom';
|
||||
import { EASE_OUT, SMOOTH, still, play } from '../../../portal/motion';
|
||||
import { fadeAway } from '../../../portal/ui/morph';
|
||||
import { ago } from '../../../shared/format';
|
||||
import { fmt, plural } from '../../../shared/i18n';
|
||||
import { plainOrg } from '../../../shared/org';
|
||||
import { emptyState } from '../../ui/empty';
|
||||
import { face } from '../../ui/face';
|
||||
import { ic } from '../../ui/icons';
|
||||
import { refill } from '../../ui/reshape';
|
||||
import { stage, type Stage } from '../../ui/split';
|
||||
import { tabs } from '../../ui/tabs';
|
||||
import { deviceUrl, settingsUrl } from '../../shell/routes';
|
||||
import { mapBox, type MapBox } from '../../widgets/map-box';
|
||||
import { deviceRuns, placeRow, runsStrip, spanOf } from '../../widgets/place-rows';
|
||||
import { cities, inPeriod, union, type City } from '../../places/model';
|
||||
import type { PeopleRoute, Range } from '../../people/route';
|
||||
import type { PeopleHost } from './host';
|
||||
import { putChildren } from '../../../portal/ui/put';
|
||||
|
||||
const DAYS30 = 30 * 86400;
|
||||
/** The period the view opens on. */
|
||||
const RANGE: Range = '30d';
|
||||
const RANGES: Range[] = ['online', '24h', '7d', '30d'];
|
||||
const rangeLabel = (r: Range): string => ({ online: _('Now', 'period'), '24h': _('24h'), '7d': _('7 days'), '30d': _('30 days') })[r];
|
||||
/** Faces a city's row shows before «+N». */
|
||||
const FACES = 4;
|
||||
|
||||
/** A device at a place, with its person. */
|
||||
interface At {
|
||||
pt: GeoPoint;
|
||||
p: Person;
|
||||
d: Device;
|
||||
}
|
||||
|
||||
export class MapView {
|
||||
el = h('div', { class: 'pp-mapview' });
|
||||
private map: MapBox | null = null;
|
||||
private stage: Stage | null = null;
|
||||
/** The inspector's head: the count, the scope, the period. */
|
||||
private count = h('div', { class: 'pp-insp-n' });
|
||||
private scopeBox = h('div', { class: 'pp-insp-scope' });
|
||||
/** The two levels of its body: the places, and the city open (kept apart, so the list keeps its rows and scroll). */
|
||||
private list = h('div', { class: 'pp-cities', 'aria-label': _('Places') });
|
||||
private place = h('div', { class: 'pp-city' });
|
||||
/** The city open in the inspector (placeKey); null: the places. */
|
||||
private city: string | null = null;
|
||||
/** The list's scroll when a city opened. */
|
||||
private listY = 0;
|
||||
/** Everyone's connections of the longest period (the strips); null: not read yet. */
|
||||
private events: LogEvent[] | null = null;
|
||||
private asked = false;
|
||||
private people: Person[] = [];
|
||||
private route: PeopleRoute = {};
|
||||
/** Whose places the map shows (everyone's, a person's, a device's): another scope is framed anew. */
|
||||
private scope = '';
|
||||
|
||||
constructor(private host: PeopleHost) {}
|
||||
|
||||
private range(): Range {
|
||||
return this.route.range ?? RANGE;
|
||||
}
|
||||
|
||||
/** The person the view is narrowed to (a device's owner). */
|
||||
private owner(): string | undefined {
|
||||
const r = this.route;
|
||||
return r.device ? this.host.st().people.find((p) => p.devices.some((d) => d.id === r.device))?.id : r.id;
|
||||
}
|
||||
|
||||
/** Draw for a route and the people in scope (the bar's filters and search). */
|
||||
paint(route: PeopleRoute, people: Person[]) {
|
||||
const was = this.route;
|
||||
this.route = route;
|
||||
this.people = people;
|
||||
const st = this.host.st();
|
||||
if (!st.geo.enabled) {
|
||||
this.map = null;
|
||||
this.stage = null;
|
||||
putChildren(this.el, [
|
||||
emptyState({
|
||||
icon: 'pin',
|
||||
title: _('No map of places'),
|
||||
text: _(
|
||||
'Dawnline does not look up the city and network of an address, so there is no map. It is turned on in System, under History and storage.',
|
||||
),
|
||||
action: h('a', { class: 'btn soft sm', href: settingsUrl('history') }, h('span', {}, _('Open the setting'))),
|
||||
}),
|
||||
]);
|
||||
return;
|
||||
}
|
||||
if (!this.asked) {
|
||||
this.asked = true;
|
||||
void api.events(5000, undefined, st.now - DAYS30 - 1).then(
|
||||
(r) => {
|
||||
this.events = r.events;
|
||||
this.paintSide();
|
||||
},
|
||||
() => undefined,
|
||||
);
|
||||
}
|
||||
const scope = route.device ? `d:${route.device}` : route.id ? `p:${route.id}` : '';
|
||||
if (!this.map || !this.stage) {
|
||||
this.map = mapBox({
|
||||
height: 'fill',
|
||||
range: this.range(),
|
||||
data: () => this.mapData(),
|
||||
cb: {
|
||||
openPerson: (id) => this.host.go({ ...this.route, id, device: undefined, s: undefined, sheet: undefined }),
|
||||
openDevice: (_p, d) => this.host.go({ ...this.route, device: d, id: undefined, s: undefined, sheet: undefined }),
|
||||
pickPlace: (key) => this.open(key, true),
|
||||
},
|
||||
});
|
||||
const period = tabs<Range>(
|
||||
RANGES.map((x) => ({ id: x, label: rangeLabel(x) })),
|
||||
this.range(),
|
||||
(v) => this.host.go({ ...this.route, range: v }, 'replace'),
|
||||
{ cls: 'pp-insp-range', label: _('Period'), keep: 'map-range' },
|
||||
);
|
||||
const head = h('div', { class: 'pp-insp-head' }, h('div', { class: 'pp-insp-top' }, this.count, this.scopeBox), period.el);
|
||||
this.stage = stage({ map: this.map.el, head, skip: _('Skip to the list of places') });
|
||||
this.stage.body.append(this.list);
|
||||
putChildren(this.el, [this.stage.el]);
|
||||
requestAnimationFrame(() => this.stage?.fit());
|
||||
} else {
|
||||
this.map.refresh();
|
||||
// another period, or another scope (everyone's places, a person's, a device's): framed anew, the city let go
|
||||
if (was.range !== route.range || scope !== this.scope) {
|
||||
if (this.city) this.back(false);
|
||||
this.map.setRange(this.range());
|
||||
}
|
||||
this.stage.fit();
|
||||
}
|
||||
this.scope = scope;
|
||||
this.paintSide();
|
||||
}
|
||||
|
||||
private mapData() {
|
||||
const st = this.host.st();
|
||||
const ids = new Set(this.people.map((p) => p.id));
|
||||
return {
|
||||
geo: { ...st.geo, points: st.geo.points.filter((x) => ids.has(x.person)) },
|
||||
people: st.people,
|
||||
now: this.host.now(),
|
||||
person: this.owner(),
|
||||
device: this.route.device,
|
||||
};
|
||||
}
|
||||
|
||||
/** The places in the period and the scope, a city each. */
|
||||
private cities(): City[] {
|
||||
const st = this.host.st();
|
||||
const ids = new Set(this.people.map((p) => p.id));
|
||||
const owner = this.owner();
|
||||
const dev = this.route.device;
|
||||
return cities(
|
||||
st.geo.points.filter(
|
||||
(x) => ids.has(x.person) && inPeriod(x, this.range(), st.now) && (!owner || x.person === owner) && (!dev || x.device === dev),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/** A city's devices with their people (those still known). */
|
||||
private at(c: City): At[] {
|
||||
const st = this.host.st();
|
||||
return c.points
|
||||
.map((pt) => {
|
||||
const p = st.people.find((x) => x.id === pt.person);
|
||||
const d = p?.devices.find((x) => x.id === pt.device);
|
||||
return p && d ? { pt, p, d } : null;
|
||||
})
|
||||
.filter((x): x is At => !!x);
|
||||
}
|
||||
|
||||
/** The inspector: its head, and the level that stands. */
|
||||
private paintSide() {
|
||||
if (!this.stage) return;
|
||||
const st = this.host.st();
|
||||
const list = this.cities();
|
||||
const live = list.reduce((n, c) => n + c.live, 0);
|
||||
refill(this.count, [
|
||||
h('b', {}, plural(list.length, '%s place', '%s places')),
|
||||
live ? h('span', { class: 'pp-insp-live' }, plural(live, '%s device online', '%s devices online')) : '',
|
||||
]);
|
||||
this.paintScope();
|
||||
// the city open, unless the period or the filters left it out
|
||||
const open = this.city ? list.find((c) => c.key === this.city) : null;
|
||||
if (this.city && !open) this.back(false);
|
||||
if (open) refill(this.place, this.cityLevel(open));
|
||||
if (!list.length) {
|
||||
const r = this.range();
|
||||
refill(this.list, [
|
||||
h(
|
||||
'div',
|
||||
{ class: 'pp-insp-none' },
|
||||
h('b', {}, r === 'online' ? _('Nobody is online now') : _('No places in this period')),
|
||||
h(
|
||||
'span',
|
||||
{},
|
||||
r === 'online'
|
||||
? _('Pick a period to see where they connected from before.')
|
||||
: _('No connections from a known place in this period.'),
|
||||
),
|
||||
),
|
||||
]);
|
||||
return;
|
||||
}
|
||||
refill(
|
||||
this.list,
|
||||
list.map((c) => this.cityRow(c, st.now)),
|
||||
);
|
||||
}
|
||||
|
||||
/** Whose places these are, with the way back to everyone's. */
|
||||
private paintScope() {
|
||||
const st = this.host.st();
|
||||
const r = this.route;
|
||||
const p = st.people.find((x) => x.id === this.owner());
|
||||
const d = r.device ? p?.devices.find((x) => x.id === r.device) : undefined;
|
||||
if (!p) return refill(this.scopeBox, []);
|
||||
const clear = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
class: 'kt-chip pp-insp-chip',
|
||||
'aria-label': fmt(_('Everyone’s places, not only %s'), d ? `${p.name} · ${d.name}` : p.name),
|
||||
},
|
||||
h('span', {}, d ? `${p.name} · ${d.name}` : p.name),
|
||||
ic('x'),
|
||||
);
|
||||
clear.addEventListener('click', () => this.host.go({ ...this.route, id: undefined, device: undefined }, 'replace'));
|
||||
refill(this.scopeBox, [clear]);
|
||||
}
|
||||
|
||||
/** A city's strip: when any of its devices was there over the period. */
|
||||
private cityStrip(c: City, at: At[]): HTMLElement {
|
||||
const st = this.host.st();
|
||||
const span = spanOf(this.range());
|
||||
const runs = union(at.flatMap(({ pt, d }) => deviceRuns(st, pt, d, this.events, span).map(([l, w]) => [l, l + w] as [number, number])));
|
||||
return runsStrip(
|
||||
runs.map(([a, b]) => [a, b - a]),
|
||||
c.live > 0,
|
||||
);
|
||||
}
|
||||
|
||||
/** Its networks, plain, the most used first. */
|
||||
private orgs(at: At[]): string {
|
||||
const n = new Map<string, number>();
|
||||
for (const { pt } of at) if (pt.org) n.set(plainOrg(pt.org), (n.get(plainOrg(pt.org)) ?? 0) + 1);
|
||||
return [...n]
|
||||
.sort((a, b) => b[1] - a[1])
|
||||
.map(([o]) => o)
|
||||
.join(', ');
|
||||
}
|
||||
|
||||
/** A city of the list: who was there, how many devices on which networks, when, the strip; it opens the city. */
|
||||
private cityRow(c: City, now: number): HTMLElement {
|
||||
const at = this.at(c);
|
||||
const people = [...new Map(at.map((x) => [x.p.id, x])).values()];
|
||||
// the live ones first, as the map rings them
|
||||
people.sort(
|
||||
(a, b) =>
|
||||
Number(c.points.some((x) => x.person === b.p.id && x.online)) - Number(c.points.some((x) => x.person === a.p.id && x.online)),
|
||||
);
|
||||
const faces = h(
|
||||
'span',
|
||||
{ class: 'pp-faces', 'aria-hidden': 'true' },
|
||||
...people.slice(0, FACES).map(({ p }) => face(p.name, c.points.some((x) => x.person === p.id && x.online) ? 'ok' : '')),
|
||||
people.length > FACES ? h('span', { class: 'pav kt-face pp-more' }, `+${people.length - FACES}`) : null,
|
||||
);
|
||||
const orgs = this.orgs(at);
|
||||
const b = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
class: 'prow2 pp-cityrow',
|
||||
'data-key': c.key,
|
||||
'aria-label': `${c.name}: ${people.map(({ p }) => p.name).join(', ')}`,
|
||||
},
|
||||
h(
|
||||
'span',
|
||||
{ class: 'prow2-t' },
|
||||
h(
|
||||
'span',
|
||||
{ class: 'pp-cr-top' },
|
||||
h('b', {}, c.name),
|
||||
h('span', { class: `prow2-w${c.live ? ' now' : ''}` }, c.live ? plural(c.live, '%s now', '%s now') : ago(c.last, now)),
|
||||
),
|
||||
h(
|
||||
'span',
|
||||
{ class: 'pp-cr-who' },
|
||||
faces,
|
||||
h('span', {}, [plural(at.length, '%s device', '%s devices'), orgs].filter(Boolean).join(' · ')),
|
||||
),
|
||||
this.cityStrip(c, at),
|
||||
),
|
||||
);
|
||||
b.addEventListener('click', () => this.open(c.key, false));
|
||||
b.addEventListener('mouseenter', () => this.map?.hoverCity(c.key));
|
||||
b.addEventListener('mouseleave', () => this.map?.hoverCity(null));
|
||||
b.addEventListener('focus', () => this.map?.hoverCity(c.key));
|
||||
b.addEventListener('blur', () => this.map?.hoverCity(null));
|
||||
return b;
|
||||
}
|
||||
|
||||
/** An open city: the way back, its words, its devices as place rows. */
|
||||
private cityLevel(c: City): HTMLElement[] {
|
||||
const st = this.host.st();
|
||||
const at = this.at(c);
|
||||
const backBtn = h('button', { type: 'button', class: 'pill-link pp-back' }, ic('chevron'), _('All places'));
|
||||
backBtn.addEventListener('click', () => this.back(true));
|
||||
const country = c.points[0]?.country || c.points[0]?.cc || '';
|
||||
return [
|
||||
h(
|
||||
'div',
|
||||
{ class: 'pp-city-head' },
|
||||
backBtn,
|
||||
h('b', { class: 'pp-city-name' }, c.name),
|
||||
h(
|
||||
'span',
|
||||
{ class: 'pp-city-meta' },
|
||||
[country, this.orgs(at), c.live ? plural(c.live, '%s now', '%s now') : ago(c.last, st.now)].filter(Boolean).join(' · '),
|
||||
),
|
||||
this.cityStrip(c, at),
|
||||
),
|
||||
h(
|
||||
'div',
|
||||
{ class: 'pp-city-rows' },
|
||||
...at.map(({ pt, p, d }) =>
|
||||
placeRow({ st, pt, p, d, events: this.events, range: this.range(), href: deviceUrl(d.id), current: d.id === this.route.device }),
|
||||
),
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
/** A city opened (its row, or its marker: `fromMap`): it takes the body's place, the camera eases to it. */
|
||||
private open(key: string, fromMap: boolean) {
|
||||
const s = this.stage;
|
||||
const c = this.cities().find((x) => x.key === key);
|
||||
if (!s || !c) return;
|
||||
const swap = this.city !== key;
|
||||
if (!this.city) this.listY = s.scroll.get();
|
||||
this.city = key;
|
||||
this.map?.showCity(key);
|
||||
this.map?.hoverCity(key);
|
||||
refill(this.place, this.cityLevel(c));
|
||||
if (!swap) return;
|
||||
// another city while one is open: it changes in place
|
||||
if (this.place.parentElement === s.body) return s.scroll.set(0);
|
||||
this.cross(this.place, 1, 0);
|
||||
if (!fromMap) this.place.querySelector<HTMLElement>('.pp-back')?.focus({ preventScroll: true });
|
||||
}
|
||||
|
||||
/** Back to the places (`animate`: a press, not a period or a filter that left the city out). */
|
||||
private back(animate: boolean) {
|
||||
const s = this.stage;
|
||||
const was = this.city;
|
||||
if (!s || !was) return;
|
||||
this.city = null;
|
||||
this.map?.showCity(null);
|
||||
this.map?.hoverCity(null);
|
||||
if (animate) this.cross(this.list, -1, this.listY);
|
||||
else {
|
||||
putChildren(s.body, [this.list]);
|
||||
s.scroll.set(this.listY);
|
||||
}
|
||||
const row = this.list.querySelector<HTMLElement>(`[data-key="${CSS.escape(was)}"]`);
|
||||
if (row) {
|
||||
s.reveal(row);
|
||||
if (animate) row.focus({ preventScroll: true });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* `next` in the body's place: what stood there fades where it stood (out, b4, 180 EASE_IN), the new level comes in
|
||||
* from 10 px aside (`dir`: 1 from the right, a city; -1 from the left, the list) with its opacity, on SMOOTH, as a
|
||||
* page of the list does (ui/subpage.ts). The body then scrolls to `y`; the old one stays where it was seen.
|
||||
*/
|
||||
private cross(next: HTMLElement, dir: 1 | -1, y: number) {
|
||||
const s = this.stage!;
|
||||
const body = s.body;
|
||||
const old = [...body.children].find((x) => x !== next && !x.hasAttribute('aria-hidden')) as HTMLElement | undefined;
|
||||
if (old && !still() && body.getClientRects().length) {
|
||||
const b = body.getBoundingClientRect();
|
||||
// placed in the body's content, which scrolls to y under it
|
||||
fadeAway(old, old.getBoundingClientRect(), body, new DOMRect(b.x, b.y - y, b.width, b.height));
|
||||
} else old?.remove();
|
||||
body.append(next);
|
||||
s.scroll.set(y);
|
||||
if (still()) return;
|
||||
play(next, [{ transform: `translateX(${10 * dir}px)` }, { transform: 'none' }], { duration: SMOOTH.duration, easing: SMOOTH.easing });
|
||||
play(
|
||||
next,
|
||||
[
|
||||
{ opacity: 0, filter: 'blur(4px)' },
|
||||
{ opacity: 1, filter: 'blur(0px)' },
|
||||
],
|
||||
{ duration: 280, delay: 60, easing: EASE_OUT, fill: 'backwards' },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
// Moving inside the People page without a page load. The page's address says where it is (people/route.ts); a move
|
||||
// writes the address and tells the page: opening a person or a device pushes a history entry (Back returns to the
|
||||
// list where it was), filters and the order replace it. The way back of a page («‹ People», «‹ Dima», ×, Escape)
|
||||
// steps back in history when the entry before is where it leads, so it never piles up entries. Every way to an address of this view ends here: a plain click on a
|
||||
// link in the page or in the layer (a name in a feed, a device's icon, the way back; in a sheet, once the sheet has
|
||||
// gone), visit() from code (shell/visit.ts), and Back or Forward between the view's own entries. The section row's
|
||||
// links are the browser's (a section is opened afresh). All of it is let go when LuCI leaves the page.
|
||||
|
||||
import { onSheetEntry, sheetOpen } from '../../../portal/ui/sheet';
|
||||
import { layer } from '../../../portal/ui/layer';
|
||||
import { onNavigate } from '../../ui/nav';
|
||||
import { href, peopleAt } from '../../shell/routes';
|
||||
import { leaveTo, plain } from '../../shell/sheets';
|
||||
import { ownVisits } from '../../shell/visit';
|
||||
import { follow, parseRoute, type PeopleRoute } from '../../people/route';
|
||||
|
||||
export interface Moves {
|
||||
go(r: PeopleRoute, how?: 'push' | 'replace'): void;
|
||||
/** The way back to `r`: a step back in history when the entry before is `r`, else a move there. */
|
||||
back(r: PeopleRoute): void;
|
||||
}
|
||||
|
||||
/** What the page keeps in each of its history entries: its route, and where the entry stands among the page's own. */
|
||||
interface Entry {
|
||||
people: PeopleRoute;
|
||||
n: number;
|
||||
}
|
||||
|
||||
const search = (s: string): string => s.replace(/^\?/, '');
|
||||
|
||||
/** `route`: where the page is; `arrive`: the page at another route, by a pick or a traversal (Back). */
|
||||
export function pageMoves(page: HTMLElement, route: () => PeopleRoute, arrive: (r: PeopleRoute, how: 'pick' | 'back') => void): Moves {
|
||||
/** The route this view has for an address; null: the address is another page's. */
|
||||
const own = (url: string): PeopleRoute | null => {
|
||||
const u = new URL(url, location.href);
|
||||
const mine = new URL(href({ view: 'people' }), location.href);
|
||||
return u.origin === mine.origin && u.pathname === mine.pathname ? follow(route(), parseRoute(search(u.search))) : null;
|
||||
};
|
||||
/** This tab's entries of the page by their place (state.n): the address of each, to know where Back leads. */
|
||||
let n = (history.state as Partial<Entry> | null)?.n ?? 0;
|
||||
const trail: string[] = [];
|
||||
const go = (r: PeopleRoute, how: 'push' | 'replace' = 'push') => {
|
||||
// A sheet is closing under us (its own history entry is still the current one): the page moves once it is off
|
||||
// it, or the new entry would land on top of the sheet's.
|
||||
if (onSheetEntry()) {
|
||||
let done = false;
|
||||
const run = () => {
|
||||
if (done) return;
|
||||
done = true;
|
||||
removeEventListener('popstate', run);
|
||||
go(r, how);
|
||||
};
|
||||
addEventListener('popstate', run);
|
||||
setTimeout(run, 400);
|
||||
return;
|
||||
}
|
||||
const url = peopleAt(r);
|
||||
if (how === 'push' && url !== peopleAt(route())) {
|
||||
trail[n] = peopleAt(route());
|
||||
n++;
|
||||
history.pushState({ people: r, n } satisfies Entry, '', url);
|
||||
} else history.replaceState({ people: r, n } satisfies Entry, '', url);
|
||||
arrive(r, 'pick');
|
||||
};
|
||||
const back = (r: PeopleRoute) => {
|
||||
if (n > 0 && trail[n - 1] === peopleAt(r) && !onSheetEntry()) history.back();
|
||||
else go(r);
|
||||
};
|
||||
const click = (inLayer: boolean) => (e: Event) => {
|
||||
if (e.defaultPrevented || !plain(e)) return;
|
||||
const a = e.composedPath().find((x): x is HTMLAnchorElement => x instanceof HTMLAnchorElement);
|
||||
if (!a || a.target || a.hasAttribute('download') || a.closest('.dl-nav')) return;
|
||||
const to = own(a.href);
|
||||
if (!to) return;
|
||||
e.preventDefault();
|
||||
if (inLayer && sheetOpen()) leaveTo(a.href);
|
||||
else if (a.classList.contains('back-a')) back(to);
|
||||
else go(to);
|
||||
};
|
||||
const inPage = click(false);
|
||||
const inLayer = click(true);
|
||||
const lay = layer();
|
||||
page.addEventListener('click', inPage);
|
||||
lay.addEventListener('click', inLayer);
|
||||
const offVisits = ownVisits((url) => {
|
||||
const to = page.isConnected ? own(url) : null;
|
||||
if (to) go(to);
|
||||
return !!to;
|
||||
});
|
||||
// Back and Forward between this view's own entries. A sheet's entry is not a place of the page.
|
||||
const pop = (e: PopStateEvent) => {
|
||||
const s = e.state as ({ sheet?: boolean } & Partial<Entry>) | null;
|
||||
if (s?.sheet || !page.isConnected) return;
|
||||
n = s?.n ?? 0;
|
||||
arrive(s?.people ?? parseRoute(search(location.search)), 'back');
|
||||
};
|
||||
addEventListener('popstate', pop);
|
||||
// the entry the page stands on says its route too (a traversal reads it back)
|
||||
history.replaceState({ ...(history.state as object | null), people: route(), n }, '', location.href);
|
||||
const off = onNavigate(() => {
|
||||
off();
|
||||
offVisits();
|
||||
removeEventListener('popstate', pop);
|
||||
lay.removeEventListener('click', inLayer);
|
||||
});
|
||||
return { go, back };
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
// The notices over the People list: what stops many people at once is said once, not on each of their cards. A
|
||||
// server that is turned off and has people: «Server Dacha is turned off · 1 person without access · Turn on». A
|
||||
// rollout: «New configuration · 4 people have not fetched it yet · Who waits» (the last narrows
|
||||
// the list to them, the «Waiting for a new configuration» chip). Their cards say only a quiet line (the server) or
|
||||
// a warn tile (the rollout). On a phone two or more notices fold into one line («Server Dacha is turned off · New
|
||||
// configuration for 4») that unfolds on a tap: they would take a screen before the list begins.
|
||||
|
||||
import { refill, unfold } from '../../ui/reshape';
|
||||
import type { Status } from '../../../shared/types';
|
||||
import { h } from '../../../portal/dom';
|
||||
import { once } from '../../../portal/ui/feedback';
|
||||
import { fmt, plural } from '../../../shared/i18n';
|
||||
import { glass } from '../../ui/glass';
|
||||
import { ic } from '../../ui/icons';
|
||||
import { waitsForConfig } from '../../people/roster';
|
||||
import type { ActCtx } from '../../people/ctx';
|
||||
import { serverOn } from '../../flows/person-acts';
|
||||
|
||||
export interface NoticeCtx {
|
||||
write: boolean;
|
||||
acts: ActCtx;
|
||||
/** Narrow the list to the people the rollout waits on. */
|
||||
waiting(): void;
|
||||
}
|
||||
|
||||
/** The notices (their words for the folded line beside each), for the people the page has. */
|
||||
function notices(st: Status, c: NoticeCtx): { el: HTMLElement; short: string }[] {
|
||||
const out: { el: HTMLElement; short: string }[] = [];
|
||||
for (const s of st.servers) {
|
||||
if (s.enabled) continue;
|
||||
const n = st.people.filter((p) => p.server === s.id).length;
|
||||
if (!n) continue;
|
||||
const on = c.write
|
||||
? (h('button', { type: 'button', class: 'btn tint sm' }, ic('play'), h('span', {}, _('Turn on'))) as HTMLButtonElement)
|
||||
: null;
|
||||
on?.addEventListener('click', () => void once(on, () => serverOn(c.acts, s)));
|
||||
const title = fmt(_('Server %s is turned off'), s.name);
|
||||
out.push({
|
||||
short: title,
|
||||
el: h(
|
||||
'div',
|
||||
{ class: 'notice warn pp-notice', role: 'status' },
|
||||
glass('server', 'orange'),
|
||||
h('div', { class: 't' }, h('b', {}, title), h('span', {}, plural(n, '%s person without access', '%s people without access'))),
|
||||
on ? h('span', { class: 'pp-notice-acts' }, on) : null,
|
||||
),
|
||||
});
|
||||
}
|
||||
const who = st.people.filter(waitsForConfig).length;
|
||||
if (who) {
|
||||
const list = h('button', { type: 'button', class: 'btn soft sm' }, h('span', {}, _('Who waits')));
|
||||
list.addEventListener('click', () => c.waiting());
|
||||
out.push({
|
||||
short: plural(who, 'New configuration for %s', 'New configuration for %s'),
|
||||
el: h(
|
||||
'div',
|
||||
{ class: 'notice warn pp-notice', role: 'status' },
|
||||
glass('refresh', 'orange'),
|
||||
h(
|
||||
'div',
|
||||
{ class: 't' },
|
||||
h('b', {}, _('New configuration')),
|
||||
h('span', {}, plural(who, '%s person has not fetched it yet', '%s people have not fetched it yet')),
|
||||
),
|
||||
h('span', { class: 'pp-notice-acts' }, list),
|
||||
),
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The notices over the list, in `box` (emptied when there are none); `open`: a phone's fold stays unfolded. */
|
||||
export function paintNotices(box: HTMLElement, st: Status, c: NoticeCtx) {
|
||||
const ns = notices(st, c);
|
||||
const key = JSON.stringify(ns.map((n) => n.el.textContent));
|
||||
if (box.dataset.key === key) return;
|
||||
box.dataset.key = key;
|
||||
const open = box.classList.contains('open');
|
||||
box.classList.toggle('many', ns.length > 1);
|
||||
// notices that come or go unfold and fold (ui/reshape.ts)
|
||||
if (!ns.length) return void refill(box, []);
|
||||
const fold = h(
|
||||
'button',
|
||||
{ type: 'button', class: 'pp-nfold', 'aria-expanded': String(open) },
|
||||
glass('pulse', 'orange'),
|
||||
h('span', { class: 'pp-nfold-t' }, ns.map((n) => n.short).join('\u00a0· ')),
|
||||
ic('chevron', 'i pp-nfold-c'),
|
||||
);
|
||||
const list = h('div', { class: 'pp-nlist' }, ...ns.map((n) => n.el));
|
||||
// shown by a class the stylesheet reads only on a phone (wider, the notices always stand): it unfolds and folds
|
||||
// as an accordion's row does (ui/reshape.ts)
|
||||
box.classList.toggle('shows', open);
|
||||
fold.addEventListener('click', () => {
|
||||
const now = !box.classList.contains('open');
|
||||
box.classList.toggle('open', now);
|
||||
fold.setAttribute('aria-expanded', String(now));
|
||||
if (getComputedStyle(fold).display === 'none') return void box.classList.toggle('shows', now);
|
||||
unfold(list, now, { is: () => box.classList.contains('shows'), set: (v) => box.classList.toggle('shows', v) });
|
||||
});
|
||||
refill(box, [fold, list]);
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
// A person's devices as the portal's cards (portal/page/devices.ts, in the
|
||||
// admin's words): each a link to its own panel (its name a real <a>, its hit
|
||||
// area stretched over the card; ⋯ and the button stay their own), its glass,
|
||||
// name and one line in its state's colour (people/diagnosis.ts deviceLine);
|
||||
// under it the last 7 days as bars, or Show set-up where the device needs it
|
||||
// (never set up, an outdated configuration, nothing it sends usable). Then
|
||||
// the card that adds one, over the limit too (an admin may). ⋯ on a card:
|
||||
// open, show its set-up, turn off or on, reset its traffic, new keys, remove.
|
||||
|
||||
import type { Device } from '../../../../shared/types';
|
||||
import { h } from '../../../../portal/dom';
|
||||
import { openMenu, type MenuItem } from '../../../../portal/ui/menu';
|
||||
import { fmt } from '../../../../shared/i18n';
|
||||
import { glass } from '../../../ui/glass';
|
||||
import { weekUse } from '../../../widgets/week-use';
|
||||
import { ic } from '../../../ui/icons';
|
||||
import { deviceLine } from '../../../people/diagnosis';
|
||||
import { deviceUrl } from '../../../shell/routes';
|
||||
import { visit } from '../../../shell/visit';
|
||||
import { showSetup } from '../../../flows/setup';
|
||||
import { addDevice } from '../../../flows/add-device';
|
||||
import { newKeys } from '../../../flows/new-keys';
|
||||
import { removeDevice, resetDeviceTraffic, toggleDevice, type DeviceActCtx } from '../../../flows/device-acts';
|
||||
import type { PersonCtx } from '../../../people/ctx';
|
||||
import { EASE_IN, SMOOTH, play } from '../../../../portal/motion';
|
||||
import { asksNow, routerDeclined } from '../../../servers/behind';
|
||||
import { replaces } from '../../../../portal/ui/carry';
|
||||
import { glide } from '../../../../portal/ui/chips-motion';
|
||||
|
||||
/** It needs its set-up shown: never set up, an outdated configuration, or nothing it sends is usable. */
|
||||
const needsSetup = (d: Device) => !d.disabled && (!d.handshake || d.config_stale || d.link?.state === 'dropped');
|
||||
|
||||
/** The last 7 days down and up over their bars; a day under the pointer puts its own numbers in their place. */
|
||||
const week = (d: Device): HTMLElement => weekUse(d.id, d.name, d.spark).el;
|
||||
|
||||
function menu(c: PersonCtx, d: Device, anchor: HTMLElement, reload: () => void) {
|
||||
const dc: DeviceActCtx = { device: d, reload };
|
||||
// calm to grave: what only shows it; what resets something of it; what stops it: off in warn, then Remove, last
|
||||
const items: (MenuItem | null)[] = [
|
||||
{ label: _('Open'), icon: 'open', run: () => visit(deviceUrl(d.id)) },
|
||||
{ label: _('Show set-up'), icon: 'qr', run: () => void showSetup({ person: c.p, device: d, now: c.now, done: reload }).then(reload) },
|
||||
null,
|
||||
{ label: _('Reset traffic'), icon: 'reset', run: () => resetDeviceTraffic(dc) },
|
||||
{
|
||||
label: _('New keys'),
|
||||
icon: 'key',
|
||||
run: () => newKeys({ person: c.p, device: d, server: c.srv, now: c.now, made: reload, setup: { done: reload } }),
|
||||
},
|
||||
null,
|
||||
d.disabled
|
||||
? { label: _('Turn on'), icon: 'play', run: () => void toggleDevice(dc, false) }
|
||||
: { label: _('Turn off'), icon: 'pause', tone: 'warn', run: () => void toggleDevice(dc, true) },
|
||||
{ label: _('Remove'), icon: 'trash', tone: 'bad', run: () => removeDevice(dc) },
|
||||
];
|
||||
// a router that waits for an answer: it is opened (where it is answered), or removed
|
||||
openMenu(anchor, d.waiting ? [items[0], null, items[items.length - 1]] : items, d.name);
|
||||
}
|
||||
|
||||
function card(c: PersonCtx, d: Device, reload: () => void): HTMLElement {
|
||||
const line = deviceLine(d, c.p, { now: c.now(), today: c.today, tz: c.st.tz });
|
||||
const stat = h(
|
||||
'span',
|
||||
{ class: `dev-stat ${line.tone ? `${line.tone}-t` : ''}`, id: `dev-st-${d.id}`, title: line.why ?? line.text },
|
||||
line.text,
|
||||
);
|
||||
const more = c.write
|
||||
? (h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
class: 'knob more',
|
||||
'aria-label': fmt(_('%s: set-up, turn off, new keys, remove'), d.name),
|
||||
'aria-haspopup': 'menu',
|
||||
},
|
||||
ic('more'),
|
||||
) as HTMLButtonElement)
|
||||
: null;
|
||||
more?.addEventListener('click', () => menu(c, d, more, reload));
|
||||
// It asks for something: where «Show set-up» would stand, one button that opens its dialog, where the question
|
||||
// is answered (a question with its answers does not fit a card). A router that waits has no set-up to show.
|
||||
const foot = asksNow(d)
|
||||
? c.write
|
||||
? h(
|
||||
'button',
|
||||
{ type: 'button', class: 'btn tint block setup-btn', onclick: () => visit(deviceUrl(d.id)) },
|
||||
ic('clock'),
|
||||
h('span', {}, _('Answer the request')),
|
||||
)
|
||||
: null
|
||||
: c.write && needsSetup(d)
|
||||
? h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
class: 'btn tint block setup-btn',
|
||||
onclick: () => void showSetup({ person: c.p, device: d, now: c.now, done: reload }).then(reload),
|
||||
},
|
||||
ic('qr'),
|
||||
h('span', {}, _('Show set-up')),
|
||||
)
|
||||
: week(d);
|
||||
return h(
|
||||
'article',
|
||||
{ class: `dev as-link${d.disabled ? ' off' : ''}`, 'data-id': d.id },
|
||||
h(
|
||||
'div',
|
||||
{ class: 'dev-top' },
|
||||
glass(d.kind, 'grey'),
|
||||
h(
|
||||
'div',
|
||||
{ class: 'dev-id' },
|
||||
h('a', { class: 'dev-name dev-a', href: deviceUrl(d.id), title: d.name, 'aria-describedby': `dev-st-${d.id}` }, d.name),
|
||||
stat,
|
||||
),
|
||||
more,
|
||||
),
|
||||
foot,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The grid a press here drew again (ui/carry.ts) moves as the portal's does (portal/page/devices.ts): a card that is
|
||||
* no more fades where it stood (180 ms EASE_IN, through a 4 px blur), the cards that stay glide to their places
|
||||
* (FLIP on SMOOTH), one that is new comes in a beat after (from nine tenths, blurred, on SMOOTH), and the grid goes
|
||||
* to its new height so the blocks under it travel with it. Each from where it stands on screen.
|
||||
*/
|
||||
function carryGrid(key: string, grid: HTMLElement) {
|
||||
const old = replaces(key, grid);
|
||||
if (!old) return;
|
||||
const o = old.getBoundingClientRect();
|
||||
const was = new Map<string, { el: HTMLElement; x: number; y: number; w: number; h: number }>();
|
||||
for (const c of old.children as Iterable<HTMLElement>) {
|
||||
const r = c.getBoundingClientRect();
|
||||
was.set(c.dataset.id ?? '#add', { el: c, x: r.left - o.left, y: r.top - o.top, w: r.width, h: r.height });
|
||||
}
|
||||
const h0 = o.height;
|
||||
requestAnimationFrame(() => {
|
||||
if (!grid.isConnected) return;
|
||||
const g = grid.getBoundingClientRect();
|
||||
const now = new Set<string>();
|
||||
for (const c of grid.children as Iterable<HTMLElement>) {
|
||||
const id = c.dataset.id ?? '#add';
|
||||
now.add(id);
|
||||
const f = was.get(id);
|
||||
const r = c.getBoundingClientRect();
|
||||
const dx = f ? f.x - (r.left - g.left) : 0;
|
||||
const dy = f ? f.y - (r.top - g.top) : 0;
|
||||
if (!f)
|
||||
play(
|
||||
c,
|
||||
[
|
||||
{ opacity: 0, transform: 'scale(.9)', filter: 'blur(6px)' },
|
||||
{ opacity: getComputedStyle(c).opacity, transform: 'none', filter: 'none' },
|
||||
],
|
||||
{
|
||||
duration: SMOOTH.duration,
|
||||
delay: 60,
|
||||
easing: SMOOTH.easing,
|
||||
fill: 'backwards',
|
||||
},
|
||||
);
|
||||
else if (Math.abs(dx) > 0.5 || Math.abs(dy) > 0.5)
|
||||
play(c, [{ transform: `translate(${dx}px, ${dy}px)` }, { transform: 'none' }], {
|
||||
duration: SMOOTH.duration,
|
||||
easing: SMOOTH.easing,
|
||||
});
|
||||
}
|
||||
for (const [id, f] of was) {
|
||||
if (now.has(id)) continue;
|
||||
const ghost = f.el.cloneNode(true) as HTMLElement;
|
||||
ghost.setAttribute('aria-hidden', 'true');
|
||||
ghost.inert = true;
|
||||
Object.assign(ghost.style, {
|
||||
position: 'absolute',
|
||||
left: `${f.x}px`,
|
||||
top: `${f.y}px`,
|
||||
width: `${f.w}px`,
|
||||
height: `${f.h}px`,
|
||||
margin: '0',
|
||||
pointerEvents: 'none',
|
||||
});
|
||||
grid.append(ghost);
|
||||
play(
|
||||
ghost,
|
||||
[
|
||||
{ opacity: 1, filter: 'blur(0px)' },
|
||||
{ opacity: 0, filter: 'blur(4px)' },
|
||||
],
|
||||
{ duration: 180, easing: EASE_IN, fill: 'forwards' },
|
||||
).finished.then(
|
||||
() => ghost.remove(),
|
||||
() => ghost.remove(),
|
||||
);
|
||||
}
|
||||
glide(grid, h0);
|
||||
});
|
||||
}
|
||||
|
||||
/** The cards and the add card. */
|
||||
export function deviceGrid(c: PersonCtx, reload: () => void): HTMLElement {
|
||||
const over = c.p.devices.length >= c.p.device_limit;
|
||||
const grid = h(
|
||||
'div',
|
||||
{ class: 'dgrid' },
|
||||
// a router asked for and turned down is not the admin's to see: it stays on its owner's page until they remove it
|
||||
...c.p.devices.filter((d) => !routerDeclined(d)).map((d) => card(c, d, reload)),
|
||||
c.write
|
||||
? h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
class: 'dev add',
|
||||
title: over ? _('Over the limit: admins can still add') : null,
|
||||
onclick: () => addDevice({ person: c.p, server: c.srv, now: c.now, added: reload, people: c.st.people, servers: c.st.servers }),
|
||||
},
|
||||
glass('plus'),
|
||||
h('span', {}, over ? _('Add over the limit') : _('Add device')),
|
||||
)
|
||||
: null,
|
||||
);
|
||||
carryGrid(`dgrid:${c.p.id}`, grid);
|
||||
return grid;
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
// A person's head, on their page: their glass and name; under it one line —
|
||||
// their phrase in its state's colour (the only place it is said), their server
|
||||
// (a link to it) only when there is more than one; under that the admin's note as a
|
||||
// quiet line of its own, edited where it stands (a press: the note sheet). On the
|
||||
// right the phrase's one action (people/lines.ts, done at once with Undo),
|
||||
// their invite (Link once they have devices, Invite before), and ⋯: move to
|
||||
// another server, rename, the note, pause or resume, remove (asked first). Their name is also changed where it
|
||||
// stands: a click on it turns it into its own field (ui/rename-title.ts), as a device's is in its dialog.
|
||||
// A read-only login sees the facts and «View only».
|
||||
|
||||
import { h } from '../../../../portal/dom';
|
||||
import { openMenu, type MenuItem } from '../../../../portal/ui/menu';
|
||||
import { openSheet } from '../../../../portal/ui/sheet';
|
||||
import { once } from '../../../../portal/ui/feedback';
|
||||
import { api } from '../../../api';
|
||||
import { fmt, plural } from '../../../../shared/i18n';
|
||||
import { nameHelp } from '../../../netcheck';
|
||||
import { glass } from '../../../ui/glass';
|
||||
import { ic } from '../../../ui/icons';
|
||||
import { fact, knob, pageHead } from '../../../ui/page-head';
|
||||
import { notify } from '../../../ui/toast';
|
||||
import { href, settingsUrl } from '../../../shell/routes';
|
||||
import { leaveTo } from '../../../shell/sheets';
|
||||
import { personLine } from '../../../people/lines';
|
||||
import { askView } from '../../../flows/ask';
|
||||
import { openInvite } from '../../../flows/invite';
|
||||
import { movePerson } from '../../../flows/move-person';
|
||||
import { textSheet } from '../../../flows/text-sheet';
|
||||
import { editableTitle, renameTitle, type RenameTitle } from '../../../ui/rename-title';
|
||||
import { actButton, pause, runAct } from '../../../flows/person-acts';
|
||||
import type { PersonCtx } from '../../../people/ctx';
|
||||
|
||||
function editNote(c: PersonCtx) {
|
||||
textSheet({
|
||||
title: _('Note'),
|
||||
value: c.p.note ?? '',
|
||||
placeholder: _('Only you see this'),
|
||||
long: true,
|
||||
max: 500,
|
||||
refuse: () => null,
|
||||
save: async (v) => {
|
||||
if (!(await c.patch({ note: v }, v ? _('Note saved') : _('Note removed')))) throw new Error(_('The router did not take it.'));
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/** Their name is changed where it stands, as a device's is (ui/rename-title.ts): a click on it, or Rename in ⋯. */
|
||||
const renaming = (c: PersonCtx, head: HTMLElement): RenameTitle => ({
|
||||
head,
|
||||
name: c.p.name,
|
||||
label: fmt(_('Rename %s'), c.p.name),
|
||||
free: { max: 48 },
|
||||
refuse: (v) => {
|
||||
const r = nameHelp(
|
||||
v,
|
||||
c.st.people.filter((x) => x.id !== c.p.id).map((x) => x.name),
|
||||
);
|
||||
return r.bad ? r.text : null;
|
||||
},
|
||||
save: async (v) => {
|
||||
if (!(await c.patch({ name: v }, fmt(_('Renamed: %s'), v)))) throw new Error(_('The router did not take it.'));
|
||||
},
|
||||
});
|
||||
|
||||
function remove(c: PersonCtx) {
|
||||
const p = c.p;
|
||||
openSheet(() =>
|
||||
askView({
|
||||
icon: 'trash',
|
||||
tone: 'red',
|
||||
title: fmt(_('Remove %s?'), p.name),
|
||||
text: [
|
||||
p.devices.length
|
||||
? fmt(
|
||||
_('Their link and %s stop working at once: %s.'),
|
||||
plural(p.devices.length, '%s device', '%s devices'),
|
||||
p.devices.map((d) => d.name).join(', '),
|
||||
)
|
||||
: _('Their link stops working at once.'),
|
||||
' ',
|
||||
_('Only a backup brings them back.'),
|
||||
],
|
||||
action: _('Remove'),
|
||||
cls: 'red',
|
||||
run: async () => {
|
||||
await api.personDelete(p.id);
|
||||
notify(fmt(_('%s removed'), p.name), 'success', 3000);
|
||||
// the list without them: their panel shuts once the question has gone
|
||||
void c.acts.reload();
|
||||
leaveTo(href({ view: 'people' }));
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function menu(c: PersonCtx, anchor: HTMLElement) {
|
||||
const p = c.p;
|
||||
// calm to grave: what is theirs alone (the name, the note), what moves them (their devices fetch a new
|
||||
// configuration), what stops them: Pause in warn, then Remove, last
|
||||
const items: (MenuItem | null)[] = [
|
||||
{
|
||||
label: _('Rename'),
|
||||
icon: 'edit',
|
||||
run: () => {
|
||||
const head = anchor.closest<HTMLElement>('.ph');
|
||||
if (head) renameTitle(renaming(c, head));
|
||||
},
|
||||
},
|
||||
{ label: p.note ? _('Edit note') : _('Add note'), icon: 'file', run: () => editNote(c) },
|
||||
null,
|
||||
c.st.servers.length > 1
|
||||
? {
|
||||
label: _('Move to another server'),
|
||||
icon: 'terminal',
|
||||
run: () => movePerson({ person: p, st: c.st, moved: () => void c.acts.reload() }),
|
||||
}
|
||||
: null,
|
||||
null,
|
||||
p.paused
|
||||
? { label: _('Resume'), icon: 'play', run: () => void pause(c.acts, p, false) }
|
||||
: { label: _('Pause'), icon: 'pause', tone: 'warn', run: () => void pause(c.acts, p, true) },
|
||||
{ label: _('Remove'), icon: 'trash', tone: 'bad', run: () => remove(c) },
|
||||
];
|
||||
openMenu(anchor, items, p.name);
|
||||
}
|
||||
|
||||
/** The head: their name, their state in a line (its one action beside), the note under it. */
|
||||
export function personHead(c: PersonCtx): HTMLElement {
|
||||
const p = c.p;
|
||||
const line = personLine(p, { today: c.today, now: c.now() });
|
||||
const acts: HTMLElement[] = [];
|
||||
if (c.write) {
|
||||
if (line.act && line.act.id !== 'invite') {
|
||||
const a = line.act;
|
||||
const b = actButton(a, 'tint');
|
||||
b.addEventListener('click', () => void once(b, () => runAct(a, p, c.acts)));
|
||||
acts.push(b);
|
||||
}
|
||||
if (p.has_link)
|
||||
acts.push(
|
||||
h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
class: 'btn soft',
|
||||
onclick: () => void openInvite({ person: p, server: c.srv?.name ?? '', changed: () => void c.acts.reload() }),
|
||||
},
|
||||
ic('link'),
|
||||
h('span', {}, p.devices.length ? _('Link') : _('Invite')),
|
||||
),
|
||||
);
|
||||
const more = knob('more', _('Move, rename, note, pause, remove'));
|
||||
more.setAttribute('aria-haspopup', 'menu');
|
||||
more.addEventListener('click', () => menu(c, more));
|
||||
acts.push(more);
|
||||
}
|
||||
const head = pageHead({ icon: glass('person', 'grey'), title: p.name, acts });
|
||||
if (c.write) editableTitle(() => renaming(c, head));
|
||||
// the state; their speed now is the Traffic card's «Now»
|
||||
const facts = [
|
||||
fact(h('span', { class: `ph-state ${line.tone ? `${line.tone}-t` : ''}`, title: line.why ?? null }, line.text)),
|
||||
// with one server its name says nothing
|
||||
c.srv && c.st.servers.length > 1 ? fact(h('a', { class: 'ph-link', href: settingsUrl(undefined, c.srv.id) }, c.srv.name)) : null,
|
||||
c.write ? null : fact([ic('eye'), _('View only')]),
|
||||
];
|
||||
head.querySelector('.ph-sub')?.replaceChildren(...facts.filter((f): f is HTMLElement => !!f));
|
||||
// the note: a line of its own under the head's row, in the words' colour, no frame; a press edits it
|
||||
if (p.note) {
|
||||
const note = c.write
|
||||
? h(
|
||||
'button',
|
||||
{ type: 'button', class: 'ph-note', 'aria-label': fmt(_('Note: %s. Edit'), p.note), onclick: () => editNote(c) },
|
||||
h('span', {}, p.note),
|
||||
ic('edit', 'i ph-note-ed'),
|
||||
)
|
||||
: h('p', { class: 'ph-note' }, h('span', {}, p.note));
|
||||
// under the name and its state, in their own column: it stays with them wherever the actions go (a narrow
|
||||
// head puts them on a line of their own, and the note stood under the buttons then)
|
||||
head.querySelector('.ph-t')?.append(h('div', { class: 'ph-noterow' }, note));
|
||||
}
|
||||
return head;
|
||||
}
|
||||
@@ -0,0 +1,499 @@
|
||||
// A person as a page of its own inside People (people?id=): what they have and what they may do, every part on the
|
||||
// page at once. The way back and ×; the head (head.ts: their phrase, its one action, their link, ⋯) across; under it
|
||||
// two columns, as the portal's (devices on the left, access on the right): the main column has their devices as
|
||||
// cards (devices.ts, two across) under «Devices 3 of − 4 +» (the limit in the block's head, where the count stands),
|
||||
// their traffic as a device's page has it (device/traffic.ts: the week, this month, all time, the speed now), their
|
||||
// places (rows with strips of 7 days) and their latest events as the Log's rows; the side column is one «Access»
|
||||
// stack that stays in sight while the page scrolls: the term, the data limit and what they reach
|
||||
// (widgets/term.ts, limit-meter.ts, reach.ts), each a card with its head inside (one line while there is
|
||||
// nothing more to say: no end date). Narrower: one column, the access stack first. ?s=<block> brings one
|
||||
// into view, ?sheet=add opens adding a device, ?sheet=places their places' close-up (&pick=: on one device).
|
||||
//
|
||||
// Live: the status comes from the page; their events (after the newest it has) and their days are read on opening,
|
||||
// with every status the page takes and after a change made here; their speed now from the meter once a second,
|
||||
// only while a device of theirs is online and the panel is in the page. A part holding the focus (a field being
|
||||
// edited, a handle held) is left alone by a background repaint.
|
||||
//
|
||||
// What changes how their access works (what they reach, the limit, how many devices) is not made by one
|
||||
// press: it waits (people/draft.ts), the page shows them as they would be with «not applied» on the part's head, and
|
||||
// the dock at the window's foot applies everything at once or lets it go. A name, a note and the one-tap actions
|
||||
// (pause, extend, more data this month) are made at once, as before. Leaving while changes wait is asked about.
|
||||
|
||||
import { openCloseUp } from '../../../flows/places-closeup';
|
||||
import { plain } from '../../../shell/sheets';
|
||||
import { refill } from '../../../ui/reshape';
|
||||
import type { DayUsage, LogEvent, Person } from '../../../../shared/types';
|
||||
import { api, type PersonPatch } from '../../../api';
|
||||
import { h } from '../../../../portal/dom';
|
||||
import { todayOf } from '../../../../shared/format';
|
||||
import { fill, fmt, num, plural } from '../../../../shared/i18n';
|
||||
import { closeSheet, openSheet } from '../../../../portal/ui/sheet';
|
||||
import { askView } from '../../../flows/ask';
|
||||
import { draftCount, draftParts, draftRefetch, preview, split, stageDraft, type Draft, type DraftPart } from '../../../people/draft';
|
||||
import { pendingDock } from '../../settings/pending-dock';
|
||||
import { errorText, notify } from '../../../ui/toast';
|
||||
import { blockHead } from '../../../ui/page-head';
|
||||
import { pageBar } from '../../../ui/subpage';
|
||||
import { stepper } from '../../../ui/stepper';
|
||||
import { ic } from '../../../ui/icons';
|
||||
import { focusInside, type Poller } from '../../../state/poller';
|
||||
import { LiveMeter } from '../../../state/meter';
|
||||
import { pollMeter } from '../../../state/meterpoll';
|
||||
import { routerDay } from '../../../events/clock';
|
||||
import { say } from '../../../shell/toast';
|
||||
import { deviceUrl, peopleAt, placesUrl } from '../../../shell/routes';
|
||||
import { addDevice } from '../../../flows/add-device';
|
||||
import { listOf } from '../../../people/route';
|
||||
import type { ActCtx, PersonCtx } from '../../../people/ctx';
|
||||
import { termBlock } from '../../../widgets/term';
|
||||
import { limitMeter, limitPeriod } from '../../../widgets/limit-meter';
|
||||
import { reachFork, reachMark } from '../../../widgets/reach';
|
||||
import { feedShort, logLink } from '../../../widgets/feed';
|
||||
import { placeRow } from '../../../widgets/place-rows';
|
||||
import type { PeopleHost } from '../host';
|
||||
import { personHead } from './head';
|
||||
import { deviceGrid } from './devices';
|
||||
import { personUse, trafficCard, type TrafficCard } from '../device/traffic';
|
||||
|
||||
/** Their events the panel reads (30 days of them). */
|
||||
const LIMIT = 3000;
|
||||
const DAYS30 = 30 * 86400;
|
||||
|
||||
type Block = 'use' | 'devices' | 'term' | 'traffic' | 'reach' | 'places' | 'log';
|
||||
|
||||
/** A part of the access stack: its card with its head inside, first. */
|
||||
function part(head: HTMLElement, card: HTMLElement): HTMLElement {
|
||||
card.classList.add('pp-part');
|
||||
card.prepend(head);
|
||||
return card;
|
||||
}
|
||||
|
||||
export class PersonPanel {
|
||||
readonly kind = 'person';
|
||||
el = h('article', { class: 'kt-panel pp-person' });
|
||||
private c!: PersonCtx;
|
||||
private events: LogEvent[] = [];
|
||||
private days: DayUsage[] = [];
|
||||
private gone = false;
|
||||
/** Reading again after a change made here: the status that comes meanwhile is drawn with the events, once. */
|
||||
private batching = false;
|
||||
private headBox = h('div', { class: 'kt-phead' });
|
||||
private box: Record<Block, HTMLElement>;
|
||||
/** Their Traffic card, its speed now fed by the meter. */
|
||||
private traffic?: TrafficCard;
|
||||
private meter = new LiveMeter();
|
||||
private poll: Poller<unknown>;
|
||||
/** Service lines of their feed left unfolded. */
|
||||
private open = new Set<string>();
|
||||
/** The person as the router has them (`c.p` is them with what waits over it). */
|
||||
private real!: Person;
|
||||
/** Their changes that wait for «Apply». */
|
||||
private draft: Draft = {};
|
||||
private applying = false;
|
||||
private dock = pendingDock({ apply: () => void this.apply(), cancel: () => this.forget(), column: () => this.el });
|
||||
|
||||
constructor(
|
||||
readonly id: string,
|
||||
private host: PeopleHost,
|
||||
close: () => void,
|
||||
) {
|
||||
const sec = (cls: string) => h('section', { class: `kt-b ${cls}` });
|
||||
const b = (this.box = {
|
||||
use: sec('b-use'),
|
||||
devices: sec('b-devices'),
|
||||
term: sec('b-term'),
|
||||
traffic: sec('b-traffic'),
|
||||
reach: sec('b-reach'),
|
||||
places: sec('b-places'),
|
||||
log: sec('b-log'),
|
||||
});
|
||||
this.el.append(
|
||||
pageBar({ back: _('People'), to: peopleAt(listOf(host.route())), close: () => this.leave(close) }),
|
||||
this.headBox,
|
||||
h(
|
||||
'div',
|
||||
{ class: 'pp-cols' },
|
||||
// their traffic first, then the devices it is made of (the owner, 2026-11-12: «траффик должен идти выше devices»)
|
||||
h('div', { class: 'pp-main kt-blocks' }, b.use, b.devices, b.places, b.log),
|
||||
h(
|
||||
'aside',
|
||||
{ class: 'pp-side', 'aria-label': _('Access') },
|
||||
blockHead(_('Access')),
|
||||
h('div', { class: 'pp-stack' }, b.term, b.traffic, b.reach),
|
||||
),
|
||||
),
|
||||
);
|
||||
// a link that leads off their page while changes wait is held and asked about first
|
||||
this.el.addEventListener(
|
||||
'click',
|
||||
(e) => {
|
||||
if (!draftCount(this.draft) || e.defaultPrevented || !plain(e)) return;
|
||||
const a = e.composedPath().find((x): x is HTMLAnchorElement => x instanceof HTMLAnchorElement && !!x.href);
|
||||
if (!a || a.target === '_blank' || a.hasAttribute('download')) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
this.leave(() => a.click());
|
||||
},
|
||||
true,
|
||||
);
|
||||
this.take();
|
||||
this.paint(false);
|
||||
void this.load(false);
|
||||
this.poll = pollMeter(
|
||||
this.meter,
|
||||
() => this.el.isConnected && !this.gone && this.c.p.online > 0 && !!this.c.srv?.enabled,
|
||||
() => this.paintSpeed(),
|
||||
);
|
||||
}
|
||||
|
||||
destroy() {
|
||||
this.gone = true;
|
||||
this.poll.stop();
|
||||
// left by a way that could not ask (the browser's Back): what waited is gone with the page, and said
|
||||
if (draftCount(this.draft))
|
||||
notify(plural(draftCount(this.draft), '%s change was not applied', '%s changes were not applied'), 'warning');
|
||||
this.draft = {};
|
||||
this.syncDock();
|
||||
}
|
||||
|
||||
/** How many of their changes wait for «Apply». */
|
||||
waiting(): number {
|
||||
return draftCount(this.draft);
|
||||
}
|
||||
|
||||
/** Leave their page: asked first while changes wait («Leave» lets them go). */
|
||||
leave(go: () => void) {
|
||||
const n = draftCount(this.draft);
|
||||
if (!n) return go();
|
||||
openSheet(() =>
|
||||
askView({
|
||||
icon: 'out',
|
||||
tone: 'orange',
|
||||
title: _('Leave without applying?'),
|
||||
text: [plural(n, '%s change is not applied: it will be lost.', '%s changes are not applied: they will be lost.')],
|
||||
action: _('Leave'),
|
||||
cls: 'warn',
|
||||
run: async () => {
|
||||
this.draft = {};
|
||||
this.syncDock();
|
||||
closeSheet(true);
|
||||
go();
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/** «Cancel»: every part goes back to what the router has. */
|
||||
private forget() {
|
||||
this.draft = {};
|
||||
this.syncDock();
|
||||
if (this.take()) this.paint(false);
|
||||
}
|
||||
|
||||
private syncDock() {
|
||||
const n = this.real ? draftRefetch(this.real, this.draft) : 0;
|
||||
this.dock.sync({ changes: draftCount(this.draft), refetch: { n, paused: 0, fresh: 0, people: n ? 1 : 0 }, breaks: false });
|
||||
}
|
||||
|
||||
/** «Apply»: everything that waits in one person_update; asked first when devices fetch their configuration again. */
|
||||
private async apply() {
|
||||
const draft = this.draft;
|
||||
const count = draftCount(draft);
|
||||
if (!count || this.applying) return;
|
||||
const save = async () => {
|
||||
this.applying = true;
|
||||
try {
|
||||
await api.personUpdate(this.id, draft);
|
||||
this.draft = {};
|
||||
this.syncDock();
|
||||
say(plural(count, '%s change applied', '%s changes applied'));
|
||||
await this.reload();
|
||||
return true;
|
||||
} catch (e) {
|
||||
notify(errorText(e), 'error', 10000);
|
||||
return false;
|
||||
} finally {
|
||||
this.applying = false;
|
||||
}
|
||||
};
|
||||
const n = draftRefetch(this.real, draft);
|
||||
if (!n) return void save();
|
||||
openSheet(() =>
|
||||
askView({
|
||||
icon: 'refresh',
|
||||
tone: 'orange',
|
||||
title: fmt(_('Apply the changes for %s?'), this.real.name),
|
||||
text: [
|
||||
plural(
|
||||
n,
|
||||
'%s device fetches its configuration again. Until then it works the old way.',
|
||||
'%s devices fetch their configuration again. Until then they work the old way.',
|
||||
),
|
||||
],
|
||||
action: _('Apply'),
|
||||
cls: 'warn',
|
||||
run: async () => {
|
||||
if (await save()) closeSheet();
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/** What the address asks to open on arrival: a block brought into view, adding a device, their places' close-up. */
|
||||
arrive(s?: string, sheet?: string) {
|
||||
const box = s && s in this.box ? this.box[s as Block] : null;
|
||||
if (box) requestAnimationFrame(() => box.scrollIntoView({ block: 'start' }));
|
||||
if (sheet === 'add' && this.c.write) this.addDevice();
|
||||
else if (sheet === 'places') this.openPlaces(new URLSearchParams(location.search).get('pick'));
|
||||
}
|
||||
|
||||
/** Their devices with places: the one online, else the one seen last, first. */
|
||||
private placed(): string[] {
|
||||
const pts = this.c.st.geo.points;
|
||||
const newest = (id: string) => Math.max(...pts.filter((x) => x.device === id).map((x) => (x.online ? Infinity : x.ts)));
|
||||
return this.c.p.devices
|
||||
.filter((d) => pts.some((x) => x.device === d.id))
|
||||
.map((d) => d.id)
|
||||
.sort((a, b) => newest(b) - newest(a));
|
||||
}
|
||||
|
||||
/** Their places' close-up: all their devices at once when there are several, else the one; `pick`: that one. */
|
||||
private openPlaces(pick?: string | null) {
|
||||
const devs = this.placed();
|
||||
if (!this.c.st.geo.enabled || !devs.length) return;
|
||||
const id = pick && devs.includes(pick) ? pick : devs.length > 1 ? null : devs[0];
|
||||
openCloseUp(id, this.c.st, { person: this.c.p.id, devices: devs });
|
||||
}
|
||||
|
||||
private addDevice() {
|
||||
addDevice({
|
||||
person: this.c.p,
|
||||
server: this.c.srv,
|
||||
now: this.c.now,
|
||||
added: () => void this.reload(),
|
||||
people: this.c.st.people,
|
||||
servers: this.c.st.servers,
|
||||
});
|
||||
}
|
||||
|
||||
/** The person in the page's status; false when they are not there (removed). */
|
||||
private take(): boolean {
|
||||
const st = this.host.st();
|
||||
const real = st.people.find((x) => x.id === this.id);
|
||||
if (!real) return false;
|
||||
this.real = real;
|
||||
// what the router has by now stops waiting (the same change made elsewhere)
|
||||
this.draft = stageDraft(this.draft, real, {});
|
||||
const p = preview(real, this.draft);
|
||||
const acts: ActCtx = {
|
||||
st: () => this.host.st(),
|
||||
today: () => this.c.today,
|
||||
now: this.host.now,
|
||||
reload: () => this.reload(),
|
||||
// «Change the limit» (a limit for the whole term reached): the limit is on the panel, edited in place
|
||||
limit: () => {
|
||||
this.box.traffic.scrollIntoView({ block: 'nearest' });
|
||||
this.box.traffic.querySelector<HTMLElement>('.kt-lim-b')?.click();
|
||||
},
|
||||
};
|
||||
this.c = {
|
||||
st,
|
||||
p,
|
||||
srv: st.servers.find((s) => s.id === p.server),
|
||||
events: this.events,
|
||||
days: this.days,
|
||||
write: this.host.write,
|
||||
today: todayOf(this.days.length ? this.days : st.series) || routerDay(this.host.now(), st.tz),
|
||||
now: this.host.now,
|
||||
patch: (patch, said) => this.patch(patch, said),
|
||||
acts,
|
||||
};
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Their events (after the newest it has when `live`) and their days. */
|
||||
private async load(live: boolean) {
|
||||
const st = this.host.st();
|
||||
const newest = this.events.length ? this.events[this.events.length - 1].ts : 0;
|
||||
const since = live && newest ? newest - 1 : st.now - DAYS30 - 1;
|
||||
const [ev, use] = await Promise.all([
|
||||
api.events(LIMIT, this.id, since).then(
|
||||
(r) => r.events,
|
||||
() => null,
|
||||
),
|
||||
api.personUsage(this.id, 31).then(
|
||||
(r) => r.person,
|
||||
() => this.days,
|
||||
),
|
||||
]);
|
||||
if (this.gone) return;
|
||||
const key = (e: LogEvent) => `${e.ts}|${e.type}|${e.device ?? ''}|${e.detail ?? ''}`;
|
||||
const had = new Set(this.events.map(key));
|
||||
const fresh = ev ?? [];
|
||||
const events = live && newest && ev ? [...this.events, ...fresh.filter((e) => !had.has(key(e)))] : (ev ?? this.events);
|
||||
this.events = events.filter((e) => e.ts >= st.now - DAYS30);
|
||||
this.days = use;
|
||||
if (this.take()) this.paint(live);
|
||||
}
|
||||
|
||||
/** Read everything again now (after a change made here). */
|
||||
private async reload() {
|
||||
// one repaint for the change: the page's new status is taken in, drawn once their events are read too
|
||||
this.batching = true;
|
||||
try {
|
||||
await this.host.reload();
|
||||
} finally {
|
||||
this.batching = false;
|
||||
}
|
||||
await this.load(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* A change made on the page. What changes how their access works waits for «Apply» (drawn at once, as it would
|
||||
* be); the rest (a name, a note, a one-tap action) is saved and the router's answer drawn; false when the router
|
||||
* refused (said in a toast).
|
||||
*/
|
||||
private async patch(all: PersonPatch, said?: string): Promise<boolean> {
|
||||
const { waits, now: patch } = split(all);
|
||||
if (draftCount(waits)) {
|
||||
this.draft = stageDraft(this.draft, this.real, waits);
|
||||
this.syncDock();
|
||||
if (this.take()) this.paint(false);
|
||||
}
|
||||
if (!Object.keys(patch).length) return true;
|
||||
try {
|
||||
await api.personUpdate(this.id, patch);
|
||||
if (said) say(said);
|
||||
await this.reload();
|
||||
return true;
|
||||
} catch (e) {
|
||||
notify(errorText(e), 'error', 10000);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** A new status from the page; `quiet`: a periodic one. */
|
||||
fresh(quiet: boolean) {
|
||||
if (!this.take() || this.batching) return;
|
||||
// a periodic one: drawn once, with their new events
|
||||
if (quiet) void this.load(true);
|
||||
else this.paint(false);
|
||||
}
|
||||
|
||||
private put(box: HTMLElement, quiet: boolean, ...kids: (Node | null)[]) {
|
||||
// a part being edited (a field, a handle held, a native picker) is left alone by a background repaint
|
||||
if (quiet && (focusInside(box) || box.querySelector('.held'))) return;
|
||||
// what changes unfolds or folds and morphs, never jumps (ui/reshape.ts)
|
||||
refill(
|
||||
box,
|
||||
kids.filter((k): k is Node => !!k),
|
||||
);
|
||||
}
|
||||
|
||||
private paint(quiet: boolean) {
|
||||
const c = this.c;
|
||||
const p = c.p;
|
||||
const b = this.box;
|
||||
// «not applied» beside the name of each part that has a change waiting
|
||||
const waits = draftParts(this.draft);
|
||||
const head = (part: DraftPart, el: HTMLElement): HTMLElement => {
|
||||
if (waits.has(part)) el.querySelector('h2')?.after(h('span', { class: 'kt-wait' }, h('span', { class: 'reimp' }, _('not applied'))));
|
||||
return el;
|
||||
};
|
||||
this.put(this.headBox, quiet, personHead(c));
|
||||
// their traffic as a device's page has it (their devices summed): the week's bars, this month, all time, the
|
||||
// speed now while they are online; the card stays across repaints, its numbers morph when they change
|
||||
if (this.traffic) this.traffic.set(personUse(p));
|
||||
else {
|
||||
this.traffic = trafficCard(personUse(p), `p:${p.id}`, p.name);
|
||||
this.put(b.use, quiet, blockHead(_('Traffic')), this.traffic.el);
|
||||
}
|
||||
this.el.setAttribute('aria-label', p.name);
|
||||
this.put(
|
||||
b.devices,
|
||||
quiet,
|
||||
head(
|
||||
'devices',
|
||||
blockHead(
|
||||
_('Devices'),
|
||||
// «3 of − 4 +»: the count, and the limit changed where it stands
|
||||
fill<string | HTMLElement>(
|
||||
_('%s of %s'),
|
||||
num(p.devices.length),
|
||||
stepper(
|
||||
{
|
||||
value: p.device_limit,
|
||||
label: _('Device limit'),
|
||||
min: Math.max(1, p.devices.length),
|
||||
max: 32,
|
||||
floorWhy: _('To lower the limit, remove a device first'),
|
||||
change: (n) => c.patch({ device_limit: String(n) }),
|
||||
},
|
||||
c.write,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
p.devices.length || c.write ? deviceGrid(c, () => void this.reload()) : h('div', { class: 'card kt-none' }, _('No devices yet')),
|
||||
);
|
||||
// the access stack: each part a card with its head inside
|
||||
this.put(b.term, quiet, part(blockHead(_('Term'), p.expires ? undefined : _('No end date')), termBlock(c)));
|
||||
this.put(b.traffic, quiet, part(head('limit', blockHead(_('Usage'), undefined, limitPeriod(c))), limitMeter(c)));
|
||||
this.put(b.reach, quiet, part(head('reach', blockHead(_('What they reach'), undefined, reachMark(c))), reachFork(c)));
|
||||
this.put(b.places, quiet, ...this.places());
|
||||
this.put(
|
||||
b.log,
|
||||
quiet,
|
||||
blockHead(_('Latest'), undefined, logLink({ person: p.id })),
|
||||
feedShort(c.st, c.events, { own: p.id, open: this.open, toggled: () => this.paint(false) }),
|
||||
);
|
||||
this.paintSpeed();
|
||||
}
|
||||
|
||||
/** Where their devices are: a row a device at its newest place, with the strip of the last 7 days. */
|
||||
private places(): (Node | null)[] {
|
||||
const c = this.c;
|
||||
const st = c.st;
|
||||
if (!st.geo.enabled) return [];
|
||||
const rows = c.p.devices
|
||||
.map((d) => {
|
||||
const pt = st.geo.points.filter((x) => x.device === d.id).sort((a, b) => Number(b.online) - Number(a.online) || b.ts - a.ts)[0];
|
||||
return pt ? placeRow({ st, pt, p: c.p, d, events: c.events, range: '7d', href: deviceUrl(d.id), own: true }) : null;
|
||||
})
|
||||
.filter((r): r is HTMLElement => !!r);
|
||||
// on the map: the places' close-up over the page, all their devices or one picked in it (a new tab: the People map)
|
||||
const onMap = h(
|
||||
'a',
|
||||
{
|
||||
class: 'pill-link',
|
||||
href: placesUrl({ person: c.p.id }),
|
||||
onclick: (e: Event) => {
|
||||
if (!plain(e)) return;
|
||||
e.preventDefault();
|
||||
this.openPlaces();
|
||||
},
|
||||
},
|
||||
_('On the map'),
|
||||
ic('chevron'),
|
||||
);
|
||||
return [
|
||||
blockHead(_('Places'), _('7 days'), rows.length ? onMap : null),
|
||||
rows.length
|
||||
? h('div', { class: 'olist pl-list kt-plist' }, ...rows)
|
||||
: h('div', { class: 'card kt-none' }, _('Their devices have not connected from a known place yet.')),
|
||||
];
|
||||
}
|
||||
|
||||
/** A new second of the meter: their speed now in the Traffic card, while a device of theirs is online. */
|
||||
private paintSpeed() {
|
||||
const c = this.c;
|
||||
if (!this.traffic) return;
|
||||
if (!c.p.online || !c.srv?.enabled) return this.traffic.speed(null);
|
||||
const s = this.meter.speed(
|
||||
c.srv.id,
|
||||
Date.now(),
|
||||
c.p.devices.map((d) => d.id),
|
||||
);
|
||||
this.traffic.speed(s.pts.length ? [s.rx, s.tx] : 'wait');
|
||||
}
|
||||
}
|
||||
Loaded 100 of 788 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user