Dawnline 0.11.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 / ucode static checks (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 24.10) (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 25.12) (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 / ucode static checks (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 24.10) (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 25.12) (push) Blocked by required conditions
- Russian translation. The admin pages, the LuCI menu and the router's messages (errors, Health checks, update steps, the service log) come in Russian with the new luci-i18n-dawnline-ru package, released beside the app. LuCI shows it when its language is Russian, or "auto" with a Russian browser - The translation installs with install.sh when LuCI is in Russian (or with --lang ru), follows every Dawnline update and rollback, and can be added or removed in Components → Dawnline → Translation - The portal speaks the visitor's language: it opens in the system's language and switches between English and Russian in place, from the language pill beside its QR code. It carries its own translation and needs no package - Set-up steps quote the apps' own menus word for word, in Russian too: AmneziaVPN is "+ → Insert → Continue" (it has no "Add server"), and the Mac and Windows menus of WireGuard and AmneziaWG have their real names - Questions in the portal (Reconnect, Remove) read from the left edge and close with Cancel, without × - Numbers, sizes and dates follow the page's language. A server that can't start says why in one sentence; event details and service log lines read as whole sentences - README in Russian (README_ru.md). rules/i18n.md: how strings are written and translated; CI checks the catalogs (npm run i18n:check)
This commit is contained in:
1 parent
caed976e63
commit
2f2aaf6c34
173 files changed
+25645
-2823
No files matched your search
+107
-91
@@ -11,6 +11,7 @@ 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];
|
||||
|
||||
@@ -26,23 +27,23 @@ export const homeAccess = (p: Person) => p.access === 'both' || (p.access === 'l
|
||||
/* ---------- Home services ---------- */
|
||||
|
||||
export function serviceDialog(sv: Service | null, prefill: Partial<Service>, onSaved: () => unknown) {
|
||||
const name = input(sv?.name ?? prefill.name ?? '', { placeholder: 'NAS' });
|
||||
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',
|
||||
placeholder: _('All ports, or e.g. 445, 5000'),
|
||||
class: 'cbi-input-text dl-mono',
|
||||
});
|
||||
const nameRow = liveField('Name', 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));
|
||||
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 ? `Edit ${sv.name}` : 'Add service',
|
||||
sv ? fmt(_('Edit %s'), sv.name) : _('Add service'),
|
||||
[nameRow, addrRow, portsRow],
|
||||
[
|
||||
cancelButton(),
|
||||
' ',
|
||||
button(
|
||||
'Save',
|
||||
_('Save'),
|
||||
async () => {
|
||||
const bad = firstBad([nameRow, addrRow, portsRow]);
|
||||
if (bad) {
|
||||
@@ -50,7 +51,7 @@ export function serviceDialog(sv: Service | null, prefill: Partial<Service>, onS
|
||||
return;
|
||||
}
|
||||
const list = ports.value.split(/[ ,]+/).filter(Boolean);
|
||||
if (await attempt(() => api.serviceSet(sv?.id ?? '', name.value, addr.value, list), 'Saved')) {
|
||||
if (await attempt(() => api.serviceSet(sv?.id ?? '', name.value, addr.value, list), _('Saved'))) {
|
||||
closeModal();
|
||||
onSaved();
|
||||
}
|
||||
@@ -61,41 +62,48 @@ export function serviceDialog(sv: Service | null, prefill: Partial<Service>, onS
|
||||
);
|
||||
}
|
||||
|
||||
/** Port groups a device at home offers: what it announces over Bonjour, or the usual ones. */
|
||||
const MDNS_LABEL: Record<string, string> = {
|
||||
_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',
|
||||
};
|
||||
const DEFAULT_PORTS: [string, string[]][] = [
|
||||
['Web', ['80', '443']],
|
||||
['SMB', ['445']],
|
||||
['SSH', ['22']],
|
||||
];
|
||||
/** 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 = MDNS_LABEL[s.type.split('.')[0]];
|
||||
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)]) : DEFAULT_PORTS;
|
||||
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. */
|
||||
@@ -118,7 +126,7 @@ export function homeServices(initial: Status, serverId: string, reload: () => Pr
|
||||
/** 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 picker = E('div', { class: 'dl-stack gap8' }, E('span', { class: 'dl-sub' }, _('Looking for devices at home…')));
|
||||
|
||||
const paintRows = () => {
|
||||
const services = st.services;
|
||||
@@ -133,25 +141,30 @@ export function homeServices(initial: Status, serverId: string, reload: () => Pr
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-mono dl-faint' },
|
||||
`${sv.address}${sv.ports.length ? ` · ports ${sv.ports.join(', ')}` : ' · all ports'}`,
|
||||
`${sv.address} · ${sv.ports.length ? fmt(_('ports %s'), sv.ports.join(', ')) : _('all ports')}`,
|
||||
),
|
||||
]),
|
||||
button('Edit', () => serviceDialog(sv, {}, reload)),
|
||||
button(_('Edit'), () => serviceDialog(sv, {}, reload)),
|
||||
button(
|
||||
[icon('trash')],
|
||||
async () => {
|
||||
if (
|
||||
(await confirmDialog(`Remove ${sv.name}?`, 'People limited to this service lose access to it.', 'Remove', true)) &&
|
||||
(await attempt(() => api.serviceDelete(sv.id), 'Removed'))
|
||||
(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': `Remove ${sv.name}` },
|
||||
{ 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.')],
|
||||
: [E('div', { class: 'dl-row dl-muted' }, _('No services yet: pick ports of a device below.'))],
|
||||
);
|
||||
};
|
||||
|
||||
@@ -164,10 +177,10 @@ export function homeServices(initial: Status, serverId: string, reload: () => Pr
|
||||
const sv = st.services.find((s) => s.address === h.address);
|
||||
const ok =
|
||||
ports === null
|
||||
? sv && (await attempt(() => api.serviceDelete(sv.id), `${sv.name} removed`))
|
||||
? 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 ? `${sv.name} updated` : `${h.name || h.address} added`,
|
||||
sv ? fmt(_('%s updated'), sv.name) : fmt(_('%s added'), h.name || h.address),
|
||||
);
|
||||
if (ok) await reload();
|
||||
} finally {
|
||||
@@ -187,7 +200,7 @@ export function homeServices(initial: Status, serverId: string, reload: () => Pr
|
||||
icon(h.services.some((s) => s.type.startsWith('_ipp') || s.type.startsWith('_printer')) ? 'file' : 'computer'),
|
||||
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 dl-host-ports' }, [
|
||||
chip('All ports', all, () => choose(h, all ? null : [])),
|
||||
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, () => {
|
||||
@@ -204,15 +217,15 @@ export function homeServices(initial: Status, serverId: string, reload: () => Pr
|
||||
}
|
||||
|
||||
function paintPicker() {
|
||||
if (failed) return dom.content(picker, E('span', { class: 'dl-sub' }, "Couldn't read the devices at home."));
|
||||
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.'));
|
||||
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', {}, _('Add from devices at home')),
|
||||
E('span', { class: 'dl-pcount' }, String(r.hosts.length)),
|
||||
]),
|
||||
E('div', { class: 'dl-params-body' }, [
|
||||
@@ -220,8 +233,8 @@ export function homeServices(initial: Status, serverId: string, reload: () => Pr
|
||||
'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.',
|
||||
? _('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)),
|
||||
]),
|
||||
@@ -245,13 +258,13 @@ export function homeServices(initial: Status, serverId: string, reload: () => Pr
|
||||
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('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.',
|
||||
_('Home-only people can be limited to these instead of whole networks (chosen on their page). Shared by all servers.'),
|
||||
),
|
||||
]),
|
||||
list,
|
||||
@@ -271,13 +284,13 @@ export function homeServices(initial: Status, serverId: string, reload: () => Pr
|
||||
|
||||
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((_, i) => !used.has(i));
|
||||
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 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 swatches = E('div', { class: 'dl-swatches', role: 'radiogroup', 'aria-label': _('Colour') });
|
||||
const paintSwatches = () =>
|
||||
dom.content(
|
||||
swatches,
|
||||
@@ -288,7 +301,7 @@ export function circleDialog(st: Status, serverId: string, ci: Circle | null, on
|
||||
class: `dl-swatch${i === color ? ' on' : ''}`,
|
||||
style: `--sw:${c}`,
|
||||
'aria-checked': i === color ? 'true' : 'false',
|
||||
'aria-label': `Colour ${i + 1}`,
|
||||
'aria-label': fmt(_('Colour %s'), i + 1),
|
||||
click: () => {
|
||||
color = i;
|
||||
paintSwatches();
|
||||
@@ -309,38 +322,38 @@ export function circleDialog(st: Status, serverId: string, ci: Circle | null, on
|
||||
type: 'button',
|
||||
class: `dl-chipbtn${members.has(p.id) ? ' on' : ''}`,
|
||||
title: !homeAccess(p)
|
||||
? `${p.name} has no home access: their devices aren't reachable anyway`
|
||||
? fmt(_("%s has no home access: their devices aren't reachable anyway"), p.name)
|
||||
: other
|
||||
? `Now in ${other.name}`
|
||||
? 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) : ''],
|
||||
[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', name, () => circleNameHelp(name.value, others));
|
||||
const nameRow = liveField(_('Name', 'circle or service'), name, () => circleNameHelp(name.value, others));
|
||||
|
||||
modal(
|
||||
ci ? `Edit ${ci.name}` : 'New circle',
|
||||
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.'),
|
||||
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',
|
||||
_('Delete'),
|
||||
async () => {
|
||||
if (await attempt(() => api.circleDelete(ci.id), `${ci.name} deleted`)) {
|
||||
if (await attempt(() => api.circleDelete(ci.id), fmt(_('%s deleted'), ci.name))) {
|
||||
closeModal();
|
||||
onDone();
|
||||
}
|
||||
@@ -352,14 +365,14 @@ export function circleDialog(st: Status, serverId: string, ci: Circle | null, on
|
||||
cancelButton(),
|
||||
' ',
|
||||
button(
|
||||
'Save',
|
||||
_('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')) {
|
||||
if (await attempt(() => api.circleSet(ci?.id ?? '', serverId, name.value, color, [...members]), _('Saved'))) {
|
||||
closeModal();
|
||||
onDone();
|
||||
}
|
||||
@@ -379,8 +392,8 @@ export function circleChips(st: Status, serverId: string, onDone: () => unknown)
|
||||
const who = st.people.filter((p) => p.circle === c.id).map((p) => p.name);
|
||||
return E(
|
||||
'button',
|
||||
{ type: 'button', class: 'dl-chip', title: `Edit ${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')],
|
||||
{ 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(
|
||||
@@ -388,8 +401,8 @@ export function circleChips(st: Status, serverId: string, onDone: () => unknown)
|
||||
{
|
||||
type: 'button',
|
||||
class: 'dl-chip add',
|
||||
title: 'New circle',
|
||||
'aria-label': 'New circle',
|
||||
title: _('New circle'),
|
||||
'aria-label': _('New circle'),
|
||||
click: () => circleDialog(st, serverId, null, onDone),
|
||||
},
|
||||
icon('plus'),
|
||||
@@ -406,22 +419,23 @@ export function whoReaches(st: Status, srv: Server): HTMLElement {
|
||||
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');
|
||||
return yes([...kinds].map((k) => ({ all: 'all networks', some: 'their networks', services: 'services' })[k]).join(' / '));
|
||||
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 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' }, `${list.length} ${list.length === 1 ? 'person' : 'people'}`)]),
|
||||
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('h3', {}, _('Who reaches what')),
|
||||
E('span', { class: 'dl-spacer' }),
|
||||
E('span', { class: 'dl-sub' }, 'From the rules on this server'),
|
||||
E('span', { class: 'dl-sub' }, _('From the rules on this server')),
|
||||
]),
|
||||
E(
|
||||
'div',
|
||||
@@ -430,17 +444,19 @@ export function whoReaches(st: Status, srv: Server): HTMLElement {
|
||||
E(
|
||||
'tr',
|
||||
{},
|
||||
['', 'Internet', 'Home', 'This router', 'Each other'].map((t) => E('th', {}, t)),
|
||||
['', _('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()]),
|
||||
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.',
|
||||
_(
|
||||
'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.',
|
||||
),
|
||||
),
|
||||
]),
|
||||
]);
|
||||
@@ -458,7 +474,7 @@ export function checkAccess(st: Status, srv: Server): HTMLElement {
|
||||
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'),
|
||||
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]);
|
||||
@@ -476,8 +492,8 @@ export function checkAccess(st: Status, srv: Server): HTMLElement {
|
||||
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' : `Stops at step ${stop + 1} of ${r.steps.length}`),
|
||||
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',
|
||||
@@ -497,11 +513,11 @@ export function checkAccess(st: Status, srv: Server): HTMLElement {
|
||||
return E('section', { class: 'dl-setsec' }, [
|
||||
E('div', { class: 'dl-setsec-body' }, [
|
||||
E('div', { class: 'dl-panel-head' }, [
|
||||
E('h3', {}, 'Check access'),
|
||||
E('h3', {}, _('Check access')),
|
||||
E('span', { class: 'dl-spacer' }),
|
||||
E('span', { class: 'dl-sub' }, 'Why something does or does not connect'),
|
||||
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)]),
|
||||
E('div', { class: 'dl-check-form' }, [from.el, E('span', { class: 'dl-faint' }, '→'), to.el, button(_('Check'), run)]),
|
||||
out,
|
||||
]),
|
||||
]);
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
import type { Network, PortHold } from './netcheck';
|
||||
import type { AwgCaps, AwgState, Circle, ClientConfig, DayUsage, HealthCheck, LogEvent, MeshMode, Person, Status } from '../shared/types';
|
||||
import { notify } from './ui/toast';
|
||||
import { lang } from '../shared/i18n';
|
||||
|
||||
/** Throw a backend failure; show a warning the answer carries. */
|
||||
function settle<T>(r: any): T {
|
||||
@@ -15,9 +16,13 @@ function settle<T>(r: any): T {
|
||||
return r as T;
|
||||
}
|
||||
|
||||
/**
|
||||
* A method of luci.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 });
|
||||
return async (...args: unknown[]): Promise<T> => settle<T>(await fn(...args));
|
||||
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()));
|
||||
}
|
||||
|
||||
export interface SetupDefaults {
|
||||
@@ -129,6 +134,8 @@ export interface UpdatesStatus {
|
||||
history: UpdateEvent[];
|
||||
/** AmneziaWG interfaces (their Dawnline names): switching builds restarts them. */
|
||||
tunnels: string[];
|
||||
/** The admin's translations installed (luci-i18n-dawnline-<lang>): "ru". */
|
||||
translations?: string[];
|
||||
}
|
||||
|
||||
export interface UpdateEvent {
|
||||
|
||||
+129
-80
@@ -16,6 +16,7 @@ import { keepaliveHelp, mtuHelp, portHelp, type PortHold } from '../netcheck';
|
||||
import { vpnKey } from '../../shared/vpnkey';
|
||||
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 Core, type CoreCtx } from './common';
|
||||
|
||||
/** `.conf` names of the disguise parameters, in file order. */
|
||||
@@ -73,31 +74,38 @@ function paramsView(o: Record<string, string>): HTMLElement | null {
|
||||
};
|
||||
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.';
|
||||
? _('A first packet shaped like a DNS answer.')
|
||||
: _('Extra packets sent before the handshake.');
|
||||
const conf = keys.map(([k, n]) => `${n} = ${o[k]}`).join('\n');
|
||||
const body = E('div', { class: 'dl-pgrid' }, [
|
||||
group(
|
||||
'Junk packets',
|
||||
_('Junk packets'),
|
||||
'zap',
|
||||
jc ? `${jc} random packet${jc === 1 ? '' : 's'} of ${o.jmin}–${o.jmax} bytes before each handshake.` : 'No junk packets.',
|
||||
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.', [
|
||||
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.', [
|
||||
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',
|
||||
@@ -108,7 +116,7 @@ function paramsView(o: Record<string, string>): HTMLElement | null {
|
||||
return E('details', { class: 'dl-params' }, [
|
||||
E('summary', {}, [
|
||||
icon('chevron'),
|
||||
E('span', {}, 'Current parameters'),
|
||||
E('span', {}, _('Current parameters')),
|
||||
E('span', { class: 'dl-pcount' }, String(keys.length)),
|
||||
E('span', { class: 'dl-spacer' }),
|
||||
E(
|
||||
@@ -118,10 +126,10 @@ function paramsView(o: Record<string, string>): HTMLElement | null {
|
||||
class: 'dl-linkbtn',
|
||||
click: (ev: Event) => {
|
||||
ev.preventDefault();
|
||||
copyText(conf, 'Parameters copied');
|
||||
copyText(conf, _('Parameters copied'));
|
||||
},
|
||||
},
|
||||
'Copy as config',
|
||||
_('Copy as config'),
|
||||
),
|
||||
]),
|
||||
body,
|
||||
@@ -158,11 +166,11 @@ function fileCard(cfg: AwgConfig): HTMLElement {
|
||||
click: (ev: Event) => {
|
||||
ev.preventDefault();
|
||||
reveal = !reveal;
|
||||
dom.content(eye, [icon(reveal ? 'x' : 'key'), reveal ? 'Hide key' : 'Show key']);
|
||||
dom.content(eye, [icon(reveal ? 'x' : 'key'), reveal ? _('Hide key') : _('Show key')]);
|
||||
paint();
|
||||
},
|
||||
},
|
||||
[icon('key'), 'Show key'],
|
||||
[icon('key'), _('Show key')],
|
||||
);
|
||||
paint();
|
||||
const size = new Blob([cfg.conf]).size;
|
||||
@@ -171,14 +179,14 @@ function fileCard(cfg: AwgConfig): HTMLElement {
|
||||
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 · ${size} bytes`),
|
||||
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'),
|
||||
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', {}, _('Configuration')),
|
||||
E('span', { class: 'dl-spacer' }),
|
||||
eye,
|
||||
E(
|
||||
@@ -188,10 +196,10 @@ function fileCard(cfg: AwgConfig): HTMLElement {
|
||||
class: 'dl-chipbtn',
|
||||
click: (ev: Event) => {
|
||||
ev.preventDefault();
|
||||
copyText(cfg.conf, 'Configuration copied');
|
||||
copyText(cfg.conf, _('Configuration copied'));
|
||||
},
|
||||
},
|
||||
[icon('copy'), 'Copy'],
|
||||
[icon('copy'), _('Copy')],
|
||||
),
|
||||
]),
|
||||
pre,
|
||||
@@ -212,7 +220,7 @@ export async function connectBlock(cfg: AwgConfig, initial: 'file' | 'key' | 'qr
|
||||
return E(
|
||||
'div',
|
||||
{ class: 'dl-hint' },
|
||||
'This device generated its own keys in the browser, so its full configuration only exists on that device.',
|
||||
_('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: Record<string, () => Node> = {
|
||||
@@ -222,13 +230,20 @@ export async function connectBlock(cfg: AwgConfig, initial: 'file' | 'key' | 'qr
|
||||
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.',
|
||||
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'))]),
|
||||
E('span', { class: 'dl-sub' }, 'AmneziaVPN → Add server → Insert key. Keep it private.'),
|
||||
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),
|
||||
};
|
||||
@@ -239,9 +254,9 @@ export async function connectBlock(cfg: AwgConfig, initial: 'file' | 'key' | 'qr
|
||||
dom.content(body, panes[id]());
|
||||
};
|
||||
for (const [id, label] of [
|
||||
['file', 'File'],
|
||||
['key', 'Key'],
|
||||
['qr', 'QR code'],
|
||||
['file', _('File')],
|
||||
['key', _('Key')],
|
||||
['qr', _('QR code')],
|
||||
])
|
||||
seg.appendChild(E('button', { type: 'button', 'data-id': id, click: () => show(id) }, label));
|
||||
show(initial);
|
||||
@@ -254,14 +269,24 @@ async function applyDisguise(ctx: CoreCtx, srv: Server, m: Method, same: boolean
|
||||
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?' : `Switch to ${info.title}?`,
|
||||
`${devices} AmneziaWG device${devices === 1 ? ' stops' : 's stop'} connecting until ${devices === 1 ? 'it imports its' : '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.' : ''}`,
|
||||
same ? 'Generate and apply' : 'Switch and apply',
|
||||
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' : `${info.title} applied`)) {
|
||||
notify('Devices are marked “Update config” until they import again.', 'info', 6000);
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -271,7 +296,7 @@ export function settingsCard(ctx: CoreCtx, srv: Server): HTMLElement {
|
||||
const st: Status = ctx.st;
|
||||
const port = input(String(srv.port), { inputmode: 'numeric', class: 'cbi-input-text dl-w-port dl-mono' });
|
||||
const mtu = input(srv.mtu ? String(srv.mtu) : '', {
|
||||
placeholder: 'Auto',
|
||||
placeholder: _('Auto'),
|
||||
inputmode: 'numeric',
|
||||
class: 'cbi-input-text dl-w-port dl-mono',
|
||||
});
|
||||
@@ -280,17 +305,25 @@ export function settingsCard(ctx: CoreCtx, srv: Server): HTMLElement {
|
||||
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'] : [`Switch to ${methodInfo(selected)!.title}`]);
|
||||
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, () =>
|
||||
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.' : ''}`,
|
||||
[
|
||||
_('Opened on the WAN firewall automatically.'),
|
||||
Number(port.value) === 4500 ? _('4500 is IPsec’s port: most networks let it through.') : '',
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' '),
|
||||
),
|
||||
);
|
||||
api
|
||||
@@ -301,27 +334,30 @@ export function settingsCard(ctx: CoreCtx, srv: Server): HTMLElement {
|
||||
})
|
||||
.catch(() => {});
|
||||
const mtuRow = liveRow('MTU', mtu, () => mtuHelp(mtu.value, srv.mtus));
|
||||
const kaRow = liveRow('Keep-alive', ka, () => keepaliveHelp(ka.value));
|
||||
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', [
|
||||
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', [
|
||||
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', [
|
||||
E('b', {}, legacyTitle(srv.preset)!),
|
||||
' is AmneziaWG 1.0 junk only, which networks learned to spot; it is not offered any more. Switch to ',
|
||||
E('b', {}, 'Balanced'),
|
||||
' or ',
|
||||
E('b', {}, 'Maximum'),
|
||||
': devices import their configuration again.',
|
||||
])
|
||||
? 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,
|
||||
@@ -335,29 +371,31 @@ export function settingsCard(ctx: CoreCtx, srv: Server): HTMLElement {
|
||||
),
|
||||
// Only about an installed AmneziaWG: without one the server page says what to install.
|
||||
tools && !st.awg.v3
|
||||
? callout('info', [
|
||||
'This router runs an older AmneziaWG. ',
|
||||
E('b', {}, 'Maximum'),
|
||||
' becomes available with kmod-amneziawg and amneziawg-tools 3.1.',
|
||||
])
|
||||
? 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 ?? {}) ?? '',
|
||||
E('div', { class: 'dl-row-end' }, [
|
||||
E('span', { class: 'dl-sub' }, 'Applies at once: every AmneziaWG device imports its configuration again.'),
|
||||
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('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} · router ${srv.address}`)),
|
||||
row('Tunnel subnet', E('span', { class: 'dl-mono' }, srv.subnet), 'Device addresses come from it.'),
|
||||
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',
|
||||
_('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',
|
||||
button([icon('copy')], () => copyText(srv.public_key, _('Public key copied')), 'neutral', {
|
||||
title: _('Copy'),
|
||||
class: 'cbi-button cbi-button-neutral dl-icon-only sm',
|
||||
}),
|
||||
]),
|
||||
@@ -366,9 +404,9 @@ export function settingsCard(ctx: CoreCtx, srv: Server): HTMLElement {
|
||||
]),
|
||||
],
|
||||
[
|
||||
E('span', { class: 'dl-sub' }, 'Port, MTU and keep-alive apply at once.'),
|
||||
E('span', { class: 'dl-sub' }, _('Port, MTU and keep-alive apply at once.')),
|
||||
button(
|
||||
'Save',
|
||||
_('Save'),
|
||||
() => {
|
||||
// The help lines already say what is wrong: do not send it anyway.
|
||||
const bad = firstBad([portRow, mtuRow, kaRow]);
|
||||
@@ -376,7 +414,7 @@ export function settingsCard(ctx: CoreCtx, srv: Server): HTMLElement {
|
||||
notify(bad, 'warning');
|
||||
return;
|
||||
}
|
||||
return ctx.save({ port: port.value, mtu: mtu.value, keepalive: ka.value }, 'AmneziaWG saved');
|
||||
return ctx.save({ port: port.value, mtu: mtu.value, keepalive: ka.value }, _('AmneziaWG saved'));
|
||||
},
|
||||
'positive',
|
||||
),
|
||||
@@ -395,30 +433,30 @@ function overviewTile(srv: Server): HTMLElement {
|
||||
[0, 1, 2, 3].map((i) => E('i', { class: i < n ? 'on' : '' })),
|
||||
);
|
||||
const chips: string[] = [];
|
||||
if (+o.jc) chips.push(`${o.jc} junk · ${o.jmin}–${o.jmax} B`);
|
||||
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 (o.header_protection_key) chips.push('Encrypted headers');
|
||||
if (!chips.length) chips.push(m?.id === 'off' ? 'Plain WireGuard' : 'No values yet');
|
||||
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 (o.header_protection_key) 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/network/dawnline/server')}?server=${encodeURIComponent(srv.id)}§ion=awg` }, 'Change'),
|
||||
E('span', { class: 'dl-metric-label' }, _('Disguise')),
|
||||
E('a', { href: `${L.url('admin/network/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')),
|
||||
E('span', { class: 'dl-sub' }, m ? m.short : legacyTitle(srv.preset) ? 'Switch to Balanced or Maximum' : 'Set by hand'),
|
||||
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'),
|
||||
E('span', {}, _('Stealth')),
|
||||
segs(m.stealth, 'acc'),
|
||||
E('span', {}, 'Speed'),
|
||||
E('span', {}, _('Speed')),
|
||||
segs(m.speed, 'ok'),
|
||||
])
|
||||
: '',
|
||||
@@ -437,6 +475,17 @@ export const awg: Core = {
|
||||
overviewTile,
|
||||
connectBlock,
|
||||
qrText: (cfg) => cfg.conf,
|
||||
appKey: { label: 'Copy AmneziaVPN config', make: (cfg) => vpnKey(cfg, cfg.server) },
|
||||
file: { label: 'Download AmneziaWG config', make: (cfg) => ({ name: cfg.filename, text: 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 }),
|
||||
},
|
||||
};
|
||||
+130
-95
@@ -15,7 +15,8 @@ import { liveField } from './ui/layout';
|
||||
import { qrCode } from './ui/qr';
|
||||
import { nameHelp } from './netcheck';
|
||||
import { deviceStatus } from './ui/badges';
|
||||
import { ago, bytes, isoDay, KIND_LABEL, KINDS, todayOf } from '../shared/format';
|
||||
import { ago, bytes, isoDay, kindLabel, KINDS, todayOf } from '../shared/format';
|
||||
import { fill, fmt, locale, num } from '../shared/i18n';
|
||||
import { icon } from '../shared/icons';
|
||||
import { eventBy } from './events/model';
|
||||
import { spark } from './widgets/spark';
|
||||
@@ -43,7 +44,7 @@ export interface DeviceOpts {
|
||||
|
||||
function when(ts: number): string {
|
||||
return ts
|
||||
? new Date(ts * 1000).toLocaleString('en-GB', { day: 'numeric', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' })
|
||||
? new Date(ts * 1000).toLocaleString(locale(), { day: 'numeric', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' })
|
||||
: '—';
|
||||
}
|
||||
|
||||
@@ -52,7 +53,12 @@ function copyRow(label: string, value: string, mono = false): HTMLElement {
|
||||
E('span', { class: 'dl-kvrow-k' }, label),
|
||||
E(
|
||||
'button',
|
||||
{ type: 'button', class: `dl-kvrow-v copy${mono ? ' dl-mono' : ''}`, title: 'Copy', click: () => copyText(value, `${label} copied`) },
|
||||
{
|
||||
type: 'button',
|
||||
class: `dl-kvrow-v copy${mono ? ' dl-mono' : ''}`,
|
||||
title: _('Copy'),
|
||||
click: () => copyText(value, fmt(_('%s copied'), label)),
|
||||
},
|
||||
[E('span', {}, value), icon('copy')],
|
||||
),
|
||||
]);
|
||||
@@ -62,46 +68,55 @@ 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)]);
|
||||
}
|
||||
|
||||
const DEV_EVENT: Record<string, [string, string, string]> = {
|
||||
connect: ['ok', 'Connected', 'plug'],
|
||||
disconnect: ['', 'Went offline', 'plug'],
|
||||
roam: ['', 'Changed network', 'network'],
|
||||
device_added: ['ok', 'Added', 'plus'],
|
||||
device_removed: ['', 'Removed', 'trash'],
|
||||
device_keys: ['', 'New keys', 'reset'],
|
||||
/** 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.');
|
||||
if (!mine.length) return E('div', { class: 'dl-sub' }, _('No activity yet.'));
|
||||
return E(
|
||||
'div',
|
||||
{ class: 'dl-dev-log' },
|
||||
mine.map((e) => {
|
||||
const [tone, label, ic] = DEV_EVENT[e.type];
|
||||
// As in the main log: what happened in the text colour, the details muted.
|
||||
const extra =
|
||||
e.type === 'connect'
|
||||
? [
|
||||
e.detail ? E('span', { class: 'dl-muted' }, ` from ${e.detail}`) : '',
|
||||
e.where ? E('span', { class: 'dl-muted' }, ` · ${e.where}`) : '',
|
||||
]
|
||||
: e.type === 'roam'
|
||||
? [E('span', { class: 'dl-muted' }, ` · ${e.detail ?? ''}`)]
|
||||
: e.type === 'device_added' || e.type === 'device_removed' || e.type === 'device_keys'
|
||||
? [E('span', { class: 'dl-muted' }, eventBy(e) === 'portal' ? ' on the portal' : eventBy(e) === 'admin' ? ' by you' : '')]
|
||||
: [];
|
||||
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', title: _('Done by you in LuCI') }, icon('admin'))
|
||||
: E('span', { class: `dl-ev-tile ev ${tone}` }, icon(ic)),
|
||||
E('span', { class: 'dl-row-main' }, [E('span', {}, label), ...extra]),
|
||||
E('span', { class: 'dl-faint dl-nowrap', title: t.toLocaleString() }, ago(e.ts, now)),
|
||||
E('span', { class: 'dl-row-main' }, eventText(e)),
|
||||
E('span', { class: 'dl-faint dl-nowrap', title: t.toLocaleString(locale()) }, ago(e.ts, now)),
|
||||
]);
|
||||
}),
|
||||
);
|
||||
@@ -131,7 +146,7 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
|
||||
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…'));
|
||||
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);
|
||||
@@ -157,9 +172,9 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
|
||||
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' }),
|
||||
button([icon('edit')], () => rename(), 'neutral', { title: _('Rename'), class: 'cbi-button cbi-button-neutral dl-icon-only sm' }),
|
||||
]),
|
||||
E('span', { class: 'dl-sub' }, `${p.name} · ${KIND_LABEL[d.kind]}`),
|
||||
E('span', { class: 'dl-sub' }, `${p.name} · ${kindLabel(d.kind)}`),
|
||||
]),
|
||||
]);
|
||||
const week = d.spark.reduce((a, b) => a + b, 0);
|
||||
@@ -167,16 +182,16 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
|
||||
stats,
|
||||
E('div', { class: 'dl-dstats' }, [
|
||||
E('div', { class: 'dl-dstats-cell wide' }, [
|
||||
E('span', { class: 'dl-metric-label' }, 'Status'),
|
||||
deviceStatus(d, now, 'Waiting for the first connection', p),
|
||||
E('span', { class: 'dl-metric-label' }, _('Status')),
|
||||
deviceStatus(d, now, _('Waiting for the first connection'), p),
|
||||
]),
|
||||
E('div', { class: 'dl-dstats-cell' }, [
|
||||
E('span', { class: 'dl-metric-label' }, 'This month'),
|
||||
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('span', { class: 'dl-metric-label' }, _('Last 7 days')),
|
||||
E('b', {}, bytes(week)),
|
||||
spark(d.spark, 120, 22, today),
|
||||
]),
|
||||
@@ -185,13 +200,13 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
|
||||
dom.content(
|
||||
details,
|
||||
E('div', { class: 'dl-kv2' }, [
|
||||
copyRow('Tunnel address', d.address),
|
||||
d.hostname && p.access !== 'internet' ? copyRow('Local address', d.hostname) : '',
|
||||
copyRow(_('Tunnel address'), d.address),
|
||||
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) : '',
|
||||
d.endpoint && !geo?.points.some((x) => x.device === d.id && x.ip === d.endpoint) ? row(_('Client IP'), d.endpoint) : '',
|
||||
row(
|
||||
'Total',
|
||||
_('Total'),
|
||||
E('span', { class: 'dl-kv-act' }, [
|
||||
`↓ ${bytes(d.total[1])} · ↑ ${bytes(d.total[0])}`,
|
||||
E(
|
||||
@@ -201,36 +216,36 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
|
||||
class: 'dl-linkbtn danger',
|
||||
click: () => resetUsageDialog('device', d.id, d.name, () => setTimeout(changed, 300)),
|
||||
},
|
||||
'Reset',
|
||||
_('Reset'),
|
||||
),
|
||||
]),
|
||||
),
|
||||
row('Added', `${when(d.created)} · ${d.created_by === 'portal' ? 'from the portal' : 'by you'}`),
|
||||
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', '—'),
|
||||
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'],
|
||||
[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'))
|
||||
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 () => {
|
||||
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',
|
||||
_('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');
|
||||
const c = await attempt(() => api.deviceRotate(d.id), _('New keys generated'));
|
||||
if (c) {
|
||||
o.refresh();
|
||||
handle.close();
|
||||
@@ -239,18 +254,18 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
|
||||
}),
|
||||
E('span', { class: 'dl-spacer' }),
|
||||
button(
|
||||
[icon('trash'), ' Remove'],
|
||||
[icon('trash'), ' ', _('Remove')],
|
||||
async () => {
|
||||
if (
|
||||
!(await confirmDialog(
|
||||
`Remove ${d.name}?`,
|
||||
'The device is disconnected immediately and its configuration stops working.',
|
||||
'Remove',
|
||||
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')) {
|
||||
if (await attempt(() => api.deviceDelete(d.id), _('Device removed'))) {
|
||||
handle.close();
|
||||
o.refresh();
|
||||
}
|
||||
@@ -283,22 +298,22 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
|
||||
const rename = () => {
|
||||
const input = E('input', { type: 'text', class: 'cbi-input-text', value: d.name, maxlength: 48 }) as HTMLInputElement;
|
||||
const taken = p.devices.filter((x) => x.id !== d.id).map((x) => x.name);
|
||||
const nameRow = liveField('Name', input, () => nameHelp(input.value, taken, 'Shown in the portal and in the app.'));
|
||||
const nameRow = liveField(_('Name'), input, () => nameHelp(input.value, taken, _('Shown in the portal and in the app.')));
|
||||
modal(
|
||||
`Rename ${d.name}`,
|
||||
fmt(_('Rename %s'), d.name),
|
||||
[nameRow],
|
||||
[
|
||||
cancelButton(),
|
||||
' ',
|
||||
button(
|
||||
'Save',
|
||||
_('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')) {
|
||||
if (await attempt(() => api.deviceUpdate(d.id, input.value, undefined), _('Renamed'))) {
|
||||
closeModal();
|
||||
await changed();
|
||||
}
|
||||
@@ -313,14 +328,16 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
|
||||
const foot = E('div', { class: 'dl-drawer-actions' });
|
||||
const connectSec = E('section', { class: 'dl-dsec' }, [
|
||||
// Whether it is connected (or still waiting) is in Status above.
|
||||
E('div', { class: 'dl-dsec-head' }, [E('h4', {}, 'Connect')]),
|
||||
E('div', { class: 'dl-dsec-head' }, [E('h4', {}, _('Connect', 'section'))]),
|
||||
d.config_stale
|
||||
? E('div', { class: 'dl-note warn' }, [
|
||||
icon('alert'),
|
||||
E(
|
||||
'span',
|
||||
{},
|
||||
'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.',
|
||||
_(
|
||||
'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.',
|
||||
),
|
||||
),
|
||||
])
|
||||
: '',
|
||||
@@ -328,28 +345,35 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
|
||||
]);
|
||||
const activitySec = E('section', { class: 'dl-dsec' }, [
|
||||
E('div', { class: 'dl-dsec-head' }, [
|
||||
E('h4', {}, 'Activity'),
|
||||
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', click: () => exportEvents({ people: [p] }, logEvents, 'csv', d.id) },
|
||||
_('Export'),
|
||||
),
|
||||
E(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
class: 'dl-linkbtn danger',
|
||||
click: () =>
|
||||
clearLogDialog(`Clear ${d.name}'s activity`, `Removes events about ${d.name}.`, { device: d.id }, () => {
|
||||
clearLogDialog(fmt(_("Clear %s's activity"), d.name), fmt(_('Removes events about %s.'), d.name), { device: d.id }, () => {
|
||||
void loadLog(true);
|
||||
o.refresh();
|
||||
}),
|
||||
},
|
||||
'Clear',
|
||||
_('Clear'),
|
||||
),
|
||||
E('a', { href: `${L.url('admin/network/dawnline/diagnostics')}?tab=log` }, 'All activity'),
|
||||
E('a', { href: `${L.url('admin/network/dawnline/diagnostics')}?tab=log` }, _('All activity')),
|
||||
]),
|
||||
]),
|
||||
log,
|
||||
]);
|
||||
const detailsSec = E('section', { class: 'dl-dsec' }, [E('div', { class: 'dl-dsec-head' }, E('h4', {}, 'Details')), details]);
|
||||
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(
|
||||
@@ -366,7 +390,7 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
|
||||
}));
|
||||
locationsSec = E('section', { class: 'dl-dsec' }, [
|
||||
E('div', { class: 'dl-dsec-head' }, [
|
||||
E('h4', {}, 'Locations'),
|
||||
E('h4', {}, _('Locations')),
|
||||
rangeControl(
|
||||
range,
|
||||
(r) => {
|
||||
@@ -412,22 +436,24 @@ export function quickMenu(anchor: HTMLElement, p: Person, d: Device, o: DeviceOp
|
||||
const cfg = () => attempt(() => api.deviceConfig(d.id));
|
||||
const items: (MenuItem | null)[] = [
|
||||
{
|
||||
label: 'Show QR code',
|
||||
label: _('Show QR code'),
|
||||
icon: icon('qr'),
|
||||
run: async () => {
|
||||
const c = await cfg();
|
||||
if (!c) return;
|
||||
modal(
|
||||
`${d.name} · QR code`,
|
||||
`${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.',
|
||||
plainWg(c)
|
||||
? _('Scan with AmneziaVPN or any WireGuard app on the device.')
|
||||
: _('Scan with AmneziaVPN or AmneziaWG on the device.'),
|
||||
),
|
||||
]),
|
||||
cancelButton('Close'),
|
||||
cancelButton(_('Close')),
|
||||
);
|
||||
},
|
||||
},
|
||||
@@ -447,50 +473,50 @@ export function quickMenu(anchor: HTMLElement, p: Person, d: Device, o: DeviceOp
|
||||
icon: icon('copy'),
|
||||
run: async () => {
|
||||
const c = await cfg();
|
||||
if (c) copyText(await core.appKey!.make(c), 'Key copied');
|
||||
if (c) copyText(await core.appKey!.make(c), _('Key copied'));
|
||||
},
|
||||
}
|
||||
: null,
|
||||
null,
|
||||
{ label: 'Rename', icon: icon('edit'), run: () => openDevice(p, d, o) },
|
||||
{ label: _('Rename'), icon: icon('edit'), run: () => openDevice(p, d, o) },
|
||||
{
|
||||
label: 'New keys',
|
||||
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',
|
||||
_('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();
|
||||
if (await attempt(() => api.deviceRotate(d.id), _('New keys generated'))) o.refresh();
|
||||
},
|
||||
},
|
||||
{
|
||||
label: d.disabled ? 'Enable' : 'Disable',
|
||||
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'))
|
||||
if (await attempt(() => api.deviceUpdate(d.id, undefined, !d.disabled), d.disabled ? _('Device enabled') : _('Device disabled')))
|
||||
o.refresh();
|
||||
},
|
||||
},
|
||||
{
|
||||
label: 'Delete',
|
||||
label: _('Delete'),
|
||||
icon: icon('trash'),
|
||||
danger: true,
|
||||
run: async () => {
|
||||
if (
|
||||
await confirmDialog(
|
||||
`Remove ${d.name}?`,
|
||||
'The device is disconnected immediately and its configuration stops working.',
|
||||
'Remove',
|
||||
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();
|
||||
if (await attempt(() => api.deviceDelete(d.id), _('Device removed'))) o.refresh();
|
||||
},
|
||||
},
|
||||
];
|
||||
@@ -502,7 +528,7 @@ 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 = KIND_LABEL[k];
|
||||
const base = kindLabel(k);
|
||||
let n = 1;
|
||||
let name = base;
|
||||
while (taken.some((t) => t.toLowerCase() === name.toLowerCase())) name = `${base} ${++n}`;
|
||||
@@ -510,14 +536,14 @@ export function addDevice(person: Person, o: DeviceOpts) {
|
||||
};
|
||||
let kind: Kind = 'phone';
|
||||
const nameInput = E('input', { type: 'text', class: 'cbi-input-text', placeholder: suggest(kind), maxlength: 48 }) as HTMLInputElement;
|
||||
const nameRow = liveField('Name', nameInput, () =>
|
||||
const nameRow = liveField(_('Name'), nameInput, () =>
|
||||
nameInput.value.trim()
|
||||
? nameHelp(nameInput.value, taken, 'Shown in the portal and in the app.')
|
||||
: { text: `Named after its type: ${suggest(kind)}.`, bad: false },
|
||||
? nameHelp(nameInput.value, taken, _('Shown in the portal and in the app.'))
|
||||
: { text: fmt(_('Named after its type: %s.'), suggest(kind)), bad: false },
|
||||
);
|
||||
const kinds = E(
|
||||
'div',
|
||||
{ class: 'dl-kinds', role: 'radiogroup', 'aria-label': 'Type' },
|
||||
{ class: 'dl-kinds', role: 'radiogroup', 'aria-label': _('Type') },
|
||||
KINDS.map((k) =>
|
||||
E(
|
||||
'button',
|
||||
@@ -538,29 +564,38 @@ export function addDevice(person: Person, o: DeviceOpts) {
|
||||
nameRow.refresh();
|
||||
},
|
||||
},
|
||||
[icon(k), E('span', {}, KIND_LABEL[k])],
|
||||
[icon(k), E('span', {}, kindLabel(k))],
|
||||
),
|
||||
),
|
||||
);
|
||||
const over = person.devices.length >= person.device_limit;
|
||||
modal(
|
||||
`Add a device for ${person.name}`,
|
||||
fmt(_('Add a device for %s'), person.name),
|
||||
[
|
||||
over
|
||||
? E(
|
||||
'p',
|
||||
{ class: 'dl-hint' },
|
||||
`${person.name} already has ${person.devices.length} of ${person.device_limit} devices. As admin you can still add one.`,
|
||||
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]),
|
||||
E('div', { class: 'dl-fld' }, [E('span', { class: 'dl-fld-label' }, _('Type')), kinds]),
|
||||
nameRow,
|
||||
],
|
||||
[
|
||||
cancelButton(),
|
||||
' ',
|
||||
button(
|
||||
'Add device',
|
||||
_('Add device'),
|
||||
async () => {
|
||||
const h = nameRow.help();
|
||||
if (h.bad) {
|
||||
@@ -571,7 +606,7 @@ export function addDevice(person: Person, o: DeviceOpts) {
|
||||
const r = await attempt(() => api.deviceCreate(person.id, name, kind));
|
||||
if (!r) return;
|
||||
closeModal();
|
||||
notify(`${name} added`, 'success', 3000);
|
||||
notify(fmt(_('%s added'), name), 'success', 3000);
|
||||
o.refresh();
|
||||
await reopen(person.id, r.id, o);
|
||||
},
|
||||
|
||||
+58
-52
@@ -3,6 +3,7 @@
|
||||
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). */
|
||||
@@ -24,42 +25,47 @@ export interface MethodInfo {
|
||||
needs?: AwgNeed;
|
||||
}
|
||||
|
||||
export const METHODS: MethodInfo[] = [
|
||||
{
|
||||
id: 'off',
|
||||
title: 'Off',
|
||||
ic: 'zap',
|
||||
stealth: 0,
|
||||
speed: 4,
|
||||
text: 'Plain WireGuard-compatible traffic. Fastest, but easy to recognise and block.',
|
||||
apps: 'Any WireGuard app',
|
||||
short: 'Any WireGuard app',
|
||||
},
|
||||
{
|
||||
id: 'balanced',
|
||||
title: 'Balanced',
|
||||
ic: 'shield',
|
||||
stealth: 3,
|
||||
speed: 4,
|
||||
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',
|
||||
},
|
||||
{
|
||||
id: 'max',
|
||||
title: 'Maximum',
|
||||
ic: 'lock',
|
||||
stealth: 4,
|
||||
speed: 3,
|
||||
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',
|
||||
},
|
||||
];
|
||||
/** The methods in picker 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.'),
|
||||
apps: _('Any WireGuard app'),
|
||||
short: _('Any WireGuard app'),
|
||||
},
|
||||
{
|
||||
id: 'balanced',
|
||||
title: _('Balanced'),
|
||||
ic: 'shield',
|
||||
stealth: 3,
|
||||
speed: 4,
|
||||
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'),
|
||||
},
|
||||
{
|
||||
id: 'max',
|
||||
title: _('Maximum'),
|
||||
ic: 'lock',
|
||||
stealth: 4,
|
||||
speed: 3,
|
||||
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'),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
export const methodInfo = (id: string): MethodInfo | undefined => METHODS.find((x) => x.id === id);
|
||||
export const methodInfo = (id: string): MethodInfo | undefined => methods().find((x) => x.id === id);
|
||||
|
||||
/** 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');
|
||||
@@ -70,21 +76,21 @@ export const defaultMethod = (caps: AwgCaps): Method => (caps.v3 ? 'max' : caps.
|
||||
* the picker offers 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;
|
||||
preset === 'standard' ? _('Standard (old)') : preset === 'strong' ? _('Strong (old)') : null;
|
||||
|
||||
const NEEDS: Record<AwgNeed, string> = {
|
||||
v2: 'Needs AmneziaWG 2.0 or newer on the router (kmod-amneziawg and amneziawg-tools from July 2025 on).',
|
||||
v3: 'Needs AmneziaWG 3.1 on the router (kmod-amneziawg and amneziawg-tools 3.1).',
|
||||
};
|
||||
|
||||
/** The same while no AmneziaWG is installed at all ("newer" would be misleading). */
|
||||
const NEEDS_NONE: Record<AwgNeed, string> = {
|
||||
v2: 'Needs AmneziaWG on the router.',
|
||||
v3: 'Needs AmneziaWG 3.1 on the router: install it first.',
|
||||
};
|
||||
/**
|
||||
* 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 {
|
||||
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: `${label}: ${n} of 4` }, [
|
||||
return E('span', { class: 'dl-dots', title: fmt(_('%s: %s of 4'), label, n) }, [
|
||||
E('span', { class: 'dl-dots-label' }, label),
|
||||
E(
|
||||
'span',
|
||||
@@ -106,11 +112,11 @@ export function methodPicker(
|
||||
current?: string,
|
||||
installed = true,
|
||||
): HTMLElement {
|
||||
const el = E('div', { class: 'dl-methods', role: 'radiogroup', 'aria-label': 'Disguise method' });
|
||||
const el = E('div', { class: 'dl-methods', role: 'radiogroup', 'aria-label': _('Disguise method') });
|
||||
const paint = () =>
|
||||
dom.content(
|
||||
el,
|
||||
METHODS.map((m) => {
|
||||
methods().map((m) => {
|
||||
const ok = !m.needs || caps[m.needs];
|
||||
const on = m.id === selected;
|
||||
return E(
|
||||
@@ -132,16 +138,16 @@ export function methodPicker(
|
||||
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') : '',
|
||||
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-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', {}, (installed ? NEEDS : NEEDS_NONE)[m.needs!])],
|
||||
: [icon('alert'), E('span', {}, needsText(m.needs!, installed))],
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// CSV for the log export. Cells a spreadsheet would run as a formula (= + - @,
|
||||
// tab, CR) get a leading apostrophe; quotes, commas and line breaks are quoted.
|
||||
// The header row is the column keys unless the caller names them (translated).
|
||||
|
||||
export function csvCell(v: unknown): string {
|
||||
let s = v == null ? '' : String(v);
|
||||
@@ -7,6 +8,6 @@ export function csvCell(v: unknown): string {
|
||||
return /[",\r\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
|
||||
}
|
||||
|
||||
export function toCsv<K extends string>(cols: readonly K[], rows: Record<K, unknown>[]): string {
|
||||
return [cols.join(','), ...rows.map((r) => cols.map((c) => csvCell(r[c])).join(','))].join('\n');
|
||||
export function toCsv<K extends string>(cols: readonly K[], rows: Record<K, unknown>[], head?: Record<K, string>): string {
|
||||
return [cols.map((c) => csvCell(head?.[c] ?? c)).join(','), ...rows.map((r) => cols.map((c) => csvCell(r[c])).join(','))].join('\n');
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
// Generated by web/i18n/extract.ts from the backend's L_() strings (npm run i18n): do not edit.
|
||||
// The words of service log lines, as written; events/model.ts matches log lines against them.
|
||||
|
||||
export const LOG_TEMPLATES: string[] = [
|
||||
'%d system package',
|
||||
'%d system packages',
|
||||
'%s (after %d repair)',
|
||||
'%s (after %d repairs)',
|
||||
"%s - %d repairs didn't help",
|
||||
'%s - %s',
|
||||
"%s - not repaired again (%d repairs didn't help)",
|
||||
'%s has no IPv4 address.',
|
||||
'%s is not a bridge, so Dawnline cannot join the LAN as a device.',
|
||||
'%s needs a manual switch in Components',
|
||||
'%s still give devices the old address: set the public address in the server settings (a DDNS name keeps working), then devices need new configurations.',
|
||||
'%s still gives devices the old address: set the public address in the server settings (a DDNS name keeps working), then devices need new configurations.',
|
||||
'%s · restored',
|
||||
'Access rules',
|
||||
'Activity',
|
||||
'AmneziaWG is missing from the router',
|
||||
'AmneziaWG is running again',
|
||||
'AmneziaWG is running again · accepting connections on port %d',
|
||||
"AmneziaWG isn't accepting connections on port %d",
|
||||
"AmneziaWG isn't running",
|
||||
'Backup',
|
||||
'Browsers will refuse the portal after that. Renew it with ACME, or choose another certificate in Settings.',
|
||||
'Choose another interface name in the server settings.',
|
||||
'Components',
|
||||
'Connections',
|
||||
'DNS for Home-only devices',
|
||||
"Dawnline didn't stop it: the router's network restarted, someone stopped it by hand, or it failed.",
|
||||
'Firewall',
|
||||
'Install it in Dawnline → Components.',
|
||||
'Internet like a home device',
|
||||
'MTU is now automatic',
|
||||
'Missing: %s.',
|
||||
'No LAN detected.',
|
||||
'No free address on %s.',
|
||||
'No free link-local range for the internal link.',
|
||||
'No free routing table.',
|
||||
'People',
|
||||
'Personal links',
|
||||
'Personal portal',
|
||||
'Router',
|
||||
'Servers',
|
||||
'Speed',
|
||||
'System packages',
|
||||
'The new version did not answer in LuCI or its agent did not start. Try again from Components, or install it with install.sh to see why.',
|
||||
'Traffic',
|
||||
'Watchdog',
|
||||
'a new build needs a manual switch in Components',
|
||||
'answers again',
|
||||
'are loaded again',
|
||||
'are missing',
|
||||
'automatic update failed',
|
||||
'background check failed: %s',
|
||||
"can't reach Dawnline (luci.dawnline is missing in rpcd)",
|
||||
"can't use the network interface %s: it exists and isn't Dawnline's",
|
||||
'certificate expires %s',
|
||||
'certificate expires within 7 days',
|
||||
'certificate renewed · valid until %s',
|
||||
"couldn't be repaired: %s",
|
||||
"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 start",
|
||||
"couldn't start · %d failed attempts in %d min",
|
||||
'failed - internet goes out directly for now',
|
||||
'failed: %s',
|
||||
'has an invalid interface name "%s"',
|
||||
'installed the %s build',
|
||||
'installed the %s build · %s',
|
||||
'is kept down',
|
||||
'is kept down: its disguise needs AmneziaWG %s (installed: %s)',
|
||||
'is kept down: its disguise needs AmneziaWG %s (installed: none)',
|
||||
'is off',
|
||||
'is on · traffic enters %s as %s',
|
||||
'is ready again',
|
||||
"isn't answering on port %d",
|
||||
"isn't installed: no tunnel can run - install it in Dawnline → Components",
|
||||
"isn't installed: tunnels were left as they are",
|
||||
"isn't known to the network service - restart the network or reboot",
|
||||
"isn't running",
|
||||
"isn't running on this router (fw4): tunnels and the portal are closed",
|
||||
"kernel module isn't installed: no tunnel can run - install it in Dawnline → Components",
|
||||
"kernel module isn't loaded",
|
||||
'loading it',
|
||||
'loading them again',
|
||||
'moved to word codes',
|
||||
'netifd reads its protocol handlers when it starts; it was running before AmneziaWG was installed.',
|
||||
'network changed - Dawnline set itself up again',
|
||||
'nightly backup failed: %s',
|
||||
'public address changed · %s → %s',
|
||||
'reaches Dawnline again',
|
||||
'reloading rpcd',
|
||||
'restarted · version %s',
|
||||
'restarting for the AmneziaWG update',
|
||||
'restarting it',
|
||||
'restoring them',
|
||||
'rules for Dawnline are in place again',
|
||||
"rules for Dawnline aren't loaded",
|
||||
'rules for Dawnline were changed or removed',
|
||||
'runs again',
|
||||
'setting it up again',
|
||||
'started',
|
||||
'started with the router · version %s',
|
||||
'started · accepting connections on port %s',
|
||||
'started · version %s',
|
||||
'stopped unexpectedly',
|
||||
'stopped unexpectedly - started again',
|
||||
'update failed',
|
||||
'update to %s failed its check - rolled back to %s',
|
||||
'updated automatically · %s',
|
||||
'updated automatically · %s → %s',
|
||||
'updated · %s',
|
||||
'updated · %s → %s',
|
||||
'updates available · %s',
|
||||
'was broken - set up again (%s as %s)',
|
||||
];
|
||||
+204
-15
@@ -3,6 +3,8 @@
|
||||
|
||||
import type { LogEvent } from '../../shared/types';
|
||||
import type { LogCategory, LogsInfo, ServiceLogEntry } from '../api';
|
||||
import { fmt, known, plural } from '../../shared/i18n';
|
||||
import { LOG_TEMPLATES } from './log-templates';
|
||||
|
||||
/** Mirrors CATEGORY in dawnline.live. */
|
||||
const CATEGORY: Record<string, LogCategory> = {
|
||||
@@ -27,21 +29,24 @@ const CATEGORY: Record<string, LogCategory> = {
|
||||
|
||||
export const CATEGORIES: LogCategory[] = ['connections', 'people', 'problems'];
|
||||
|
||||
export const CATEGORY_LABEL: Record<LogCategory, string> = {
|
||||
connections: 'Connections',
|
||||
people: 'People',
|
||||
problems: 'Problems',
|
||||
};
|
||||
export function categoryLabel(c: LogCategory): string {
|
||||
return { connections: _('Connections'), people: _('People'), problems: _('Problems') }[c];
|
||||
}
|
||||
|
||||
export const CATEGORY_HELP: Record<LogCategory, string> = {
|
||||
connections: 'Connects, disconnects and IP changes',
|
||||
people: 'People and their devices added, changed, paused, removed',
|
||||
problems: 'Blocked portal sign-ins (tunnels and services are in the service log)',
|
||||
};
|
||||
export function categoryHelp(c: LogCategory): string {
|
||||
return {
|
||||
connections: _('Connects, disconnects and IP changes'),
|
||||
people: _('People and their devices added, changed, paused, removed'),
|
||||
problems: _('Blocked portal sign-ins (tunnels and services are in the service log)'),
|
||||
}[c];
|
||||
}
|
||||
|
||||
export const categoryOf = (type: string): LogCategory => CATEGORY[type] ?? 'problems';
|
||||
|
||||
export const SYSTEM_SOURCE: Record<ServiceLogEntry['src'], string> = { awg: 'AmneziaWG', dawnline: 'Dawnline', portal: 'Portal' };
|
||||
/** What a service log source is called; unknown ones by their id. */
|
||||
export function sourceName(src: ServiceLogEntry['src']): string {
|
||||
return { awg: 'AmneziaWG', dawnline: 'Dawnline', portal: _('Portal') }[src] ?? src;
|
||||
}
|
||||
|
||||
const ADMIN_TYPES = ['person_added', 'person_removed', 'person_changed'];
|
||||
|
||||
@@ -65,10 +70,194 @@ export const isProblem = (x: LogItem) =>
|
||||
x.sys ? ['error', 'repair', 'down'].includes(x.sys.level) : categoryOf(x.ev!.type) === 'problems';
|
||||
|
||||
export function retentionText(p: LogsInfo['policy']): string {
|
||||
const age = p.keep_days > 0 ? `${p.keep_days} day${p.keep_days === 1 ? '' : 's'}` : 'no age limit';
|
||||
const age = p.keep_days > 0 ? plural(p.keep_days, '%s day', '%s days') : _('no age limit');
|
||||
const where =
|
||||
p.persist === 'off'
|
||||
? 'kept in memory only (lost on reboot)'
|
||||
: `saved to flash ${p.persist === '10min' ? 'every 10 minutes' : 'hourly'}`;
|
||||
return `Kept for ${age}, up to ${p.max.toLocaleString('en-GB')} events, ${where}.`;
|
||||
? _('kept in memory only (lost on reboot)')
|
||||
: p.persist === '10min'
|
||||
? _('saved to flash every 10 minutes')
|
||||
: _('saved to flash hourly');
|
||||
return fmt(_('Kept for %s, %s, %s.'), age, plural(p.max, 'up to %s event', 'up to %s events'), where);
|
||||
}
|
||||
|
||||
/* ---------- the router's words, put into the page's language ----------
|
||||
* Events and service log lines are written once, in English, by whoever was
|
||||
* running (the agent has no language) and read later in any language: the
|
||||
* words below are their fixed vocabulary, translated when shown. Anything
|
||||
* else stays as written. */
|
||||
|
||||
/** Why someone was paused or resumed (the agent's REASON words). */
|
||||
export function reasonText(detail: string): string {
|
||||
const t: Record<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'),
|
||||
};
|
||||
return t[detail] ?? detail;
|
||||
}
|
||||
|
||||
/** Days left in an "expiring" event's detail ("3 days"), or null. */
|
||||
export function daysOf(detail: string): number | null {
|
||||
const m = /^(\d+) days?$/.exec(detail);
|
||||
return m ? Number(m[1]) : null;
|
||||
}
|
||||
|
||||
/** The person's settings a person_changed event lists (option names, "moved to <server>"). */
|
||||
export function changedText(detail: string): string {
|
||||
const f: Record<string, string> = {
|
||||
name: _('name'),
|
||||
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'),
|
||||
circle: _('circle', 'setting'),
|
||||
home_nets: _('home networks'),
|
||||
server: _('server'),
|
||||
};
|
||||
return detail
|
||||
.split(', ')
|
||||
.map((k) => {
|
||||
const to = /^moved to (.+)$/.exec(k)?.[1];
|
||||
return to ? fmt(_('moved to %s'), to) : (f[k] ?? k.replace(/_/g, ' '));
|
||||
})
|
||||
.join(', ');
|
||||
}
|
||||
|
||||
/**
|
||||
* The admin's own change in the service log ({ msg: 'changed', kind:
|
||||
* 'server', who: 'Home' }), as one sentence: with %s for the name it names,
|
||||
* or whole when the name is a fixed phrase ("the service log"); null for one
|
||||
* this page does not know.
|
||||
*/
|
||||
export function adminSentence(msg: string, kind?: string | null, who?: string | null): { text: string; named: boolean } | null {
|
||||
const fixed: Record<string, string> = {
|
||||
'cleared|the service log': _('You cleared the service log'),
|
||||
'cleared|the activity log': _('You cleared the activity log'),
|
||||
'exported|all settings': _('You exported all settings'),
|
||||
'imported|settings from a file': _('You imported settings from a file'),
|
||||
'restored|from a file': _('You restored a backup from a file'),
|
||||
'turned on|the personal portal': _('You turned on the personal portal'),
|
||||
'turned off|the personal portal': _('You turned off the personal portal'),
|
||||
'changed|the personal portal': _('You changed the personal portal'),
|
||||
'turned on|the watchdog': _('You turned on the watchdog'),
|
||||
'turned off|the watchdog': _('You turned off the watchdog'),
|
||||
'reset traffic history|for everyone': _('You reset traffic history for everyone'),
|
||||
};
|
||||
const whole = fixed[`${msg}|${who ?? ''}`];
|
||||
if (whole) return { text: whole, named: false };
|
||||
const named: Record<string, string> = {
|
||||
'created|server': _('You created server %s'),
|
||||
'changed|server': _('You changed server %s'),
|
||||
'removed|server': _('You removed server %s'),
|
||||
'turned on|server': _('You turned on server %s'),
|
||||
'turned off|server': _('You turned off server %s'),
|
||||
'added|circle': _('You added circle %s'),
|
||||
'changed|circle': _('You changed circle %s'),
|
||||
'removed|circle': _('You removed circle %s'),
|
||||
'restored|backup': _('You restored backup %s'),
|
||||
};
|
||||
const t = named[`${msg}|${kind ?? ''}`];
|
||||
if (t) return { text: t, named: true };
|
||||
// "reset traffic history" "for Anna": the name after "for".
|
||||
const forWho = msg === 'reset traffic history' && /^for (.+)$/.exec(who ?? '')?.[1];
|
||||
return forWho ? { text: _('You reset traffic history for %s'), named: true } : null;
|
||||
}
|
||||
|
||||
/** 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);
|
||||
|
||||
/** The note after an admin's change: its known pieces translated, the rest as written. */
|
||||
export function noteText(note: string): string {
|
||||
const one = (p: string): string => {
|
||||
const t: Record<string, string> = {
|
||||
'other addresses': _('other addresses'),
|
||||
certificate: _('certificate'),
|
||||
redirect: _('redirect'),
|
||||
'devices kept apart': _('devices kept apart'),
|
||||
'devices reach each other': _('devices reach each other'),
|
||||
'devices reach each other in circles': _('devices reach each other in circles'),
|
||||
'home network and internet path': _('home network and internet path'),
|
||||
'the file holds private keys': _('the file holds private keys'),
|
||||
'problems are only logged, nothing is repaired': _('problems are only logged, nothing is repaired'),
|
||||
name: _('name'),
|
||||
'public address': _('public address'),
|
||||
'AmneziaWG port': _('AmneziaWG port'),
|
||||
'tunnel network': _('tunnel network'),
|
||||
connections: categoryLabel('connections'),
|
||||
people: categoryLabel('people'),
|
||||
problems: categoryLabel('problems'),
|
||||
};
|
||||
if (t[p]) return t[p];
|
||||
let m: RegExpExecArray | null;
|
||||
if ((m = /^port (\d+)$/.exec(p))) return fmt(_('port %s'), m[1]);
|
||||
if ((m = /^address (.+)$/.exec(p))) return fmt(_('address %s'), m[1]);
|
||||
if ((m = /^disguise: (.+)$/.exec(p))) return fmt(_('disguise: %s'), m[1]);
|
||||
if ((m = /^(\d+) events?$/.exec(p))) return plural(Number(m[1]), '%s event', '%s events');
|
||||
if ((m = /^older than (\d+) days$/.exec(p))) return plural(Number(m[1]), 'older than %s day', 'older than %s days');
|
||||
if ((m = /^with (\d+) (person|people)$/.exec(p))) return plural(Number(m[1]), 'with %s person', 'with %s people');
|
||||
if ((m = /^(\d+) entr(y|ies)( older than (\d+) days)?$/.exec(p)))
|
||||
return m[4]
|
||||
? `${plural(Number(m[1]), '%s entry', '%s entries')}, ${plural(Number(m[4]), 'older than %s day', 'older than %s days')}`
|
||||
: plural(Number(m[1]), '%s entry', '%s entries');
|
||||
return p;
|
||||
};
|
||||
return note
|
||||
.split(' · ')
|
||||
.map((part) => part.split(', ').map(one).join(', '))
|
||||
.join(' · ');
|
||||
}
|
||||
|
||||
/* ---------- the service log's lines ----------
|
||||
* The router writes them in English from its L_() templates (the generated
|
||||
* list in ./log-templates); a line is put into the page's language by the
|
||||
* template it matches, its values (versions, ports, names, or another
|
||||
* template's words) put back in place. Lines written before the plain dash
|
||||
* have "—" where the templates have "-". */
|
||||
|
||||
let patterns: { t: string; re: RegExp }[] | null = null;
|
||||
const LOG_EXACT = new Set(LOG_TEMPLATES);
|
||||
|
||||
/** The templates with values in them, the most specific (most fixed text) first. */
|
||||
function logPatterns() {
|
||||
return (patterns ??= LOG_TEMPLATES.filter((t) => /%[sd]/.test(t) && t.replace(/%[sd]/g, '').trim())
|
||||
.map((t) => ({
|
||||
t,
|
||||
fixed: t.replace(/%[sd]/g, '').length,
|
||||
re: new RegExp(
|
||||
`^${t
|
||||
.split(/(%[sd])/)
|
||||
.map((p) => (p === '%s' ? '(.+?)' : p === '%d' ? '(\\d+)' : p.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')))
|
||||
.join('')}$`,
|
||||
),
|
||||
}))
|
||||
.sort((a, b) => b.fixed - a.fixed));
|
||||
}
|
||||
|
||||
/** A service log line (or its subject, or a line of its details) in the page's language; one it does not know as written. */
|
||||
export function logText(line: string, depth = 0): string {
|
||||
const s = line.replace(/ — /g, ' - ');
|
||||
if (LOG_EXACT.has(s)) return known(s);
|
||||
if (depth > 2) return line;
|
||||
for (const p of logPatterns()) {
|
||||
const m = p.re.exec(s);
|
||||
if (m) return fmt(known(p.t), ...m.slice(1).map((v) => logText(v, depth + 1)));
|
||||
}
|
||||
// A list ("Dawnline 0.3.3, 2 system packages"): each item on its own.
|
||||
return s.includes(', ')
|
||||
? s
|
||||
.split(', ')
|
||||
.map((x) => logText(x, depth + 1))
|
||||
.join(', ')
|
||||
: line;
|
||||
}
|
||||
+132
-89
@@ -1,12 +1,14 @@
|
||||
// Log rows: an activity event as a sentence ("You added device Phone for
|
||||
// Myata"), its tile and time, and a service log line.
|
||||
// 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).
|
||||
|
||||
import type { LogEvent, Status } from '../../shared/types';
|
||||
import type { ServiceLogEntry } from '../api';
|
||||
import { E } from '../e';
|
||||
import { icon } from '../../shared/icons';
|
||||
import { ago } from '../../shared/format';
|
||||
import { SYSTEM_SOURCE, eventBy, plainDetail } from './model';
|
||||
import { ago, fmtDay } from '../../shared/format';
|
||||
import { fill, fmt, locale, num } from '../../shared/i18n';
|
||||
import { adminName, adminSentence, changedText, daysOf, eventBy, logText, noteText, plainDetail, reasonText, sourceName } from './model';
|
||||
|
||||
/** What the people and servers in the log are called now. */
|
||||
export type Names = Pick<Status, 'people' | 'servers'>;
|
||||
@@ -49,6 +51,9 @@ function eventIcon(st: Names, e: LogEvent): string {
|
||||
return EVENT_ICON[e.type] ?? 'activity';
|
||||
}
|
||||
|
||||
/** 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): Node[] {
|
||||
const person = st.people.find((p) => p.id === e.person);
|
||||
const who = person?.name ?? e.pname ?? e.person ?? '';
|
||||
@@ -61,101 +66,97 @@ export function eventText(st: Pick<Status, 'people'>, e: LogEvent): Node[] {
|
||||
e.hosts?.[ip]
|
||||
? [E('span', { class: 'dl-ev-host' }, [E('b', {}, e.hosts[ip]), E('span', { class: 'dl-faint' }, ` (${ip})`)])]
|
||||
: [mono(ip)];
|
||||
// What the bold name is (a person, a device), said before it in grey.
|
||||
const kind = (t: string) => E('span', { class: 'dl-ev-kind' }, `${t} `);
|
||||
const wd = dev ? `${who} · ${dev}` : who;
|
||||
const detail = plainDetail(e);
|
||||
const devName = detail || dev || 'a device';
|
||||
// A sentence in grey around its bold names, people and devices.
|
||||
const say = (s: string, ...args: Node[]): Node[] => fill(s, ...args).map((x) => (typeof x === 'string' ? m(x) : x));
|
||||
// The admin's own actions start with an accent "You".
|
||||
const you = (verb: string) => [E('span', { class: 'dl-you' }, 'You'), m(` ${verb} `)];
|
||||
if (eventBy(e) === 'admin')
|
||||
const you = (s: string, ...args: Node[]): Node[] => {
|
||||
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(dev ? `${who} · ${dev}` : who);
|
||||
const detail = plainDetail(e);
|
||||
const devName = b(detail || dev || _('a device'));
|
||||
const by = eventBy(e);
|
||||
if (by === 'admin')
|
||||
switch (e.type) {
|
||||
case 'device_added':
|
||||
return [...you('added'), kind('device'), b(devName), m(' for '), b(who)];
|
||||
return you(_('You added device %s for %s'), devName, b(who));
|
||||
case 'device_removed':
|
||||
return [...you('removed'), kind('device'), b(devName), m(' from '), b(who)];
|
||||
return you(_('You removed device %s from %s'), devName, b(who));
|
||||
case 'paused':
|
||||
return [...you('paused'), kind('person'), b(who)];
|
||||
return you(_('You paused person %s'), b(who));
|
||||
case 'resumed':
|
||||
return [...you('resumed'), kind('person'), b(who)];
|
||||
return you(_('You resumed person %s'), b(who));
|
||||
case 'device_changed': {
|
||||
const renamed = detail.startsWith('renamed from ');
|
||||
return [
|
||||
...you(renamed ? 'renamed' : detail),
|
||||
kind('device'),
|
||||
b(dev || 'a device'),
|
||||
m(' of '),
|
||||
b(who),
|
||||
...(renamed ? [m(` · was ${detail.slice(13)}`)] : []),
|
||||
];
|
||||
const d = b(dev || _('a device'));
|
||||
if (detail.startsWith('renamed from '))
|
||||
return [...you(_('You renamed device %s of %s'), d, b(who)), m(` · ${fmt(_('was %s'), detail.slice(13))}`)];
|
||||
if (detail === 'turned off') return you(_('You turned off device %s of %s'), d, b(who));
|
||||
if (detail === 'turned on') return you(_('You turned on device %s of %s'), d, b(who));
|
||||
return [...you(_('You changed device %s of %s'), d, b(who)), ...(detail ? [m(` · ${detail}`)] : [])];
|
||||
}
|
||||
case 'device_keys':
|
||||
return [...you('issued new keys for'), kind('device'), b(devName), m(' of '), b(who), m(' · it needs its new configuration')];
|
||||
return [...you(_('You issued new keys for device %s of %s'), devName, b(who)), m(` · ${_('it needs its new configuration')}`)];
|
||||
case 'link_changed':
|
||||
return [...you('issued a new link for'), kind('person'), b(who), m(' · the old link stopped working')];
|
||||
return [...you(_('You issued a new link for person %s'), b(who)), m(` · ${_('the old link stopped working')}`)];
|
||||
}
|
||||
switch (e.type) {
|
||||
case 'connect':
|
||||
return [
|
||||
kind('Device'),
|
||||
b(wd),
|
||||
m(' connected'),
|
||||
...(e.detail ? [m(' from '), ...addr(e.detail)] : []),
|
||||
...(e.detail ? say(_('Device %s connected from %s'), wd, E('span', {}, addr(e.detail))) : say(_('Device %s connected'), wd)),
|
||||
...(e.where ? [m(` · ${e.where}`)] : []),
|
||||
];
|
||||
case 'disconnect':
|
||||
return [kind('Device'), b(wd), m(' went offline')];
|
||||
return say(_('Device %s went offline'), wd);
|
||||
case 'roam':
|
||||
return [
|
||||
kind('Device'),
|
||||
b(wd),
|
||||
m(' changed network '),
|
||||
...(e.detail ?? '').split(' → ').flatMap((ip, i) => (i ? [m(' → '), ...addr(ip)] : addr(ip))),
|
||||
];
|
||||
return say(
|
||||
_('Device %s changed network %s'),
|
||||
wd,
|
||||
E(
|
||||
'span',
|
||||
{},
|
||||
(e.detail ?? '').split(' → ').flatMap((ip, i) => (i ? [m(' → '), ...addr(ip)] : addr(ip))),
|
||||
),
|
||||
);
|
||||
case 'device_added':
|
||||
return [
|
||||
kind('Person'),
|
||||
b(who),
|
||||
m(' added '),
|
||||
kind('device'),
|
||||
b(devName),
|
||||
...(eventBy(e) === 'portal' ? [m(' on their portal')] : []),
|
||||
];
|
||||
return by === 'portal'
|
||||
? say(_('Person %s added device %s on their portal'), b(who), devName)
|
||||
: say(_('Person %s added device %s'), b(who), devName);
|
||||
case 'device_removed':
|
||||
return [
|
||||
kind('Person'),
|
||||
b(who),
|
||||
m(' removed '),
|
||||
kind('device'),
|
||||
b(devName),
|
||||
...(eventBy(e) === 'portal' ? [m(' on their portal')] : []),
|
||||
];
|
||||
return by === 'portal'
|
||||
? say(_('Person %s removed device %s on their portal'), b(who), devName)
|
||||
: say(_('Person %s removed device %s'), b(who), devName);
|
||||
case 'device_keys':
|
||||
return [kind('Person'), b(who), m(' issued new keys for '), kind('device'), b(devName), m(' on their portal')];
|
||||
return say(_('Person %s issued new keys for device %s on their portal'), b(who), devName);
|
||||
case 'person_added':
|
||||
return [...you('added'), kind('person'), b(e.detail ?? who)];
|
||||
return you(_('You added person %s'), b(e.detail ?? who));
|
||||
case 'person_removed':
|
||||
return [...you('removed'), kind('person'), b(e.detail ?? who)];
|
||||
return you(_('You removed person %s'), b(e.detail ?? who));
|
||||
case 'person_changed':
|
||||
// The detail lists changed fields by their option names (device_limit, expire_action).
|
||||
return [...you('changed'), kind('person'), b(who), ...(detail ? [m(` · ${detail.replace(/_/g, ' ')}`)] : [])];
|
||||
case 'expiring':
|
||||
return [kind('Person'), b(who), m(`’s access ends in ${e.detail ?? 'a few days'}`)];
|
||||
return [...you(_('You changed person %s'), b(who)), ...(detail ? [m(` · ${changedText(detail)}`)] : [])];
|
||||
case 'expiring': {
|
||||
const n = daysOf(e.detail ?? '');
|
||||
return n != null
|
||||
? 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(_('Person %s’s access ends in a few days'), b(who));
|
||||
}
|
||||
case 'expired_kept':
|
||||
return [kind('Person'), b(who), m(`’s end date passed (${e.detail ?? ''}) · access kept`)];
|
||||
return say(_('Person %s’s end date passed (%s) · access kept'), b(who), m(routerDay(e.detail ?? '')));
|
||||
case 'paused':
|
||||
return [kind('Person'), b(who), m(` paused — ${e.detail ?? ''}`)];
|
||||
return e.detail ? say(_('Person %s paused - %s'), b(who), m(reasonText(e.detail))) : say(_('Person %s paused'), b(who));
|
||||
case 'resumed':
|
||||
return [kind('Person'), b(who), m(' resumed'), ...(e.detail && e.detail !== 'active' ? [m(` — ${e.detail}`)] : [])];
|
||||
return e.detail && e.detail !== 'active'
|
||||
? say(_('Person %s resumed - %s'), b(who), m(reasonText(e.detail)))
|
||||
: say(_('Person %s resumed'), b(who));
|
||||
case 'portal_blocked':
|
||||
return [
|
||||
E('b', { class: 'dl-sys-src' }, 'Personal portal'),
|
||||
m(' blocked '),
|
||||
mono(e.detail ?? ''),
|
||||
m(' for 15 min after too many wrong codes'),
|
||||
];
|
||||
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 [kind('Person'), b(who), m(' — all devices removed, end date reached')];
|
||||
return say(_('Person %s - all devices removed, end date reached'), b(who));
|
||||
default:
|
||||
return [m(`${e.type}${e.detail ? `: ${e.detail}` : ''}`)];
|
||||
}
|
||||
@@ -171,7 +172,7 @@ 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) : '';
|
||||
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). */
|
||||
@@ -180,13 +181,13 @@ export function eventRow(st: Names & { now?: number }, e: LogEvent, opts: { serv
|
||||
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'))
|
||||
? 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.server === false ? '' : serverPill(st, e),
|
||||
E('span', { class: 'dl-faint dl-nowrap', title: new Date(e.ts * 1000).toLocaleString() }, opts.time ?? ago(e.ts, st.now)),
|
||||
E('span', { class: 'dl-faint dl-nowrap', title: new Date(e.ts * 1000).toLocaleString(locale()) }, opts.time ?? ago(e.ts, st.now)),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -195,9 +196,47 @@ export function eventRow(st: Names & { now?: number }, e: LogEvent, opts: { serv
|
||||
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 {
|
||||
return { info: _('info'), up: _('up'), down: _('down'), repair: _('repair'), error: _('error') }[l] ?? l;
|
||||
}
|
||||
|
||||
/**
|
||||
* The admin's own change: "You changed server Home" as one sentence of the
|
||||
* page's language, "You" in the accent; one this page does not know is put
|
||||
* together from the router's words as before.
|
||||
*/
|
||||
function adminLine(e: ServiceLogEntry): (Node | string)[] {
|
||||
const s = adminSentence(e.msg, e.kind, e.who);
|
||||
const you = _('You');
|
||||
if (!s)
|
||||
return [
|
||||
E('span', { class: 'dl-you' }, you),
|
||||
E('span', { class: 'dl-muted' }, ` ${e.msg} `),
|
||||
e.kind ? E('span', { class: 'dl-ev-kind' }, `${e.kind} `) : '',
|
||||
e.who ? E('b', {}, e.who) : '',
|
||||
];
|
||||
const parts = (s.named ? fill<Node | string>(s.text, E('b', {}, adminName(e.msg, e.who ?? ''))) : [s.text]).map((x) =>
|
||||
typeof x === 'string' ? E('span', { class: 'dl-muted' }, x) : x,
|
||||
);
|
||||
// The accent on "You" where the sentence starts with it.
|
||||
const first = parts[0]?.textContent ?? '';
|
||||
return first.startsWith(`${you} `)
|
||||
? [E('span', { class: 'dl-you' }, you), E('span', { class: 'dl-muted' }, first.slice(you.length)), ...parts.slice(1)]
|
||||
: parts;
|
||||
}
|
||||
|
||||
/** A log line's details: its sentences in the page's language, command output as it is. */
|
||||
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';
|
||||
const msg = logText(e.msg);
|
||||
const row = E(
|
||||
'div',
|
||||
{
|
||||
@@ -205,32 +244,35 @@ export function systemRow(e: ServiceLogEntry, open: boolean, toggle: () => void,
|
||||
},
|
||||
[
|
||||
admin
|
||||
? E('span', { class: 'dl-ev-tile', title: 'Done by you in LuCI' }, icon('admin'))
|
||||
: E('span', { class: 'dl-ev-tile sys', title: e.level }, icon(SYS_ICON[e.src] ?? 'zap')),
|
||||
? 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
|
||||
? [
|
||||
E('span', { class: 'dl-you' }, 'You'),
|
||||
E('span', { class: 'dl-muted' }, ` ${e.msg} `),
|
||||
e.kind ? E('span', { class: 'dl-ev-kind' }, `${e.kind} `) : '',
|
||||
e.who ? E('b', {}, e.who) : '',
|
||||
e.note ? E('span', { class: 'dl-muted' }, ` · ${e.note}`) : '',
|
||||
...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' }, e.detail) : '',
|
||||
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 ') : '',
|
||||
E('b', { class: 'dl-sys-src', title: SYSTEM_SOURCE[e.src] ?? e.src }, e.who ?? SYSTEM_SOURCE[e.src] ?? e.src),
|
||||
' ',
|
||||
E('span', { class: 'dl-muted' }, e.msg),
|
||||
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' }, e.detail) : '',
|
||||
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() }, time),
|
||||
E('span', { class: 'dl-faint dl-nowrap', title: new Date(e.ts * 1000).toLocaleString(locale()) }, time),
|
||||
],
|
||||
);
|
||||
if (e.detail)
|
||||
@@ -240,13 +282,14 @@ export function systemRow(e: ServiceLogEntry, open: boolean, toggle: () => void,
|
||||
return row;
|
||||
}
|
||||
|
||||
/** "Today", "Yesterday" or "Monday 12 October". */
|
||||
/** "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';
|
||||
return d.toLocaleDateString('en-GB', { weekday: 'long', day: 'numeric', month: 'long' });
|
||||
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);
|
||||
}
|
||||
+101
-73
@@ -11,13 +11,15 @@ import { seg, sw } from './ui/controls';
|
||||
import { attachTip } from './ui/tooltip';
|
||||
import { installMissing } from './pkgs';
|
||||
import { icon } from '../shared/icons';
|
||||
import { fill, fmt, locale, plural } from '../shared/i18n';
|
||||
|
||||
const GROUPS: [IfaceCategory, string][] = [
|
||||
/** 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'],
|
||||
['vpn', _('VPN & tunnels')],
|
||||
['other', _('Other')],
|
||||
];
|
||||
|
||||
const ICON: Record<NetDevice['kind'], string> = {
|
||||
@@ -48,7 +50,7 @@ export function accessCards(srv: Server, first: Status, refresh: () => Promise<u
|
||||
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…'))),
|
||||
E('section', { class: 'dl-setsec' }, E('div', { class: 'dl-setsec-body' }, E('p', { class: 'dl-muted' }, _('Loading interfaces…')))),
|
||||
);
|
||||
let d: InterfacesData;
|
||||
let autoWan = true,
|
||||
@@ -112,16 +114,16 @@ export function accessCards(srv: Server, first: Status, refresh: () => Promise<u
|
||||
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'
|
||||
? _('Not present right now')
|
||||
: x.own
|
||||
? 'This server'
|
||||
? _('This server')
|
||||
: x.master
|
||||
? `Port of ${x.master}`
|
||||
? fmt(_('Port of %s'), x.master)
|
||||
: isWan
|
||||
? `Internet${x.zone ? ` · zone ${x.zone}` : ''}`
|
||||
? `${_('Internet')}${x.zone ? ` · ${fmt(_('zone %s'), x.zone)}` : ''}`
|
||||
: x.nets.length
|
||||
? x.nets.join(', ')
|
||||
: 'No IPv4 network';
|
||||
: _('No IPv4 network');
|
||||
const el = E(
|
||||
'button',
|
||||
{
|
||||
@@ -140,19 +142,20 @@ export function accessCards(srv: Server, first: Status, refresh: () => Promise<u
|
||||
[
|
||||
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')) : '',
|
||||
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 ? `Interface ${x.logical}` : 'No netifd interface',
|
||||
x.zone ? ` · zone ${x.zone}` : ' · no firewall zone',
|
||||
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' }, `Ports: ${x.members.join(', ')}`) : '',
|
||||
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' }, `Choose ${x.master} to include it.`) : '',
|
||||
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;
|
||||
}
|
||||
@@ -167,36 +170,39 @@ export function accessCards(srv: Server, first: Status, refresh: () => Promise<u
|
||||
|
||||
function likeHomeText(): (Node | string)[] {
|
||||
const lh = d.like_home;
|
||||
if (!lanLike) return ['Off: internet traffic goes straight to the WAN, past whatever handles home traffic on this router.'];
|
||||
if (!lanLike) return [_('Off: internet traffic goes straight to the WAN, past whatever handles home traffic on this router.')];
|
||||
if (d.needs?.length)
|
||||
return [
|
||||
E('span', { class: 'dl-warn' }, `Needs ${d.needs.join(' and ')}.`),
|
||||
' Until they are installed, internet traffic goes straight to the WAN.',
|
||||
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.'];
|
||||
return [_('Internet traffic will enter the router from your LAN, so it is handled like any home device. Save to turn on.')];
|
||||
// A server that is off has no link on purpose: describe the setting, not its state.
|
||||
if (!srv.enabled)
|
||||
return ['Internet traffic enters the router from your LAN, so whatever handles home traffic (proxies, filters, DNS) handles it too.'];
|
||||
if (lh.active && lh.bridged)
|
||||
return [
|
||||
'Internet traffic enters ',
|
||||
E('span', { class: 'dl-mono' }, lh.dev ?? ''),
|
||||
' as ',
|
||||
E('span', { class: 'dl-mono' }, lh.address ?? ''),
|
||||
', so whatever handles home traffic (proxies, filters, DNS) handles it too.',
|
||||
_('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' }, `Not working: ${lh.error ?? 'the link is down'}`),
|
||||
' Internet traffic goes straight to the WAN for now.',
|
||||
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 MESH_TEXT: Record<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.',
|
||||
};
|
||||
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,
|
||||
@@ -217,8 +223,12 @@ export function accessCards(srv: Server, first: Status, refresh: () => Promise<u
|
||||
|
||||
const hint = (live: string | null, saved: string) => {
|
||||
const mono = (t: string) => E('span', { class: 'dl-mono' }, t);
|
||||
if (live) return E('span', {}, [' Now: ', mono(live), ...(saved && saved !== live ? [', was ', mono(saved)] : []), '.']);
|
||||
return E('span', {}, saved ? [' Not found now: using ', mono(saved), '.'] : [' Not found.']);
|
||||
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() {
|
||||
@@ -226,7 +236,7 @@ export function accessCards(srv: Server, first: Status, refresh: () => Promise<u
|
||||
'select',
|
||||
{
|
||||
class: 'cbi-input-select',
|
||||
'aria-label': 'Internet interface',
|
||||
'aria-label': _('Internet interface'),
|
||||
change: (ev: Event) => {
|
||||
wanDev = (ev.target as HTMLSelectElement).value;
|
||||
paint();
|
||||
@@ -234,7 +244,9 @@ export function accessCards(srv: Server, first: Status, refresh: () => Promise<u
|
||||
},
|
||||
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} · zone ${x.zone}`)),
|
||||
.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();
|
||||
@@ -247,17 +259,21 @@ export function accessCards(srv: Server, first: Status, refresh: () => Promise<u
|
||||
const homeDirty = changed(3, 4);
|
||||
const save = (on: boolean) =>
|
||||
button(
|
||||
'Save',
|
||||
_('Save'),
|
||||
async () => {
|
||||
const r = await attempt(
|
||||
() => api.serverInterfaces(serverId, autoWan, autoWan ? '' : wanDev, autoLan, [...lans], lanLike, mesh !== 'off', mesh),
|
||||
'Access saved',
|
||||
_('Access saved'),
|
||||
);
|
||||
if (!r) return;
|
||||
take(r, true);
|
||||
if (r.nets_changed && r.lan_only)
|
||||
notify(
|
||||
`${r.lan_only} ${r.lan_only === 1 ? 'person has' : 'people have'} Home-only access: their devices need the configuration again to reach the new networks.`,
|
||||
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,
|
||||
);
|
||||
@@ -269,17 +285,17 @@ export function accessCards(srv: Server, first: Status, refresh: () => Promise<u
|
||||
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('h3', {}, _('Internet')),
|
||||
E('span', { class: 'dl-spacer' }),
|
||||
E('span', { class: 'dl-sub' }, 'People with Internet or Both'),
|
||||
E('span', { class: 'dl-sub' }, _('People with Internet or Both')),
|
||||
]),
|
||||
setrow(
|
||||
'home',
|
||||
'Internet like a home device',
|
||||
_('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 && d.needs?.length ? button(_('Install'), () => installMissing('home', d.needs!, () => load(false)), 'positive') : '',
|
||||
sw(lanLike, _('Internet like a home device'), (v) => {
|
||||
lanLike = v;
|
||||
paint();
|
||||
}),
|
||||
@@ -288,14 +304,14 @@ export function accessCards(srv: Server, first: Status, refresh: () => Promise<u
|
||||
),
|
||||
setrow(
|
||||
'globe',
|
||||
'Auto-detect WAN',
|
||||
_('Auto-detect WAN'),
|
||||
[
|
||||
'The interface with the default route: the server port opens there and Internet access leaves through it.',
|
||||
_('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) => {
|
||||
sw(autoWan, _('Auto-detect WAN'), (v) => {
|
||||
autoWan = v;
|
||||
paint();
|
||||
}),
|
||||
@@ -307,10 +323,13 @@ export function accessCards(srv: Server, first: Status, refresh: () => Promise<u
|
||||
'span',
|
||||
{ class: 'dl-sub' },
|
||||
lanLike
|
||||
? ['Internet like a home device', currentWan() ? [' · leaves through ', E('span', { class: 'dl-mono' }, currentWan())] : '']
|
||||
? [
|
||||
_('Internet like a home device'),
|
||||
currentWan() ? [' · ', ...fill(_('leaves through %s'), E('span', { class: 'dl-mono' }, currentWan()))] : '',
|
||||
]
|
||||
: currentWan()
|
||||
? ['Internet straight to ', E('span', { class: 'dl-mono' }, currentWan())]
|
||||
: 'No WAN found',
|
||||
? fill(_('Internet straight to %s'), E('span', { class: 'dl-mono' }, currentWan()))
|
||||
: _('No WAN found'),
|
||||
),
|
||||
save(netDirty),
|
||||
]),
|
||||
@@ -318,19 +337,19 @@ export function accessCards(srv: Server, first: Status, refresh: () => Promise<u
|
||||
|
||||
const meshSeg = seg(
|
||||
[
|
||||
['off', 'Off'],
|
||||
['all', 'Everyone'],
|
||||
['circles', 'Circles'],
|
||||
['off', _('Off')],
|
||||
['all', _('Everyone')],
|
||||
['circles', _('Circles')],
|
||||
] as [MeshMode, string][],
|
||||
mesh,
|
||||
{
|
||||
label: 'Devices reach each other',
|
||||
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 }), `Devices reach each other: ${t}`))) return;
|
||||
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();
|
||||
@@ -342,23 +361,25 @@ export function accessCards(srv: Server, first: Status, refresh: () => Promise<u
|
||||
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('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' }),
|
||||
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.',
|
||||
_('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',
|
||||
MESH_TEXT[mesh],
|
||||
_('Devices reach each other'),
|
||||
meshText(mesh),
|
||||
meshSeg,
|
||||
'',
|
||||
mesh === 'circles' ? circleChips(st, serverId, refresh) : undefined,
|
||||
@@ -370,8 +391,15 @@ export function accessCards(srv: Server, first: Status, refresh: () => Promise<u
|
||||
'span',
|
||||
{ class: 'dl-sub dl-if-summary' },
|
||||
nets.length
|
||||
? ['Home access reaches ', ...nets.flatMap(([n, dev], i) => [i ? ', ' : '', E('span', { class: 'dl-mono' }, n), ` (${dev})`])]
|
||||
: 'No home network: Home access reaches nothing but this router.',
|
||||
? 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),
|
||||
]),
|
||||
@@ -392,13 +420,13 @@ export function accessCards(srv: Server, first: Status, refresh: () => Promise<u
|
||||
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('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)]),
|
||||
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) => {
|
||||
sw(autoLan, _('Auto-detect LAN'), (v) => {
|
||||
autoLan = v;
|
||||
paint();
|
||||
}),
|
||||
@@ -414,16 +442,16 @@ export function accessCards(srv: Server, first: Status, refresh: () => Promise<u
|
||||
[
|
||||
E('summary', {}, [
|
||||
icon('chevron'),
|
||||
E('span', {}, 'Other interfaces'),
|
||||
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.',
|
||||
_('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]) => {
|
||||
...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))])
|
||||
|
||||
+35
-28
@@ -10,6 +10,7 @@ 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;
|
||||
@@ -23,8 +24,9 @@ const esc = (s: string) => s.replace(/[&<>"']/g, (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 * (4 + p.name.length))));
|
||||
const nameSize = Math.min(92, Math.floor((W - 2 * M) / (0.58 * hi.length)));
|
||||
const tile = W - 2 * M,
|
||||
top = 392,
|
||||
pad = 40;
|
||||
@@ -39,8 +41,8 @@ function cardSvg(p: Pick<Person, 'name'>, server: string, link: string): string
|
||||
`<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', `Hi, ${esc(p.name)}`, 'font-weight="600"') +
|
||||
text(M, 340, 40, '#8a8a8a', `Scan to connect to ${esc(server)}`) +
|
||||
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 +
|
||||
@@ -60,7 +62,7 @@ async function toPng(svg: string): Promise<Blob> {
|
||||
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'),
|
||||
canvas.toBlob((b) => (b ? resolve(b) : reject(new Error(_('Could not draw the card')))), 'image/png'),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -72,7 +74,7 @@ export async function personLinks(id: string): Promise<{ link: string; links: st
|
||||
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');
|
||||
notify(_('The personal portal is off. Turn it on in Settings.'), 'warning');
|
||||
return null;
|
||||
}
|
||||
return { link: r.link, links: r.links ?? [] };
|
||||
@@ -81,7 +83,7 @@ export async function personLinks(id: string): Promise<{ link: string; links: st
|
||||
/** 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');
|
||||
if (r) await copyText(r.link, _('Personal link copied'));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -98,7 +100,7 @@ export async function inviteCard(p: Invitee, server: string, opts: { title?: str
|
||||
links = r.links;
|
||||
}
|
||||
if (!link) {
|
||||
notify('The personal portal is off. Turn it on in Settings.', 'warning');
|
||||
notify(_('The personal portal is off. Turn it on in Settings.'), 'warning');
|
||||
return;
|
||||
}
|
||||
const href = link;
|
||||
@@ -123,49 +125,54 @@ export async function inviteCard(p: Invitee, server: string, opts: { title?: str
|
||||
}
|
||||
};
|
||||
const share = canShareFile
|
||||
? button([icon('link'), ' Share card'], () => shareIt({ files: [file], title: `Invite ${p.name}` }), 'positive')
|
||||
? 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: `Invite ${p.name}`, text: `Your personal VPN link` }),
|
||||
[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');
|
||||
: button([icon('download'), ' ', _('Download card')], () => downloadFile(file.name, png), 'positive');
|
||||
modal(
|
||||
opts.title ?? `Invite ${p.name}`,
|
||||
opts.title ?? fmt(_('Invite %s'), p.name),
|
||||
E('div', { class: 'dl-invite' }, [
|
||||
E('img', { src: url, alt: `Invite card for ${p.name}` }),
|
||||
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 ?? `Send ${p.name} the card or the link. They open it, add their devices and connect — no account needed.`,
|
||||
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')],
|
||||
),
|
||||
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(
|
||||
'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', {}, ['Install ', E('b', {}, 'AmneziaVPN'), ' on the device']),
|
||||
E('li', {}, 'Open the link or scan the code'),
|
||||
E('li', {}, 'Add the device and connect'),
|
||||
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')),
|
||||
button([icon('copy'), ' ', _('Copy link')], () => copyText(href, _('Personal link copied'))),
|
||||
]),
|
||||
]),
|
||||
]),
|
||||
[E('button', { class: 'cbi-button cbi-button-neutral', click: close }, 'Done')],
|
||||
[E('button', { class: 'cbi-button cbi-button-neutral', click: close }, _('Done'))],
|
||||
'wide',
|
||||
);
|
||||
}
|
||||
+37
-29
@@ -8,8 +8,9 @@ import { button } from './ui/button';
|
||||
import { cancelButton, closeModal, modal } from './ui/modal';
|
||||
import { downloadFile } from './ui/files';
|
||||
import { attempt, errorText, notify } from './ui/toast';
|
||||
import { CATEGORIES, CATEGORY_LABEL, SYSTEM_SOURCE, categoryOf, eventBy } from './events/model';
|
||||
import { CATEGORIES, categoryLabel, 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]));
|
||||
@@ -44,7 +45,7 @@ export function exportEvents(
|
||||
person: '',
|
||||
device: '',
|
||||
detail: `${e.who ? `${e.who} ` : ''}${e.msg}${e.detail ? `\n${e.detail}` : ''}`,
|
||||
where: SYSTEM_SOURCE[e.src] ?? e.src,
|
||||
where: sourceName(e.src),
|
||||
by: '',
|
||||
})),
|
||||
]
|
||||
@@ -57,17 +58,26 @@ export function exportEvents(
|
||||
return;
|
||||
}
|
||||
const cols = ['time', 'category', 'type', 'person', 'device', 'detail', 'where', 'by'] as const;
|
||||
downloadFile(name, toCsv(cols, rows), 'text/csv');
|
||||
// The header row in the page's language; the cells are the log's ids, names and details.
|
||||
const head = {
|
||||
time: _('Time'),
|
||||
category: _('Category'),
|
||||
type: _('Type'),
|
||||
person: _('Person'),
|
||||
device: _('Device'),
|
||||
detail: _('Detail'),
|
||||
where: _('Where'),
|
||||
by: _('By'),
|
||||
};
|
||||
downloadFile(name, toCsv(cols, rows, head), 'text/csv');
|
||||
}
|
||||
|
||||
const AGES: [string, string][] = [
|
||||
['', 'Everything'],
|
||||
['7', 'Older than 7 days'],
|
||||
['30', 'Older than 30 days'],
|
||||
['90', 'Older than 90 days'],
|
||||
];
|
||||
/** The ages the dialog offers, in days ('' = everything). */
|
||||
const AGES = ['', '7', '30', '90'];
|
||||
|
||||
const removed = (n: number) => (n ? `${n} event${n === 1 ? '' : 's'} removed` : 'Nothing matched');
|
||||
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
|
||||
@@ -82,27 +92,27 @@ export function clearLogDialog(
|
||||
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 }, CATEGORY_LABEL[c])),
|
||||
withSystem ? E('option', { value: 'system', selected: category === 'system' ? 'selected' : null }, 'System') : '',
|
||||
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, t]) => E('option', { value: v }, t)),
|
||||
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]),
|
||||
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',
|
||||
_('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.
|
||||
@@ -120,11 +130,9 @@ export function clearLogDialog(
|
||||
n += (await api.serviceLogClear(age.value)).removed;
|
||||
} catch (e) {
|
||||
closeModal();
|
||||
notify(
|
||||
`${cat.value === 'system' ? '' : `Activity: ${removed(n).toLowerCase()}. `}The service log was not cleared: ${errorText(e)}`,
|
||||
'error',
|
||||
10000,
|
||||
);
|
||||
// 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;
|
||||
}
|
||||
@@ -143,20 +151,20 @@ export function clearLogDialog(
|
||||
export function resetUsageDialog(scope: 'all' | 'person' | 'device', id: string, label: string, done: () => unknown) {
|
||||
const body =
|
||||
scope === 'device'
|
||||
? `Clears ${label}'s daily and monthly traffic history. Their person's totals and data limit are not changed.`
|
||||
? fmt(_("Clears %s's daily and monthly traffic history. Their person's totals and data limit are not changed."), label)
|
||||
: scope === 'person'
|
||||
? `Clears ${label}'s traffic history and that of their devices. Their data limit starts again from zero.`
|
||||
: 'Clears traffic history for everyone. Data limits start again from zero.';
|
||||
? 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?' : `Reset traffic history for ${label}?`,
|
||||
scope === 'all' ? _('Reset all traffic history?') : fmt(_('Reset traffic history for %s?'), label),
|
||||
[E('p', { class: 'dl-muted' }, body)],
|
||||
[
|
||||
cancelButton(),
|
||||
' ',
|
||||
button(
|
||||
'Reset',
|
||||
_('Reset'),
|
||||
async () => {
|
||||
if (!(await attempt(() => api.usageClear(scope, id), 'Traffic history reset'))) return;
|
||||
if (!(await attempt(() => api.usageClear(scope, id), _('Traffic history reset')))) return;
|
||||
closeModal();
|
||||
done();
|
||||
},
|
||||
|
||||
Vendored
-2
@@ -113,8 +113,6 @@ declare global {
|
||||
}
|
||||
|
||||
const E: (tag: string, attrs?: ElementAttrs | Child, children?: Child) => HTMLElement;
|
||||
const _: (msg: string, ctx?: string) => string;
|
||||
const N_: (n: number, singular: string, plural: string, ctx?: string) => string;
|
||||
const L: LuciL;
|
||||
const ui: LuciUI;
|
||||
const rpc: LuciRpc;
|
||||
|
||||
+51
-31
@@ -8,6 +8,7 @@
|
||||
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 { icon, iconSvg } from '../shared/icons';
|
||||
import { onNavigate } from './ui/nav';
|
||||
import { isDark } from './ui/theme';
|
||||
@@ -64,8 +65,8 @@ function loadMapLibre(host: HTMLElement): Promise<any> {
|
||||
loading = null;
|
||||
throw new Error(
|
||||
e?.message === 'integrity'
|
||||
? 'The map library from the CDN is not the expected file: not loading it.'
|
||||
: 'Could not load the map library (no internet access from this browser?)',
|
||||
? _('The map library from the CDN is not the expected file: not loading it.')
|
||||
: _('Could not load the map library (no internet access from this browser?)'),
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -416,11 +417,11 @@ export class ConnectionMap {
|
||||
this.dockKey = '';
|
||||
const el = E(
|
||||
'div',
|
||||
{ class: 'dl-mk-hub', title: `Home router${home.city ? ` · ${home.city}` : ''}${home.org ? ` · ${home.org}` : ''}` },
|
||||
[host, E('span', { class: 'dl-mk-label chip' }, home.city || 'Home')],
|
||||
{ class: 'dl-mk-hub', title: `${_('Home router')}${home.city ? ` · ${home.city}` : ''}${home.org ? ` · ${home.org}` : ''}` },
|
||||
[host, E('span', { class: 'dl-mk-label chip' }, home.city || _('Home'))],
|
||||
);
|
||||
// Who is docked here: listed on hover; a click on the plate zooms to them (an avatar opens its card).
|
||||
el.addEventListener('mouseenter', () => this.showMerged(home.city || 'the server'));
|
||||
el.addEventListener('mouseenter', () => this.showMerged(home.city));
|
||||
el.addEventListener('mouseleave', () => this.focus(this.focused));
|
||||
el.addEventListener('click', () => this.zoomToMerged());
|
||||
this.add(el, [home.lon, home.lat], true);
|
||||
@@ -448,7 +449,9 @@ export class ConnectionMap {
|
||||
{
|
||||
type: 'button',
|
||||
class: `dl-mk${g.online ? ' online' : ''}`,
|
||||
'aria-label': `${person?.name ?? 'Someone'}: ${n} device${n === 1 ? '' : 's'} in ${g.city || 'an unknown city'}`,
|
||||
'aria-label': g.city
|
||||
? fmt(N_(n, '%s: %s device in %s', '%s: %s devices in %s'), person?.name ?? _('Someone'), num(n), g.city)
|
||||
: 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]),
|
||||
@@ -462,7 +465,15 @@ export class ConnectionMap {
|
||||
ev.stopPropagation();
|
||||
this.openPopup(g, at, el);
|
||||
});
|
||||
this.add(el, at, false, person?.name ?? 'Someone', `${g.city || g.cc || '?'} · ${g.online ? 'now' : ago(g.ts, data.now)}`, g.key, g);
|
||||
this.add(
|
||||
el,
|
||||
at,
|
||||
false,
|
||||
person?.name ?? _('Someone'),
|
||||
`${g.city || g.cc || '?'} · ${g.online ? _('now') : ago(g.ts, data.now)}`,
|
||||
g.key,
|
||||
g,
|
||||
);
|
||||
}
|
||||
this.declutter();
|
||||
|
||||
@@ -488,7 +499,7 @@ export class ConnectionMap {
|
||||
this.fit(coords, animate);
|
||||
}
|
||||
}
|
||||
this.status.textContent = placed.length || home ? '' : 'No locations yet';
|
||||
this.status.textContent = placed.length || home ? '' : _('No locations yet');
|
||||
this.status.style.display = this.status.textContent ? '' : 'none';
|
||||
this.focus(this.focused && this.people.some((x) => x.person === this.focused) ? this.focused : null);
|
||||
}
|
||||
@@ -605,11 +616,14 @@ export class ConnectionMap {
|
||||
this.popup = null;
|
||||
}
|
||||
|
||||
/** The people folded into the server, in the corner card. */
|
||||
private showMerged(place: string) {
|
||||
/** The people folded into the server, in the corner card; `city` is the server's, when known. */
|
||||
private showMerged(city: string) {
|
||||
if (!this.merged.length) return;
|
||||
dom.content(this.card, [
|
||||
E('div', { class: 'dl-map-card-head' }, [E('b', {}, `Near ${place}`), ' · click to zoom in']),
|
||||
E('div', { class: 'dl-map-card-head' }, [
|
||||
E('b', {}, city ? fmt(_('Near %s'), city) : _('Near the server')),
|
||||
` · ${_('click to zoom in')}`,
|
||||
]),
|
||||
...this.merged.map((m) => E('div', { class: 'dl-map-card-row' }, [E('span', {}, m.who), E('span', { class: 'dl-faint' }, m.where)])),
|
||||
]);
|
||||
this.card.classList.add('on');
|
||||
@@ -682,7 +696,7 @@ export class ConnectionMap {
|
||||
const cities = [...new Set(slots.map((x) => x.g?.city || x.g?.cc || '?'))];
|
||||
const el = E('div', { class: 'dl-mk-pile' }, [
|
||||
box,
|
||||
E('span', { class: 'dl-mk-label below' }, cities.length === 1 ? cities[0] : `${slots.length} people`),
|
||||
E('span', { class: 'dl-mk-label below' }, cities.length === 1 ? cities[0] : plural(slots.length, '%s person', '%s people')),
|
||||
]);
|
||||
pile = { marker: new this.gl.Marker({ element: el }).setLngLat(at).addTo(this.map), el, box, faces };
|
||||
el.addEventListener('mouseleave', () => this.focus(this.focused));
|
||||
@@ -796,14 +810,16 @@ export class ConnectionMap {
|
||||
const n = g.points.length;
|
||||
const tile = E('span', { class: 'dl-mk-tile' });
|
||||
tile.innerHTML = iconSvg(kind, 'dl-mk-tile-ic') + (n > 1 ? `<span class="dl-mk-tile-n">${n}</span>` : '');
|
||||
const when = g.online ? 'now' : ago(g.ts, now);
|
||||
const when = g.online ? _('now') : ago(g.ts, now);
|
||||
const el = E(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
class: `dl-mk place${g.online ? ' online' : ''}`,
|
||||
style: g.online ? null : `--dl-mk-fade:${Math.max(0.4, 1 - (0.6 * (now - g.ts)) / (30 * 86400)).toFixed(2)}`,
|
||||
'aria-label': `${n} device${n === 1 ? '' : 's'} in ${g.city || 'an unknown city'}, ${when}`,
|
||||
'aria-label': g.city
|
||||
? fmt(N_(n, '%s device in %s, %s', '%s devices in %s, %s'), num(n), g.city, when)
|
||||
: fmt(N_(n, '%s device in an unknown city, %s', '%s devices in an unknown city, %s'), num(n), when),
|
||||
},
|
||||
[tile, E('span', { class: 'dl-mk-label below' }, [g.city || g.cc || '?', E('span', { class: 'dl-mk-when' }, when)])],
|
||||
);
|
||||
@@ -850,11 +866,11 @@ export class ConnectionMap {
|
||||
x.when = null;
|
||||
if (on) {
|
||||
// In the replay the time goes on the city's line (two lines would run into a place below).
|
||||
x.when = E('span', { class: `dl-mk-when${r ? ' inline' : ''}` }, r ? r.when : 'now');
|
||||
x.when = E('span', { class: `dl-mk-when${r ? ' inline' : ''}` }, r ? r.when : _('now'));
|
||||
x.label.replaceChildren(city, r ? ' · ' : '', x.when);
|
||||
} else x.label.replaceChildren(`${city} · ${x.g.online ? 'now' : ago(x.g.ts, this.data!.now)}`);
|
||||
const when = on ? (r ? r.when : 'now') : x.g.online ? 'now' : ago(x.g.ts, this.data!.now);
|
||||
x.el.setAttribute('aria-label', `${x.n ? `${x.n}: ` : ''}${x.g.city || 'an unknown city'}, ${when}`);
|
||||
} else x.label.replaceChildren(`${city} · ${x.g.online ? _('now') : ago(x.g.ts, this.data!.now)}`);
|
||||
const when = on ? (r ? r.when : _('now')) : x.g.online ? _('now') : ago(x.g.ts, this.data!.now);
|
||||
x.el.setAttribute('aria-label', `${x.n ? `${x.n}: ` : ''}${x.g.city || _('an unknown city')}, ${when}`);
|
||||
if (animate && on && !was) {
|
||||
x.el.classList.remove('arrive');
|
||||
void x.el.offsetWidth;
|
||||
@@ -940,11 +956,11 @@ export class ConnectionMap {
|
||||
.filter((p) => p.person === person)
|
||||
.sort((a, b) => Number(b.online) - Number(a.online) || b.ts - a.ts);
|
||||
dom.content(this.card, [
|
||||
E('div', { class: 'dl-map-card-head' }, [E('b', {}, who?.name ?? person), ` · ${pts.length} device${pts.length === 1 ? '' : 's'}`]),
|
||||
E('div', { class: 'dl-map-card-head' }, [E('b', {}, who?.name ?? person), ` · ${plural(pts.length, '%s device', '%s devices')}`]),
|
||||
...pts.map((p) =>
|
||||
E('div', { class: 'dl-map-card-row' }, [
|
||||
E('span', {}, who?.devices.find((d) => d.id === p.device)?.name ?? 'Device'),
|
||||
E('span', { class: 'dl-faint' }, `${p.city || p.cc || '?'} · ${p.online ? 'now' : ago(p.ts, data.now)}`),
|
||||
E('span', {}, who?.devices.find((d) => d.id === p.device)?.name ?? _('Device')),
|
||||
E('span', { class: 'dl-faint' }, `${p.city || p.cc || '?'} · ${p.online ? _('now') : ago(p.ts, data.now)}`),
|
||||
]),
|
||||
),
|
||||
]);
|
||||
@@ -1010,6 +1026,7 @@ export class ConnectionMap {
|
||||
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))];
|
||||
const owner = people.length === 1 ? data.people.find((x) => x.id === people[0])?.name : undefined;
|
||||
const rows = g.points
|
||||
.sort((a, b) => Number(b.online) - Number(a.online) || b.ts - a.ts)
|
||||
.map((p) => {
|
||||
@@ -1017,16 +1034,19 @@ export class ConnectionMap {
|
||||
const dev = person?.devices.find((d) => d.id === p.device);
|
||||
return E('button', { type: 'button', class: 'dl-pop-row', click: () => this.cb.openDevice(p.person, p.device) }, [
|
||||
E('span', { class: `dl-pop-dot${p.online ? ' on' : ''}` }),
|
||||
E('span', { class: 'dl-pop-name' }, [E('b', {}, person?.name ?? p.person), ` · ${dev?.name ?? 'device'}`]),
|
||||
E('span', { class: 'dl-faint dl-nowrap' }, p.online ? 'now' : ago(p.ts, data.now)),
|
||||
E('span', { class: 'dl-pop-name' }, [E('b', {}, person?.name ?? p.person), ` · ${dev?.name ?? _('device')}`]),
|
||||
E('span', { class: 'dl-faint dl-nowrap' }, p.online ? _('now') : ago(p.ts, data.now)),
|
||||
]);
|
||||
});
|
||||
const body = E('div', { class: 'dl-pop' }, [
|
||||
E('div', { class: 'dl-pop-head' }, [
|
||||
E('span', { class: 'dl-pop-net' }, icon('globe')),
|
||||
E('div', { class: 'dl-stack' }, [
|
||||
E('strong', {}, g.org || 'Unknown network'),
|
||||
E('span', { class: 'dl-faint' }, [g.asn ? `AS${g.asn} · ` : '', where ? `${where} · approximate` : 'approximate location']),
|
||||
E('strong', {}, g.org || _('Unknown network')),
|
||||
E('span', { class: 'dl-faint' }, [
|
||||
g.asn ? `AS${g.asn} · ` : '',
|
||||
where ? `${where} · ${_('approximate')}` : _('approximate location'),
|
||||
]),
|
||||
]),
|
||||
]),
|
||||
E('div', { class: 'dl-pop-list' }, rows),
|
||||
@@ -1035,7 +1055,7 @@ export class ConnectionMap {
|
||||
E(
|
||||
'button',
|
||||
{ type: 'button', class: 'cbi-button cbi-button-positive important', click: () => this.cb.openPerson(people[0]) },
|
||||
`Open ${data.people.find((x) => x.id === people[0])?.name ?? 'person'}`,
|
||||
owner ? fmt(_('Open %s'), owner) : _('Open person'),
|
||||
),
|
||||
])
|
||||
: '',
|
||||
@@ -1198,7 +1218,7 @@ export interface Face {
|
||||
function face(slot: { el: HTMLElement; at: [number, number]; who?: string; where?: string; g?: Group }): Face {
|
||||
return {
|
||||
key: slot.el.dataset.key ?? '',
|
||||
who: slot.who ?? 'Someone',
|
||||
who: slot.who ?? _('Someone'),
|
||||
where: slot.where ?? '',
|
||||
online: !!slot.g?.online,
|
||||
at: slot.at,
|
||||
@@ -1350,10 +1370,10 @@ interface Group {
|
||||
/** 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'],
|
||||
['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) {
|
||||
|
||||
+106
-63
@@ -2,6 +2,8 @@
|
||||
// them (rpc/servers.uc) and said in plain words for the setup wizard. The
|
||||
// addresses are three numbers ("10.77.0"): the tunnel is that /24.
|
||||
|
||||
import { fmt, locale, num, plural } from '../shared/i18n';
|
||||
|
||||
/** A network on the router, by name: an interface ("lan") or a server ("Home"). */
|
||||
export interface Network {
|
||||
name: string;
|
||||
@@ -56,19 +58,19 @@ export function subnetOf(range: string): string {
|
||||
export function rangeHelp(range: string, nets: Network[], suggest: string): Help {
|
||||
const r = range.trim();
|
||||
const c = /^\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(r) ? parseCidr(subnetOf(r)) : null;
|
||||
if (!c) return { text: 'Three numbers, like 10.77.0.', bad: true };
|
||||
if (!c) return { text: _('Three numbers, like 10.77.0.'), bad: true };
|
||||
if (!PRIVATE.some((p) => c.net >= p.net && c.net + c.size <= p.net + p.size))
|
||||
return { text: 'Use a private range: 10.x.x, 172.16–31.x or 192.168.x.', bad: true };
|
||||
return { text: _('Use a private range: 10.x.x, 172.16–31.x or 192.168.x.'), bad: true };
|
||||
const hit = nets.find((n) => {
|
||||
const o = parseCidr(n.cidr);
|
||||
return o != null && overlaps(c, o);
|
||||
});
|
||||
if (hit) {
|
||||
const used = hit.cidr.endsWith('/24') ? `${rangeOf(hit.cidr)}.x` : hit.cidr;
|
||||
const other = suggest && suggest !== r ? ` Try ${suggest}.` : '';
|
||||
return { text: `${hit.name} already uses ${used}.${other}`, bad: true };
|
||||
const uses = fmt(_('%s already uses %s.'), hit.name, used);
|
||||
return { text: suggest && suggest !== r ? `${uses} ${fmt(_('Try %s.'), suggest)}` : uses, bad: true };
|
||||
}
|
||||
return { text: `Devices get ${r}.2 – ${r}.254, the router ${r}.1.`, bad: false };
|
||||
return { text: fmt(_('Devices get %s – %s, the router %s.'), `${r}.2`, `${r}.254`, `${r}.1`), bad: false };
|
||||
}
|
||||
|
||||
const holder = (port: number, taken: PortHold[]): string | null => taken.find((t) => t.from <= port && port <= t.to)?.who ?? null;
|
||||
@@ -77,19 +79,21 @@ const validPort = (port: number): boolean => Number.isInteger(port) && port >= 1
|
||||
|
||||
/** A port: `free` when nobody holds it, or who does. */
|
||||
export function portHelp(port: number, taken: PortHold[], free: string): Help {
|
||||
if (!validPort(port)) return { text: 'Use a port from 1 to 65535.', bad: true };
|
||||
if (!validPort(port)) return { text: _('Use a port from 1 to 65535.'), bad: true };
|
||||
const who = holder(port, taken);
|
||||
return who ? { text: `Used by ${who}. Choose another port.`, bad: true } : { text: free, bad: false };
|
||||
return who ? { text: fmt(_('Used by %s. Choose another port.'), who), bad: true } : { text: free, bad: false };
|
||||
}
|
||||
|
||||
/** The portal's TCP port; links on IP addresses (`ipLinks`) use plain HTTP on the next one too. */
|
||||
export function portalPortHelp(port: number, taken: PortHold[], ipLinks: boolean): Help {
|
||||
const free = ipLinks ? `HTTPS here, plain HTTP for links on IP addresses on ${port + 1}.` : 'HTTPS on this port, opened on WAN.';
|
||||
const free = ipLinks
|
||||
? fmt(_('HTTPS here, plain HTTP for links on IP addresses on %s.'), port + 1)
|
||||
: _('HTTPS on this port, opened on WAN.');
|
||||
const h = portHelp(port, taken, free);
|
||||
if (h.bad || !ipLinks) return h;
|
||||
if (port === 65535) return { text: 'Links on IP addresses also need the next port: choose a lower one.', bad: true };
|
||||
if (port === 65535) return { text: _('Links on IP addresses also need the next port: choose a lower one.'), bad: true };
|
||||
const who = holder(port + 1, taken);
|
||||
return who ? { text: `Links on IP addresses also need ${port + 1}, used by ${who}. Choose another port.`, bad: true } : h;
|
||||
return who ? { text: fmt(_('Links on IP addresses also need %s, used by %s. Choose another port.'), port + 1, who), bad: true } : h;
|
||||
}
|
||||
|
||||
/* ---------- other fields, mirroring the router's rules (dawnline.util, schema, core) ---------- */
|
||||
@@ -100,23 +104,28 @@ export const chars = (s: string): number => Array.from(s).length;
|
||||
const NAME_MAX = 48;
|
||||
const BAD_NAME = /[<>"\\\u0000-\u001f\u007f]/;
|
||||
|
||||
/** "Up to 48 characters (50 now).": a name over its limit. */
|
||||
const tooLong = (max: number, s: string): string =>
|
||||
fmt(N_(max, 'Up to %s character (%s now).', 'Up to %s characters (%s now).'), num(max), num(chars(s)));
|
||||
|
||||
/**
|
||||
* A name people see (util.valid_name): 1–48 characters, none of < > " \.
|
||||
* `taken` are names already used where it must be unique (case-insensitive).
|
||||
*/
|
||||
export function nameHelp(s: string, taken: string[] = [], good = ''): Help {
|
||||
const t = s.trim();
|
||||
if (!t) return { text: 'Enter a name.', bad: true };
|
||||
if (chars(s) > NAME_MAX) return { text: `Up to ${NAME_MAX} characters (${chars(s)} now).`, bad: true };
|
||||
if (BAD_NAME.test(s)) return { text: 'Names can’t contain < > " or \\.', bad: true };
|
||||
if (taken.some((x) => x.toLowerCase() === t.toLowerCase())) return { text: `“${t}” already exists — pick another name.`, bad: true };
|
||||
if (!t) return { text: _('Enter a name.'), bad: true };
|
||||
if (chars(s) > NAME_MAX) return { text: tooLong(NAME_MAX, s), bad: true };
|
||||
if (BAD_NAME.test(s)) return { text: _('Names can’t contain < > " or \\.'), bad: true };
|
||||
if (taken.some((x) => x.toLowerCase() === t.toLowerCase()))
|
||||
return { text: fmt(_('“%s” already exists - pick another name.'), t), bad: true };
|
||||
return { text: good, bad: false };
|
||||
}
|
||||
|
||||
/** A circle's name: like a name, up to 32 characters. */
|
||||
export function circleNameHelp(s: string, taken: string[] = []): Help {
|
||||
if (chars(s) > 32) return { text: `Up to 32 characters (${chars(s)} now).`, bad: true };
|
||||
return nameHelp(s, taken, 'Shown on the person cards.');
|
||||
if (chars(s) > 32) return { text: tooLong(32, s), bad: true };
|
||||
return nameHelp(s, taken, _('Shown on the person cards.'));
|
||||
}
|
||||
|
||||
const HOSTNAME = /^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/;
|
||||
@@ -138,24 +147,28 @@ export function isIpv6(s: string): boolean {
|
||||
*/
|
||||
export function hostHelp(s: string, port?: number, empty: string | null = null): Help {
|
||||
const t = s.trim();
|
||||
if (!t) return empty != null ? { text: empty, bad: false } : { text: 'Enter a hostname or IP address.', bad: true };
|
||||
if (/^[a-z]+:\/\//i.test(t)) return { text: 'Leave out https:// — just the name.', bad: true };
|
||||
if (/\/.*/.test(t)) return { text: 'Just the name, without a path.', bad: true };
|
||||
if (/^[^:\[]+:\d+$/.test(t)) return { text: 'Just the name, without a port (the port is on AmneziaWG).', bad: true };
|
||||
if (/\s/.test(t)) return { text: 'A hostname has no spaces.', bad: true };
|
||||
if (t.length > 253 || !(HOSTNAME.test(t) || isIpv4(t) || isIpv6(t))) return { text: 'Use a hostname or an IP address.', bad: true };
|
||||
if (!t) return empty != null ? { text: empty, bad: false } : { text: _('Enter a hostname or IP address.'), bad: true };
|
||||
if (/^[a-z]+:\/\//i.test(t)) return { text: _('Leave out https:// - just the name.'), bad: true };
|
||||
if (/\/.*/.test(t)) return { text: _('Just the name, without a path.'), bad: true };
|
||||
if (/^[^:\[]+:\d+$/.test(t)) return { text: _('Just the name, without a port (the port is on AmneziaWG).'), bad: true };
|
||||
if (/\s/.test(t)) return { text: _('A hostname has no spaces.'), bad: true };
|
||||
if (t.length > 253 || !(HOSTNAME.test(t) || isIpv4(t) || isIpv6(t))) return { text: _('Use a hostname or an IP address.'), bad: true };
|
||||
const shown = isIpv6(t) ? `[${t}]` : t;
|
||||
return { text: port ? `Devices connect to ${shown}:${port}.` : `Links use ${shown}.`, bad: false };
|
||||
return { text: port ? fmt(_('Devices connect to %s.'), `${shown}:${port}`) : fmt(_('Links use %s.'), shown), bad: false };
|
||||
}
|
||||
|
||||
/** The DNS list a server hands to devices (rpc/servers.uc dns_list): IPs, comma-separated; empty = this router. */
|
||||
export function dnsHelp(s: string, routerAddr: string): Help {
|
||||
const items = s.split(/[ ,]+/).filter(Boolean);
|
||||
if (!items.length)
|
||||
return { text: `This router (${routerAddr}): queries go where your home network sends them, and home names work.`, bad: false };
|
||||
return {
|
||||
text: fmt(_('This router (%s): queries go where your home network sends them, and home names work.'), routerAddr),
|
||||
bad: false,
|
||||
};
|
||||
const bad = items.find((x) => !isIpv4(x) && !isIpv6(x));
|
||||
if (bad) return { text: `“${bad}” is not an IP address. Separate several with commas.`, bad: true };
|
||||
return { text: `Devices use ${items.join(' and ')} — home names and your LAN’s DNS filters no longer apply to them.`, bad: false };
|
||||
if (bad) return { text: fmt(_('“%s” is not an IP address. Separate several with commas.'), bad), bad: true };
|
||||
const list = new Intl.ListFormat(locale(), { type: 'conjunction' }).format(items);
|
||||
return { text: fmt(_('Devices use %s - home names and your LAN’s DNS filters no longer apply to them.'), list), bad: false };
|
||||
}
|
||||
|
||||
/** MTU (rpc/servers.uc check_mtu): empty = automatic, else 1280–1500. */
|
||||
@@ -163,42 +176,66 @@ export function mtuHelp(s: string, mtus: { computer: number; phone: number }): H
|
||||
const t = s.trim();
|
||||
if (!t)
|
||||
return {
|
||||
text: `Automatic by device type and disguise: ${mtus.computer} for computers and routers, ${mtus.phone} for phones and tablets.`,
|
||||
text: fmt(
|
||||
_('Automatic by device type and disguise: %s for computers and routers, %s for phones and tablets.'),
|
||||
mtus.computer,
|
||||
mtus.phone,
|
||||
),
|
||||
bad: false,
|
||||
};
|
||||
if (!/^\d{1,4}$/.test(t) || Number(t) < 1280 || Number(t) > 1500)
|
||||
return { text: 'MTU must be 1280–1500, or empty for automatic.', bad: true };
|
||||
return { text: _('MTU must be 1280–1500, or empty for automatic.'), bad: true };
|
||||
const n = Number(t);
|
||||
return { text: `Computers and routers get ${n}, phones and tablets ${Math.min(n, 1280)}.`, bad: false };
|
||||
return { text: fmt(_('Computers and routers get %s, phones and tablets %s.'), n, Math.min(n, 1280)), bad: false };
|
||||
}
|
||||
|
||||
/** Keep-alive (rpc/servers.uc): 0–600 s; empty = 25. */
|
||||
export function keepaliveHelp(s: string): Help {
|
||||
const t = s.trim();
|
||||
if (!t) return { text: 'Default: a packet every 25 s keeps NAT open and “Connected” accurate.', bad: false };
|
||||
if (!/^\d{1,3}$/.test(t) || Number(t) > 600) return { text: 'Use 0–600 seconds.', bad: true };
|
||||
if (Number(t) === 0) return { text: 'Off: NAT may close the tunnel when idle, and “Connected” lags.', bad: false };
|
||||
return { text: `Devices send a packet every ${t} s to keep NAT open (a little battery on phones).`, bad: false };
|
||||
if (!t) return { text: _('Default: a packet every 25 s keeps NAT open and “Connected” accurate.'), bad: false };
|
||||
if (!/^\d{1,3}$/.test(t) || Number(t) > 600) return { text: _('Use 0–600 seconds.'), bad: true };
|
||||
if (Number(t) === 0) return { text: _('Off: NAT may close the tunnel when idle, and “Connected” lags.'), bad: false };
|
||||
return { text: fmt(_('Devices send a packet every %s s to keep NAT open (a little battery on phones).'), t), bad: false };
|
||||
}
|
||||
|
||||
/** Device limit (core.create_person): 1–32; `have` is how many they have now (an edit). */
|
||||
export function limitHelp(s: string, have = 0): Help {
|
||||
const t = s.trim();
|
||||
if (!/^\d{1,2}$/.test(t) || Number(t) < 1 || Number(t) > 32) return { text: 'Use 1–32.', bad: true };
|
||||
if (!/^\d{1,2}$/.test(t) || Number(t) < 1 || Number(t) > 32) return { text: _('Use 1–32.'), bad: true };
|
||||
const n = Number(t);
|
||||
if (have > n)
|
||||
return { text: `Already has ${have} devices: remove ${have - n === 1 ? 'one' : `${have - n}`} first, or allow more.`, bad: true };
|
||||
return { text: `They can add ${n} device${n === 1 ? '' : 's'} themselves.`, bad: false };
|
||||
return {
|
||||
text:
|
||||
have - n === 1
|
||||
? fmt(
|
||||
N_(
|
||||
have,
|
||||
'Already has %s device: remove one first, or allow more.',
|
||||
'Already has %s devices: remove one first, or allow more.',
|
||||
),
|
||||
num(have),
|
||||
)
|
||||
: fmt(
|
||||
N_(have, 'Already has %s device: remove %s first, or allow more.', 'Already has %s devices: remove %s first, or allow more.'),
|
||||
num(have),
|
||||
num(have - n),
|
||||
),
|
||||
bad: true,
|
||||
};
|
||||
return { text: plural(n, 'They can add %s device themselves.', 'They can add %s devices themselves.'), bad: false };
|
||||
}
|
||||
|
||||
/** Monthly data in GB (core.create_person): empty = unlimited, else 0–100000. */
|
||||
export function quotaHelp(s: string, monthly = true): Help {
|
||||
const t = s.trim();
|
||||
if (!t) return { text: 'Optional. No data limit.', bad: false };
|
||||
if (!t) return { text: _('Optional. No data limit.'), bad: false };
|
||||
const n = Number(t);
|
||||
if (!/^\d+(\.\d+)?$/.test(t) || n < 0 || n > 100000) return { text: 'A number of GB, up to 100000.', bad: true };
|
||||
if (n === 0) return { text: 'Optional. No data limit.', bad: false };
|
||||
return { text: monthly ? `Paused after ${t} GB this month, resumed on the 1st.` : `Paused after ${t} GB in total.`, bad: false };
|
||||
if (!/^\d+(\.\d+)?$/.test(t) || n < 0 || n > 100000) return { text: _('A number of GB, up to 100000.'), bad: true };
|
||||
if (n === 0) return { text: _('Optional. No data limit.'), bad: false };
|
||||
return {
|
||||
text: fmt(monthly ? _('Paused after %s GB this month, resumed on the 1st.') : _('Paused after %s GB in total.'), num(n)),
|
||||
bad: false,
|
||||
};
|
||||
}
|
||||
|
||||
/** An end date (YYYY-MM-DD) against the router's day; empty = none. */
|
||||
@@ -209,64 +246,70 @@ export function expiresHelp(
|
||||
date: (d: string) => string,
|
||||
): Help {
|
||||
const t = s.trim();
|
||||
if (!t) return { text: 'Optional. No end date.', bad: false };
|
||||
if (!t) return { text: _('Optional. No end date.'), bad: false };
|
||||
const left = daysLeft(t, today);
|
||||
if (left == null) return { text: 'Use a date.', bad: true };
|
||||
if (left < 0) return { text: 'That date has passed: access would end at once.', bad: true };
|
||||
return { text: left === 1 ? `Access ends today (${date(t)}).` : `Access ends in ${left} days (${date(t)}).`, bad: false };
|
||||
if (left == null) return { text: _('Use a date.'), bad: true };
|
||||
if (left < 0) return { text: _('That date has passed: access would end at once.'), bad: true };
|
||||
return {
|
||||
text:
|
||||
left === 1
|
||||
? fmt(_('Access ends today (%s).'), date(t))
|
||||
: fmt(N_(left, 'Access ends in %s day (%s).', 'Access ends in %s days (%s).'), num(left), date(t)),
|
||||
bad: false,
|
||||
};
|
||||
}
|
||||
|
||||
/** A home service's address (rpc/home.uc): IPv4; `homeNets` warn when it is outside every home network. */
|
||||
export function ipv4Help(s: string, inHome: ((ip: string) => boolean) | null = null): Help {
|
||||
const t = s.trim();
|
||||
if (!t) return { text: 'The device’s address at home.', bad: true };
|
||||
if (!isIpv4(t)) return { text: 'Use an IPv4 address, like 192.168.1.10.', bad: true };
|
||||
if (inHome && !inHome(t)) return { text: `${t} is not in any home network of this server: nobody would reach it.`, bad: false };
|
||||
if (!t) return { text: _('The device’s address at home.'), bad: true };
|
||||
if (!isIpv4(t)) return { text: _('Use an IPv4 address, like 192.168.1.10.'), bad: true };
|
||||
if (inHome && !inHome(t)) return { text: fmt(_('%s is not in any home network of this server: nobody would reach it.'), t), bad: false };
|
||||
return { text: '', bad: false };
|
||||
}
|
||||
|
||||
/** A service's ports: empty = all, else numbers 1–65535. */
|
||||
export function portsHelp(s: string): Help {
|
||||
const items = s.split(/[ ,]+/).filter(Boolean);
|
||||
if (!items.length) return { text: 'All ports.', bad: false };
|
||||
if (!items.length) return { text: _('All ports.'), bad: false };
|
||||
const bad = items.find((x) => !/^\d{1,5}$/.test(x) || Number(x) < 1 || Number(x) > 65535);
|
||||
if (bad) return { text: `“${bad}” is not a port (1–65535).`, bad: true };
|
||||
return { text: `Port${items.length === 1 ? '' : 's'} ${items.join(', ')}.`, bad: false };
|
||||
if (bad) return { text: fmt(_('“%s” is not a port (1–65535).'), bad), bad: true };
|
||||
return { text: fmt(N_(items.length, 'Port %s.', 'Ports %s.'), items.join(', ')), bad: false };
|
||||
}
|
||||
|
||||
/** The portal's redirect for unknown links (schema portal_redirect): a full http(s) URL, or empty. */
|
||||
export function urlHelp(s: string): Help {
|
||||
const t = s.trim();
|
||||
if (!t) return { text: 'Wrong links get a bare “Not found”.', bad: false };
|
||||
if (!/^https?:\/\//i.test(t)) return { text: 'Must start with http:// or https://.', bad: true };
|
||||
if (!t) return { text: _('Wrong links get a bare “Not found”.'), bad: false };
|
||||
if (!/^https?:\/\//i.test(t)) return { text: _('Must start with http:// or https://.'), bad: true };
|
||||
if (t.length > 300 || !/^https?:\/\/[A-Za-z0-9.-]+(:[0-9]+)?(\/[^\s"'<>]*)?$/.test(t))
|
||||
return { text: 'Not a usable address (no spaces or quotes).', bad: true };
|
||||
return { text: 'Wrong links are sent there instead of a “Not found”.', bad: false };
|
||||
return { text: _('Not a usable address (no spaces or quotes).'), bad: true };
|
||||
return { text: _('Wrong links are sent there instead of a “Not found”.'), bad: false };
|
||||
}
|
||||
|
||||
/** The home domain for device hostnames (schema domain): lowercase letters, digits, dashes, dots. */
|
||||
export function domainHelp(s: string, example = 'phone.myata'): Help {
|
||||
const t = s.trim();
|
||||
// Empty keeps the default (the router stores nothing then).
|
||||
if (!t) return { text: `The default, lan: devices get names like ${example}.lan.`, bad: false };
|
||||
if (!t) return { text: fmt(_('The default, lan: devices get names like %s.'), `${example}.lan`), bad: false };
|
||||
if (!/^[a-z0-9-]{1,32}(\.[a-z0-9-]{1,32})*$/.test(t))
|
||||
return { text: /[A-Z]/.test(t) ? 'Lowercase only.' : 'Lowercase letters, digits, dashes and dots.', bad: true };
|
||||
return { text: `Devices get names like ${example}.${t}.`, bad: false };
|
||||
return { text: /[A-Z]/.test(t) ? _('Lowercase only.') : _('Lowercase letters, digits, dashes and dots.'), bad: true };
|
||||
return { text: fmt(_('Devices get names like %s.'), `${example}.${t}`), bad: false };
|
||||
}
|
||||
|
||||
/** The fallback DNS for home-names devices: an IPv4 address, or empty for none. */
|
||||
export function fallbackDnsHelp(s: string): Help {
|
||||
const t = s.trim();
|
||||
if (!t) return { text: 'None: without the tunnel those devices have no DNS.', bad: false };
|
||||
if (!isIpv4(t)) return { text: 'Use an IPv4 address, or leave it empty.', bad: true };
|
||||
return { text: `${t} takes over when the tunnel is down.`, bad: false };
|
||||
if (!t) return { text: _('None: without the tunnel those devices have no DNS.'), bad: false };
|
||||
if (!isIpv4(t)) return { text: _('Use an IPv4 address, or leave it empty.'), bad: true };
|
||||
return { text: fmt(_('%s takes over when the tunnel is down.'), t), bad: false };
|
||||
}
|
||||
|
||||
/** The daily update time (schema update_time): HH:MM. */
|
||||
export function timeHelp(s: string): Help {
|
||||
const t = s.trim();
|
||||
if (!/^([01]?[0-9]|2[0-3]):[0-5][0-9]$/.test(t)) return { text: 'Use HH:MM, 00:00–23:59.', bad: true };
|
||||
return { text: `Runs within an hour after ${t} (router time).`, bad: false };
|
||||
if (!/^([01]?[0-9]|2[0-3]):[0-5][0-9]$/.test(t)) return { text: _('Use HH:MM, 00:00–23:59.'), bad: true };
|
||||
return { text: fmt(_('Runs within an hour after %s (router time).'), t), bad: false };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -310,7 +353,7 @@ export function endpointProbe(
|
||||
if (h.bad || !host.trim()) return h;
|
||||
if (result && result.host === host.trim()) return { text: result.text, bad: result.bad };
|
||||
const idle = opts.idle?.();
|
||||
return { text: idle ? `${idle} Checking where it points…` : `${h.text} Checking where it points…`, bad: false };
|
||||
return { text: `${idle || h.text} ${_('Checking where it points…')}`, bad: false };
|
||||
};
|
||||
return { help, schedule };
|
||||
}
|
||||
@@ -4,47 +4,71 @@ 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';
|
||||
|
||||
const NAMES: Record<string, string> = { app: 'Dawnline', amneziawg: 'AmneziaWG', pkgs: 'System packages', all: 'Components' };
|
||||
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 = NAMES[comp] ?? 'Components';
|
||||
const how = e.auto ? 'automatically' : 'by you';
|
||||
const who = E('b', {}, compName(comp));
|
||||
let tone = 'ok',
|
||||
ic = 'check',
|
||||
text: (Node | string)[];
|
||||
if (e.kind === 'found') {
|
||||
tone = 'accent';
|
||||
ic = 'download';
|
||||
text = [E('b', {}, (e.items ?? []).join(', ')), ` found by ${e.auto ? 'the automatic check' : 'a check'}`];
|
||||
// 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 = [E('b', {}, who), ` ${e.kind === 'install' ? 'update' : 'check'} failed${e.error ? ` · ${e.error}` : ''}`];
|
||||
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 ? ` ${e.to}` : '';
|
||||
text = [E('b', {}, who), `${ver} ${ver ? '' : 'updated '}${how}${e.took ? ` · ${duration(e.took)}` : ''}`.replace(/\s+/g, ' ')];
|
||||
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() }, ago(e.ts, st.now)),
|
||||
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('h3', {}, _('Activity')),
|
||||
E('span', { class: 'dl-spacer' }),
|
||||
E('a', { href: `${L.url('admin/network/dawnline/diagnostics')}?tab=log` }, 'All in Log →'),
|
||||
E('a', { href: `${L.url('admin/network/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.'),
|
||||
: E('p', { class: 'dl-sub dl-comp-empty' }, _('Updates, and checks that found something, show up here.')),
|
||||
]);
|
||||
}
|
||||
@@ -8,6 +8,7 @@ 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';
|
||||
|
||||
@@ -25,60 +26,72 @@ export function awgRows(page: ComponentsPage, w: UpdateComponent | undefined): N
|
||||
const actions: MenuEntry[] = [];
|
||||
if (cur && installed)
|
||||
actions.push({
|
||||
label: 'Reinstall this build',
|
||||
label: _('Reinstall this build'),
|
||||
warn: true,
|
||||
ic: 'reset',
|
||||
run: () => page.op(`amneziawg:${cur}${ru ? ':ru' : ''}`, 'Reinstalling AmneziaWG', installed),
|
||||
run: () => page.op(`amneziawg:${cur}${ru ? ':ru' : ''}`, _('Reinstalling AmneziaWG'), installed),
|
||||
});
|
||||
if (kept)
|
||||
actions.push({
|
||||
label: `Roll back to ${kept.version}`,
|
||||
label: fmt(_('Roll back to %s'), kept.version),
|
||||
ic: 'archive',
|
||||
warn: true,
|
||||
run: async () => {
|
||||
if (
|
||||
await confirmDialog(
|
||||
`Roll back AmneziaWG to ${kept.version}?`,
|
||||
'The build kept on the router is installed again. Every AmneziaWG tunnel restarts for a few seconds.',
|
||||
'Roll back',
|
||||
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);
|
||||
void page.op('amneziawg:rollback', _('Rolling back AmneziaWG'), installed ?? undefined);
|
||||
},
|
||||
});
|
||||
const menu: (MenuEntry | null)[] = [
|
||||
w?.release
|
||||
? {
|
||||
label: 'What’s new',
|
||||
label: _('What’s new'),
|
||||
ic: 'file',
|
||||
run: () => whatsNew('amneziawg', w.release!, `What’s new in the ${curSrc?.label ?? 'AmneziaWG'} build`, cur ?? 'slava'),
|
||||
run: () => whatsNew('amneziawg', w.release!, fmt(_('What’s new in the %s build'), curSrc?.label ?? 'AmneziaWG'), cur ?? 'slava'),
|
||||
}
|
||||
: null,
|
||||
{
|
||||
label: 'Open on GitHub',
|
||||
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 restarts ${tun.length === 1 ? 'the tunnel' : `${tun.length} tunnels`} for a few seconds: ${tun.join(', ')}. Devices keep their configurations.`
|
||||
: 'Switching takes a few seconds. Devices keep their configurations.';
|
||||
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 ? `${tun.slice(0, -1).join(', ')} and ${tun[tun.length - 1]}` : tun[0];
|
||||
const notice = tun.length ? `Switching restarts ${names} for a few seconds.` : 'Switching takes 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 ? `Switch to AmneziaWG ${x.gen}?` : `Install AmneziaWG ${x.gen}?`,
|
||||
`The ${x.label} build, ${x.version}. ${restarts}${x.gen === '3.1' ? ' Devices need AmneziaVPN 3.1 or newer.' : ''}`,
|
||||
installed ? 'Switch' : 'Install',
|
||||
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 ? `Switching to AmneziaWG ${x.gen}` : 'Installing AmneziaWG',
|
||||
installed ? fmt(_('Switching to AmneziaWG %s'), x.gen) : _('Installing AmneziaWG'),
|
||||
installed ?? undefined,
|
||||
);
|
||||
};
|
||||
@@ -88,47 +101,51 @@ export function awgRows(page: ComponentsPage, w: UpdateComponent | undefined): N
|
||||
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-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-mono dl-faint dl-comp-bver' }, x.version ?? _('none yet')),
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-comp-bact' },
|
||||
on
|
||||
? pill('ok', 'Active')
|
||||
? pill('ok', _('Active', 'build'))
|
||||
: x.version
|
||||
? button(installed ? 'Switch' : 'Install', () => switchTo(id), installed ? 'neutral' : 'positive', { disabled: page.busy })
|
||||
: pill('', 'No build'),
|
||||
? button(installed ? _('Switch') : _('Install'), () => switchTo(id), installed ? 'neutral' : 'positive', {
|
||||
disabled: page.busy,
|
||||
})
|
||||
: pill('', _('No build')),
|
||||
),
|
||||
]);
|
||||
};
|
||||
const newer = ids
|
||||
.map((id) =>
|
||||
srcs[id]?.newer ? `${srcs[id]!.label} moves to ${srcs[id]!.newer!.gen} with OpenWrt ${srcs[id]!.newer!.tag.replace(/^v/, '')}.` : '',
|
||||
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) => {
|
||||
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',
|
||||
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('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-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('b', {}, _('Russian translation')),
|
||||
E('span', { class: 'dl-sub' }, _('LuCI pages for AmneziaWG')),
|
||||
]),
|
||||
E('span', { class: 'dl-comp-bact' }, ruSw),
|
||||
]),
|
||||
@@ -146,24 +163,29 @@ export function awgRows(page: ComponentsPage, w: UpdateComponent | undefined): N
|
||||
const right: Node[] = [];
|
||||
if (w?.update && installed && cur)
|
||||
right.push(
|
||||
button(`Update to ${w.latest}`, () => page.op(`amneziawg:${cur}${ru ? ':ru' : ''}`, 'Updating AmneziaWG', installed), 'neutral', {
|
||||
disabled: page.busy,
|
||||
}),
|
||||
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));
|
||||
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 ? ` · ${w.release} build` : ''}`
|
||||
? `${installed}${w?.release ? ` · ${fmt(_('%s build'), w.release)}` : ''}`
|
||||
: missing.length
|
||||
? `missing ${missing.join(', ')}`
|
||||
? fmt(_('missing %s'), missing.join(', '))
|
||||
: w
|
||||
? 'not installed'
|
||||
: 'version not checked',
|
||||
? _('not installed')
|
||||
: _('version not checked'),
|
||||
],
|
||||
right,
|
||||
),
|
||||
|
||||
@@ -1,19 +1,30 @@
|
||||
// Components → the Dawnline block: version, what the update brings, its
|
||||
// settings at a glance, and every release to install (Versions).
|
||||
// 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 } from '../../ui/controls';
|
||||
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';
|
||||
|
||||
const EVERY: Record<string, string> = { '6h': 'every 6 h', '12h': 'every 12 h', '1d': 'daily', '7d': 'weekly' };
|
||||
/** 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) : '');
|
||||
@@ -34,7 +45,7 @@ export function hero(page: ComponentsPage, a: UpdateComponent | undefined): HTML
|
||||
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, `What’s new in Dawnline ${t.replace(/^v/, '')}`);
|
||||
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;
|
||||
@@ -43,29 +54,29 @@ export function hero(page: ComponentsPage, a: UpdateComponent | undefined): HTML
|
||||
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') },
|
||||
{ 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: `Reinstall ${st.version}`,
|
||||
label: fmt(_('Reinstall %s'), st.version),
|
||||
ic: 'reset',
|
||||
warn: true,
|
||||
run: () => page.op('app:reinstall', 'Reinstalling Dawnline', st.version),
|
||||
run: () => page.op('app:reinstall', _('Reinstalling Dawnline'), st.version),
|
||||
},
|
||||
kept
|
||||
? {
|
||||
label: `Roll back to ${kept.version}`,
|
||||
label: fmt(_('Roll back to %s'), kept.version),
|
||||
ic: 'archive',
|
||||
warn: true,
|
||||
run: async () => {
|
||||
if (
|
||||
await confirmDialog(
|
||||
`Roll back to Dawnline ${kept.version}?`,
|
||||
`The copy kept on the router replaces ${st.version}. A backup of the settings is made first.`,
|
||||
'Roll back',
|
||||
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);
|
||||
void page.op('app:rollback', _('Rolling back Dawnline'), st.version);
|
||||
},
|
||||
}
|
||||
: null,
|
||||
@@ -77,7 +88,7 @@ export function hero(page: ComponentsPage, a: UpdateComponent | undefined): HTML
|
||||
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),
|
||||
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' }, [
|
||||
@@ -87,7 +98,7 @@ export function hero(page: ComponentsPage, a: UpdateComponent | undefined): HTML
|
||||
a?.update
|
||||
? E('small', {}, `→ ${a.latest}`)
|
||||
: a?.status === 'dev' && a.latest
|
||||
? E('small', { class: 'dl-faint' }, `release ${a.latest}`)
|
||||
? E('small', { class: 'dl-faint' }, fmt(_('release %s'), a.latest))
|
||||
: '',
|
||||
]),
|
||||
E(
|
||||
@@ -97,13 +108,13 @@ export function hero(page: ComponentsPage, a: UpdateComponent | undefined): HTML
|
||||
? ''
|
||||
: a?.update
|
||||
? a.published
|
||||
? `released ${released(a.published)}`
|
||||
? fmt(_('released %s'), released(a.published))
|
||||
: ''
|
||||
: a?.status === 'dev'
|
||||
? 'ahead of the latest release'
|
||||
? _('ahead of the latest release')
|
||||
: a
|
||||
? `latest release${a.published ? ` · released ${released(a.published)}` : ''}`
|
||||
: 'not checked yet',
|
||||
? [_('latest release'), a.published ? fmt(_('released %s'), released(a.published)) : ''].filter(Boolean).join(' · ')
|
||||
: _('not checked yet'),
|
||||
),
|
||||
]),
|
||||
]),
|
||||
@@ -119,7 +130,7 @@ export function hero(page: ComponentsPage, a: UpdateComponent | undefined): HTML
|
||||
? E(
|
||||
'button',
|
||||
{ type: 'button', class: 'dl-linkbtn dl-comp-more', click: notesOf(ptag) },
|
||||
`+${items.total - items.items.length} more in What’s new`,
|
||||
plural(items.total - items.items.length, '+%s more in What’s new', '+%s more in What’s new'),
|
||||
)
|
||||
: '',
|
||||
])
|
||||
@@ -128,42 +139,43 @@ export function hero(page: ComponentsPage, a: UpdateComponent | undefined): HTML
|
||||
// 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)),
|
||||
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'),
|
||||
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'
|
||||
: `${EVERY[pol.interval] === 'weekly' ? 'weekly' : 'daily'} at ${pol.time}`
|
||||
? _('as soon as found')
|
||||
: fmt(pol.interval === '7d' ? _('weekly at %s') : _('daily at %s'), pol.time)
|
||||
: pol.check
|
||||
? `checks ${EVERY[pol.interval]}`
|
||||
: 'checks off',
|
||||
? checksEvery(pol.interval)
|
||||
: _('checks off'),
|
||||
),
|
||||
]),
|
||||
side(
|
||||
'Last check',
|
||||
_('Last check'),
|
||||
st.check
|
||||
? [
|
||||
ago(st.check.time, st.now),
|
||||
nextCheck > st.now ? E('span', { class: 'dl-faint' }, `· next in ${duration(nextCheck - st.now)}`) : '',
|
||||
nextCheck > st.now ? E('span', { class: 'dl-faint' }, `· ${fmt(_('next in %s'), duration(nextCheck - st.now))}`) : '',
|
||||
]
|
||||
: ['Never'],
|
||||
: [_('Never')],
|
||||
),
|
||||
side(
|
||||
'Rollback',
|
||||
_('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')],
|
||||
? [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'))],
|
||||
),
|
||||
]),
|
||||
]);
|
||||
@@ -191,10 +203,52 @@ function bullets(page: ComponentsPage, tag: string, from: string): { items: stri
|
||||
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')]),
|
||||
E('summary', {}, [icon('chevron'), E('span', {}, _('Versions')), E('span', { class: 'dl-sub' }, _('install any release'))]),
|
||||
body,
|
||||
]);
|
||||
fold.addEventListener('toggle', () => {
|
||||
@@ -206,10 +260,10 @@ function versions(page: ComponentsPage): HTMLElement {
|
||||
}
|
||||
|
||||
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 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');
|
||||
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) => {
|
||||
@@ -220,7 +274,7 @@ async function paintVersions(page: ComponentsPage, body: HTMLElement) {
|
||||
});
|
||||
const head = E('div', { class: 'dl-comp-tag' }, [
|
||||
tag,
|
||||
button('Install', () => installTag(tag.value), 'neutral', { disabled: page.busy }),
|
||||
button(_('Install'), () => installTag(tag.value), 'neutral', { disabled: page.busy }),
|
||||
]);
|
||||
const pageNo = page.versPage;
|
||||
const turn = (d: number) => {
|
||||
@@ -229,13 +283,13 @@ async function paintVersions(page: ComponentsPage, body: HTMLElement) {
|
||||
};
|
||||
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' }, `Page ${pageNo}`),
|
||||
E('button', { type: 'button', class: 'dl-linkbtn', disabled: more ? null : 'disabled', click: () => turn(1) }, 'Older →'),
|
||||
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…')]);
|
||||
dom.content(body, [head, E('p', { class: 'dl-muted dl-loading' }, _('Loading versions…'))]);
|
||||
try {
|
||||
rows = (await api.updatesReleases(pageNo)).releases;
|
||||
} catch (e) {
|
||||
@@ -244,8 +298,8 @@ async function paintVersions(page: ComponentsPage, body: HTMLElement) {
|
||||
dom.content(body, [
|
||||
head,
|
||||
E('div', { class: 'dl-row-actions' }, [
|
||||
E('span', { class: 'dl-muted' }, `Failed to load versions: ${errorText(e)}`),
|
||||
button('Try again', () => paintVersions(page, body)),
|
||||
E('span', { class: 'dl-muted' }, fmt(_('Failed to load versions: %s'), errorText(e))),
|
||||
button(_('Try again'), () => paintVersions(page, body)),
|
||||
]),
|
||||
pager(false),
|
||||
]);
|
||||
@@ -255,7 +309,11 @@ async function paintVersions(page: ComponentsPage, body: HTMLElement) {
|
||||
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)]);
|
||||
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,
|
||||
@@ -264,13 +322,13 @@ async function paintVersions(page: ComponentsPage, body: HTMLElement) {
|
||||
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') : '',
|
||||
r.prerelease ? pill('warn', _('Pre-release')) : '',
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-comp-ic' },
|
||||
iconButton('file', 'What’s new', () => whatsNew('app', r.tag, `What’s new in Dawnline ${v}`)),
|
||||
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 }),
|
||||
v === cur ? pill('ok', _('Installed')) : button(_('Install'), () => install(page, r.tag), 'neutral', { disabled: page.busy }),
|
||||
]);
|
||||
}),
|
||||
pager(rows.length >= 5),
|
||||
@@ -284,11 +342,14 @@ async function install(page: ComponentsPage, tag: string) {
|
||||
if (
|
||||
older &&
|
||||
!(await confirmDialog(
|
||||
`Install Dawnline ${v}?`,
|
||||
`It is older than ${page.st.version}. A backup of the settings is made first; restore it from Settings if something looks wrong.`,
|
||||
'Install',
|
||||
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}`, `Installing Dawnline ${v}`, page.st.version);
|
||||
void page.op(`app@${tag}`, fmt(_('Installing Dawnline %s'), v), page.st.version);
|
||||
}
|
||||
@@ -13,6 +13,7 @@ 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';
|
||||
@@ -44,6 +45,8 @@ export class ComponentsPage {
|
||||
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();
|
||||
@@ -85,7 +88,7 @@ export class ComponentsPage {
|
||||
/** 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');
|
||||
notify(_('Another component action is already running'), 'warning');
|
||||
return;
|
||||
}
|
||||
this.following = 'starting';
|
||||
@@ -101,10 +104,10 @@ export class ComponentsPage {
|
||||
if (comp === 'amneziawg' && c.amneziawg?.current)
|
||||
void this.op(
|
||||
`amneziawg:${c.amneziawg.current}${c.amneziawg.ru ? ':ru' : ''}`,
|
||||
'Updating AmneziaWG',
|
||||
_('Updating AmneziaWG'),
|
||||
c.amneziawg.installed ?? undefined,
|
||||
);
|
||||
else void this.op('app', 'Updating Dawnline', this.st.version);
|
||||
else void this.op('app', _('Updating Dawnline'), this.st.version);
|
||||
},
|
||||
});
|
||||
if (this.following === 'starting') this.following = job?.id ?? null;
|
||||
@@ -113,14 +116,17 @@ export class ComponentsPage {
|
||||
|
||||
async follow(job: UpdateJob) {
|
||||
this.following = job.id;
|
||||
const comp = runningComponent(job);
|
||||
const what =
|
||||
({ app: 'Dawnline', amneziawg: 'AmneziaWG', pkgs: 'system packages', all: 'components' } as Record<string, string>)[comp] ??
|
||||
'components';
|
||||
// [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: `${job.action === 'check' ? 'Checking' : job.auto ? 'Automatic update:' : 'Updating'} ${what}`,
|
||||
title: (titles[runningComponent(job)] ?? titles.all)[job.action === 'check' ? 0 : job.auto ? 1 : 2],
|
||||
onDone: (s) => this.refresh(s),
|
||||
},
|
||||
job,
|
||||
@@ -139,13 +145,13 @@ export class ComponentsPage {
|
||||
dom.content(this.root, [
|
||||
E('div', { class: 'dl-pagehead' }, [
|
||||
E('div', { class: 'dl-stack' }, [
|
||||
E('h2', { class: 'dl-h1' }, 'Components'),
|
||||
E('h2', { class: 'dl-h1' }, _('Components')),
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-faint' },
|
||||
[
|
||||
fw?.version ? `OpenWrt ${fw.version} · ${fw.target}` : '',
|
||||
st.check ? `checked ${ago(st.check.time, st.now)}` : 'not checked yet',
|
||||
st.check ? fmt(_('checked %s'), ago(st.check.time, st.now)) : _('not checked yet'),
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' · '),
|
||||
@@ -155,29 +161,31 @@ export class ComponentsPage {
|
||||
E(
|
||||
'a',
|
||||
{ class: 'cbi-button cbi-button-neutral dl-icon-btn', href: `${L.url('admin/network/dawnline/settings')}?section=updates` },
|
||||
[icon('edit'), ' Settings'],
|
||||
[icon('edit'), ' ', _('Settings')],
|
||||
),
|
||||
button([icon('refresh'), ' Check all'], () => this.op('check', 'Checking all components'), 'neutral', { disabled: this.busy }),
|
||||
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('h3', {}, _('Components')),
|
||||
E('span', { class: 'dl-spacer' }),
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-faint dl-comp-count' },
|
||||
awgMissing
|
||||
? n
|
||||
? `AmneziaWG not installed · ${n} update${n === 1 ? '' : 's'}`
|
||||
: 'AmneziaWG not installed'
|
||||
? `${_('AmneziaWG not installed')} · ${plural(n, '%s update', '%s updates')}`
|
||||
: _('AmneziaWG not installed')
|
||||
: !c.amneziawg && !c.packages
|
||||
? ''
|
||||
: n
|
||||
? `${n} of ${1 + pk.total} need${n === 1 ? 's' : ''} an update`
|
||||
: 'Everything is up to date',
|
||||
? 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]),
|
||||
@@ -194,16 +202,15 @@ export class ComponentsPage {
|
||||
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',
|
||||
'…',
|
||||
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', `The latest release is ${latest}`);
|
||||
return pill('ok', 'Up to date');
|
||||
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). */
|
||||
@@ -219,7 +226,7 @@ export class ComponentsPage {
|
||||
.map((x) => (x ? { label: x.label, icon: icon(x.ic), warn: x.warn, run: x.run } : null)),
|
||||
),
|
||||
'neutral',
|
||||
{ title: 'More', 'aria-label': 'More' },
|
||||
{ title: _('More'), 'aria-label': _('More') },
|
||||
);
|
||||
return b;
|
||||
}
|
||||
@@ -229,16 +236,16 @@ export class ComponentsPage {
|
||||
const busy = this.busy ? ' is-busy' : '';
|
||||
let btn: HTMLButtonElement;
|
||||
if (label)
|
||||
btn = button([icon('refresh'), ' Check'], check, 'neutral', {
|
||||
btn = button([icon('refresh'), ' ', _('Check')], check, 'neutral', {
|
||||
class: `cbi-button cbi-button-neutral dl-comp-check${busy}`,
|
||||
'aria-label': 'Check for updates',
|
||||
'aria-label': _('Check for updates'),
|
||||
});
|
||||
else {
|
||||
btn = iconButton('refresh', 'Check for updates', check, 'neutral', busy.trim());
|
||||
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']);
|
||||
btn.setAttribute('aria-label', _('Check for updates'));
|
||||
attachTip(btn, () => [_('Check for updates')]);
|
||||
}
|
||||
return E('span', { class: 'dl-comp-ic' }, [btn, this.more(menu)]);
|
||||
}
|
||||
|
||||
@@ -5,38 +5,49 @@ 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';
|
||||
|
||||
const SYS_ITEMS: { title: string; sub: string; pkgs: string[]; feature: 'home' | 'https' | 'acme'; optional?: boolean }[] = [
|
||||
{ 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,
|
||||
},
|
||||
];
|
||||
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 = SYS_ITEMS.filter((it) => (it.feature === 'home' ? st.home : st.portal));
|
||||
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(
|
||||
`Update ${what}?`,
|
||||
`${shown.join(', ')} from the OpenWrt feeds. Services that use them restart for a moment.`,
|
||||
'Update',
|
||||
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(',')}`, `Updating ${what}`);
|
||||
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: _('Check system packages'), ic: 'refresh', run: () => page.op('check:packages', _('Checking system packages')) },
|
||||
{
|
||||
label: 'Open the OpenWrt package list',
|
||||
label: _('Open the OpenWrt package list'),
|
||||
ic: 'globe',
|
||||
run: () => window.open('https://openwrt.org/packages/start', '_blank', 'noopener'),
|
||||
},
|
||||
@@ -52,11 +63,16 @@ export function packageRows(page: ComponentsPage, p: UpdateComponent | undefined
|
||||
return page.row(
|
||||
ICONS[it.feature],
|
||||
it.title,
|
||||
[`${it.optional ? 'not installed' : `missing ${lacks.join(', ')}`}`],
|
||||
[it.optional ? _('not installed') : fmt(_('missing %s'), lacks.join(', '))],
|
||||
[
|
||||
button('Install', () => page.op(`pkgs:${lacks.join(',')}`, `Installing ${it.title}`), it.optional ? 'neutral' : 'positive', {
|
||||
disabled: page.busy,
|
||||
}),
|
||||
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)),
|
||||
],
|
||||
);
|
||||
@@ -68,7 +84,7 @@ export function packageRows(page: ComponentsPage, p: UpdateComponent | undefined
|
||||
main ? [`${pkgs[main]!.installed} → ${pkgs[main]!.latest}`, upd.length > 1 ? ` · +${upd.length - 1}` : ''] : [upd.join(', ')],
|
||||
[
|
||||
button(
|
||||
'Update',
|
||||
_('Update'),
|
||||
() =>
|
||||
runPkgs(
|
||||
present.filter((x) => pkgs[x]?.latest || pkgs[x]?.with?.length),
|
||||
|
||||
@@ -9,6 +9,7 @@ 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';
|
||||
@@ -59,8 +60,8 @@ export class HealthTab {
|
||||
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…'),
|
||||
E('div', { class: 'dl-panel-head' }, [E('h3', {}, _('Checks'))]),
|
||||
E('p', { class: 'dl-muted dl-loading' }, _('Running checks…')),
|
||||
]);
|
||||
return;
|
||||
}
|
||||
@@ -69,16 +70,16 @@ export class HealthTab {
|
||||
dom.content(
|
||||
this.summary,
|
||||
bad
|
||||
? callout('error', `${bad} problem${bad > 1 ? 's' : ''} need attention.`)
|
||||
? callout('error', plural(bad, '%s problem needs attention.', '%s problems need attention.'))
|
||||
: warn
|
||||
? callout('warn', `${warn} warning${warn > 1 ? 's' : ''}.`)
|
||||
: callout('ok', 'All checks passed.'),
|
||||
? 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('div', { class: 'dl-panel-head' }, [E('h3', {}, _('Checks')), E('span', { class: 'dl-spacer' }), button(_('Run again'), refresh)]),
|
||||
E(
|
||||
'ul',
|
||||
{ class: 'dl-checks' },
|
||||
@@ -86,10 +87,11 @@ export class HealthTab {
|
||||
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' }, `Repaired by the watchdog at ${clock(repaired.get(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),
|
||||
@@ -107,8 +109,8 @@ export class HealthTab {
|
||||
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');
|
||||
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);
|
||||
@@ -119,13 +121,13 @@ export class HealthTab {
|
||||
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-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.',
|
||||
? _('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' }),
|
||||
@@ -140,8 +142,13 @@ export class HealthTab {
|
||||
'span',
|
||||
{
|
||||
class: `dl-check-chip${t.ok ? '' : ' error'}`,
|
||||
title: t.ok ? 'OK' : `Not working${t.tries ? ` · ${t.tries} repair${t.tries > 1 ? 's' : ''}` : ''}`,
|
||||
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],
|
||||
),
|
||||
),
|
||||
@@ -150,13 +157,18 @@ export class HealthTab {
|
||||
'span',
|
||||
{ class: `dl-sub${stale ? ' dl-warn-text' : ''}` },
|
||||
stale
|
||||
? `The agent has not checked in for ${Math.round((wd.now - wd.beat!) / 60)} min; cron restarts it after 5.`
|
||||
? 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 ? `Looked ${ago(wd.last, wd.now)}` : 'Starts within a minute',
|
||||
wd.last ? fmt(_('Looked %s'), ago(wd.last, wd.now)) : _('Starts within a minute'),
|
||||
' · ',
|
||||
today.length
|
||||
? `${today.length} repair${today.length > 1 ? 's' : ''} today, last ${lastRep.name} at ${clock(lastRep.ts)}`
|
||||
: 'no repairs today',
|
||||
? 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'),
|
||||
],
|
||||
),
|
||||
]),
|
||||
@@ -172,16 +184,16 @@ export class HealthTab {
|
||||
.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('h3', {}, _('Recent problems')),
|
||||
E('span', { class: 'dl-spacer' }),
|
||||
items.length ? E('a', { href: '#', click: (e: Event) => (e.preventDefault(), this.toLog()) }, 'All in Log →') : '',
|
||||
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.',
|
||||
_('No problems in the last 7 days.'),
|
||||
]),
|
||||
]);
|
||||
return;
|
||||
|
||||
@@ -13,10 +13,9 @@ type Tab = 'health' | 'log';
|
||||
type Events = Awaited<ReturnType<typeof api.events>>;
|
||||
type Loaded = [Status, Events, ServiceLog];
|
||||
|
||||
const TABS: [Tab, string][] = [
|
||||
['health', 'Health'],
|
||||
['log', 'Log'],
|
||||
];
|
||||
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;
|
||||
@@ -25,7 +24,7 @@ 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' });
|
||||
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', {});
|
||||
@@ -61,7 +60,7 @@ export class DiagnosticsPage {
|
||||
});
|
||||
return E('div', {}, [
|
||||
E('div', { class: 'dl-pagehead' }, [
|
||||
E('div', { class: 'dl-stack' }, [E('h2', { class: 'dl-h1' }, 'Diagnostics'), this.subEl]),
|
||||
E('div', { class: 'dl-stack' }, [E('h2', { class: 'dl-h1' }, _('Diagnostics')), this.subEl]),
|
||||
this.actionsEl,
|
||||
]),
|
||||
this.segEl,
|
||||
@@ -87,7 +86,7 @@ export class DiagnosticsPage {
|
||||
this.tab = tab;
|
||||
dom.content(
|
||||
this.segEl,
|
||||
TABS.map(([k, t]) =>
|
||||
TABS.map((k) =>
|
||||
E(
|
||||
'button',
|
||||
{
|
||||
@@ -97,14 +96,14 @@ export class DiagnosticsPage {
|
||||
'aria-selected': k === tab ? 'true' : 'false',
|
||||
click: () => k !== this.tab && this.show(k),
|
||||
},
|
||||
t,
|
||||
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.';
|
||||
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();
|
||||
|
||||
@@ -8,9 +8,10 @@ import { api, type LogCategory, type LogsInfo, type ServiceLogEntry } from '../.
|
||||
import { button } from '../../ui/button';
|
||||
import { dropdown } from '../../ui/menu';
|
||||
import { icon } from '../../../shared/icons';
|
||||
import { CATEGORIES, CATEGORY_LABEL, categoryOf, isProblem, retentionText, type LogItem } from '../../events/model';
|
||||
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>>;
|
||||
@@ -54,16 +55,16 @@ export class LogTab {
|
||||
items.filter((x) => x.sys).map((x) => x.sys!),
|
||||
);
|
||||
};
|
||||
const exp = button([icon('download'), ' Export'], () =>
|
||||
const exp = button([icon('download'), ` ${_('Export')}`], () =>
|
||||
dropdown(exp, [
|
||||
{ label: 'CSV (spreadsheet)', icon: icon('download'), run: run('csv') },
|
||||
{ label: _('CSV (spreadsheet)'), icon: icon('download'), run: run('csv') },
|
||||
{ label: 'JSON', icon: icon('download'), run: run('json') },
|
||||
]),
|
||||
);
|
||||
const clear = button([icon('trash'), ' Clear'], () =>
|
||||
const clear = button([icon('trash'), ` ${_('Clear')}`], () =>
|
||||
clearLogDialog(
|
||||
'Clear the log',
|
||||
'Removes events from the log on the router.',
|
||||
_('Clear the log'),
|
||||
_('Removes events from the log on the router.'),
|
||||
{},
|
||||
() => this.reload(),
|
||||
this.kind === 'all' ? undefined : this.kind,
|
||||
@@ -77,7 +78,8 @@ export class LogTab {
|
||||
this.events = r.events;
|
||||
this.policy = r.policy;
|
||||
const off = CATEGORIES.filter((c) => !r.policy.categories.includes(c));
|
||||
this.sub = `${retentionText(r.policy)}${off.length ? ` Not recorded: ${off.map((c) => CATEGORY_LABEL[c].toLowerCase()).join(', ')}.` : ''}`;
|
||||
const kept = retentionText(r.policy);
|
||||
this.sub = off.length ? `${kept} ${fmt(_('Not recorded: %s.'), off.map((c) => categoryLabel(c).toLowerCase()).join(', '))}` : kept;
|
||||
}
|
||||
|
||||
async reload() {
|
||||
@@ -119,7 +121,7 @@ export class LogTab {
|
||||
click: () => this.show(k),
|
||||
},
|
||||
[
|
||||
k === 'all' ? 'All' : k === 'system' ? 'System' : CATEGORY_LABEL[k],
|
||||
k === 'all' ? _('All') : k === 'system' ? _('System') : categoryLabel(k),
|
||||
E('b', {}, String(all.filter((x) => this.matches(x, k)).length)),
|
||||
],
|
||||
),
|
||||
@@ -139,7 +141,9 @@ export class LogTab {
|
||||
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.')]),
|
||||
E('div', { class: 'dl-empty' }, [
|
||||
E('p', {}, this.events.length || this.system.length ? _('No events match.') : _('The log is empty.')),
|
||||
]),
|
||||
);
|
||||
return;
|
||||
}
|
||||
@@ -153,7 +157,7 @@ export class LogTab {
|
||||
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('en-GB', { hour: '2-digit', minute: '2-digit' });
|
||||
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(
|
||||
@@ -176,7 +180,7 @@ export class LogTab {
|
||||
E(
|
||||
'div',
|
||||
{ class: 'dl-more-row' },
|
||||
button(`Show ${Math.min(PAGE, items.length - this.shown)} more of ${items.length - this.shown}`, () => {
|
||||
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();
|
||||
}),
|
||||
|
||||
@@ -8,7 +8,8 @@ import { api } from '../api';
|
||||
import { svg } from '../ui/layout';
|
||||
import { attachTip } from '../ui/tooltip';
|
||||
import { icon } from '../../shared/icons';
|
||||
import { ago, bits, bytes, date, daysLeft, endsIn, endsSoon, initials, todayOf } from '../../shared/format';
|
||||
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';
|
||||
@@ -32,29 +33,27 @@ interface Attention {
|
||||
function attention(st: Status): Attention[] {
|
||||
const out: Attention[] = [];
|
||||
const link = (href: string, t: string) => E('a', { href }, t);
|
||||
const diagnostics = () => link(L.url('admin/network/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, not just "down": its interface name is taken by a network section Dawnline didn't make.
|
||||
out.push({ tone: 'bad', text: [`${s.name} ${s.blocked}. `, link(L.url('admin/network/dawnline/diagnostics'), 'Open Diagnostics')] });
|
||||
else if (s.enabled && !s.up && !awg)
|
||||
out.push({
|
||||
tone: 'bad',
|
||||
text: [`Tunnel ${s.ifname} is down. `, link(L.url('admin/network/dawnline/diagnostics'), 'Open Diagnostics')],
|
||||
});
|
||||
// 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) {
|
||||
if (p.state === 'quota') out.push({ tone: 'warn', text: [link(personUrl(p.id), p.name), ' reached the data limit.'] });
|
||||
else if (p.state === 'expired') out.push({ tone: 'warn', text: [link(personUrl(p.id), p.name), '’s access has ended.'] });
|
||||
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: [link(personUrl(p.id), p.name), `’s access ${endsIn(left as number)}.`] });
|
||||
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: [link(personUrl(p.id), p.name), `’s end date passed (${date(p.expires)}) · access kept.`] });
|
||||
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: [link(personUrl(p.id), p.name), ' has used 90% of the data limit.'] });
|
||||
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));
|
||||
@@ -63,11 +62,17 @@ function attention(st: Status): Attention[] {
|
||||
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}`),
|
||||
' needs its configuration again.',
|
||||
]
|
||||
: [`${stale.length} devices need their configuration again (networks or DNS changed).`],
|
||||
)
|
||||
: [
|
||||
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)
|
||||
@@ -75,7 +80,8 @@ function attention(st: Status): Attention[] {
|
||||
out.push({
|
||||
tone: 'warn',
|
||||
text: [
|
||||
`Public address changed: ${s.name} still gives devices ${s.endpoint}, the router is ${st.wan} now. `,
|
||||
fmt(_('Public address changed: %s still gives devices %s, the router is %s now.'), s.name, s.endpoint, st.wan),
|
||||
' ',
|
||||
E(
|
||||
'button',
|
||||
{
|
||||
@@ -86,24 +92,30 @@ function attention(st: Status): Attention[] {
|
||||
b.disabled = true;
|
||||
await attempt(
|
||||
() => api.serverUpdate(s.id, { endpoint: st.wan }),
|
||||
`${s.name} uses ${st.wan} now — devices need their configuration again`,
|
||||
fmt(_('%s uses %s now - devices need their configuration again'), s.name, st.wan),
|
||||
);
|
||||
b.disabled = false;
|
||||
},
|
||||
},
|
||||
'Use the new address',
|
||||
_('Use the new address'),
|
||||
),
|
||||
' A DDNS name would follow it by itself.',
|
||||
' ',
|
||||
_('A DDNS name would follow it by itself.'),
|
||||
],
|
||||
});
|
||||
if (st.servers.some((s) => s.lan_like) && st.like_home.error)
|
||||
out.push({
|
||||
tone: 'warn',
|
||||
text: [`Internet through the LAN is off: ${st.like_home.error} `, link(L.url('admin/network/dawnline/diagnostics'), 'Details')],
|
||||
// The reason is the router's.
|
||||
text: [
|
||||
fmt(_('Internet through the LAN is off: %s'), st.like_home.error),
|
||||
' ',
|
||||
link(L.url('admin/network/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/network/dawnline/settings'), 'Turn on')] });
|
||||
out.push({ tone: '', text: [_('The personal portal is off.'), ' ', link(L.url('admin/network/dawnline/settings'), _('Turn on'))] });
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -188,8 +200,8 @@ export class ServerOverview {
|
||||
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('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) => {
|
||||
@@ -202,11 +214,11 @@ export class ServerOverview {
|
||||
if (!st.geo.enabled)
|
||||
return E('div', { class: 'dl-panel flush' }, [
|
||||
head,
|
||||
E('div', { class: 'dl-map-off' }, [
|
||||
'Locations are off. ',
|
||||
E('a', { href: L.url('admin/network/dawnline/settings') }, 'Turn them on in Settings'),
|
||||
'.',
|
||||
]),
|
||||
E(
|
||||
'div',
|
||||
{ class: 'dl-map-off' },
|
||||
fill(_('Locations are off. %s.'), E('a', { href: L.url('admin/network/dawnline/settings') }, _('Turn them on in Settings'))),
|
||||
),
|
||||
]);
|
||||
const map = (this.map = new ConnectionMap(
|
||||
{
|
||||
@@ -224,8 +236,8 @@ export class ServerOverview {
|
||||
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']),
|
||||
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()));
|
||||
@@ -248,9 +260,9 @@ export class ServerOverview {
|
||||
this.parts.side,
|
||||
E('div', { class: 'dl-panel flush' }, [
|
||||
E('div', { class: 'dl-panel-head pad' }, [
|
||||
E('h3', {}, 'Needs attention'),
|
||||
E('h3', {}, _('Needs attention')),
|
||||
E('span', { class: 'dl-spacer' }),
|
||||
E('a', { href: L.url('admin/network/dawnline/diagnostics') }, 'Health'),
|
||||
E('a', { href: L.url('admin/network/dawnline/diagnostics') }, _('Health')),
|
||||
]),
|
||||
att.length
|
||||
? att
|
||||
@@ -262,7 +274,7 @@ export class ServerOverview {
|
||||
a.action ?? '',
|
||||
]),
|
||||
)
|
||||
: E('div', { class: 'dl-row dl-muted' }, [icon('check'), 'All good. Nothing needs you right now.']),
|
||||
: E('div', { class: 'dl-row dl-muted' }, [icon('check'), _('All good. Nothing needs you right now.')]),
|
||||
]),
|
||||
quiet,
|
||||
);
|
||||
@@ -272,13 +284,13 @@ export class ServerOverview {
|
||||
this.parts.activity,
|
||||
E('div', { class: 'dl-panel flush' }, [
|
||||
E('div', { class: 'dl-panel-head pad' }, [
|
||||
E('h3', {}, 'Activity'),
|
||||
E('h3', {}, _('Activity')),
|
||||
E('span', { class: 'dl-spacer' }),
|
||||
E('a', { href: `${L.url('admin/network/dawnline/diagnostics')}?tab=log` }, 'View all'),
|
||||
E('a', { href: `${L.url('admin/network/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.'),
|
||||
: E('div', { class: 'dl-row dl-muted' }, _('Nothing yet. Connections, new devices and pauses appear here.')),
|
||||
]),
|
||||
quiet,
|
||||
);
|
||||
@@ -332,7 +344,7 @@ export class ServerOverview {
|
||||
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 ? `online for ${ago(since, st.now).replace(' ago', '')}` : 'online'),
|
||||
E('span', { class: 'dl-hc-since' }, since ? fmt(_('online for %s'), duration(Math.max(60, st.now - since))) : _('online')),
|
||||
]),
|
||||
E(
|
||||
'span',
|
||||
@@ -345,12 +357,12 @@ export class ServerOverview {
|
||||
'div',
|
||||
{ class: 'dl-hc-speed-row' },
|
||||
idle
|
||||
? [E('span', { class: 'dl-faint' }, 'Idle right now')]
|
||||
? [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' }, '15 min'),
|
||||
E('span', { class: 'dl-faint' }, _('15 min')),
|
||||
],
|
||||
),
|
||||
chart,
|
||||
@@ -364,7 +376,7 @@ export class ServerOverview {
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-faint' },
|
||||
`${bytes(devs.reduce((n, d) => n + today(d), 0))} today · ${bytes(p.month[0] + p.month[1])} this month`,
|
||||
`${fmt(_('%s today'), bytes(devs.reduce((n, d) => n + today(d), 0)))} · ${fmt(_('%s this month'), bytes(p.month[0] + p.month[1]))}`,
|
||||
),
|
||||
]),
|
||||
]),
|
||||
@@ -374,7 +386,7 @@ export class ServerOverview {
|
||||
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));
|
||||
const el = E('a', { class: `dl-onl-p${big ? '' : ' sm'}`, href: personUrl(p.id), 'aria-label': `${p.name}, online` }, [
|
||||
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) : '',
|
||||
big
|
||||
@@ -391,15 +403,14 @@ export class ServerOverview {
|
||||
|
||||
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, () => [`${on.length} ${on.length === 1 ? 'person' : 'people'} · ${ndev} device${ndev === 1 ? '' : 's'}`]);
|
||||
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]),
|
||||
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),
|
||||
@@ -409,7 +420,7 @@ export class ServerOverview {
|
||||
{
|
||||
class: 'dl-onl-p sm more',
|
||||
href: `${L.url('admin/network/dawnline/server')}?server=${encodeURIComponent(this.srvId)}§ion=people&filter=online`,
|
||||
title: 'Everyone online',
|
||||
title: _('Everyone online'),
|
||||
click: (ev: Event) => {
|
||||
if (this.go) {
|
||||
ev.preventDefault();
|
||||
@@ -423,10 +434,10 @@ export class ServerOverview {
|
||||
])
|
||||
: 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'),
|
||||
E('span', {}, off ? _('The server is turned off') : _('Nobody is connected')),
|
||||
last
|
||||
? E('span', { class: 'dl-sub' }, `Last: ${last.p.name}, ${ago(last.d.handshake, st.now)}`)
|
||||
: E('span', { class: 'dl-sub' }, off ? 'Devices connect once it is on' : 'No device has connected yet'),
|
||||
? 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')),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
@@ -448,6 +459,6 @@ export class ServerOverview {
|
||||
.filter(([, n]) => n > 0)
|
||||
.sort((a, b) => b[1] - a[1])
|
||||
.slice(0, 2);
|
||||
return daysTile(this.st.series, top.length ? `Most: ${top.map(([p, n]) => `${p.name} ${bytes(n)}`).join(' · ')}` : '');
|
||||
return daysTile(this.st.series, top.length ? fmt(_('Most: %s'), top.map(([p, n]) => `${p.name} ${bytes(n)}`).join(' · ')) : '');
|
||||
}
|
||||
}
|
||||
+131
-87
@@ -24,7 +24,7 @@ import { expiresHelp, limitHelp, nameHelp, quotaHelp } from '../netcheck';
|
||||
import { coreFor } from '../cores';
|
||||
import { icon } from '../../shared/icons';
|
||||
import {
|
||||
KIND_LABEL,
|
||||
kindLabel,
|
||||
addMonthsClamped,
|
||||
ago,
|
||||
bits,
|
||||
@@ -38,6 +38,7 @@ import {
|
||||
initials,
|
||||
todayOf,
|
||||
} from '../../shared/format';
|
||||
import { fill, fmt, num, plural } from '../../shared/i18n';
|
||||
|
||||
type Sid = string;
|
||||
|
||||
@@ -64,13 +65,13 @@ function slotBar(p: Person): HTMLElement {
|
||||
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: `${used} of ${p.device_limit} devices` }, [
|
||||
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 }, (_, i) => E('i', { class: i >= p.device_limit ? 'over' : i < used ? 'used' : '' })),
|
||||
Array.from({ length: n }, (_x, i) => E('i', { class: i >= p.device_limit ? 'over' : i < used ? 'used' : '' })),
|
||||
),
|
||||
E('span', { class: 'dl-slotbar-text' }, `${used} of ${p.device_limit}`),
|
||||
E('span', { class: 'dl-slotbar-text' }, fmt(_('%s of %s'), used, p.device_limit)),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -201,8 +202,8 @@ export class PeoplePage {
|
||||
'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.',
|
||||
? _('No people yet. Add someone and send them their personal link.')
|
||||
: _('Set up the server first, then add people.'),
|
||||
),
|
||||
);
|
||||
this.decorate();
|
||||
@@ -229,7 +230,7 @@ export class PeoplePage {
|
||||
'select',
|
||||
{
|
||||
class: 'dl-select',
|
||||
'aria-label': 'Sort',
|
||||
'aria-label': _('Sort'),
|
||||
change: (ev: Event) => {
|
||||
page.sort = (ev.target as HTMLSelectElement).value as SortBy;
|
||||
remember('dl.people.sort', page.sort);
|
||||
@@ -237,17 +238,17 @@ export class PeoplePage {
|
||||
},
|
||||
},
|
||||
[
|
||||
E('option', { value: 'seen', selected: page.sort === 'seen' ? 'selected' : null }, 'Last seen'),
|
||||
E('option', { value: 'name', selected: page.sort === 'name' ? 'selected' : null }, 'Name'),
|
||||
E('option', { value: 'usage', selected: page.sort === 'usage' ? 'selected' : null }, 'Usage'),
|
||||
E('option', { value: 'seen', selected: page.sort === 'seen' ? 'selected' : null }, _('Last seen', 'sort')),
|
||||
E('option', { value: 'name', selected: page.sort === 'name' ? 'selected' : null }, _('Name', 'sort')),
|
||||
E('option', { value: 'usage', selected: page.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',
|
||||
placeholder: _('Find…'),
|
||||
'aria-label': _('Find a person or device'),
|
||||
hidden: st.people.length > 8 ? null : 'hidden',
|
||||
input: (ev: Event) => {
|
||||
page.query = (ev.target as HTMLInputElement).value.trim().toLowerCase();
|
||||
@@ -268,25 +269,28 @@ export class PeoplePage {
|
||||
? ''
|
||||
: E('div', { class: 'dl-pagehead' }, [
|
||||
E('div', { class: 'dl-stack' }, [
|
||||
E('h2', { class: 'dl-h1' }, 'People'),
|
||||
E('h2', { class: 'dl-h1' }, _('People')),
|
||||
E('span', { class: 'dl-muted dl-people-count' }, this.countText()),
|
||||
]),
|
||||
st.servers.length ? button([icon('plus'), ' Add person'], () => page.openCreate(), 'add') : '',
|
||||
st.servers.length ? button([icon('plus'), ` ${_('Add person')}`], () => page.openCreate(), 'add') : '',
|
||||
]),
|
||||
st.servers.length
|
||||
? ''
|
||||
: E('div', { class: 'alert-message warning' }, [
|
||||
'No server yet. ',
|
||||
E('a', { href: L.url('admin/network/dawnline/server') }, 'Run the setup wizard'),
|
||||
' before adding people.',
|
||||
]),
|
||||
: E(
|
||||
'div',
|
||||
{ class: 'alert-message warning' },
|
||||
fill(
|
||||
_('No server yet. %s before adding people.'),
|
||||
E('a', { href: L.url('admin/network/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,
|
||||
page.serverId ? button([icon('plus'), ' Add person'], () => page.openCreate(), 'add') : '',
|
||||
page.serverId ? button([icon('plus'), ` ${_('Add person')}`], () => page.openCreate(), 'add') : '',
|
||||
]),
|
||||
]),
|
||||
this.list,
|
||||
@@ -311,7 +315,11 @@ export class PeoplePage {
|
||||
|
||||
countText(): string {
|
||||
const t = this.st.totals;
|
||||
return `${t.people} ${t.people === 1 ? 'person' : 'people'} · ${t.devices} device${t.devices === 1 ? '' : 's'} · ${t.online} online`;
|
||||
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. */
|
||||
@@ -329,7 +337,7 @@ export class PeoplePage {
|
||||
};
|
||||
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' };
|
||||
const label: Record<Filter, string> = { all: _('All'), online: _('Online'), attention: _('Needs attention'), paused: _('Paused') };
|
||||
dom.content(
|
||||
tabs,
|
||||
(Object.keys(label) as Filter[]).map((f) =>
|
||||
@@ -385,7 +393,7 @@ export class PeoplePage {
|
||||
// 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.'));
|
||||
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();
|
||||
}
|
||||
@@ -397,7 +405,7 @@ export class PeoplePage {
|
||||
renderCard(node: HTMLElement, sid: Sid): HTMLElement {
|
||||
const p = this.person(sid);
|
||||
if (!p) {
|
||||
dom.content(node, E('em', {}, 'This person was just removed.'));
|
||||
dom.content(node, E('em', {}, _('This person was just removed.')));
|
||||
return node;
|
||||
}
|
||||
const today = this.today;
|
||||
@@ -413,14 +421,14 @@ export class PeoplePage {
|
||||
const soon = endsSoon(p, left);
|
||||
const over = left != null && left < 0;
|
||||
pills.push(
|
||||
E('span', { class: `dl-pill-ic${over ? ' bad' : soon ? ' warn' : ''}`, title: `Access ends ${date(p.expires)}` }, [
|
||||
E('span', { class: `dl-pill-ic${over ? ' bad' : soon ? ' warn' : ''}`, title: fmt(_('Access ends %s'), date(p.expires)) }, [
|
||||
icon('calendar'),
|
||||
over ? `ended ${date(p.expires)}` : soon ? endsIn(left as number) : `until ${date(p.expires)}`,
|
||||
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('-', '–')]));
|
||||
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(
|
||||
@@ -428,7 +436,13 @@ export class PeoplePage {
|
||||
{
|
||||
type: 'button',
|
||||
class: `dl-chip${d.disabled ? ' disabled' : ''}${d.online ? ' live' : ''}`,
|
||||
title: `${KIND_LABEL[d.kind]} · ${d.address}${d.online ? ` · online from ${d.endpoint}` : d.handshake ? ` · seen ${ago(d.handshake, this.st.now)}` : ''}`,
|
||||
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));
|
||||
@@ -437,7 +451,7 @@ export class PeoplePage {
|
||||
[
|
||||
icon(d.kind),
|
||||
E('span', { class: 'dl-chip-name' }, d.name),
|
||||
!d.handshake && !d.disabled ? E('span', { class: 'dl-chip-tag' }, 'not set up') : '',
|
||||
!d.handshake && !d.disabled ? E('span', { class: 'dl-chip-tag' }, _('not set up')) : '',
|
||||
// Online shows as the green chip (.dl-chip.live); no dots.
|
||||
],
|
||||
);
|
||||
@@ -449,13 +463,13 @@ export class PeoplePage {
|
||||
{
|
||||
type: 'button',
|
||||
class: 'dl-chip add',
|
||||
title: free > 0 ? 'Add device' : 'Over the limit: admins can still 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'],
|
||||
[icon('plus'), _('Add device')],
|
||||
),
|
||||
);
|
||||
|
||||
@@ -465,20 +479,24 @@ export class PeoplePage {
|
||||
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',
|
||||
{
|
||||
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',
|
||||
_('More'),
|
||||
(ev: MouseEvent) =>
|
||||
dropdown(
|
||||
ev.currentTarget as HTMLElement,
|
||||
[
|
||||
{
|
||||
label: 'Open',
|
||||
label: _('Open'),
|
||||
icon: icon('open'),
|
||||
run: () => {
|
||||
location.href = personUrl(p.id);
|
||||
@@ -486,27 +504,27 @@ export class PeoplePage {
|
||||
},
|
||||
portal
|
||||
? {
|
||||
label: 'Invite card',
|
||||
label: _('Invite card'),
|
||||
icon: icon('qr'),
|
||||
run: () => inviteCard(p, this.st.servers.find((s) => s.id === p.server)?.name ?? 'Home'),
|
||||
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,
|
||||
free > 0 ? { label: _('Add device'), icon: icon('plus'), run: () => addDevice(p, this.deviceOpts(p)) } : null,
|
||||
null,
|
||||
{
|
||||
label: p.paused ? 'Resume' : 'Pause',
|
||||
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) },
|
||||
{ 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') : '',
|
||||
portal ? iconButton('link', _('Copy link'), () => copyPersonLink(p.id), 'neutral', 'dl-icon-only') : '',
|
||||
more,
|
||||
]);
|
||||
|
||||
@@ -541,28 +559,34 @@ export class PeoplePage {
|
||||
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 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)]],
|
||||
paused: ['pause', 'warn', _('Paused'), _('Devices can’t connect until you resume'), ['play', _('Resume'), () => this.togglePause(p)]],
|
||||
quota:
|
||||
p.quota_period === 'month'
|
||||
? ['chart', 'bad', 'Data limit reached', `Paused until it resets on ${date(reset)}`, ['plus', '+10 GB this month', extra]]
|
||||
? [
|
||||
'chart',
|
||||
'bad',
|
||||
_('Data limit reached'),
|
||||
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))],
|
||||
_('Data limit reached'),
|
||||
_('Paused until the limit is raised'),
|
||||
['edit', _('Change limit'), () => (location.href = personUrl(p.id))],
|
||||
],
|
||||
expired: [
|
||||
'calendar',
|
||||
'bad',
|
||||
`Access ended ${date(p.expires)}`,
|
||||
'Devices can’t connect',
|
||||
['calendar', 'Extend 1 month', () => this.quick(p, { expires: addMonth(p.expires, today) }, 'Extended by 1 month')],
|
||||
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', `Access ${p.hours.replace('-', '–')} (router time)`, null],
|
||||
no_server: ['alert', 'warn', 'No server', 'Choose a server on their page', null],
|
||||
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}` }, [
|
||||
@@ -586,16 +610,18 @@ export class PeoplePage {
|
||||
fill.style.width = `${pct}%`;
|
||||
bar.appendChild(fill);
|
||||
attachTip(bar, () => [
|
||||
E('div', { class: 'dl-tip-title' }, `${pct.toFixed(1)}% used`),
|
||||
E('div', { class: 'dl-tip-title' }, fmt(_('%s%% used'), num(pct, 1))),
|
||||
E(
|
||||
'div',
|
||||
{ class: 'dl-muted' },
|
||||
`${bytes(p.quota_used)} of ${bytes(p.quota_limit)} · ${bytes(Math.max(0, p.quota_limit - p.quota_used))} left`,
|
||||
`${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)))}`,
|
||||
),
|
||||
E(
|
||||
'div',
|
||||
{ class: 'dl-faint' },
|
||||
p.quota_period === 'total' ? 'In total' : `This month${p.bonus_gb ? ` · includes +${p.bonus_gb} GB extra` : ''}`,
|
||||
p.quota_period === 'total'
|
||||
? _('In total')
|
||||
: [_('This month'), p.bonus_gb ? fmt(_('includes +%s GB extra'), num(p.bonus_gb)) : ''].filter(Boolean).join(' · '),
|
||||
),
|
||||
]);
|
||||
} else {
|
||||
@@ -610,7 +636,7 @@ export class PeoplePage {
|
||||
});
|
||||
if (devs.length)
|
||||
attachTip(bar, () => [
|
||||
E('div', { class: 'dl-tip-title' }, 'This month by device'),
|
||||
E('div', { class: 'dl-tip-title' }, _('This month by device')),
|
||||
...devs.map((x, i) =>
|
||||
E('div', { class: 'dl-tip-row' }, [
|
||||
E('span', { class: `dl-swatch c${Math.min(i, 4)}` }),
|
||||
@@ -621,12 +647,12 @@ export class PeoplePage {
|
||||
]);
|
||||
}
|
||||
|
||||
const limitText = p.quota_limit ? `${bytes(Math.max(0, p.quota_limit - p.quota_used))} left` : 'no limit';
|
||||
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'),
|
||||
? 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' }, [
|
||||
@@ -634,38 +660,50 @@ export class PeoplePage {
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-faint' },
|
||||
p.quota_limit ? `of ${bytes(p.quota_limit)}` : p.quota_period === 'total' && p.quota_gb ? 'in total' : 'this month',
|
||||
p.quota_limit
|
||||
? fmt(_('of %s'), bytes(p.quota_limit))
|
||||
: p.quota_period === 'total' && p.quota_gb
|
||||
? _('in total')
|
||||
: _('this month'),
|
||||
),
|
||||
]),
|
||||
bar,
|
||||
live
|
||||
? E('div', { class: 'dl-use-live', title: 'Right now' }, [`↓ ${bits(r![2])}`, E('span', { class: 'dl-faint' }, `↑ ${bits(r![1])}`)])
|
||||
: E('div', { class: 'dl-faint dl-pside-foot' }, today ? `today ${bytes(today)} · ${limitText}` : limitText),
|
||||
? E('div', { class: 'dl-use-live', title: _('Right now') }, [
|
||||
`↓ ${bits(r![2])}`,
|
||||
E('span', { class: 'dl-faint' }, `↑ ${bits(r![1])}`),
|
||||
])
|
||||
: E('div', { class: 'dl-faint dl-pside-foot' }, today ? `${fmt(_('today %s'), bytes(today))} · ${limitText}` : limitText),
|
||||
]);
|
||||
}
|
||||
|
||||
async togglePause(p: Person) {
|
||||
if (await attempt(() => api.personPause(p.id, !p.paused), p.paused ? `${p.name} resumed` : `${p.name} paused`)) await this.refresh();
|
||||
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(
|
||||
`Remove ${p?.name ?? sid}?`,
|
||||
`All ${p?.devices.length ?? 0} devices are disconnected immediately and the personal link stops working. Usage history is kept in backups.`,
|
||||
'Remove',
|
||||
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();
|
||||
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');
|
||||
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;
|
||||
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 {
|
||||
@@ -688,7 +726,7 @@ export class PeoplePage {
|
||||
class: 'cbi-input-text',
|
||||
min: 0,
|
||||
step: 'any',
|
||||
placeholder: 'Unlimited',
|
||||
placeholder: _('Unlimited'),
|
||||
value: last.quota ?? '',
|
||||
}) as HTMLInputElement;
|
||||
const quick = (label: string, months: number) =>
|
||||
@@ -721,26 +759,32 @@ export class PeoplePage {
|
||||
]);
|
||||
// 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', name, () => nameHelp(name.value, [], 'Shown in their portal and apps.'));
|
||||
const limitRow = liveField('Devices', limit, () => limitHelp(limit.value));
|
||||
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',
|
||||
_('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', 0)]),
|
||||
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));
|
||||
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',
|
||||
_('Add person'),
|
||||
[
|
||||
nameRow,
|
||||
server ? row('Server', server) : '',
|
||||
server ? row(_('Server'), server) : '',
|
||||
E('div', { class: 'cbi-value dl-block' }, [
|
||||
E('label', { class: 'cbi-value-title' }, 'Access'),
|
||||
E('label', { class: 'cbi-value-title' }, _('Access')),
|
||||
E('div', { class: 'cbi-value-field' }, access.el),
|
||||
]),
|
||||
limitRow,
|
||||
@@ -752,7 +796,7 @@ export class PeoplePage {
|
||||
' ',
|
||||
button(
|
||||
// Without the portal there is no link to copy.
|
||||
portalOn ? 'Create and copy link' : 'Create',
|
||||
portalOn ? _('Create and copy link') : _('Create'),
|
||||
async () => {
|
||||
const bad = firstBad([nameRow, limitRow, expRow, quotaRow]);
|
||||
if (bad) {
|
||||
@@ -774,7 +818,7 @@ export class PeoplePage {
|
||||
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);
|
||||
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();
|
||||
},
|
||||
@@ -788,28 +832,28 @@ export class PeoplePage {
|
||||
showCreated(id: string, name: string, link: string | null, server: string) {
|
||||
if (link) {
|
||||
inviteCard({ id, name, link }, server, {
|
||||
title: `${name} is ready`,
|
||||
lead: `Send ${name} the card or the link. They open it, add their devices and connect — no account needed.`,
|
||||
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(
|
||||
`${name} is ready`,
|
||||
[E('p', {}, 'Created. Turn on the personal portal in Settings to get a link, or add devices for them here.')],
|
||||
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('button', { class: 'cbi-button cbi-button-neutral', click: closeModal }, _('Done')),
|
||||
' ',
|
||||
E(
|
||||
'a',
|
||||
{ class: 'cbi-button cbi-button-neutral', href: `${L.url('admin/network/dawnline/settings')}?section=portal` },
|
||||
'Open Settings',
|
||||
_('Open Settings'),
|
||||
),
|
||||
' ',
|
||||
p
|
||||
? button(
|
||||
'Add device',
|
||||
_('Add device'),
|
||||
() => {
|
||||
closeModal();
|
||||
addDevice(p, this.deviceOpts(p));
|
||||
|
||||
@@ -4,6 +4,7 @@ import { E } from '../../e';
|
||||
import { button } from '../../ui/button';
|
||||
import { dropdown } from '../../ui/menu';
|
||||
import { icon } from '../../../shared/icons';
|
||||
import { fill, fmt, num, plural } from '../../../shared/i18n';
|
||||
import { ConnectionMap, rangeControl } from '../../map';
|
||||
import { eventRow, eventText } from '../../events/render';
|
||||
import { clearLogDialog, exportEvents } from '../../logs';
|
||||
@@ -13,11 +14,11 @@ import type { PersonPage } from './index';
|
||||
function mapCard(page: PersonPage): HTMLElement {
|
||||
const st = page.st;
|
||||
const head = E('div', { class: 'dl-panel-head pad' }, [
|
||||
E('h3', {}, 'Locations'),
|
||||
E('h3', {}, _('Locations')),
|
||||
E('span', { class: 'dl-spacer' }),
|
||||
st.geo.enabled ? rangeControl('30d', (r) => page.map?.setRange(r), false) : '',
|
||||
button(
|
||||
'Hide',
|
||||
_('Hide'),
|
||||
() => {
|
||||
page.mapOpen = false;
|
||||
page.map?.destroy();
|
||||
@@ -30,11 +31,11 @@ function mapCard(page: PersonPage): HTMLElement {
|
||||
if (!st.geo.enabled)
|
||||
return E('div', { class: 'dl-panel flush' }, [
|
||||
head,
|
||||
E('div', { class: 'dl-map-off' }, [
|
||||
'Locations are off. ',
|
||||
E('a', { href: L.url('admin/network/dawnline/settings') }, 'Turn them on in Settings'),
|
||||
'.',
|
||||
]),
|
||||
E(
|
||||
'div',
|
||||
{ class: 'dl-map-off' },
|
||||
fill(_('Locations are off. %s.'), E('a', { href: L.url('admin/network/dawnline/settings') }, _('Turn them on in Settings'))),
|
||||
),
|
||||
]);
|
||||
const map = new ConnectionMap(
|
||||
{
|
||||
@@ -59,11 +60,11 @@ export function placesPart(page: PersonPage): HTMLElement | null {
|
||||
return E('div', { class: 'dl-places' }, [
|
||||
icon('pin'),
|
||||
E('div', { class: 'dl-stack' }, [
|
||||
E('span', {}, 'Locations are off'),
|
||||
E('span', { class: 'dl-sub' }, 'City-level, from the client IP'),
|
||||
E('span', {}, _('Locations are off')),
|
||||
E('span', { class: 'dl-sub' }, _('City-level, from the client IP')),
|
||||
]),
|
||||
E('span', { class: 'dl-spacer' }),
|
||||
E('a', { class: 'cbi-button cbi-button-neutral', href: L.url('admin/network/dawnline/settings') }, 'Turn on'),
|
||||
E('a', { class: 'cbi-button cbi-button-neutral', href: L.url('admin/network/dawnline/settings') }, _('Turn on')),
|
||||
]);
|
||||
if (page.mapOpen) return page.map && page.parts.places.contains(page.map.el) ? null : mapCard(page);
|
||||
const since = st.now - 30 * 86400;
|
||||
@@ -73,19 +74,19 @@ export function placesPart(page: PersonPage): HTMLElement | null {
|
||||
return E('div', { class: 'dl-places' }, [
|
||||
icon('pin'),
|
||||
E('div', { class: 'dl-stack' }, [
|
||||
E('span', {}, last ? last.city || last.country : 'No locations yet'),
|
||||
E('span', {}, last ? last.city || last.country : _('No locations yet')),
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-sub' },
|
||||
last
|
||||
? `${places.length} place${places.length === 1 ? '' : 's'} in 30 days${last.org ? ` · ${last.org}` : ''}`
|
||||
: 'Shown after a device connects',
|
||||
? [plural(places.length, '%s place in 30 days', '%s places in 30 days'), last.org].filter(Boolean).join(' · ')
|
||||
: _('Shown after a device connects'),
|
||||
),
|
||||
]),
|
||||
E('span', { class: 'dl-spacer' }),
|
||||
pts.length
|
||||
? button(
|
||||
'Show map',
|
||||
_('Show map'),
|
||||
() => {
|
||||
page.mapOpen = true;
|
||||
page.paintPlaces();
|
||||
@@ -110,7 +111,7 @@ export function activityPart(page: PersonPage): HTMLElement {
|
||||
const row = eventRow(st, e, { server: false });
|
||||
if (n > 1) {
|
||||
const main = row.querySelector('.dl-row-main') as HTMLElement;
|
||||
dom.content(main, [...eventText(st, e).slice(0, 3), E('span', { class: 'dl-muted' }, `${n} times`)]);
|
||||
dom.content(main, [...eventText(st, e).slice(0, 3), E('span', { class: 'dl-muted' }, plural(n, '%s time', '%s times'))]);
|
||||
main.title = latest
|
||||
.slice(i, i + n)
|
||||
.map((x) => x.detail ?? '')
|
||||
@@ -123,29 +124,32 @@ export function activityPart(page: PersonPage): HTMLElement {
|
||||
[icon('more')],
|
||||
() =>
|
||||
dropdown(more, [
|
||||
{ label: 'Export CSV', icon: icon('download'), run: () => exportEvents(st, all, 'csv', p.id) },
|
||||
{ label: 'Export JSON', icon: icon('download'), run: () => exportEvents(st, all, 'json', p.id) },
|
||||
{ label: _('Export CSV'), icon: icon('download'), run: () => exportEvents(st, all, 'csv', p.id) },
|
||||
{ label: _('Export JSON'), icon: icon('download'), run: () => exportEvents(st, all, 'json', p.id) },
|
||||
null,
|
||||
{
|
||||
label: `Clear ${p.name}'s activity`,
|
||||
label: fmt(_("Clear %s's activity"), p.name),
|
||||
icon: icon('trash'),
|
||||
danger: true,
|
||||
run: () =>
|
||||
clearLogDialog(`Clear ${p.name}'s activity`, `Removes events about ${p.name} and their devices.`, { person: p.id }, () =>
|
||||
page.refresh(),
|
||||
clearLogDialog(
|
||||
fmt(_("Clear %s's activity"), p.name),
|
||||
fmt(_('Removes events about %s and their devices.'), p.name),
|
||||
{ person: p.id },
|
||||
() => page.refresh(),
|
||||
),
|
||||
},
|
||||
]),
|
||||
'neutral',
|
||||
{ title: 'Export or clear', class: 'cbi-button cbi-button-neutral dl-icon-only' },
|
||||
{ title: _('Export or clear'), class: 'cbi-button cbi-button-neutral dl-icon-only' },
|
||||
);
|
||||
return E('div', { class: 'dl-panel flush' }, [
|
||||
E('div', { class: 'dl-panel-head pad' }, [
|
||||
E('h3', {}, 'Activity'),
|
||||
E('span', { class: 'dl-sub' }, all.length > 10 ? `latest 10 of ${all.length}` : ''),
|
||||
E('h3', {}, _('Activity')),
|
||||
E('span', { class: 'dl-sub' }, all.length > 10 ? fmt(_('latest 10 of %s'), num(all.length)) : ''),
|
||||
E('span', { class: 'dl-spacer' }),
|
||||
more,
|
||||
]),
|
||||
rows.length ? rows : E('div', { class: 'dl-row dl-muted' }, 'Nothing yet.'),
|
||||
rows.length ? rows : E('div', { class: 'dl-row dl-muted' }, _('Nothing yet.')),
|
||||
]);
|
||||
}
|
||||
@@ -9,7 +9,8 @@ import { downloadFile } from '../../ui/files';
|
||||
import { attempt, notify } from '../../ui/toast';
|
||||
import { deviceStatus } from '../../ui/badges';
|
||||
import { icon } from '../../../shared/icons';
|
||||
import { KIND_LABEL, ago, byDeviceState, bytes } from '../../../shared/format';
|
||||
import { kindLabel, ago, byDeviceState, bytes } from '../../../shared/format';
|
||||
import { fmt, num } from '../../../shared/i18n';
|
||||
import { addDevice, openDevice, quickMenu } from '../../device';
|
||||
import { dayBars } from '../../widgets/tiles';
|
||||
import type { PersonPage } from './index';
|
||||
@@ -18,14 +19,14 @@ import type { PersonPage } from './index';
|
||||
async function showDeviceQr(page: PersonPage, d: Device) {
|
||||
const cfg = await attempt(() => api.deviceConfig(d.id));
|
||||
if (!cfg) return;
|
||||
modal(`Set up ${d.name}`, [await page.core.connectBlock(cfg, 'qr')], [cancelButton('Close')]);
|
||||
modal(fmt(_('Set up %s'), d.name), [await page.core.connectBlock(cfg, 'qr')], [cancelButton(_('Close'))]);
|
||||
}
|
||||
|
||||
async function downloadConfig(page: PersonPage, d: Device) {
|
||||
const cfg = await attempt(() => api.deviceConfig(d.id));
|
||||
if (!cfg) return;
|
||||
if (!cfg.has_private_key) {
|
||||
notify('This device made its own keys in the browser; its configuration only exists there.', 'warning');
|
||||
notify(_('This device made its own keys in the browser; its configuration only exists there.'), 'warning');
|
||||
return;
|
||||
}
|
||||
const f = page.core.file.make(cfg);
|
||||
@@ -42,7 +43,7 @@ export function devicesPart(page: PersonPage): HTMLElement {
|
||||
};
|
||||
const more = (d: Device) =>
|
||||
button([icon('more')], (ev: MouseEvent) => quickMenu(ev.currentTarget as HTMLElement, p, d, page.deviceOpts()), 'neutral', {
|
||||
title: 'QR, file, key, rename, new keys, remove',
|
||||
title: _('QR, file, key, rename, new keys, remove'),
|
||||
class: 'cbi-button cbi-button-neutral dl-icon-only',
|
||||
});
|
||||
const cards = byDeviceState(p.devices).map((d) => {
|
||||
@@ -51,12 +52,12 @@ export function devicesPart(page: PersonPage): HTMLElement {
|
||||
E('button', { type: 'button', class: 'dl-dcard-title', click: () => open(d) }, [
|
||||
E('b', {}, d.name),
|
||||
deviceStatus(d, now, undefined, p),
|
||||
d.config_stale ? E('span', { class: 'dl-pill warn dl-stale' }, 'Update config') : '',
|
||||
d.config_stale ? E('span', { class: 'dl-pill warn dl-stale' }, _('Update config')) : '',
|
||||
]),
|
||||
more(d),
|
||||
]);
|
||||
const trend = E('div', { class: 'dl-dcard-trend' }, [
|
||||
E('div', { class: 'dl-stack' }, [E('b', {}, bytes(d.month[0] + d.month[1])), E('span', { class: 'dl-sub' }, 'this month')]),
|
||||
E('div', { class: 'dl-stack' }, [E('b', {}, bytes(d.month[0] + d.month[1])), E('span', { class: 'dl-sub' }, _('this month'))]),
|
||||
dayBars(page.devSeries[d.id] ?? []),
|
||||
]);
|
||||
return E('article', { class: `dl-dcard clickable${d.online ? ' online' : ''}${d.disabled ? ' off' : ''}`, click: clickCard(d) }, [
|
||||
@@ -67,11 +68,11 @@ export function devicesPart(page: PersonPage): HTMLElement {
|
||||
? E(
|
||||
'div',
|
||||
{ class: 'dl-sub' },
|
||||
`${KIND_LABEL[d.kind]} · created ${ago(d.created, now)} ${d.created_by === 'portal' ? 'in the portal' : 'by you'}.`,
|
||||
`${kindLabel(d.kind)} · ${fmt(d.created_by === 'portal' ? _('created %s in the portal.') : _('created %s by you.'), ago(d.created, now))}`,
|
||||
)
|
||||
: E('div', { class: 'dl-chips-row' }, [
|
||||
E('button', { type: 'button', class: 'dl-chipbtn', click: () => showDeviceQr(page, d) }, [icon('qr'), 'Show QR']),
|
||||
E('button', { type: 'button', class: 'dl-chipbtn', click: () => downloadConfig(page, d) }, [icon('download'), 'Config']),
|
||||
E('button', { type: 'button', class: 'dl-chipbtn', click: () => showDeviceQr(page, d) }, [icon('qr'), _('Show QR')]),
|
||||
E('button', { type: 'button', class: 'dl-chipbtn', click: () => downloadConfig(page, d) }, [icon('download'), _('Config')]),
|
||||
]),
|
||||
]);
|
||||
});
|
||||
@@ -81,17 +82,19 @@ export function devicesPart(page: PersonPage): HTMLElement {
|
||||
E('button', { type: 'button', class: 'dl-dslot add', click: () => addDevice(p, page.deviceOpts()) }, [
|
||||
E('span', { class: 'dl-dslot-ic' }, icon('plus')),
|
||||
E('span', { class: 'dl-stack' }, [
|
||||
E('b', {}, 'Add device'),
|
||||
E('b', {}, _('Add device')),
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-sub' },
|
||||
over ? `Over the limit · ${p.devices.length} of ${p.device_limit}` : `${p.devices.length} of ${p.device_limit}`,
|
||||
over
|
||||
? `${_('Over the limit')} · ${fmt(_('%s of %s'), p.devices.length, p.device_limit)}`
|
||||
: fmt(_('%s of %s'), p.devices.length, p.device_limit),
|
||||
),
|
||||
]),
|
||||
]),
|
||||
);
|
||||
return E('section', { class: 'dl-devsec' }, [
|
||||
E('div', { class: 'dl-panel-head' }, [E('h3', {}, 'Devices'), E('span', { class: 'dl-sub' }, `${p.online} online`)]),
|
||||
E('div', { class: 'dl-panel-head' }, [E('h3', {}, _('Devices')), E('span', { class: 'dl-sub' }, fmt(_('%s online'), num(p.online)))]),
|
||||
E('div', { class: 'dl-dgrid' }, cards),
|
||||
]);
|
||||
}
|
||||
@@ -10,13 +10,14 @@ import { liveField } from '../../ui/layout';
|
||||
import { nameHelp } from '../../netcheck';
|
||||
import { inviteCard } from '../../invite';
|
||||
import { peopleUrl } from '../../urls';
|
||||
import { fmt, plural } from '../../../shared/i18n';
|
||||
import type { PersonPage } from './index';
|
||||
|
||||
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)]);
|
||||
|
||||
export function invite(page: PersonPage) {
|
||||
const server = page.st.servers.find((s) => s.id === page.p.server)?.name ?? 'Home';
|
||||
const server = page.st.servers.find((s) => s.id === page.p.server)?.name ?? _('Home');
|
||||
void inviteCard(page.p, server);
|
||||
}
|
||||
|
||||
@@ -32,10 +33,10 @@ export async function newLink(page: PersonPage) {
|
||||
const boxes = suspect.map(
|
||||
(d) => E('input', { type: 'checkbox', id: `dl-rm-${d.id}`, checked: 'checked', 'data-id': d.id }) as HTMLInputElement,
|
||||
);
|
||||
const body: Node[] = [E('p', {}, 'The old link stops working right away.')];
|
||||
const body: Node[] = [E('p', {}, _('The old link stops working right away.'))];
|
||||
if (suspect.length)
|
||||
body.push(
|
||||
E('p', {}, 'Devices added through the old link keep working until they are removed. Remove them too:'),
|
||||
E('p', {}, _('Devices added through the old link keep working until they are removed. Remove them too:')),
|
||||
E(
|
||||
'div',
|
||||
{ class: 'dl-checklist' },
|
||||
@@ -46,33 +47,35 @@ export async function newLink(page: PersonPage) {
|
||||
const remove = boxes.filter((b) => b.checked).map((b) => b.dataset.id as string);
|
||||
const r = await attempt(
|
||||
() => api.personRegen(p.id, remove),
|
||||
remove.length ? `New link created, ${remove.length} device${remove.length === 1 ? '' : 's'} removed` : 'New link created',
|
||||
remove.length
|
||||
? plural(remove.length, 'New link created, %s device removed', 'New link created, %s devices removed')
|
||||
: _('New link created'),
|
||||
);
|
||||
if (!r) return;
|
||||
closeModal();
|
||||
if (remove.length) await page.refresh();
|
||||
if (r.link) await copyText(r.link, 'New link copied');
|
||||
if (r.link) await copyText(r.link, _('New link copied'));
|
||||
};
|
||||
modal('Create a new link?', body, [cancelButton(), ' ', button('Create new link', go, 'negative')]);
|
||||
modal(_('Create a new link?'), body, [cancelButton(), ' ', button(_('Create new link'), go, 'negative')]);
|
||||
}
|
||||
|
||||
export function editNote(page: PersonPage) {
|
||||
const input = E(
|
||||
'textarea',
|
||||
{ class: 'cbi-input-textarea dl-note-input', rows: 3, maxlength: 500, placeholder: 'Only you see this' },
|
||||
{ class: 'cbi-input-textarea dl-note-input', rows: 3, maxlength: 500, placeholder: _('Only you see this') },
|
||||
page.p.note ?? '',
|
||||
) as HTMLTextAreaElement;
|
||||
modal(
|
||||
'Note',
|
||||
_('Note'),
|
||||
[input],
|
||||
[
|
||||
cancelButton(),
|
||||
' ',
|
||||
button(
|
||||
'Save',
|
||||
_('Save'),
|
||||
async () => {
|
||||
closeModal();
|
||||
await page.patch({ note: input.value.trim() }, input.value.trim() ? 'Note saved' : 'Note removed');
|
||||
await page.patch({ note: input.value.trim() }, input.value.trim() ? _('Note saved') : _('Note removed'));
|
||||
},
|
||||
'positive',
|
||||
),
|
||||
@@ -84,9 +87,9 @@ export function editNote(page: PersonPage) {
|
||||
export function endSettings(page: PersonPage) {
|
||||
const p = page.p;
|
||||
const act = E('select', { class: 'cbi-input-select' }, [
|
||||
E('option', { value: 'pause', selected: p.expire_action === 'pause' ? 'selected' : null }, 'Pause access'),
|
||||
E('option', { value: 'notify', selected: p.expire_action === 'notify' ? 'selected' : null }, 'Keep access'),
|
||||
E('option', { value: 'remove', selected: p.expire_action === 'remove' ? 'selected' : null }, 'Remove their devices'),
|
||||
E('option', { value: 'pause', selected: p.expire_action === 'pause' ? 'selected' : null }, _('Pause access')),
|
||||
E('option', { value: 'notify', selected: p.expire_action === 'notify' ? 'selected' : null }, _('Keep access')),
|
||||
E('option', { value: 'remove', selected: p.expire_action === 'remove' ? 'selected' : null }, _('Remove their devices')),
|
||||
]) as HTMLSelectElement;
|
||||
const warn = E(
|
||||
'select',
|
||||
@@ -95,19 +98,19 @@ export function endSettings(page: PersonPage) {
|
||||
E(
|
||||
'option',
|
||||
{ value: n, selected: p.expire_warn === n ? 'selected' : null },
|
||||
n ? `${n} day${n === 1 ? '' : 's'} before` : 'Don’t warn',
|
||||
n ? plural(n, '%s day before', '%s days before') : _('Don’t warn'),
|
||||
),
|
||||
),
|
||||
) as HTMLSelectElement;
|
||||
modal(
|
||||
'When access ends',
|
||||
_('When access ends'),
|
||||
[
|
||||
field('Then', act),
|
||||
field(_('Then'), act),
|
||||
E('div', { class: 'cbi-value' }, [
|
||||
E('label', { class: 'cbi-value-title' }, 'Warn'),
|
||||
E('label', { class: 'cbi-value-title' }, _('Warn')),
|
||||
E('div', { class: 'cbi-value-field' }, [
|
||||
warn,
|
||||
E('div', { class: 'cbi-value-description' }, 'Shown in their portal and on the Overview.'),
|
||||
E('div', { class: 'cbi-value-description' }, _('Shown in their portal and on the Overview.')),
|
||||
]),
|
||||
]),
|
||||
],
|
||||
@@ -115,10 +118,10 @@ export function endSettings(page: PersonPage) {
|
||||
cancelButton(),
|
||||
' ',
|
||||
button(
|
||||
'Save',
|
||||
_('Save'),
|
||||
async () => {
|
||||
closeModal();
|
||||
await page.patch({ expire_action: act.value, expire_warn: warn.value }, 'Saved');
|
||||
await page.patch({ expire_action: act.value, expire_warn: warn.value }, _('Saved'));
|
||||
},
|
||||
'positive',
|
||||
),
|
||||
@@ -128,15 +131,15 @@ export function endSettings(page: PersonPage) {
|
||||
|
||||
export function rename(page: PersonPage) {
|
||||
const input = E('input', { type: 'text', class: 'cbi-input-text', value: page.p.name, maxlength: 48 }) as HTMLInputElement;
|
||||
const nameRow = liveField('Name', input, () => nameHelp(input.value, [], 'Shown in their portal and apps.'));
|
||||
const nameRow = liveField(_('Name', 'person'), input, () => nameHelp(input.value, [], _('Shown in their portal and apps.')));
|
||||
modal(
|
||||
'Rename',
|
||||
_('Rename'),
|
||||
[nameRow],
|
||||
[
|
||||
cancelButton(),
|
||||
' ',
|
||||
button(
|
||||
'Save',
|
||||
_('Save'),
|
||||
async () => {
|
||||
const h = nameRow.help();
|
||||
if (h.bad) {
|
||||
@@ -144,7 +147,7 @@ export function rename(page: PersonPage) {
|
||||
return;
|
||||
}
|
||||
// The dialog stays open on a refusal, with the name still typed.
|
||||
if (await page.patch({ name: input.value.trim() }, 'Renamed')) closeModal();
|
||||
if (await page.patch({ name: input.value.trim() }, _('Renamed'))) closeModal();
|
||||
},
|
||||
'positive',
|
||||
),
|
||||
@@ -160,30 +163,36 @@ export function moveToServer(page: PersonPage) {
|
||||
const sel = E(
|
||||
'select',
|
||||
{ class: 'cbi-input-select' },
|
||||
others.map((s) => E('option', { value: s.id }, `${s.name} · ${s.endpoint || 'no address'}:${s.port}`)),
|
||||
others.map((s) => E('option', { value: s.id }, `${s.name} · ${s.endpoint || _('no address')}:${s.port}`)),
|
||||
) as HTMLSelectElement;
|
||||
const n = p.devices.length;
|
||||
modal(
|
||||
`Move ${p.name} to another server`,
|
||||
fmt(_('Move %s to another server'), p.name),
|
||||
[
|
||||
field('Server', sel),
|
||||
field(_('Server'), sel),
|
||||
E(
|
||||
'p',
|
||||
{ class: 'dl-muted' },
|
||||
n
|
||||
? `${n} device${n === 1 ? ' gets a new address and stops' : 's get new addresses and stop'} connecting until ${n === 1 ? 'it imports its' : 'they import their'} configuration again (from the personal link or from you). Circles and home networks of the old server are left behind.`
|
||||
: 'They have no devices yet: nothing else changes.',
|
||||
? plural(
|
||||
n,
|
||||
'%s device gets a new address and stops connecting until it imports its configuration again (from the personal link or from you). Circles and home networks of the old server are left behind.',
|
||||
'%s devices get new addresses and stop connecting until they import their configuration again (from the personal link or from you). Circles and home networks of the old server are left behind.',
|
||||
)
|
||||
: _('They have no devices yet: nothing else changes.'),
|
||||
),
|
||||
],
|
||||
[
|
||||
cancelButton(),
|
||||
' ',
|
||||
button(
|
||||
'Move',
|
||||
_('Move'),
|
||||
async () => {
|
||||
if (await page.patch({ server: sel.value }, `Moved to ${others.find((s) => s.id === sel.value)?.name ?? 'the server'}`)) {
|
||||
if (
|
||||
await page.patch({ server: sel.value }, fmt(_('Moved to %s'), others.find((s) => s.id === sel.value)?.name ?? _('the server')))
|
||||
) {
|
||||
closeModal();
|
||||
if (n) notify('Devices are marked “Update config” until they import again.', 'info', 6000);
|
||||
if (n) notify(_('Devices are marked “Update config” until they import again.'), 'info', 6000);
|
||||
}
|
||||
},
|
||||
'positive',
|
||||
@@ -195,10 +204,14 @@ export function moveToServer(page: PersonPage) {
|
||||
export async function remove(page: PersonPage) {
|
||||
const p = page.p;
|
||||
const ok = await confirmDialog(
|
||||
`Delete ${p.name}?`,
|
||||
`All ${p.devices.length} devices are disconnected immediately and the personal link stops working.`,
|
||||
'Delete',
|
||||
fmt(_('Delete %s?'), p.name),
|
||||
plural(
|
||||
p.devices.length,
|
||||
'%s device is disconnected immediately and the personal link stops working.',
|
||||
'All %s devices are disconnected immediately and the personal link stops working.',
|
||||
),
|
||||
_('Delete'),
|
||||
true,
|
||||
);
|
||||
if (ok && (await attempt(() => api.personDelete(p.id), 'Deleted'))) location.href = peopleUrl(p.server);
|
||||
if (ok && (await attempt(() => api.personDelete(p.id), _('Deleted')))) location.href = peopleUrl(p.server);
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import { dropdown, type MenuItem } from '../../ui/menu';
|
||||
import { statePill } from '../../ui/badges';
|
||||
import { icon } from '../../../shared/icons';
|
||||
import { ago, bytes, date, initials, isoDay } from '../../../shared/format';
|
||||
import { fmt } from '../../../shared/i18n';
|
||||
import { copyPersonLink } from '../../invite';
|
||||
import { daysTile, speedTile } from '../../widgets/tiles';
|
||||
import { editNote, invite, moveToServer, newLink, remove, rename } from './dialogs';
|
||||
@@ -14,26 +15,26 @@ import type { PersonPage } from './index';
|
||||
export function headPart(page: PersonPage): HTMLElement {
|
||||
const p = page.p;
|
||||
const st = page.st;
|
||||
const lastSeen = p.online ? 'online now' : p.last_seen ? `last seen ${ago(p.last_seen, st.now)}` : 'never connected';
|
||||
const added = p.created ? `Added ${date(isoDay(new Date(p.created * 1000)))}` : '';
|
||||
const lastSeen = p.online ? _('online now') : p.last_seen ? fmt(_('last seen %s'), ago(p.last_seen, st.now)) : _('never connected');
|
||||
const added = p.created ? fmt(_('Added %s', 'date'), date(isoDay(new Date(p.created * 1000)))) : '';
|
||||
// The personal link is not in the status: its actions ask for it while there is one.
|
||||
const portal = p.has_link ?? st.settings.portal_enabled;
|
||||
const menu: (MenuItem | null)[] = [
|
||||
{ label: 'Rename', icon: icon('edit'), run: () => rename(page) },
|
||||
{ label: p.note ? 'Edit note' : 'Add note', icon: icon('file'), run: () => editNote(page) },
|
||||
{ label: _('Rename'), icon: icon('edit'), run: () => rename(page) },
|
||||
{ label: p.note ? _('Edit note') : _('Add note'), icon: icon('file'), run: () => editNote(page) },
|
||||
// With one server there is nowhere to move to.
|
||||
...(st.servers.length > 1 ? [{ label: 'Move to server…', icon: icon('server'), run: () => moveToServer(page) }] : []),
|
||||
...(st.servers.length > 1 ? [{ label: _('Move to server…'), icon: icon('server'), run: () => moveToServer(page) }] : []),
|
||||
...(portal
|
||||
? [
|
||||
null,
|
||||
{ label: 'Invite card', icon: icon('qr'), run: () => invite(page) },
|
||||
{ label: 'New link', icon: icon('key'), run: () => newLink(page) },
|
||||
{ label: _('Invite card'), icon: icon('qr'), run: () => invite(page) },
|
||||
{ label: _('New link'), icon: icon('key'), run: () => newLink(page) },
|
||||
]
|
||||
: []),
|
||||
null,
|
||||
// While paused, Resume is the page's own button (as the server's Turn on).
|
||||
...(p.paused ? [] : [{ label: 'Pause', icon: icon('pause'), warn: true, run: () => page.patch({ paused: true }, 'Paused') }]),
|
||||
{ label: 'Delete', icon: icon('trash'), danger: true, run: () => remove(page) },
|
||||
...(p.paused ? [] : [{ label: _('Pause'), icon: icon('pause'), warn: true, run: () => page.patch({ paused: true }, _('Paused')) }]),
|
||||
{ label: _('Delete'), icon: icon('trash'), danger: true, run: () => remove(page) },
|
||||
];
|
||||
return E('div', { class: 'dl-person-head' }, [
|
||||
E('div', { class: 'dl-pagehead' }, [
|
||||
@@ -41,19 +42,23 @@ export function headPart(page: PersonPage): HTMLElement {
|
||||
E('span', { class: `dl-avatar lg${p.online ? ' online' : ''}` }, initials(p.name)),
|
||||
E('div', { class: 'dl-stack' }, [
|
||||
E('div', { class: 'dl-title-row' }, [E('h2', { class: 'dl-h1' }, p.name), statePill(p)]),
|
||||
E('span', { class: 'dl-faint', title: added }, `${p.devices.length} of ${p.device_limit} devices · ${lastSeen}`),
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-faint', title: added },
|
||||
`${fmt(N_(p.device_limit, '%s of %s device', '%s of %s devices'), p.devices.length, p.device_limit)} · ${lastSeen}`,
|
||||
),
|
||||
]),
|
||||
]),
|
||||
E('div', { class: 'dl-pcard-actions' }, [
|
||||
// White, as the server's Turn on.
|
||||
p.paused ? button([icon('play'), ' Resume'], () => page.patch({ paused: false }, 'Resumed'), 'add') : '',
|
||||
portal ? iconButton('link', 'Copy link', () => copyPersonLink(p.id), 'neutral', 'dl-icon-only') : '',
|
||||
iconButton('more', 'More', (ev: MouseEvent) => dropdown(ev.currentTarget as HTMLElement, menu), 'neutral', 'dl-icon-only'),
|
||||
p.paused ? button([icon('play'), ` ${_('Resume')}`], () => page.patch({ paused: false }, _('Resumed')), 'add') : '',
|
||||
portal ? iconButton('link', _('Copy link'), () => copyPersonLink(p.id), 'neutral', 'dl-icon-only') : '',
|
||||
iconButton('more', _('More'), (ev: MouseEvent) => dropdown(ev.currentTarget as HTMLElement, menu), 'neutral', 'dl-icon-only'),
|
||||
]),
|
||||
]),
|
||||
// Under the name block, not inside it, so the avatar centres on name + status; indented to the name.
|
||||
p.note
|
||||
? E('button', { type: 'button', class: 'dl-pnote', title: 'Edit note', click: () => editNote(page) }, [
|
||||
? E('button', { type: 'button', class: 'dl-pnote', title: _('Edit note'), click: () => editNote(page) }, [
|
||||
icon('file'),
|
||||
E('span', {}, p.note),
|
||||
])
|
||||
@@ -68,6 +73,6 @@ export function trafficPart(page: PersonPage): HTMLElement {
|
||||
const todayUse = page.series[page.series.length - 1];
|
||||
return E('div', { class: `dl-person-live${p.online ? '' : ' solo'}` }, [
|
||||
p.online ? speedTile(p.rate ?? [], page.st.now, todayUse ? [todayUse.rx, todayUse.tx] : [0, 0]) : '',
|
||||
daysTile(page.series, `${bytes(p.month[0] + p.month[1])} this month`),
|
||||
daysTile(page.series, fmt(_('%s this month'), bytes(p.month[0] + p.month[1]))),
|
||||
]);
|
||||
}
|
||||
@@ -64,9 +64,9 @@ export class PersonPage {
|
||||
const p = this.st.people.find((x) => x.id === this.id);
|
||||
if (!p)
|
||||
return E('div', { class: 'dl-empty' }, [
|
||||
E('h3', {}, 'Person not found'),
|
||||
E('p', {}, 'They may have been removed.'),
|
||||
E('a', { class: 'cbi-button', href: L.url('admin/network/dawnline/server') }, 'Back to Servers'),
|
||||
E('h3', {}, _('Person not found')),
|
||||
E('p', {}, _('They may have been removed.')),
|
||||
E('a', { class: 'cbi-button', href: L.url('admin/network/dawnline/server') }, _('Back to Servers')),
|
||||
]);
|
||||
this.p = p;
|
||||
for (const k of ['crumbs', 'head', 'devices', 'traffic', 'places', 'activity', 'limits'] as Part[]) this.parts[k] = E('div', {});
|
||||
@@ -173,10 +173,10 @@ export class PersonPage {
|
||||
/** Server / People / name: the server changes when the person is moved. */
|
||||
private crumbs(): HTMLElement {
|
||||
const p = this.p;
|
||||
return E('nav', { class: 'dl-crumbs', 'aria-label': 'Breadcrumb' }, [
|
||||
E('a', { href: peopleUrl(p.server) }, this.st.servers.find((x) => x.id === p.server)?.name ?? 'Servers'),
|
||||
return E('nav', { class: 'dl-crumbs', 'aria-label': _('Breadcrumb') }, [
|
||||
E('a', { href: peopleUrl(p.server) }, this.st.servers.find((x) => x.id === p.server)?.name ?? _('Servers')),
|
||||
E('span', {}, '/'),
|
||||
E('a', { href: peopleUrl(p.server) }, 'People'),
|
||||
E('a', { href: peopleUrl(p.server) }, _('People')),
|
||||
E('span', {}, '/'),
|
||||
E('span', {}, p.name),
|
||||
]);
|
||||
|
||||
@@ -11,18 +11,21 @@ import { liveField } from '../../ui/layout';
|
||||
import { quotaHelp } from '../../netcheck';
|
||||
import { attachTip } from '../../ui/tooltip';
|
||||
import { icon } from '../../../shared/icons';
|
||||
import { ACCESS_LABEL, bytes, date, daysLeft, endsSoon, shiftDay } from '../../../shared/format';
|
||||
import { accessLabel, bytes, date, daysLeft, endsSoon, shiftDay } from '../../../shared/format';
|
||||
import { fmt, num, plural } from '../../../shared/i18n';
|
||||
import { resetUsageDialog } from '../../logs';
|
||||
import { homeAccess } from '../../access';
|
||||
import { endSettings } from './dialogs';
|
||||
import { circleTile, devTile, dnsPicker, netsPicker, servicesPicker } from './pickers';
|
||||
import type { PersonPage } from './index';
|
||||
|
||||
const ACCESS_TEXT: Record<Person['access'], string> = {
|
||||
internet: 'Browse the internet through your router. No access to devices at home, and home cannot reach theirs.',
|
||||
lan: 'Reach devices at home, and home reaches theirs. Internet stays on their own connection.',
|
||||
both: 'Home devices and the internet, all through your router. Home reaches their devices too.',
|
||||
};
|
||||
function accessText(a: Person['access']): string {
|
||||
return {
|
||||
internet: _('Browse the internet through your router. No access to devices at home, and home cannot reach theirs.'),
|
||||
lan: _('Reach devices at home, and home reaches theirs. Internet stays on their own connection.'),
|
||||
both: _('Home devices and the internet, all through your router. Home reaches their devices too.'),
|
||||
}[a];
|
||||
}
|
||||
|
||||
const TIME = /^([01]\d|2[0-3]):[0-5]\d$/;
|
||||
|
||||
@@ -39,19 +42,19 @@ function endTile(page: PersonPage): HTMLElement {
|
||||
}) as HTMLInputElement;
|
||||
dateInput.addEventListener(
|
||||
'change',
|
||||
() => dateInput.value && page.patch({ expires: dateInput.value }, `Access until ${date(dateInput.value)}`),
|
||||
() => dateInput.value && page.patch({ expires: dateInput.value }, fmt(_('Access until %s'), date(dateInput.value))),
|
||||
);
|
||||
// Extend from the current end, or from today when there is none or it has passed.
|
||||
const extend = (step: 'week' | 'month' | 'year', n: number) => {
|
||||
const next = shiftDay(p.expires && (left ?? -1) >= 0 ? p.expires : '', step, n, today);
|
||||
void page.patch({ expires: next }, `Access until ${date(next)}`);
|
||||
void page.patch({ expires: next }, fmt(_('Access until %s'), date(next)));
|
||||
};
|
||||
const ext = (
|
||||
[
|
||||
['week', 1, '+1 week'],
|
||||
['month', 1, '+1 month'],
|
||||
['month', 3, '+3 months'],
|
||||
['year', 1, '+1 year'],
|
||||
['week', 1, _('+1 week')],
|
||||
['month', 1, _('+1 month')],
|
||||
['month', 3, _('+3 months')],
|
||||
['year', 1, _('+1 year')],
|
||||
] as const
|
||||
).map(([step, n, label]) => E('button', { type: 'button', class: 'dl-chipbtn', click: () => extend(step, n) }, label));
|
||||
// The native date input stays hidden behind the chip and only opens its picker. It takes the
|
||||
@@ -71,34 +74,40 @@ function endTile(page: PersonPage): HTMLElement {
|
||||
}
|
||||
},
|
||||
},
|
||||
[icon('calendar'), p.expires ? date(p.expires) : 'Date'],
|
||||
[icon('calendar'), p.expires ? date(p.expires) : _('Date')],
|
||||
),
|
||||
dateInput,
|
||||
]);
|
||||
const action = { pause: 'pause access', notify: 'keep access', remove: 'remove their devices' }[p.expire_action];
|
||||
const action = { pause: _('pause access'), notify: _('keep access'), remove: _('remove their devices') }[p.expire_action];
|
||||
return E('div', { class: 'dl-tile2' }, [
|
||||
E('div', { class: 'dl-tile2-label' }, [
|
||||
E('span', {}, 'Access ends'),
|
||||
E('span', {}, _('Access ends')),
|
||||
p.expires
|
||||
? E(
|
||||
'span',
|
||||
{ class: left != null && left < 0 ? 'dl-bad' : endsSoon(p, left) ? 'dl-warn' : 'dl-ok' },
|
||||
left != null && left < 0 ? 'ended' : `${left} day${left === 1 ? '' : 's'} left`,
|
||||
left != null && left < 0 ? _('ended') : plural(left ?? 0, '%s day left', '%s days left'),
|
||||
)
|
||||
: E('span', { class: 'dl-faint' }, 'no end date'),
|
||||
: E('span', { class: 'dl-faint' }, _('no end date')),
|
||||
]),
|
||||
E('div', { class: 'dl-chips-row' }, [
|
||||
...ext,
|
||||
pick,
|
||||
p.expires
|
||||
? E('button', { type: 'button', class: 'dl-chipbtn', click: () => page.patch({ expires: '' }, 'No end date') }, 'No end')
|
||||
? E('button', { type: 'button', class: 'dl-chipbtn', click: () => page.patch({ expires: '' }, _('No end date')) }, _('No end'))
|
||||
: '',
|
||||
]),
|
||||
E('div', { class: 'dl-tile2-foot' }, [
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-muted' },
|
||||
`When it ends: ${action}${p.expire_warn ? `, warn ${p.expire_warn} day${p.expire_warn === 1 ? '' : 's'} before` : ''}`,
|
||||
p.expire_warn
|
||||
? fmt(
|
||||
N_(p.expire_warn, 'When it ends: %s, warn %s day before', 'When it ends: %s, warn %s days before'),
|
||||
action,
|
||||
num(p.expire_warn),
|
||||
)
|
||||
: fmt(_('When it ends: %s'), action),
|
||||
),
|
||||
E(
|
||||
'a',
|
||||
@@ -109,7 +118,7 @@ function endTile(page: PersonPage): HTMLElement {
|
||||
endSettings(page);
|
||||
},
|
||||
},
|
||||
'Change',
|
||||
_('Change'),
|
||||
),
|
||||
]),
|
||||
]);
|
||||
@@ -121,26 +130,26 @@ function dataTile(page: PersonPage): HTMLElement {
|
||||
const pct = p.quota_limit ? Math.min(100, (p.quota_used / p.quota_limit) * 100) : 0;
|
||||
const bar = E('div', { class: `dl-meter${pct >= 100 ? ' bad' : pct >= 90 ? ' warn' : ''}` }, [
|
||||
E('i'),
|
||||
p.quota_limit ? E('span', { class: 'mark', title: 'Alert at 90%' }) : '',
|
||||
p.quota_limit ? E('span', { class: 'mark', title: _('Alert at 90%') }) : '',
|
||||
]);
|
||||
(bar.firstChild as HTMLElement).style.width = `${pct}%`;
|
||||
if (p.quota_limit)
|
||||
attachTip(bar, () => [
|
||||
E('div', { class: 'dl-tip-title' }, `${pct.toFixed(1)}% used`),
|
||||
E('div', { class: 'dl-tip-title' }, fmt(_('%s%% used'), num(pct, 1))),
|
||||
E(
|
||||
'div',
|
||||
{ class: 'dl-muted' },
|
||||
`${bytes(p.quota_used)} of ${bytes(p.quota_limit)} · ${bytes(Math.max(0, p.quota_limit - p.quota_used))} left`,
|
||||
`${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)))}`,
|
||||
),
|
||||
E('div', { class: 'dl-faint' }, 'Alert at 90%'),
|
||||
E('div', { class: 'dl-faint' }, _('Alert at 90%')),
|
||||
]);
|
||||
const period = seg(
|
||||
[
|
||||
['month', 'Monthly'],
|
||||
['total', 'Total'],
|
||||
['month', _('Monthly')],
|
||||
['total', _('Total')],
|
||||
],
|
||||
p.quota_period,
|
||||
{ label: 'Data limit period', cls: 'sm', optimistic: false, onChange: (v) => page.patch({ quota_period: v }) },
|
||||
{ label: _('Data limit period'), cls: 'sm', optimistic: false, onChange: (v) => page.patch({ quota_period: v }) },
|
||||
);
|
||||
const presets = [10, 50, 100].map((gb) =>
|
||||
E(
|
||||
@@ -148,16 +157,16 @@ function dataTile(page: PersonPage): HTMLElement {
|
||||
{
|
||||
type: 'button',
|
||||
class: `dl-chipbtn${p.quota_gb === gb ? ' on' : ''}`,
|
||||
click: () => page.patch({ quota_gb: String(gb) }, `Data limit ${gb} GB`),
|
||||
click: () => page.patch({ quota_gb: String(gb) }, fmt(_('Data limit %s GB'), num(gb))),
|
||||
},
|
||||
`${gb} GB`,
|
||||
`${num(gb)} ${_('GB')}`,
|
||||
),
|
||||
);
|
||||
presets.push(
|
||||
E(
|
||||
'button',
|
||||
{ type: 'button', class: `dl-chipbtn${!p.quota_gb ? ' on' : ''}`, click: () => page.patch({ quota_gb: '' }, 'No data limit') },
|
||||
'Unlimited',
|
||||
{ type: 'button', class: `dl-chipbtn${!p.quota_gb ? ' on' : ''}`, click: () => page.patch({ quota_gb: '' }, _('No data limit')) },
|
||||
_('Unlimited'),
|
||||
),
|
||||
);
|
||||
presets.push(
|
||||
@@ -174,15 +183,15 @@ function dataTile(page: PersonPage): HTMLElement {
|
||||
step: 'any',
|
||||
value: p.quota_gb ? String(p.quota_gb) : '',
|
||||
}) as HTMLInputElement;
|
||||
const row = liveField('Data limit (GB)', inp, () => quotaHelp(inp.value, p.quota_period === 'month'));
|
||||
const row = liveField(_('Data limit (GB)'), inp, () => quotaHelp(inp.value, p.quota_period === 'month'));
|
||||
modal(
|
||||
'Data limit',
|
||||
_('Data limit'),
|
||||
[row],
|
||||
[
|
||||
cancelButton(),
|
||||
' ',
|
||||
button(
|
||||
'Save',
|
||||
_('Save'),
|
||||
async () => {
|
||||
const h = row.help();
|
||||
if (h.bad) {
|
||||
@@ -190,7 +199,10 @@ function dataTile(page: PersonPage): HTMLElement {
|
||||
return;
|
||||
}
|
||||
const v = inp.value.trim();
|
||||
if (await page.patch({ quota_gb: v }, v && Number(v) > 0 ? `Data limit ${v} GB` : 'No data limit')) closeModal();
|
||||
if (
|
||||
await page.patch({ quota_gb: v }, v && Number(v) > 0 ? fmt(_('Data limit %s GB'), num(Number(v))) : _('No data limit'))
|
||||
)
|
||||
closeModal();
|
||||
},
|
||||
'positive',
|
||||
),
|
||||
@@ -199,38 +211,44 @@ function dataTile(page: PersonPage): HTMLElement {
|
||||
setTimeout(() => inp.select(), 50);
|
||||
},
|
||||
},
|
||||
'Custom',
|
||||
_('Custom'),
|
||||
),
|
||||
);
|
||||
return E('div', { class: 'dl-tile2' }, [
|
||||
E('div', { class: 'dl-tile2-label' }, [E('span', {}, 'Data'), period]),
|
||||
E('div', { class: 'dl-tile2-label' }, [E('span', {}, _('Data')), period]),
|
||||
E('div', { class: 'dl-tile2-row' }, [
|
||||
E('span', { class: 'dl-tile2-value' }, [
|
||||
bytes(used),
|
||||
p.quota_limit ? E('span', { class: 'dl-faint' }, ` of ${bytes(p.quota_limit)}`) : E('span', { class: 'dl-faint' }, ' · no limit'),
|
||||
p.quota_limit
|
||||
? E('span', { class: 'dl-faint' }, ` ${fmt(_('of %s'), bytes(p.quota_limit))}`)
|
||||
: E('span', { class: 'dl-faint' }, ` · ${_('no limit')}`),
|
||||
]),
|
||||
p.quota_period === 'month' ? E('span', { class: 'dl-sub' }, 'resets on the 1st') : '',
|
||||
p.quota_period === 'month' ? E('span', { class: 'dl-sub' }, _('resets on the 1st')) : '',
|
||||
]),
|
||||
p.quota_limit ? bar : '',
|
||||
E('div', { class: 'dl-chips-row' }, presets),
|
||||
p.quota_gb && p.quota_period === 'month'
|
||||
? E('div', { class: 'dl-tile2-foot' }, [
|
||||
E('span', { class: 'dl-muted' }, p.bonus_gb ? `Includes +${p.bonus_gb} GB extra this month` : 'Need a little more this month?'),
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-muted' },
|
||||
p.bonus_gb ? fmt(_('Includes +%s GB extra this month'), num(p.bonus_gb)) : _('Need a little more this month?'),
|
||||
),
|
||||
E(
|
||||
'a',
|
||||
{
|
||||
href: '#',
|
||||
click: (ev: Event) => {
|
||||
ev.preventDefault();
|
||||
void page.patch({ bonus_gb: String((p.bonus_gb || 0) + 10) }, '+10 GB this month');
|
||||
void page.patch({ bonus_gb: String((p.bonus_gb || 0) + 10) }, _('+10 GB this month'));
|
||||
},
|
||||
},
|
||||
'+10 GB this month',
|
||||
_('+10 GB this month'),
|
||||
),
|
||||
])
|
||||
: '',
|
||||
E('div', { class: 'dl-tile2-foot' }, [
|
||||
E('span', { class: 'dl-muted' }, `${bytes(p.total[0] + p.total[1])} in total`),
|
||||
E('span', { class: 'dl-muted' }, fmt(_('%s in total'), bytes(p.total[0] + p.total[1]))),
|
||||
E(
|
||||
'button',
|
||||
{
|
||||
@@ -238,7 +256,7 @@ function dataTile(page: PersonPage): HTMLElement {
|
||||
class: 'dl-linkbtn danger',
|
||||
click: () => resetUsageDialog('person', p.id, p.name, () => setTimeout(() => page.refresh(), 300)),
|
||||
},
|
||||
'Reset usage',
|
||||
_('Reset usage'),
|
||||
),
|
||||
]),
|
||||
]);
|
||||
@@ -253,15 +271,15 @@ function hoursTile(page: PersonPage): HTMLElement {
|
||||
const p = page.p;
|
||||
const hoursOn = !!p.hours;
|
||||
const [h1, h2] = (p.hours || '07:00-23:00').split('-');
|
||||
const from = E('input', { type: 'time', class: 'cbi-input-text', value: h1, 'aria-label': 'From' }) as HTMLInputElement;
|
||||
const to = E('input', { type: 'time', class: 'cbi-input-text', value: h2, 'aria-label': 'To' }) as HTMLInputElement;
|
||||
const times = E('div', { class: 'dl-tile2-row' }, [from, E('span', { class: 'dl-faint' }, 'to'), to]);
|
||||
const from = E('input', { type: 'time', class: 'cbi-input-text', value: h1, 'aria-label': _('From') }) as HTMLInputElement;
|
||||
const to = E('input', { type: 'time', class: 'cbi-input-text', value: h2, 'aria-label': _('To') }) as HTMLInputElement;
|
||||
const times = E('div', { class: 'dl-tile2-row' }, [from, E('span', { class: 'dl-faint' }, _('to', 'time range')), to]);
|
||||
const commit = () => {
|
||||
const v = `${from.value}-${to.value}`;
|
||||
if (v === p.hours) return;
|
||||
if (!TIME.test(from.value) || !TIME.test(to.value)) return notify('Enter both times, like 07:00 and 23:00.', 'warning');
|
||||
if (from.value === to.value) return notify('The start and the end must differ.', 'warning');
|
||||
void page.patch({ hours: v }, `Allowed ${from.value}–${to.value}`);
|
||||
if (!TIME.test(from.value) || !TIME.test(to.value)) return notify(_('Enter both times, like 07:00 and 23:00.'), 'warning');
|
||||
if (from.value === to.value) return notify(_('The start and the end must differ.'), 'warning');
|
||||
void page.patch({ hours: v }, fmt(_('Allowed %s–%s'), from.value, to.value));
|
||||
};
|
||||
times.addEventListener('focusout', (ev: FocusEvent) => {
|
||||
if (!times.contains(ev.relatedTarget as Node | null)) commit();
|
||||
@@ -280,23 +298,23 @@ function hoursTile(page: PersonPage): HTMLElement {
|
||||
role: 'switch',
|
||||
'aria-checked': hoursOn ? 'true' : 'false',
|
||||
class: `dl-switch${hoursOn ? ' on' : ''}`,
|
||||
'aria-label': 'Limit hours',
|
||||
'aria-label': _('Limit hours'),
|
||||
// Turning on shows the times to set; nothing is enforced until they are saved.
|
||||
click: () => {
|
||||
if (hoursOn) return page.patch({ hours: '' }, 'Any time');
|
||||
if (hoursOn) return page.patch({ hours: '' }, _('Any time'));
|
||||
sw.classList.add('on');
|
||||
sw.setAttribute('aria-checked', 'true');
|
||||
label.textContent = 'Set the hours, then press Enter';
|
||||
label.textContent = _('Set the hours, then press Enter');
|
||||
tile.appendChild(times);
|
||||
from.focus();
|
||||
},
|
||||
},
|
||||
E('i'),
|
||||
);
|
||||
const label = E('span', {}, hoursOn ? `${h1} – ${h2} (router time)` : 'Any time');
|
||||
const label = E('span', {}, hoursOn ? fmt(_('%s – %s (router time)'), h1, h2) : _('Any time'));
|
||||
const tile = E('div', { class: 'dl-tile2' }, [
|
||||
E('div', { class: 'dl-tile2-row' }, [
|
||||
E('div', { class: 'dl-stack' }, [E('span', { class: 'dl-tile2-label' }, 'Allowed hours'), label]),
|
||||
E('div', { class: 'dl-stack' }, [E('span', { class: 'dl-tile2-label' }, _('Allowed hours')), label]),
|
||||
sw,
|
||||
]),
|
||||
hoursOn ? times : '',
|
||||
@@ -309,19 +327,27 @@ export function limitsPart(page: PersonPage): HTMLElement {
|
||||
const access = seg(
|
||||
(['internet', 'lan', 'both'] as const).map((a) => [
|
||||
a,
|
||||
[icon(a === 'internet' ? 'globe' : a === 'lan' ? 'home' : 'shield'), a === 'internet' ? 'Internet' : a === 'lan' ? 'Home' : 'Both'],
|
||||
[
|
||||
icon(a === 'internet' ? 'globe' : a === 'lan' ? 'home' : 'shield'),
|
||||
a === 'internet' ? _('Internet') : a === 'lan' ? _('Home') : _('Both'),
|
||||
],
|
||||
]),
|
||||
p.access,
|
||||
{ label: 'Access', cls: 'wide', optimistic: false, onChange: (a) => page.patch({ access: a }, `Access: ${ACCESS_LABEL[a]}`) },
|
||||
{
|
||||
label: _('Access'),
|
||||
cls: 'wide',
|
||||
optimistic: false,
|
||||
onChange: (a) => page.patch({ access: a }, fmt(_('Access: %s'), accessLabel(a))),
|
||||
},
|
||||
);
|
||||
// Heading above the card, like "Devices", so both columns line up (as on the portal).
|
||||
return E('section', { class: 'dl-devsec', 'aria-label': 'Access and limits' }, [
|
||||
E('div', { class: 'dl-panel-head' }, [E('h3', {}, 'Access & limits')]),
|
||||
return E('section', { class: 'dl-devsec', 'aria-label': _('Access and limits') }, [
|
||||
E('div', { class: 'dl-panel-head' }, [E('h3', {}, _('Access & limits'))]),
|
||||
E('div', { class: 'dl-panel' }, [
|
||||
E('div', { class: 'dl-stack gap8' }, [
|
||||
E('span', { class: 'dl-tile2-label' }, 'Can reach'),
|
||||
E('span', { class: 'dl-tile2-label' }, _('Can reach')),
|
||||
access,
|
||||
E('span', { class: 'dl-sub' }, ACCESS_TEXT[p.access]),
|
||||
E('span', { class: 'dl-sub' }, accessText(p.access)),
|
||||
p.access === 'lan' && page.st.services.length ? servicesPicker(page) : '',
|
||||
homeAccess(p) ? netsPicker(page) : '',
|
||||
p.access === 'lan' ? dnsPicker(page) : '',
|
||||
|
||||
@@ -8,6 +8,7 @@ import { dropdown } from '../../ui/menu';
|
||||
import { attachTip } from '../../ui/tooltip';
|
||||
import { icon } from '../../../shared/icons';
|
||||
import { ago, initials } from '../../../shared/format';
|
||||
import { fill, fmt, plural } from '../../../shared/i18n';
|
||||
import { circleDialog, circleDot, homeAccess } from '../../access';
|
||||
import type { PersonPage } from './index';
|
||||
|
||||
@@ -19,8 +20,8 @@ export function dnsPicker(page: PersonPage): HTMLElement {
|
||||
const p = page.p;
|
||||
const choice = seg(
|
||||
[
|
||||
['device', 'Device’s own DNS'],
|
||||
['home', 'Home names'],
|
||||
['device', _('Device’s own DNS')],
|
||||
['home', _('Home names')],
|
||||
],
|
||||
p.dns_mode,
|
||||
{
|
||||
@@ -30,7 +31,9 @@ export function dnsPicker(page: PersonPage): HTMLElement {
|
||||
onChange: (v) =>
|
||||
page.patch(
|
||||
{ dns_mode: v },
|
||||
v === 'home' ? 'Home names on — devices need their configuration again' : 'Device DNS — devices need their configuration again',
|
||||
v === 'home'
|
||||
? _('Home names on - devices need their configuration again')
|
||||
: _('Device DNS - devices need their configuration again'),
|
||||
),
|
||||
},
|
||||
);
|
||||
@@ -41,15 +44,19 @@ export function dnsPicker(page: PersonPage): HTMLElement {
|
||||
'span',
|
||||
{ class: 'dl-sub' },
|
||||
p.dns_mode === 'home'
|
||||
? [
|
||||
'Names like ',
|
||||
E('span', { class: 'dl-mono' }, `nas.${page.st.settings.domain}`),
|
||||
' work. Internet names are resolved at home, so they depend on the tunnel',
|
||||
fb
|
||||
? [' (', E('span', { class: 'dl-mono' }, fb), ' takes over when it is down).']
|
||||
: ' — with no fallback set, they stop when it is down.',
|
||||
]
|
||||
: 'Internet keeps working exactly as without the VPN. Reach home devices by IP address.',
|
||||
? fb
|
||||
? fill(
|
||||
_('Names like %s work. Internet names are resolved at home, so they depend on the tunnel (%s takes over when it is down).'),
|
||||
E('span', { class: 'dl-mono' }, `nas.${page.st.settings.domain}`),
|
||||
E('span', { class: 'dl-mono' }, fb),
|
||||
)
|
||||
: fill(
|
||||
_(
|
||||
'Names like %s work. Internet names are resolved at home, so they depend on the tunnel - with no fallback set, they stop when it is down.',
|
||||
),
|
||||
E('span', { class: 'dl-mono' }, `nas.${page.st.settings.domain}`),
|
||||
)
|
||||
: _('Internet keeps working exactly as without the VPN. Reach home devices by IP address.'),
|
||||
),
|
||||
]);
|
||||
}
|
||||
@@ -72,11 +79,11 @@ export function netsPicker(page: PersonPage): HTMLElement | '' {
|
||||
() => {
|
||||
const next = new Set(picked);
|
||||
if (!next.delete(h.dev)) next.add(h.dev);
|
||||
if (!next.size) return notify('Keep at least one network, or choose Internet only.', 'warning', 5000);
|
||||
if (!next.size) return notify(_('Keep at least one network, or choose Internet only.'), 'warning', 5000);
|
||||
const list = next.size === all.length ? [] : [...next];
|
||||
void page.patch(
|
||||
{ home_nets: list },
|
||||
list.length ? `${p.name} reaches ${list.join(', ')}` : `${p.name} reaches every home network`,
|
||||
list.length ? fmt(_('%s reaches %s'), p.name, list.join(', ')) : fmt(_('%s reaches every home network'), p.name),
|
||||
);
|
||||
},
|
||||
{ title: h.nets.join(', ') },
|
||||
@@ -87,8 +94,8 @@ export function netsPicker(page: PersonPage): HTMLElement | '' {
|
||||
'span',
|
||||
{ class: 'dl-sub' },
|
||||
p.home_nets?.length
|
||||
? `Home networks ${p.name} reaches. Networks added to the server later stay out.`
|
||||
: `Home networks ${p.name} reaches: all of them. Untick one to keep ${p.name} out of it.`,
|
||||
? fmt(_('Home networks %s reaches. Networks added to the server later stay out.'), p.name)
|
||||
: fmt(_('Home networks %s reaches: all of them. Untick one to keep %s out of it.'), p.name, p.name),
|
||||
),
|
||||
]);
|
||||
}
|
||||
@@ -108,7 +115,7 @@ export function servicesPicker(page: PersonPage): HTMLElement {
|
||||
// A copy: the chips show the saved choice until the router has it (a failed save changes nothing).
|
||||
const next = new Set(chosen);
|
||||
if (!next.delete(sv.id)) next.add(sv.id);
|
||||
void page.patch({ services: [...next] }, next.size ? 'Home services updated' : 'Whole home network');
|
||||
void page.patch({ services: [...next] }, next.size ? _('Home services updated') : _('Whole home network'));
|
||||
},
|
||||
{ title: `${sv.address}${sv.ports.length ? ` · ${sv.ports.join(', ')}` : ''}` },
|
||||
),
|
||||
@@ -117,7 +124,7 @@ export function servicesPicker(page: PersonPage): HTMLElement {
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-sub' },
|
||||
chosen.size ? 'Only the selected services at home.' : 'Whole home network. Pick services to narrow it down.',
|
||||
chosen.size ? _('Only the selected services at home.') : _('Whole home network. Pick services to narrow it down.'),
|
||||
),
|
||||
]);
|
||||
}
|
||||
@@ -141,20 +148,22 @@ export function circleTile(page: PersonPage): HTMLElement | '' {
|
||||
...circles.map((c) => ({
|
||||
label: c.name,
|
||||
icon: circleDot(c),
|
||||
run: () => c.id !== p.circle && page.patch({ circle: c.id }, `${p.name} is in ${c.name}`),
|
||||
run: () => c.id !== p.circle && page.patch({ circle: c.id }, fmt(_('%s is in %s'), p.name, c.name)),
|
||||
})),
|
||||
p.circle ? { label: 'No circle', icon: icon('x'), run: () => page.patch({ circle: '' }, `${p.name} is in no circle`) } : null,
|
||||
{ label: 'New circle', icon: icon('plus'), run: () => circleDialog(st, p.server, null, () => page.refresh()) },
|
||||
p.circle
|
||||
? { label: _('No circle'), icon: icon('x'), run: () => page.patch({ circle: '' }, fmt(_('%s is in no circle'), p.name)) }
|
||||
: null,
|
||||
{ label: _('New circle'), icon: icon('plus'), run: () => circleDialog(st, p.server, null, () => page.refresh()) },
|
||||
]),
|
||||
},
|
||||
'Change',
|
||||
_('Change'),
|
||||
);
|
||||
// As the other tiles: the name is the value; who is in it as avatars.
|
||||
const people = ci ? st.people.filter((x) => x.circle === ci.id && homeAccess(x)) : [p];
|
||||
return E('div', { class: 'dl-tile2' }, [
|
||||
E('div', { class: 'dl-tile2-label' }, [E('span', {}, 'Devices see each other'), change]),
|
||||
E('div', { class: 'dl-tile2-label' }, [E('span', {}, _('Devices see each other')), change]),
|
||||
E('div', { class: 'dl-tile2-row' }, [
|
||||
E('span', { class: 'dl-tile2-value' }, ci ? ci.name : 'No circle'),
|
||||
E('span', { class: 'dl-tile2-value' }, ci ? ci.name : _('No circle')),
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-avstack', title: people.map((x) => x.name).join(', ') },
|
||||
@@ -164,7 +173,11 @@ export function circleTile(page: PersonPage): HTMLElement | '' {
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-sub' },
|
||||
!ci ? `Only ${p.name}'s own devices` : mates.length ? [p.name, ...mates].join(', ') : `Nobody else in ${ci.name} yet`,
|
||||
!ci
|
||||
? fmt(_("Only %s's own devices"), p.name)
|
||||
: mates.length
|
||||
? [p.name, ...mates].join(', ')
|
||||
: fmt(_('Nobody else in %s yet'), ci.name),
|
||||
),
|
||||
]);
|
||||
}
|
||||
@@ -180,11 +193,17 @@ export function devTile(page: PersonPage): HTMLElement {
|
||||
const over = i >= p.device_limit;
|
||||
const slot = E('i', { class: over ? 'over' : d ? 'used' : '' });
|
||||
attachTip(slot, () => [
|
||||
E('div', { class: 'dl-tip-title' }, d ? `${d.name}${over ? ' · over the limit' : ''}` : 'Free slot'),
|
||||
E('div', { class: 'dl-tip-title' }, d ? `${d.name}${over ? ` · ${_('over the limit')}` : ''}` : _('Free slot')),
|
||||
E(
|
||||
'div',
|
||||
{ class: 'dl-muted' },
|
||||
d ? (d.online ? 'Connected' : d.handshake ? `Last seen ${ago(d.handshake, now)}` : 'Not set up yet') : 'They can add a device here',
|
||||
d
|
||||
? d.online
|
||||
? _('Connected')
|
||||
: d.handshake
|
||||
? fmt(_('Last seen %s'), ago(d.handshake, now))
|
||||
: _('Not set up yet')
|
||||
: _('They can add a device here'),
|
||||
),
|
||||
]);
|
||||
slots.appendChild(slot);
|
||||
@@ -194,7 +213,7 @@ export function devTile(page: PersonPage): HTMLElement {
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
'aria-label': 'Allow fewer devices',
|
||||
'aria-label': _('Allow fewer devices'),
|
||||
disabled: p.device_limit <= floor ? 'disabled' : null,
|
||||
click: () => page.patch({ device_limit: String(p.device_limit - 1) }),
|
||||
},
|
||||
@@ -202,11 +221,11 @@ export function devTile(page: PersonPage): HTMLElement {
|
||||
);
|
||||
if (p.device_limit <= floor && p.devices.length > 1)
|
||||
attachTip(minus, () => [
|
||||
E('div', { class: 'dl-tip-title' }, `${p.devices.length} devices in use`),
|
||||
E('div', { class: 'dl-muted' }, 'Remove a device first to lower the limit'),
|
||||
E('div', { class: 'dl-tip-title' }, plural(p.devices.length, '%s device in use', '%s devices in use')),
|
||||
E('div', { class: 'dl-muted' }, _('Remove a device first to lower the limit')),
|
||||
]);
|
||||
return E('div', { class: 'dl-tile2' }, [
|
||||
E('div', { class: 'dl-tile2-label' }, 'Devices'),
|
||||
E('div', { class: 'dl-tile2-label' }, _('Devices')),
|
||||
E('div', { class: 'dl-tile2-row' }, [
|
||||
E('span', { class: 'dl-tile2-value' }, [String(p.devices.length), E('span', { class: 'dl-faint' }, ` / ${p.device_limit}`)]),
|
||||
E('div', { class: 'dl-stepper' }, [
|
||||
@@ -215,7 +234,7 @@ export function devTile(page: PersonPage): HTMLElement {
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
'aria-label': 'Allow more devices',
|
||||
'aria-label': _('Allow more devices'),
|
||||
disabled: p.device_limit >= 32 ? 'disabled' : null,
|
||||
click: () => page.patch({ device_limit: String(p.device_limit + 1) }),
|
||||
},
|
||||
|
||||
+156
-116
@@ -16,6 +16,7 @@ import { card, firstBad, group, liveRow, needRow, row } from '../ui/layout';
|
||||
import { dnsHelp, endpointProbe, hostHelp, nameHelp, portalPortHelp, portHelp, rangeHelp, rangeOf, subnetOf } from '../netcheck';
|
||||
import { icon } from '../../shared/icons';
|
||||
import { ago, duration } from '../../shared/format';
|
||||
import { fmt, locale, plural } from '../../shared/i18n';
|
||||
import { accessCards } from '../interfaces';
|
||||
import { checkAccess, whoReaches } from '../access';
|
||||
import { defaultMethod, methodPicker } from '../disguise';
|
||||
@@ -27,13 +28,10 @@ import { PeoplePage } from './people';
|
||||
|
||||
/** `awg` is the server's core section (named after its core; the key stays for old links). */
|
||||
type Section = 'overview' | 'people' | 'connection' | 'access' | 'awg';
|
||||
const SECTIONS: [Section, string][] = [
|
||||
['overview', 'Overview'],
|
||||
['people', 'People'],
|
||||
['connection', 'Connection'],
|
||||
['access', 'Access'],
|
||||
['awg', ''],
|
||||
];
|
||||
const SECTIONS: Section[] = ['overview', 'people', 'connection', 'access', 'awg'];
|
||||
/** A section's tab; the core's own is named after the core. */
|
||||
const sectionLabel = (k: Exclude<Section, 'awg'>): string =>
|
||||
({ overview: _('Overview'), people: _('People'), connection: _('Connection'), access: _('Access') })[k];
|
||||
/** Section names from before the regrouping, for old links. */
|
||||
const OLD_SECTIONS: Record<string, Section> = {
|
||||
general: 'connection',
|
||||
@@ -82,7 +80,7 @@ export class ServerPage {
|
||||
const q = new URLSearchParams(location.search);
|
||||
const raw = q.get('section') ?? '';
|
||||
const want = (OLD_SECTIONS[raw] ?? raw) as Section;
|
||||
if (SECTIONS.some(([k]) => k === want)) this.section = want;
|
||||
if (SECTIONS.includes(want)) this.section = want;
|
||||
this.srvId = (st.servers.find((x) => x.id === q.get('server')) ?? st.servers[0]).id;
|
||||
dom.content(this.root, [this.tabsEl, this.headEl, this.secEl, this.bodyEl]);
|
||||
this.paint();
|
||||
@@ -146,7 +144,7 @@ export class ServerPage {
|
||||
const srv = this.current();
|
||||
dom.content(
|
||||
this.tabsEl,
|
||||
E('div', { class: 'dl-srvtabs', role: 'tablist', 'aria-label': 'Servers' }, [
|
||||
E('div', { class: 'dl-srvtabs', role: 'tablist', 'aria-label': _('Servers') }, [
|
||||
...this.st.servers.map((x) =>
|
||||
E(
|
||||
'button',
|
||||
@@ -164,7 +162,7 @@ export class ServerPage {
|
||||
[E('i', { class: `dot ${!x.enabled ? 'warn' : x.up ? 'ok' : 'bad'}` }), E('b', {}, x.name)],
|
||||
),
|
||||
),
|
||||
E('button', { type: 'button', class: 'dl-srvtab add', click: () => this.addServer() }, [icon('plus'), 'Add server']),
|
||||
E('button', { type: 'button', class: 'dl-srvtab add', click: () => this.addServer() }, [icon('plus'), _('Add server')]),
|
||||
]),
|
||||
);
|
||||
}
|
||||
@@ -175,8 +173,8 @@ export class ServerPage {
|
||||
this.secEl,
|
||||
E(
|
||||
'div',
|
||||
{ class: 'dl-seg dl-srvsections', role: 'tablist', 'aria-label': 'Server' },
|
||||
SECTIONS.map(([k, t]) =>
|
||||
{ class: 'dl-seg dl-srvsections', role: 'tablist', 'aria-label': _('Server') },
|
||||
SECTIONS.map((k) =>
|
||||
E(
|
||||
'button',
|
||||
{
|
||||
@@ -187,7 +185,7 @@ export class ServerPage {
|
||||
'aria-selected': k === this.section ? 'true' : 'false',
|
||||
click: () => this.showSection(k),
|
||||
},
|
||||
k === 'awg' ? core.label : t,
|
||||
k === 'awg' ? core.label : sectionLabel(k),
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -241,7 +239,7 @@ export class ServerPage {
|
||||
void pp.update();
|
||||
return pp.el;
|
||||
}
|
||||
const holder = E('div', {}, E('p', { class: 'dl-muted' }, 'Loading people…'));
|
||||
const holder = E('div', {}, E('p', { class: 'dl-muted' }, _('Loading people…')));
|
||||
const page = (this.pp[srv.id] ??= new PeoplePage());
|
||||
page
|
||||
.embed(st, srv.id)
|
||||
@@ -252,7 +250,7 @@ export class ServerPage {
|
||||
.catch((e) => {
|
||||
// Try again on the next visit instead of keeping a broken page.
|
||||
delete this.pp[srv.id];
|
||||
dom.content(holder, E('p', { class: 'dl-muted' }, `Couldn't show people: ${errorText(e)}`));
|
||||
dom.content(holder, E('p', { class: 'dl-muted' }, fmt(_("Couldn't show people: %s"), errorText(e))));
|
||||
});
|
||||
return holder;
|
||||
},
|
||||
@@ -273,8 +271,8 @@ export class ServerPage {
|
||||
const actions = E('div', { class: 'dl-actions' }, [
|
||||
!srv.enabled
|
||||
? button(
|
||||
[icon('play'), ' Turn on'],
|
||||
() => this.save(srv, { enabled: '1' }, 'Server turned on'),
|
||||
[icon('play'), ` ${_('Turn on')}`],
|
||||
() => this.save(srv, { enabled: '1' }, _('Server turned on')),
|
||||
// White, as the other main actions (Add person).
|
||||
'add',
|
||||
)
|
||||
@@ -288,7 +286,7 @@ export class ServerPage {
|
||||
'span',
|
||||
// Off on purpose is a warning (yellow), not a failure (red).
|
||||
{ class: `dl-pill ${!srv.enabled ? 'warn' : srv.up ? 'ok' : 'bad'}` },
|
||||
!srv.enabled ? 'Turned off' : srv.up ? 'Running' : srv.blocked ? 'Can’t start' : 'Not running',
|
||||
!srv.enabled ? _('Turned off') : srv.up ? _('Running') : srv.blocked ? _('Can’t start') : _('Not running'),
|
||||
),
|
||||
E('span', { class: 'dl-spacer' }),
|
||||
actions,
|
||||
@@ -296,78 +294,82 @@ export class ServerPage {
|
||||
E('div', { class: 'dl-addrbar' }, [
|
||||
E(
|
||||
'button',
|
||||
{ type: 'button', class: 'dl-addrbar-seg main', title: 'Copy address', click: () => copyText(addr, 'Address copied') },
|
||||
{ type: 'button', class: 'dl-addrbar-seg main', title: _('Copy address'), click: () => copyText(addr, _('Address copied')) },
|
||||
[icon('globe'), E('span', { class: 'dl-mono' }, addr), icon('copy')],
|
||||
),
|
||||
part(coreOf(srv).id === 'awg' ? 'amneziawg' : 'tunnel', [E('span', { class: 'dl-mono' }, `${coreOf(srv).label} :${srv.port}`)]),
|
||||
srv.up ? part('clock', [`up ${duration(srv.uptime)}`]) : '',
|
||||
srv.up ? part('clock', [fmt(_('up %s'), duration(srv.uptime))]) : '',
|
||||
]),
|
||||
// The reason the tunnel can't run at all ("can't use the network interface awg0: it exists and isn't Dawnline's").
|
||||
srv.blocked ? E('div', { class: 'dl-note warn' }, [icon('alert'), E('span', {}, `${srv.name} ${srv.blocked}.`)]) : '',
|
||||
srv.blocked ? E('div', { class: 'dl-note warn' }, [icon('alert'), E('span', {}, srv.blocked)]) : '',
|
||||
]);
|
||||
}
|
||||
|
||||
async save(srv: Server, values: Record<string, unknown>, ok = 'Saved') {
|
||||
async save(srv: Server, values: Record<string, unknown>, ok = _('Saved')) {
|
||||
if (await attempt(() => api.serverUpdate(srv.id, values), ok)) await this.refresh();
|
||||
}
|
||||
|
||||
/** The name, where devices find the router, DNS; then the danger zone. */
|
||||
connection(srv: Server): HTMLElement {
|
||||
const name = input(srv.name, { placeholder: 'Home' });
|
||||
const name = input(srv.name, { placeholder: _('Home') });
|
||||
const endpoint = input(srv.endpoint, { placeholder: 'vpn.example.com', class: 'cbi-input-text dl-mono' });
|
||||
const dns = input(srv.dns.join(', '), { placeholder: 'This router (recommended)', class: 'cbi-input-text dl-mono' });
|
||||
const dns = input(srv.dns.join(', '), { placeholder: _('This router (recommended)'), class: 'cbi-input-text dl-mono' });
|
||||
const people = this.st.people.filter((p) => p.server === srv.id).length;
|
||||
const toggle = button(
|
||||
[icon(srv.enabled ? 'pause' : 'play'), srv.enabled ? ' Turn off' : ' Turn on'],
|
||||
[icon(srv.enabled ? 'pause' : 'play'), ` ${srv.enabled ? _('Turn off') : _('Turn on')}`],
|
||||
async () => {
|
||||
if (
|
||||
srv.enabled &&
|
||||
!(await confirmDialog(
|
||||
`Turn off ${srv.name}?`,
|
||||
`The tunnel stops and ${people} ${people === 1 ? 'person is' : 'people are'} disconnected until you turn it back on. Nothing is deleted.`,
|
||||
'Turn off',
|
||||
fmt(_('Turn off %s?'), srv.name),
|
||||
plural(
|
||||
people,
|
||||
'The tunnel stops and %s person is disconnected until you turn it back on. Nothing is deleted.',
|
||||
'The tunnel stops and %s people are disconnected until you turn it back on. Nothing is deleted.',
|
||||
),
|
||||
_('Turn off'),
|
||||
true,
|
||||
))
|
||||
)
|
||||
return;
|
||||
await this.save(srv, { enabled: srv.enabled ? '0' : '1' }, srv.enabled ? 'Server turned off' : 'Server turned on');
|
||||
await this.save(srv, { enabled: srv.enabled ? '0' : '1' }, srv.enabled ? _('Server turned off') : _('Server turned on'));
|
||||
},
|
||||
srv.enabled ? 'negative' : 'positive',
|
||||
);
|
||||
const portalHost = this.st.settings.portal_host;
|
||||
const nameRow = liveRow('Name', name, () => nameHelp(name.value, [], 'Shown to people in their portal and apps.'));
|
||||
const nameRow = liveRow(_('Name'), name, () => nameHelp(name.value, [], _('Shown to people in their portal and apps.')));
|
||||
// Where the address points is checked on the router as it is typed (debounced).
|
||||
const ep = endpointProbe(
|
||||
() => ({ host: endpoint.value, port: srv.port, id: srv.id }),
|
||||
(h, id, port) => api.endpointProbe(h, id, port),
|
||||
() => epRow.refresh(),
|
||||
{ empty: portalHost ? `Empty = the portal’s address (${portalHost}).` : 'Empty = the portal’s address.' },
|
||||
{ empty: portalHost ? fmt(_('Empty = the portal’s address (%s).'), portalHost) : _('Empty = the portal’s address.') },
|
||||
);
|
||||
const epRow = liveRow('Public address', endpoint, ep.help);
|
||||
const epRow = liveRow(_('Public address'), endpoint, ep.help);
|
||||
endpoint.addEventListener('input', ep.schedule);
|
||||
ep.schedule();
|
||||
const reached = srv.reached
|
||||
? `Reached from the internet ${ago(srv.reached, this.st.now)}.`
|
||||
: 'Never reached from the internet yet — test with a phone on mobile data.';
|
||||
const dnsRow = liveRow('DNS for devices', dns, () => dnsHelp(dns.value, srv.address));
|
||||
? fmt(_('Reached from the internet %s.'), ago(srv.reached, this.st.now))
|
||||
: _('Never reached from the internet yet - test with a phone on mobile data.');
|
||||
const dnsRow = liveRow(_('DNS for devices'), dns, () => dnsHelp(dns.value, srv.address));
|
||||
return E('div', { class: 'dl-stack gap16' }, [
|
||||
card(
|
||||
'Connection',
|
||||
_('Connection'),
|
||||
[
|
||||
E('p', { class: 'dl-muted' }, 'The name people see, where devices find the router, and DNS. The port is on AmneziaWG.'),
|
||||
group('router', 'Server', 'What people see', [nameRow]),
|
||||
E('p', { class: 'dl-muted' }, _('The name people see, where devices find the router, and DNS. The port is on AmneziaWG.')),
|
||||
group('router', _('Server'), _('What people see'), [nameRow]),
|
||||
group(
|
||||
'globe',
|
||||
'Devices connect to',
|
||||
'A DDNS name keeps links working when your IP changes; not through Cloudflare (use a DNS-only name or an IP)',
|
||||
_('Devices connect to'),
|
||||
_('A DDNS name keeps links working when your IP changes; not through Cloudflare (use a DNS-only name or an IP)'),
|
||||
[epRow, E('div', { class: `dl-sub ${srv.reached ? 'ok' : 'warn'}` }, reached)],
|
||||
),
|
||||
group('file', 'For every device', 'Changing it marks devices “Update config” until they import again', [dnsRow]),
|
||||
group('file', _('For every device'), _('Changing it marks devices “Update config” until they import again'), [dnsRow]),
|
||||
],
|
||||
[
|
||||
E('span'),
|
||||
button(
|
||||
'Save',
|
||||
_('Save'),
|
||||
() => {
|
||||
const bad = firstBad([nameRow, epRow, dnsRow]);
|
||||
if (bad) {
|
||||
@@ -381,49 +383,58 @@ export class ServerPage {
|
||||
],
|
||||
),
|
||||
card(
|
||||
'Danger zone',
|
||||
_('Danger zone'),
|
||||
[
|
||||
E('div', { class: 'dl-setrow' }, [
|
||||
E('div', { class: 'dl-stack' }, [
|
||||
E('span', { class: 'dl-setrow-label' }, srv.enabled ? 'Turn off this server' : 'This server is off'),
|
||||
E('span', { class: 'dl-setrow-label' }, srv.enabled ? _('Turn off this server') : _('This server is off')),
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-sub' },
|
||||
srv.enabled
|
||||
? 'Stops the tunnel and disconnects everyone on it. Settings and people are kept.'
|
||||
: 'Nobody can connect. Turn it on to bring the tunnel back.',
|
||||
? _('Stops the tunnel and disconnects everyone on it. Settings and people are kept.')
|
||||
: _('Nobody can connect. Turn it on to bring the tunnel back.'),
|
||||
),
|
||||
]),
|
||||
E('div', { class: 'dl-setrow-ctl' }, toggle),
|
||||
]),
|
||||
E('div', { class: 'dl-setrow' }, [
|
||||
E('div', { class: 'dl-stack' }, [
|
||||
E('span', { class: 'dl-setrow-label' }, 'Change the tunnel network'),
|
||||
E('span', { class: 'dl-setrow-label' }, _('Change the tunnel network')),
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-sub' },
|
||||
`Devices have ${rangeOf(srv.subnet)}.x addresses now. A new range when it clashes with a network you connect to; every device then needs its configuration again.`,
|
||||
fmt(
|
||||
_(
|
||||
'Devices have %s addresses now. A new range when it clashes with a network you connect to; every device then needs its configuration again.',
|
||||
),
|
||||
`${rangeOf(srv.subnet)}.x`,
|
||||
),
|
||||
),
|
||||
]),
|
||||
E(
|
||||
'div',
|
||||
{ class: 'dl-setrow-ctl' },
|
||||
button([icon('edit'), ' Change'], () => this.changeSubnet(srv), 'negative'),
|
||||
button([icon('edit'), ` ${_('Change')}`], () => this.changeSubnet(srv), 'negative'),
|
||||
),
|
||||
]),
|
||||
E('div', { class: 'dl-setrow' }, [
|
||||
E('div', { class: 'dl-stack' }, [
|
||||
E('span', { class: 'dl-setrow-label' }, 'Remove server'),
|
||||
E('span', { class: 'dl-setrow-label' }, _('Remove server')),
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-sub' },
|
||||
`Removes the tunnel, its firewall rules and ${people} ${people === 1 ? 'person' : 'people'} with all their devices. A backup is made first.`,
|
||||
plural(
|
||||
people,
|
||||
'Removes the tunnel, its firewall rules and %s person with all their devices. A backup is made first.',
|
||||
'Removes the tunnel, its firewall rules and %s people with all their devices. A backup is made first.',
|
||||
),
|
||||
),
|
||||
]),
|
||||
E(
|
||||
'div',
|
||||
{ class: 'dl-setrow-ctl' },
|
||||
button([icon('trash'), ' Remove'], () => this.remove(srv), 'negative'),
|
||||
button([icon('trash'), ` ${_('Remove')}`], () => this.remove(srv), 'negative'),
|
||||
),
|
||||
]),
|
||||
],
|
||||
@@ -483,24 +494,28 @@ export class ServerPage {
|
||||
const nets = taken.networks ?? [];
|
||||
const devices = this.st.people.filter((p) => p.server === srv.id).reduce((n, p) => n + p.devices.length, 0);
|
||||
const range = input(rangeOf(srv.subnet), { class: 'cbi-input-text dl-mono dl-w-range' });
|
||||
const rangeRow = liveRow('Address range', range, () => rangeHelp(range.value, nets, ''));
|
||||
const rangeRow = liveRow(_('Address range'), range, () => rangeHelp(range.value, nets, ''));
|
||||
modal(
|
||||
'Change the tunnel network',
|
||||
_('Change the tunnel network'),
|
||||
[
|
||||
rangeRow,
|
||||
E(
|
||||
'p',
|
||||
{ class: 'dl-muted' },
|
||||
devices
|
||||
? `${devices} device${devices === 1 ? ' gets a new address and stops' : 's get new addresses and stop'} connecting until ${devices === 1 ? 'it imports its' : 'they import their'} configuration again (from their personal link or from you).`
|
||||
: 'No devices on this server yet: nothing else changes.',
|
||||
? plural(
|
||||
devices,
|
||||
'%s device gets a new address and stops connecting until it imports its configuration again (from their personal link or from you).',
|
||||
'%s devices get new addresses and stop connecting until they import their configuration again (from their personal link or from you).',
|
||||
)
|
||||
: _('No devices on this server yet: nothing else changes.'),
|
||||
),
|
||||
],
|
||||
[
|
||||
cancelButton(),
|
||||
' ',
|
||||
button(
|
||||
'Change',
|
||||
_('Change'),
|
||||
async () => {
|
||||
const h = rangeRow.help();
|
||||
if (h.bad) {
|
||||
@@ -512,9 +527,9 @@ export class ServerPage {
|
||||
closeModal();
|
||||
return;
|
||||
}
|
||||
if (await attempt(() => api.serverUpdate(srv.id, { subnet }), 'Tunnel network changed')) {
|
||||
if (await attempt(() => api.serverUpdate(srv.id, { subnet }), _('Tunnel network changed'))) {
|
||||
closeModal();
|
||||
if (devices) notify('Devices are marked “Update config” until they import again.', 'info', 6000);
|
||||
if (devices) notify(_('Devices are marked “Update config” until they import again.'), 'info', 6000);
|
||||
await this.refresh();
|
||||
}
|
||||
},
|
||||
@@ -528,22 +543,26 @@ export class ServerPage {
|
||||
async remove(srv: Server) {
|
||||
const people = this.st.people.filter((p) => p.server === srv.id);
|
||||
modal(
|
||||
`Remove ${srv.name}?`,
|
||||
fmt(_('Remove %s?'), srv.name),
|
||||
[
|
||||
E(
|
||||
'p',
|
||||
{},
|
||||
`This removes the tunnel, its firewall rules and ${people.length} ${people.length === 1 ? 'person' : 'people'} with all their devices. A backup is made first.`,
|
||||
plural(
|
||||
people.length,
|
||||
'This removes the tunnel, its firewall rules and %s person with all their devices. A backup is made first.',
|
||||
'This removes the tunnel, its firewall rules and %s people with all their devices. A backup is made first.',
|
||||
),
|
||||
),
|
||||
],
|
||||
[
|
||||
cancelButton(),
|
||||
' ',
|
||||
button(
|
||||
'Remove',
|
||||
_('Remove'),
|
||||
async () => {
|
||||
closeModal();
|
||||
if (await attempt(() => api.serverDelete(srv.id), 'Server removed'))
|
||||
if (await attempt(() => api.serverDelete(srv.id), _('Server removed')))
|
||||
setTimeout(() => {
|
||||
location.href = url();
|
||||
}, 800);
|
||||
@@ -584,13 +603,15 @@ export class ServerPage {
|
||||
portHelp(
|
||||
state.port,
|
||||
d.udp_taken ?? [],
|
||||
`Opened on the WAN firewall automatically.${state.port === 4500 ? ' 4500 is IPsec’s port: most networks let it through.' : ''}`,
|
||||
state.port === 4500
|
||||
? `${_('Opened on the WAN firewall automatically.')} ${_('4500 is IPsec’s port: most networks let it through.')}`
|
||||
: _('Opened on the WAN firewall automatically.'),
|
||||
);
|
||||
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.',
|
||||
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 ep = endpointProbe(
|
||||
() => ({ host: state.endpoint, port: state.port }),
|
||||
@@ -605,10 +626,14 @@ export class ServerPage {
|
||||
? needRow(
|
||||
'alert',
|
||||
'warn',
|
||||
d.wan_kind === 'cgnat' ? 'Your router has no public address (CGNAT)' : `Your router is behind another router (WAN ${d.wan_ip})`,
|
||||
d.wan_kind === '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.'
|
||||
: 'Forward the UDP port on the upstream router to this one and use a DDNS name or that router’s public address here.',
|
||||
? _('Your router has no public address (CGNAT)')
|
||||
: fmt(_('Your router is behind another router (WAN %s)'), d.wan_ip),
|
||||
d.wan_kind === '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.',
|
||||
)
|
||||
: _('Forward the UDP port on the upstream router to this one and use a DDNS name or that router’s public address here.'),
|
||||
'',
|
||||
)
|
||||
: '';
|
||||
@@ -616,7 +641,11 @@ export class ServerPage {
|
||||
d.awg_state?.tools && d.awg_state.handler === false
|
||||
? E('div', { class: 'dl-note warn' }, [
|
||||
icon('alert'),
|
||||
E('span', {}, 'Creating the server restarts the network for a few seconds: AmneziaWG was installed after the network started.'),
|
||||
E(
|
||||
'span',
|
||||
{},
|
||||
_('Creating the server restarts the network for a few seconds: AmneziaWG was installed after the network started.'),
|
||||
),
|
||||
])
|
||||
: '';
|
||||
const rangeHelpNow = () => rangeHelp(state.range, d.networks ?? [], rangeOf(d.subnet));
|
||||
@@ -636,27 +665,33 @@ export class ServerPage {
|
||||
type Page = { id: string; title: string; render: () => Node; check?: () => string | null };
|
||||
const serverPage: Page = {
|
||||
id: 'server',
|
||||
title: 'Server',
|
||||
title: _('Server'),
|
||||
render: () =>
|
||||
E('div', { class: 'dl-wizard-groups' }, [
|
||||
E(
|
||||
'p',
|
||||
{ class: 'dl-muted' },
|
||||
extra
|
||||
? 'One more server: another port or disguise for networks where the first does not get through, or its own home access rules. People are moved between servers from their page.'
|
||||
: 'Where devices connect to. A hostname that always points at your router (DDNS) keeps links working when your IP changes.',
|
||||
? _(
|
||||
'One more server: another port or disguise for networks where the first does not get through, or its own home access rules. People are moved between servers from their page.',
|
||||
)
|
||||
: _(
|
||||
'Where devices connect to. A hostname that always points at your router (DDNS) keeps links working when your IP changes.',
|
||||
),
|
||||
),
|
||||
group('router', 'Server', 'What people see', [
|
||||
liveRow('Name', field('name'), () => nameHelp(state.name, [], 'Shown to people in their portal and apps.')),
|
||||
group('router', _('Server'), _('What people see'), [
|
||||
liveRow(_('Name'), field('name'), () => nameHelp(state.name, [], _('Shown to people in their portal and apps.'))),
|
||||
]),
|
||||
group(
|
||||
'globe',
|
||||
'Devices connect to',
|
||||
'A hostname or IP address of your router on the internet; not through Cloudflare (use a DNS-only name or an IP). IPv6 works too, and is the way out of CGNAT',
|
||||
_('Devices connect to'),
|
||||
_(
|
||||
'A hostname or IP address of your router on the internet; not through Cloudflare (use a DNS-only name or an IP). IPv6 works too, and is the way out of CGNAT',
|
||||
),
|
||||
[
|
||||
(() => {
|
||||
const el = field('endpoint', { placeholder: 'vpn.example.com', class: 'cbi-input-text dl-mono' });
|
||||
epRow = liveRow('Public address', el, ep.help);
|
||||
epRow = liveRow(_('Public address'), el, ep.help);
|
||||
el.addEventListener('input', ep.schedule);
|
||||
ep.schedule();
|
||||
return epRow;
|
||||
@@ -668,9 +703,9 @@ export class ServerPage {
|
||||
]),
|
||||
check: () => {
|
||||
const n = nameHelp(state.name);
|
||||
if (n.bad) return `Name: ${n.text}`;
|
||||
if (n.bad) return fmt(_('Name: %s'), n.text);
|
||||
const h = hostHelp(state.endpoint, state.port);
|
||||
return h.bad ? `Public address: ${h.text}` : null;
|
||||
return h.bad ? fmt(_('Public address: %s'), h.text) : null;
|
||||
},
|
||||
};
|
||||
const awgPage: Page = {
|
||||
@@ -678,50 +713,50 @@ export class ServerPage {
|
||||
title: 'AmneziaWG',
|
||||
render: () =>
|
||||
E('div', { class: 'dl-wizard-groups' }, [
|
||||
group('globe', 'Listening', 'Where devices reach AmneziaWG from the internet', [
|
||||
liveRow('UDP port', field('port', { inputmode: 'numeric', class: 'cbi-input-text dl-w-port dl-mono' }), portHelpNow),
|
||||
group('globe', _('Listening'), _('Where devices reach AmneziaWG from the internet'), [
|
||||
liveRow(_('UDP port'), field('port', { inputmode: 'numeric', class: 'cbi-input-text dl-w-port dl-mono' }), portHelpNow),
|
||||
]),
|
||||
group('network', 'Tunnel network', 'Addresses devices get inside the tunnel', [
|
||||
group('network', _('Tunnel network'), _('Addresses devices get inside the tunnel'), [
|
||||
(() => {
|
||||
const el = field('range', {
|
||||
class: 'cbi-input-text dl-w-range dl-mono',
|
||||
'aria-label': 'First three numbers of the device addresses',
|
||||
'aria-label': _('First three numbers of the device addresses'),
|
||||
});
|
||||
return liveRow(
|
||||
'Device addresses',
|
||||
_('Device addresses'),
|
||||
el,
|
||||
rangeHelpNow,
|
||||
E('span', { class: 'dl-suffixed' }, [el, E('span', { class: 'dl-mono' }, '.x')]),
|
||||
);
|
||||
})(),
|
||||
]),
|
||||
group('shield', 'Disguise', 'So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard', [
|
||||
group('shield', _('Disguise'), _('So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard'), [
|
||||
methodPicker(d.awg, state.preset, (m) => (state.preset = m), undefined, d.awg_state?.tools !== false),
|
||||
]),
|
||||
]),
|
||||
check: () => {
|
||||
const p = portHelpNow();
|
||||
if (p.bad) return `UDP port: ${p.text}`;
|
||||
if (p.bad) return fmt(_('UDP port: %s'), p.text);
|
||||
const r = rangeHelpNow();
|
||||
return r.bad ? `Device addresses: ${r.text}` : null;
|
||||
return r.bad ? fmt(_('Device addresses: %s'), r.text) : null;
|
||||
},
|
||||
};
|
||||
const portalPage: Page = {
|
||||
id: 'portal',
|
||||
title: 'Portal',
|
||||
title: _('Portal'),
|
||||
render: () => {
|
||||
const portalPort = field('portal_port', { inputmode: 'numeric', class: 'cbi-input-text dl-w-port dl-mono' });
|
||||
const portRow = liveRow('Listening port', portalPort, portalHelpNow);
|
||||
const portRow = liveRow(_('Listening port'), portalPort, portalHelpNow);
|
||||
portRow.hidden = !state.portal;
|
||||
// Off | On, Off first: the same segmented control as in Settings.
|
||||
const onOff = seg(
|
||||
[
|
||||
['off', 'Off'],
|
||||
['on', 'On'],
|
||||
['off', _('Off')],
|
||||
['on', _('On')],
|
||||
],
|
||||
state.portal ? 'on' : 'off',
|
||||
{
|
||||
label: 'Personal portal',
|
||||
label: _('Personal portal'),
|
||||
onChange: (v) => {
|
||||
state.portal = v === 'on';
|
||||
portRow.hidden = !state.portal;
|
||||
@@ -729,15 +764,17 @@ export class ServerPage {
|
||||
},
|
||||
);
|
||||
return E('div', { class: 'dl-wizard-groups' }, [
|
||||
group('home', 'Internet like a home device', 'How devices reach the internet', [
|
||||
group('home', _('Internet like a home device'), _('How devices reach the internet'), [
|
||||
row(
|
||||
'Through the home network',
|
||||
sw(state.lan_like, 'Internet like a home device', (v) => (state.lan_like = v)),
|
||||
'Whatever handles home traffic on this router (proxies, filters, DNS) handles theirs too. Change it later under Servers → Access.',
|
||||
_('Through the home network'),
|
||||
sw(state.lan_like, _('Internet like a home device'), (v) => (state.lan_like = v)),
|
||||
_(
|
||||
'Whatever handles home traffic on this router (proxies, filters, DNS) handles theirs too. Change it later under Servers → Access.',
|
||||
),
|
||||
),
|
||||
]),
|
||||
group('link', 'Personal portal', 'A page where each person adds their own devices with their personal link', [
|
||||
row('Portal', onOff, 'Off: only you add devices, from LuCI. On: people manage their devices within the limits you set.'),
|
||||
group('link', _('Personal portal'), _('A page where each person adds their own devices with their personal link'), [
|
||||
row(_('Portal'), onOff, _('Off: only you add devices, from LuCI. On: people manage their devices within the limits you set.')),
|
||||
portRow,
|
||||
]),
|
||||
]);
|
||||
@@ -745,7 +782,7 @@ export class ServerPage {
|
||||
check: () => {
|
||||
if (!state.portal) return null;
|
||||
const h = portalHelpNow();
|
||||
return h.bad ? `Portal port: ${h.text}` : null;
|
||||
return h.bad ? fmt(_('Portal port: %s'), h.text) : null;
|
||||
},
|
||||
};
|
||||
const pages = (): Page[] => [serverPage, awgPage, extra ? null : portalPage].filter((x): x is Page => x != null);
|
||||
@@ -757,9 +794,12 @@ export class ServerPage {
|
||||
needRow(
|
||||
'shield',
|
||||
'bad',
|
||||
'AmneziaWG isn’t installed',
|
||||
`The tunnel needs ${missing.join(' and ')}. Install the build made for this firmware, then create the server.`,
|
||||
button('Install', () => installAwg(() => location.reload()), 'positive'),
|
||||
_('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),
|
||||
),
|
||||
button(_('Install'), () => installAwg(() => location.reload()), 'positive'),
|
||||
),
|
||||
])
|
||||
: aw && !aw.loaded
|
||||
@@ -767,9 +807,9 @@ export class ServerPage {
|
||||
needRow(
|
||||
'shield',
|
||||
'warn',
|
||||
'AmneziaWG’s kernel module doesn’t load on this firmware',
|
||||
'Try another build in Components, or update OpenWrt. The server can’t start until it loads.',
|
||||
E('a', { class: 'cbi-button cbi-button-neutral', href: L.url('admin/network/dawnline/updates') }, 'Open Components'),
|
||||
_('AmneziaWG’s kernel module doesn’t load on this firmware'),
|
||||
_('Try another build in Components, or update OpenWrt. The server can’t start until it loads.'),
|
||||
E('a', { class: 'cbi-button cbi-button-neutral', href: L.url('admin/network/dawnline/updates') }, _('Open Components')),
|
||||
),
|
||||
])
|
||||
: '';
|
||||
@@ -778,7 +818,7 @@ export class ServerPage {
|
||||
const ps = pages();
|
||||
if (step >= ps.length) step = ps.length - 1;
|
||||
dom.content(root, [
|
||||
E('h2', {}, extra ? 'Add a server' : 'Set up Dawnline'),
|
||||
E('h2', {}, extra ? _('Add a server') : _('Set up Dawnline')),
|
||||
awgNotice,
|
||||
E(
|
||||
'div',
|
||||
@@ -793,17 +833,17 @@ export class ServerPage {
|
||||
E('div', { class: 'dl-panel' }, ps[step].render()),
|
||||
E('div', { class: 'dl-actions' }, [
|
||||
step > 0
|
||||
? button('Back', () => {
|
||||
? button(_('Back'), () => {
|
||||
step--;
|
||||
paint();
|
||||
})
|
||||
: onCancel
|
||||
? button('Cancel', onCancel)
|
||||
? button(_('Cancel'), onCancel)
|
||||
: '',
|
||||
E('span', { class: 'dl-spacer' }),
|
||||
step < ps.length - 1
|
||||
? button(
|
||||
'Next',
|
||||
_('Next'),
|
||||
() => {
|
||||
const err = ps[step].check?.();
|
||||
if (err) {
|
||||
@@ -816,7 +856,7 @@ export class ServerPage {
|
||||
'positive',
|
||||
)
|
||||
: button(
|
||||
'Create server',
|
||||
_('Create server'),
|
||||
async () => {
|
||||
for (const pg of ps) {
|
||||
const err = pg.check?.();
|
||||
@@ -843,11 +883,11 @@ export class ServerPage {
|
||||
extra ? undefined : state.portal,
|
||||
extra ? undefined : state.portal_port,
|
||||
),
|
||||
'Server created',
|
||||
_('Server created'),
|
||||
);
|
||||
if (!r) return;
|
||||
// A network restart drops the connection to LuCI for a few seconds.
|
||||
if (r.network_restart) notify('Restarting the network so it knows AmneziaWG: back in a few seconds');
|
||||
if (r.network_restart) notify(_('Restarting the network so it knows AmneziaWG: back in a few seconds'));
|
||||
setTimeout(
|
||||
() => {
|
||||
location.href = url(r.id);
|
||||
@@ -856,7 +896,7 @@ export class ServerPage {
|
||||
);
|
||||
},
|
||||
'positive',
|
||||
{ disabled: missing.length > 0, title: missing.length ? 'Install AmneziaWG first' : null },
|
||||
{ disabled: missing.length > 0, title: missing.length ? _('Install AmneziaWG first') : null },
|
||||
),
|
||||
]),
|
||||
]);
|
||||
|
||||
@@ -10,26 +10,33 @@ import { dropdown } from '../../ui/menu';
|
||||
import { attempt, notify } from '../../ui/toast';
|
||||
import { icon } from '../../../shared/icons';
|
||||
import { bytes } from '../../../shared/format';
|
||||
import { fmt, locale, plural } from '../../../shared/i18n';
|
||||
|
||||
/** After a change: `true` when everything changed (restore, import), else only the list. */
|
||||
type Done = (all?: boolean) => void;
|
||||
|
||||
const REASON: Record<string, string> = {
|
||||
manual: 'Manual',
|
||||
auto: 'Nightly',
|
||||
'pre-restore': 'Before restore',
|
||||
'pre-import': 'Before import',
|
||||
'pre-delete': 'Before removing a server',
|
||||
'pre-update': 'Before update',
|
||||
};
|
||||
/** Why a backup was made, from its reason id; an unknown id as it is. */
|
||||
function reasonLabel(r: string): string {
|
||||
const label: Record<string, string> = {
|
||||
manual: _('Manual'),
|
||||
auto: _('Nightly'),
|
||||
'pre-restore': _('Before restore'),
|
||||
'pre-import': _('Before import'),
|
||||
'pre-delete': _('Before removing a server'),
|
||||
'pre-update': _('Before update'),
|
||||
};
|
||||
return label[r] ?? r;
|
||||
}
|
||||
const SHOWN = 3;
|
||||
|
||||
/** "Today, 03:00", "Yesterday, 03:00" or "12 Oct, 03:00". */
|
||||
function when(ts: number): string {
|
||||
const d = new Date(ts * 1000);
|
||||
const t = d.toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' });
|
||||
const t = d.toLocaleTimeString(locale(), { hour: '2-digit', minute: '2-digit' });
|
||||
const days = Math.round((new Date(new Date().toDateString()).getTime() - new Date(d.toDateString()).getTime()) / 86400000);
|
||||
return `${days === 0 ? 'Today' : days === 1 ? 'Yesterday' : d.toLocaleDateString('en-GB', { day: 'numeric', month: 'short' })}, ${t}`;
|
||||
if (days === 0) return fmt(_('Today, %s'), t);
|
||||
if (days === 1) return fmt(_('Yesterday, %s'), t);
|
||||
return `${d.toLocaleDateString(locale(), { day: 'numeric', month: 'short' })}, ${t}`;
|
||||
}
|
||||
|
||||
async function download(b: Backup) {
|
||||
@@ -47,43 +54,43 @@ function backupRow(b: Backup, done: Done): HTMLElement {
|
||||
E('span', { class: 'dl-group-ic' }, icon('archive')),
|
||||
E('span', { class: 'dl-row-main dl-stack' }, [
|
||||
E('b', {}, when(b.created)),
|
||||
E('span', { class: 'dl-sub' }, `${REASON[b.reason] ?? b.reason} · ${bytes(b.size)}`),
|
||||
E('span', { class: 'dl-sub' }, `${reasonLabel(b.reason)} · ${bytes(b.size)}`),
|
||||
]),
|
||||
E('span', { class: 'dl-pcard-actions' }, [
|
||||
iconButton('download', 'Download', () => download(b), 'neutral', 'dl-icon-only'),
|
||||
iconButton('download', _('Download'), () => download(b), 'neutral', 'dl-icon-only'),
|
||||
iconButton(
|
||||
'more',
|
||||
'More',
|
||||
_('More'),
|
||||
(ev: MouseEvent) =>
|
||||
dropdown(ev.currentTarget as HTMLElement, [
|
||||
{
|
||||
label: 'Restore',
|
||||
label: _('Restore'),
|
||||
icon: icon('reset'),
|
||||
run: async () => {
|
||||
const ok = await confirmDialog(
|
||||
'Restore this backup?',
|
||||
`Everything returns to ${when(b.created)}. The current state is backed up first.`,
|
||||
'Restore',
|
||||
_('Restore this backup?'),
|
||||
fmt(_('Everything returns to %s. The current state is backed up first.'), when(b.created)),
|
||||
_('Restore'),
|
||||
true,
|
||||
);
|
||||
if (ok && (await attempt(() => api.backupRestore(b.name), 'Restored'))) done(true);
|
||||
if (ok && (await attempt(() => api.backupRestore(b.name), _('Restored')))) done(true);
|
||||
},
|
||||
},
|
||||
{
|
||||
label: 'Delete',
|
||||
label: _('Delete'),
|
||||
icon: icon('trash'),
|
||||
danger: true,
|
||||
run: async () => {
|
||||
if (
|
||||
!(await confirmDialog(
|
||||
'Delete this backup?',
|
||||
`The backup from ${when(b.created)} is removed from the router.`,
|
||||
'Delete',
|
||||
_('Delete this backup?'),
|
||||
fmt(_('The backup from %s is removed from the router.'), when(b.created)),
|
||||
_('Delete'),
|
||||
true,
|
||||
))
|
||||
)
|
||||
return;
|
||||
if (await attempt(() => api.backupDelete(b.name), 'Backup deleted')) done();
|
||||
if (await attempt(() => api.backupDelete(b.name), _('Backup deleted'))) done();
|
||||
},
|
||||
},
|
||||
]),
|
||||
@@ -103,63 +110,63 @@ export function backupsSection(list: Backup[], done: Done): HTMLElement {
|
||||
...rows,
|
||||
older.length
|
||||
? E('details', { class: 'dl-bk-older' }, [
|
||||
E('summary', {}, [icon('chevron'), `${older.length} older backup${older.length === 1 ? '' : 's'}`]),
|
||||
E('summary', {}, [icon('chevron'), plural(older.length, '%s older backup', '%s older backups')]),
|
||||
...older.map((b) => backupRow(b, done)),
|
||||
])
|
||||
: '',
|
||||
])
|
||||
: E('div', { class: 'dl-list' }, [E('div', { class: 'dl-row dl-muted' }, 'No backups yet.')]);
|
||||
: E('div', { class: 'dl-list' }, [E('div', { class: 'dl-row dl-muted' }, _('No backups yet.'))]);
|
||||
|
||||
const restoreFile = button('Restore from file', async () => {
|
||||
const restoreFile = button(_('Restore from file'), async () => {
|
||||
const f = await pickFile('.tar.gz,.tgz,application/gzip', 'base64');
|
||||
if (!f) return;
|
||||
const ok = await confirmDialog(
|
||||
'Restore from file?',
|
||||
`Replace the current Dawnline configuration with ${f.name}? The current state is backed up first.`,
|
||||
'Restore',
|
||||
_('Restore from file?'),
|
||||
fmt(_('Replace the current Dawnline configuration with %s? The current state is backed up first.'), f.name),
|
||||
_('Restore'),
|
||||
true,
|
||||
);
|
||||
if (ok && (await attempt(() => api.backupUpload(f.data), 'Restored'))) done(true);
|
||||
if (ok && (await attempt(() => api.backupUpload(f.data), _('Restored')))) done(true);
|
||||
});
|
||||
const exportJson = button('Export JSON', async () => {
|
||||
const exportJson = button(_('Export JSON'), async () => {
|
||||
const r = await attempt(() => api.exportJson());
|
||||
if (r) downloadFile(`dawnline-export-${new Date().toISOString().slice(0, 10)}.json`, JSON.stringify(r, null, 2), 'application/json');
|
||||
});
|
||||
const importJson = button('Import JSON', async () => {
|
||||
const importJson = button(_('Import JSON'), async () => {
|
||||
const f = await pickFile('.json,application/json', 'text');
|
||||
if (!f) return;
|
||||
let data: unknown;
|
||||
try {
|
||||
data = JSON.parse(f.data);
|
||||
} catch {
|
||||
notify('Not a JSON file.', 'error');
|
||||
notify(_('Not a JSON file.'), 'error');
|
||||
return;
|
||||
}
|
||||
const ok = await confirmDialog(
|
||||
'Import?',
|
||||
'This replaces the whole Dawnline configuration on this router. The current state is backed up first.',
|
||||
'Import',
|
||||
_('Import?'),
|
||||
_('This replaces the whole Dawnline configuration on this router. The current state is backed up first.'),
|
||||
_('Import'),
|
||||
true,
|
||||
);
|
||||
if (ok && (await attempt(() => api.importJson(data), 'Imported'))) done(true);
|
||||
if (ok && (await attempt(() => api.importJson(data), _('Imported')))) done(true);
|
||||
});
|
||||
|
||||
return E('section', { class: 'dl-setsec', id: 'dl-set-backups' }, [
|
||||
E('div', { class: 'dl-setsec-body' }, [
|
||||
E('div', { class: 'dl-setsec-head' }, [
|
||||
E('div', { class: 'dl-stack' }, [
|
||||
E('h3', {}, 'Backups'),
|
||||
E('h3', {}, _('Backups')),
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-sub' },
|
||||
'Nightly when something changed, and before every restore, import or update. The last 10 are kept.',
|
||||
_('Nightly when something changed, and before every restore, import or update. The last 10 are kept.'),
|
||||
),
|
||||
]),
|
||||
E('span', { class: 'dl-spacer' }),
|
||||
button(
|
||||
[icon('plus'), ' Back up now'],
|
||||
[icon('plus'), ' ', _('Back up now')],
|
||||
async () => {
|
||||
if (await attempt(() => api.backupCreate(), 'Backup created')) done();
|
||||
if (await attempt(() => api.backupCreate(), _('Backup created'))) done();
|
||||
},
|
||||
'positive',
|
||||
),
|
||||
@@ -170,7 +177,7 @@ export function backupsSection(list: Backup[], done: Done): HTMLElement {
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-sub' },
|
||||
'Backups contain private keys: keep downloads safe. JSON moves everything except usage history to another router.',
|
||||
_('Backups contain private keys: keep downloads safe. JSON moves everything except usage history to another router.'),
|
||||
),
|
||||
E('span', { class: 'dl-row-actions dl-bk-actions' }, [restoreFile, exportJson, importJson]),
|
||||
]),
|
||||
|
||||
@@ -6,15 +6,19 @@ import { button } from '../../ui/button';
|
||||
import { cancelButton, closeModal, modal } from '../../ui/modal';
|
||||
import { attempt } from '../../ui/toast';
|
||||
import { input } from '../../ui/controls';
|
||||
import { fmt } from '../../../shared/i18n';
|
||||
import { section } from './common';
|
||||
|
||||
/** The word the router demands to remove Dawnline: the same in every language. */
|
||||
const WORD = 'remove';
|
||||
|
||||
function uninstall() {
|
||||
const confirmInput = input('', { placeholder: 'remove' });
|
||||
const confirmInput = input('', { placeholder: WORD });
|
||||
// Live only once the word is typed, as the router itself demands.
|
||||
const go = button(
|
||||
'Remove Dawnline',
|
||||
_('Remove Dawnline'),
|
||||
async () => {
|
||||
if (await attempt(() => api.uninstall(confirmInput.value.trim()), 'Dawnline removed')) {
|
||||
if (await attempt(() => api.uninstall(confirmInput.value.trim()), _('Dawnline removed'))) {
|
||||
closeModal();
|
||||
setTimeout(() => location.reload(), 800);
|
||||
}
|
||||
@@ -23,15 +27,20 @@ function uninstall() {
|
||||
{ disabled: true },
|
||||
);
|
||||
confirmInput.addEventListener('input', () => {
|
||||
go.disabled = confirmInput.value.trim() !== 'remove';
|
||||
go.disabled = confirmInput.value.trim() !== WORD;
|
||||
});
|
||||
modal(
|
||||
'Remove Dawnline?',
|
||||
_('Remove Dawnline?'),
|
||||
[
|
||||
E(
|
||||
'p',
|
||||
{},
|
||||
'Everyone is disconnected and the tunnel, firewall rules and portal are removed. A backup is made first. Type “remove” to confirm.',
|
||||
fmt(
|
||||
_(
|
||||
'Everyone is disconnected and the tunnel, firewall rules and portal are removed. A backup is made first. Type “%s” to confirm.',
|
||||
),
|
||||
WORD,
|
||||
),
|
||||
),
|
||||
confirmInput,
|
||||
],
|
||||
@@ -42,15 +51,17 @@ function uninstall() {
|
||||
export function dangerCard(): HTMLElement {
|
||||
return section(
|
||||
'danger',
|
||||
'Remove Dawnline from this router',
|
||||
_('Remove Dawnline from this router'),
|
||||
[
|
||||
E(
|
||||
'p',
|
||||
{ class: 'dl-muted' },
|
||||
'Deletes the tunnel, firewall rules, access table and hostnames Dawnline created, and stops the service. People and keys are kept in a backup.',
|
||||
_(
|
||||
'Deletes the tunnel, firewall rules, access table and hostnames Dawnline created, and stops the service. People and keys are kept in a backup.',
|
||||
),
|
||||
),
|
||||
],
|
||||
[E('span'), button('Remove', () => uninstall(), 'negative')],
|
||||
[E('span'), button(_('Remove'), () => uninstall(), 'negative')],
|
||||
'danger',
|
||||
);
|
||||
}
|
||||
@@ -6,43 +6,44 @@ import { input, isOn, sw } from '../../ui/controls';
|
||||
import { firstBad, liveRow } from '../../ui/layout';
|
||||
import { notify } from '../../ui/toast';
|
||||
import { domainHelp, fallbackDnsHelp, limitHelp } from '../../netcheck';
|
||||
import { fmt } from '../../../shared/i18n';
|
||||
import { section, type SettingsHost } from './common';
|
||||
|
||||
export function defaultsCard(host: SettingsHost): HTMLElement {
|
||||
const s = host.d.settings;
|
||||
const eff = host.d.effective as Record<string, any>;
|
||||
const limit = input(s.default_device_limit, { placeholder: '3', inputmode: 'numeric', class: 'cbi-input-text dl-w-port' });
|
||||
const hn = sw(eff.hostnames, 'Device hostnames');
|
||||
const hn = sw(eff.hostnames, _('Device hostnames'));
|
||||
const domain = input(s.domain, { placeholder: 'lan', class: 'cbi-input-text dl-w-port' });
|
||||
const fallback = input(s.home_dns_fallback === 'none' ? '' : s.home_dns_fallback || eff.home_dns_fallback || '', {
|
||||
placeholder: 'None',
|
||||
placeholder: _('None'),
|
||||
inputmode: 'decimal',
|
||||
class: 'cbi-input-text dl-w-ip dl-mono',
|
||||
});
|
||||
const limitRow = liveRow('Devices per person', limit, () => {
|
||||
const limitRow = liveRow(_('Devices per person'), limit, () => {
|
||||
// Empty keeps the default (the router stores nothing then).
|
||||
if (!limit.value.trim()) return { text: 'The default, 3. Pre-filled when you add someone.', bad: false };
|
||||
if (!limit.value.trim()) return { text: _('The default, 3. Pre-filled when you add someone.'), bad: false };
|
||||
const h = limitHelp(limit.value);
|
||||
return h.bad ? h : { text: 'Pre-filled when you add someone.', bad: false };
|
||||
return h.bad ? h : { text: _('Pre-filled when you add someone.'), bad: false };
|
||||
});
|
||||
const domainRow = liveRow(
|
||||
'Device hostnames',
|
||||
_('Device hostnames'),
|
||||
domain,
|
||||
() => domainHelp(domain.value),
|
||||
E('div', { class: 'dl-hostport' }, [hn, E('span', { class: 'dl-faint dl-mono' }, 'phone.myata.'), domain]),
|
||||
);
|
||||
const fallbackRow = liveRow('Fallback DNS', fallback, () => {
|
||||
const fallbackRow = liveRow(_('Fallback DNS'), fallback, () => {
|
||||
const h = fallbackDnsHelp(fallback.value);
|
||||
return h.bad ? h : { text: `For Home-only devices using home names: ${h.text}`, bad: false };
|
||||
return h.bad ? h : { text: fmt(_('For Home-only devices using home names: %s'), h.text), bad: false };
|
||||
});
|
||||
return section(
|
||||
'defaults',
|
||||
'New people',
|
||||
_('New people'),
|
||||
[limitRow, domainRow, fallbackRow],
|
||||
[
|
||||
E('span'),
|
||||
button(
|
||||
'Save',
|
||||
_('Save'),
|
||||
() => {
|
||||
const bad = firstBad([limitRow, domainRow, fallbackRow]);
|
||||
if (bad) {
|
||||
@@ -56,7 +57,7 @@ export function defaultsCard(host: SettingsHost): HTMLElement {
|
||||
domain: domain.value,
|
||||
home_dns_fallback: fallback.value,
|
||||
},
|
||||
'Saved',
|
||||
_('Saved'),
|
||||
'defaults',
|
||||
);
|
||||
},
|
||||
|
||||
@@ -51,7 +51,7 @@ export class SettingsPage implements SettingsHost {
|
||||
// ?section=updates (from Components) and the like: open at that card.
|
||||
const sec = new URLSearchParams(location.search).get('section');
|
||||
if (sec && sec !== 'backups') requestAnimationFrame(() => document.getElementById(`dl-set-${sec}`)?.scrollIntoView({ block: 'start' }));
|
||||
return E('div', {}, [E('div', { class: 'dl-pagehead' }, [E('h2', { class: 'dl-h1' }, 'Settings')]), this.root]);
|
||||
return E('div', {}, [E('div', { class: 'dl-pagehead' }, [E('h2', { class: 'dl-h1' }, _('Settings'))]), this.root]);
|
||||
}
|
||||
|
||||
async save(values: Record<string, string | string[]>, ok: string, card: CardId) {
|
||||
|
||||
@@ -7,8 +7,9 @@ import { attempt } from '../../ui/toast';
|
||||
import { chipToggle, seg, setChip } from '../../ui/controls';
|
||||
import { row } from '../../ui/layout';
|
||||
import { icon } from '../../../shared/icons';
|
||||
import { fmtDay, kb, plural } from '../../../shared/format';
|
||||
import { CATEGORIES, CATEGORY_HELP, CATEGORY_LABEL, retentionText } from '../../events/model';
|
||||
import { fmtDay, kb } from '../../../shared/format';
|
||||
import { fmt, num, plural } from '../../../shared/i18n';
|
||||
import { CATEGORIES, categoryHelp, categoryLabel, retentionText } from '../../events/model';
|
||||
import { clearLogDialog, exportEvents, resetUsageDialog } from '../../logs';
|
||||
import { section, type SettingsHost } from './common';
|
||||
|
||||
@@ -17,54 +18,54 @@ export function logsCard(host: SettingsHost): HTMLElement {
|
||||
const p = L.policy;
|
||||
const keep = seg(
|
||||
[
|
||||
['7', '7 days'],
|
||||
['30', '30 days'],
|
||||
['90', '90 days'],
|
||||
['365', '1 year'],
|
||||
['0', 'No limit'],
|
||||
['7', plural(7, '%s day', '%s days')],
|
||||
['30', plural(30, '%s day', '%s days')],
|
||||
['90', plural(90, '%s day', '%s days')],
|
||||
['365', plural(1, '%s year', '%s years')],
|
||||
['0', _('No limit', 'retention')],
|
||||
],
|
||||
String(p.keep_days),
|
||||
{ label: 'Keep activity', cls: 'sm' },
|
||||
{ label: _('Keep activity'), cls: 'sm' },
|
||||
);
|
||||
const size = seg(
|
||||
[
|
||||
['500', '500'],
|
||||
['2000', '2,000'],
|
||||
['5000', '5,000'],
|
||||
['20000', '20,000'],
|
||||
['500', num(500)],
|
||||
['2000', num(2000)],
|
||||
['5000', num(5000)],
|
||||
['20000', num(20000)],
|
||||
],
|
||||
String(p.max),
|
||||
{ label: 'Maximum events', cls: 'sm' },
|
||||
{ label: _('Maximum events'), cls: 'sm' },
|
||||
);
|
||||
const persist = seg(
|
||||
[
|
||||
['10min', 'Every 10 min'],
|
||||
['hourly', 'Hourly'],
|
||||
['off', 'Memory only'],
|
||||
['10min', _('Every 10 min')],
|
||||
['hourly', _('Hourly')],
|
||||
['off', _('Memory only')],
|
||||
],
|
||||
p.persist,
|
||||
{ label: 'Save to flash', cls: 'sm' },
|
||||
{ label: _('Save to flash'), cls: 'sm' },
|
||||
);
|
||||
const days = seg(
|
||||
[
|
||||
['31', '1 month'],
|
||||
['62', '2 months'],
|
||||
['180', '6 months'],
|
||||
['365', '1 year'],
|
||||
['730', '2 years'],
|
||||
['31', plural(1, '%s month', '%s months')],
|
||||
['62', plural(2, '%s month', '%s months')],
|
||||
['180', plural(6, '%s month', '%s months')],
|
||||
['365', plural(1, '%s year', '%s years')],
|
||||
['730', plural(2, '%s year', '%s years')],
|
||||
],
|
||||
String(p.usage_days),
|
||||
{ label: 'Daily traffic', cls: 'sm' },
|
||||
{ label: _('Daily traffic'), cls: 'sm' },
|
||||
);
|
||||
const months = seg(
|
||||
[
|
||||
['12', '1 year'],
|
||||
['24', '2 years'],
|
||||
['60', '5 years'],
|
||||
['120', '10 years'],
|
||||
['12', plural(1, '%s year', '%s years')],
|
||||
['24', plural(2, '%s year', '%s years')],
|
||||
['60', plural(5, '%s year', '%s years')],
|
||||
['120', plural(10, '%s year', '%s years')],
|
||||
],
|
||||
String(p.usage_months),
|
||||
{ label: 'Monthly traffic', cls: 'sm' },
|
||||
{ label: _('Monthly traffic'), cls: 'sm' },
|
||||
);
|
||||
const chosen = new Set(p.categories);
|
||||
const cats = E(
|
||||
@@ -72,13 +73,13 @@ export function logsCard(host: SettingsHost): HTMLElement {
|
||||
{ class: 'dl-chips-row' },
|
||||
CATEGORIES.map((c) => {
|
||||
const b = chipToggle(
|
||||
[CATEGORY_LABEL[c], E('b', {}, String(L.by_category[c] ?? 0))],
|
||||
[categoryLabel(c), E('b', {}, num(L.by_category[c] ?? 0))],
|
||||
chosen.has(c),
|
||||
() => {
|
||||
if (!chosen.delete(c)) chosen.add(c);
|
||||
setChip(b, chosen.has(c));
|
||||
},
|
||||
{ title: CATEGORY_HELP[c] },
|
||||
{ title: categoryHelp(c) },
|
||||
);
|
||||
return b;
|
||||
}),
|
||||
@@ -91,72 +92,83 @@ export function logsCard(host: SettingsHost): HTMLElement {
|
||||
E('span', { class: 'dl-row-main dl-stack' }, [E('b', {}, title), E('span', { class: 'dl-sub' }, detail)]),
|
||||
...actions,
|
||||
]);
|
||||
const exportBtn = (fmt: 'csv' | 'json') =>
|
||||
const exportBtn = (kind: 'csv' | 'json') =>
|
||||
button(
|
||||
fmt.toUpperCase(),
|
||||
kind.toUpperCase(),
|
||||
async () => {
|
||||
const [st, ev] = await Promise.all([api.status(1), api.events(20000)]);
|
||||
exportEvents(st, ev.events, fmt);
|
||||
exportEvents(st, ev.events, kind);
|
||||
},
|
||||
'neutral',
|
||||
{ title: `Download the log as ${fmt.toUpperCase()}` },
|
||||
{ title: fmt(_('Download the log as %s'), kind.toUpperCase()) },
|
||||
);
|
||||
|
||||
return section(
|
||||
'logs',
|
||||
'Logs & history',
|
||||
_('Logs & history'),
|
||||
[
|
||||
E('p', { class: 'dl-muted' }, retentionText(p)),
|
||||
row('Keep activity', keep, 'Older events are removed automatically.'),
|
||||
row('Maximum size', size, 'Newest events are kept when the log is full.'),
|
||||
row('Record', cats, 'Switched-off categories are not logged from now on.'),
|
||||
row(_('Keep activity'), keep, _('Older events are removed automatically.')),
|
||||
row(_('Maximum size'), size, _('Newest events are kept when the log is full.')),
|
||||
row(_('Record'), cats, _('Switched-off categories are not logged from now on.')),
|
||||
row(
|
||||
'Save to flash',
|
||||
_('Save to flash'),
|
||||
persist,
|
||||
'The log lives in memory and is copied to flash. Memory only saves flash writes but is lost on reboot.',
|
||||
_('The log lives in memory and is copied to flash. Memory only saves flash writes but is lost on reboot.'),
|
||||
),
|
||||
row('Daily traffic', days, 'Per-day history behind the charts.'),
|
||||
row('Monthly traffic', months, 'Per-month totals; data limits use the current month.'),
|
||||
E('h4', { class: 'dl-setsub' }, 'Stored data'),
|
||||
row(_('Daily traffic'), days, _('Per-day history behind the charts.')),
|
||||
row(_('Monthly traffic'), months, _('Per-month totals; data limits use the current month.')),
|
||||
E('h4', { class: 'dl-setsub' }, _('Stored data')),
|
||||
E('div', { class: 'dl-list' }, [
|
||||
stored(
|
||||
'activity',
|
||||
'Activity log',
|
||||
_('Activity log'),
|
||||
L.events
|
||||
? `${plural(L.events, 'event')} since ${since} · ${kb(L.log_ram)} in memory${p.persist === 'off' ? '' : `, ${kb(L.log_flash)} on flash`}`
|
||||
: 'Empty',
|
||||
? `${fmt(_('%s since %s'), plural(L.events, '%s event', '%s events'), since)} · ${
|
||||
p.persist === 'off'
|
||||
? fmt(_('%s in memory'), kb(L.log_ram))
|
||||
: fmt(_('%s in memory, %s on flash'), kb(L.log_ram), kb(L.log_flash))
|
||||
}`
|
||||
: _('Empty'),
|
||||
[
|
||||
exportBtn('csv'),
|
||||
exportBtn('json'),
|
||||
button(
|
||||
'Clear',
|
||||
() => clearLogDialog('Clear activity', 'Removes events from the log on the router.', {}, () => host.reload('logs')),
|
||||
_('Clear'),
|
||||
() => clearLogDialog(_('Clear activity'), _('Removes events from the log on the router.'), {}, () => host.reload('logs')),
|
||||
'negative',
|
||||
),
|
||||
],
|
||||
),
|
||||
stored(
|
||||
'chart',
|
||||
'Traffic history',
|
||||
_('Traffic history'),
|
||||
// usage_since is a router day (YYYY-MM-DD): shown as that day in any time zone.
|
||||
L.usage_days ? `${plural(L.usage_days, 'day')} since ${fmtDay(L.usage_since)} · ${kb(L.usage_flash)} on flash` : 'Empty',
|
||||
[button('Reset', () => resetUsageDialog('all', '', '', () => setTimeout(() => host.reload('logs'), 300)), 'negative')],
|
||||
L.usage_days
|
||||
? `${fmt(_('%s since %s'), plural(L.usage_days, '%s day', '%s days'), fmtDay(L.usage_since))} · ${fmt(_('%s on flash'), kb(L.usage_flash))}`
|
||||
: _('Empty'),
|
||||
[button(_('Reset'), () => resetUsageDialog('all', '', '', () => setTimeout(() => host.reload('logs'), 300)), 'negative')],
|
||||
),
|
||||
stored(
|
||||
'pin',
|
||||
_('Location cache'),
|
||||
`${plural(host.d.geo_cached, '%s address', '%s addresses')} · ${fmt(_('%s on flash'), kb(L.geo_flash))}`,
|
||||
[
|
||||
button(
|
||||
_('Clear'),
|
||||
async () => {
|
||||
if (await attempt(() => api.geoClear(), _('Location cache cleared'))) await host.reload('logs');
|
||||
},
|
||||
'negative',
|
||||
),
|
||||
],
|
||||
),
|
||||
stored('pin', 'Location cache', `${plural(host.d.geo_cached, 'address', 'addresses')} · ${kb(L.geo_flash)} on flash`, [
|
||||
button(
|
||||
'Clear',
|
||||
async () => {
|
||||
if (await attempt(() => api.geoClear(), 'Location cache cleared')) await host.reload('logs');
|
||||
},
|
||||
'negative',
|
||||
),
|
||||
]),
|
||||
]),
|
||||
],
|
||||
[
|
||||
E('span', { class: 'dl-sub' }, 'Clear one person or device from their own page.'),
|
||||
E('span', { class: 'dl-sub' }, _('Clear one person or device from their own page.')),
|
||||
button(
|
||||
'Save',
|
||||
_('Save'),
|
||||
() =>
|
||||
host.save(
|
||||
{
|
||||
@@ -167,7 +179,7 @@ export function logsCard(host: SettingsHost): HTMLElement {
|
||||
usage_keep_months: months.dataset.value!,
|
||||
log_category: [...chosen],
|
||||
},
|
||||
'Saved',
|
||||
_('Saved'),
|
||||
'logs',
|
||||
),
|
||||
'positive',
|
||||
|
||||
@@ -4,32 +4,43 @@ import { E } from '../../e';
|
||||
import { button } from '../../ui/button';
|
||||
import { isOn, sw } from '../../ui/controls';
|
||||
import { row } from '../../ui/layout';
|
||||
import { fmt } from '../../../shared/i18n';
|
||||
import { section, type SettingsHost } from './common';
|
||||
|
||||
export function mapCard(host: SettingsHost): HTMLElement {
|
||||
const eff = host.d.effective as Record<string, any>;
|
||||
const gOn = sw(eff.geo_enabled, 'Locations');
|
||||
const gOn = sw(eff.geo_enabled, _('Locations'));
|
||||
const prov = E('select', { class: 'cbi-input-select' }, [
|
||||
E('option', { value: 'ipwho.is', selected: eff.geo_provider !== 'ipapi.co' ? 'selected' : null }, 'ipwho.is (fallback: ipapi.co)'),
|
||||
E('option', { value: 'ipapi.co', selected: eff.geo_provider === 'ipapi.co' ? 'selected' : null }, 'ipapi.co (fallback: ipwho.is)'),
|
||||
E(
|
||||
'option',
|
||||
{ value: 'ipwho.is', selected: eff.geo_provider !== 'ipapi.co' ? 'selected' : null },
|
||||
fmt(_('%s (fallback: %s)'), 'ipwho.is', 'ipapi.co'),
|
||||
),
|
||||
E(
|
||||
'option',
|
||||
{ value: 'ipapi.co', selected: eff.geo_provider === 'ipapi.co' ? 'selected' : null },
|
||||
fmt(_('%s (fallback: %s)'), 'ipapi.co', 'ipwho.is'),
|
||||
),
|
||||
]) as HTMLSelectElement;
|
||||
return section(
|
||||
'map',
|
||||
'Map & locations',
|
||||
_('Map & locations'),
|
||||
[
|
||||
E('div', { class: 'dl-setrow head' }, [
|
||||
E('span', { class: 'dl-muted' }, 'Show where people connect from on the Overview and person pages, at city level.'),
|
||||
E('span', { class: 'dl-muted' }, _('Show where people connect from on the Overview and person pages, at city level.')),
|
||||
gOn,
|
||||
]),
|
||||
row('Provider', prov),
|
||||
row(_('Provider'), prov),
|
||||
],
|
||||
[
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-sub' },
|
||||
'The router sends each new client IP to the provider once and caches the city. Map tiles load in your browser from CARTO; people never see the map.',
|
||||
_(
|
||||
'The router sends each new client IP to the provider once and caches the city. Map tiles load in your browser from CARTO; people never see the map.',
|
||||
),
|
||||
),
|
||||
button('Save', () => host.save({ geo_enabled: isOn(gOn) ? '1' : '0', geo_provider: prov.value }, 'Saved', 'map'), 'positive'),
|
||||
button(_('Save'), () => host.save({ geo_enabled: isOn(gOn) ? '1' : '0', geo_provider: prov.value }, _('Saved'), 'map'), 'positive'),
|
||||
],
|
||||
);
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import { firstBad, group, liveRow, needRow, row } from '../../ui/layout';
|
||||
import { hostHelp, portalPortHelp, urlHelp } from '../../netcheck';
|
||||
import { icon } from '../../../shared/icons';
|
||||
import { fmtDay } from '../../../shared/format';
|
||||
import { fmt, locale, num, plural } from '../../../shared/i18n';
|
||||
import { installMissing } from '../../pkgs';
|
||||
import { notify } from '../../ui/toast';
|
||||
import { section, type SettingsHost } from './common';
|
||||
@@ -27,10 +28,10 @@ export function portalCard(host: SettingsHost): HTMLElement {
|
||||
const s = host.d.settings;
|
||||
const eff = host.d.effective as Record<string, any>;
|
||||
const c = host.d.cert;
|
||||
const pOn = sw(eff.portal_enabled, 'Enable portal');
|
||||
const pOn = sw(eff.portal_enabled, _('Enable portal'));
|
||||
const port = input(s.portal_port, { placeholder: '8443', inputmode: 'numeric', class: 'cbi-input-text dl-w-port' });
|
||||
const redirect = input(s.portal_redirect, { placeholder: 'Show “Not found”', class: 'cbi-input-text dl-mono' });
|
||||
const other = input('', { placeholder: 'vpn.example.com or an IP', 'aria-label': 'Other address' });
|
||||
const redirect = input(s.portal_redirect, { placeholder: _('Show “Not found”'), class: 'cbi-input-text dl-mono' });
|
||||
const other = input('', { placeholder: _('vpn.example.com or an IP'), 'aria-label': _('Other address') });
|
||||
const isIp = (h: string) => /^\d{1,3}(\.\d{1,3}){3}$/.test(h);
|
||||
// Chosen addresses, the main one first; custom ones join the list of options.
|
||||
let picked: string[] = [eff.portal_host, ...(eff.portal_alt ?? [])].filter(
|
||||
@@ -53,21 +54,23 @@ export function portalCard(host: SettingsHost): HTMLElement {
|
||||
|
||||
const note = (x: PortalInfo['candidates'][number]): Node =>
|
||||
x.kind === 'ip'
|
||||
? E('span', { class: 'dl-addr-warn' }, [icon('alert'), 'Plain HTTP: the link and VPN keys travel unencrypted'])
|
||||
? E('span', { class: 'dl-addr-warn' }, [icon('alert'), _('Plain HTTP: the link and VPN keys travel unencrypted')])
|
||||
: E(
|
||||
'span',
|
||||
{ class: 'dl-sub' },
|
||||
x.cloudflare
|
||||
? 'Behind Cloudflare · often stalls in Russia'
|
||||
? _('Behind Cloudflare · often stalls in Russia')
|
||||
: !x.ips.length
|
||||
? found
|
||||
? 'Your address'
|
||||
: 'Checking where it points…'
|
||||
? _('Your address')
|
||||
: _('Checking where it points…')
|
||||
: x.here
|
||||
? `Points at this router${x.cert ? ' · Let’s Encrypt certificate' : ' · no certificate yet'}`
|
||||
: `Points at ${x.ips.join(', ')}, not this router`,
|
||||
? x.cert
|
||||
? _('Points at this router · Let’s Encrypt certificate')
|
||||
: _('Points at this router · no certificate yet')
|
||||
: fmt(_('Points at %s, not this router'), x.ips.join(', ')),
|
||||
);
|
||||
const opts = E('div', { class: 'dl-addr-opts', role: 'group', 'aria-label': 'Portal addresses' });
|
||||
const opts = E('div', { class: 'dl-addr-opts', role: 'group', 'aria-label': _('Portal addresses') });
|
||||
const toggle = (h: string) => {
|
||||
if (picked.includes(h)) {
|
||||
if (picked.length > 1) picked = picked.filter((x) => x !== h);
|
||||
@@ -99,7 +102,7 @@ export function portalCard(host: SettingsHost): HTMLElement {
|
||||
E('i', { class: 'dl-addr-check' }, on ? icon('check') : ''),
|
||||
E('span', { class: 'dl-stack' }, [E('span', { class: 'dl-mono' }, x.host), note(x)]),
|
||||
main
|
||||
? E('span', { class: 'dl-pill info' }, 'Main')
|
||||
? E('span', { class: 'dl-pill info' }, _('Main'))
|
||||
: on
|
||||
? E(
|
||||
'button',
|
||||
@@ -113,14 +116,14 @@ export function portalCard(host: SettingsHost): HTMLElement {
|
||||
paintLinks();
|
||||
},
|
||||
},
|
||||
'Make main',
|
||||
_('Make main'),
|
||||
)
|
||||
: x.cloudflare
|
||||
? E('span', { class: 'dl-pill warn' }, 'Cloudflare')
|
||||
: x.kind === 'ip'
|
||||
? E('span', { class: 'dl-pill' }, 'IP')
|
||||
: x.here && x.cert
|
||||
? E('span', { class: 'dl-pill ok' }, 'Recommended')
|
||||
? E('span', { class: 'dl-pill ok' }, _('Recommended'))
|
||||
: '',
|
||||
],
|
||||
);
|
||||
@@ -128,7 +131,7 @@ export function portalCard(host: SettingsHost): HTMLElement {
|
||||
E('div', { class: 'dl-addr-opt other' }, [
|
||||
E('i', { class: 'dl-addr-check' }, icon('plus')),
|
||||
other,
|
||||
button('Add', () => {
|
||||
button(_('Add'), () => {
|
||||
const h = other.value.trim().toLowerCase();
|
||||
if (!h) return;
|
||||
// The router would refuse it on Save: say so here.
|
||||
@@ -169,7 +172,7 @@ export function portalCard(host: SettingsHost): HTMLElement {
|
||||
return E('div', { class: 'dl-link-row' }, [
|
||||
E('span', { class: `dl-link-ic ${ip ? 'warn' : 'ok'}` }, icon(ip ? 'alert' : 'lock')),
|
||||
E('span', { class: 'dl-mono dl-link-url' }, [base, E('b', {}, 'kamiro-telosu-bavine')]),
|
||||
i === 0 ? E('span', { class: 'dl-pill info' }, 'Main') : ip ? E('span', { class: 'dl-pill warn' }, 'HTTP') : '',
|
||||
i === 0 ? E('span', { class: 'dl-pill info' }, _('Main')) : ip ? E('span', { class: 'dl-pill warn' }, 'HTTP') : '',
|
||||
]);
|
||||
}),
|
||||
);
|
||||
@@ -180,18 +183,18 @@ export function portalCard(host: SettingsHost): HTMLElement {
|
||||
|
||||
// Readiness: one summary line, the checks as chips, details on demand.
|
||||
const SHORT: Record<string, string> = {
|
||||
portal: 'Portal running',
|
||||
portal_dns: 'Points here',
|
||||
portal_reply: 'Answers reach visitors',
|
||||
portal_http: 'Plain HTTP',
|
||||
cert: 'Certificate',
|
||||
portal: _('Portal running'),
|
||||
portal_dns: _('Points here'),
|
||||
portal_reply: _('Answers reach visitors'),
|
||||
portal_http: _('Plain HTTP'),
|
||||
cert: _('Certificate'),
|
||||
};
|
||||
const need = host.d.needs ?? { https: [], acme: [], home: [] };
|
||||
const readyGroup = (checks: PortalInfo['checks'] | null): HTMLElement => {
|
||||
if (!eff.portal_enabled) return E('div', { hidden: true });
|
||||
if (!checks)
|
||||
return group('check', 'Ready to share', 'The portal’s checks from Health', [
|
||||
E('p', { class: 'dl-muted dl-loading' }, 'Running checks…'),
|
||||
return group('check', _('Ready to share'), _('The portal’s checks from Health'), [
|
||||
E('p', { class: 'dl-muted dl-loading' }, _('Running checks…')),
|
||||
]);
|
||||
const shown = checks.filter((x) => x.status !== 'skip');
|
||||
if (!shown.length) return E('div', { hidden: true });
|
||||
@@ -213,11 +216,13 @@ export function portalCard(host: SettingsHost): HTMLElement {
|
||||
E(
|
||||
'b',
|
||||
{},
|
||||
worst === 'ok' ? `All ${shown.length} checks passed` : `${shown.length - bad.length} of ${shown.length} checks passed`,
|
||||
worst === 'ok'
|
||||
? plural(shown.length, 'All %s check passed', 'All %s checks passed')
|
||||
: fmt(N_(shown.length, '%s of %s check passed', '%s of %s checks passed'), num(shown.length - bad.length), num(shown.length)),
|
||||
),
|
||||
bad.length
|
||||
? E('span', { class: 'dl-sub' }, bad.map((x) => x.detail).join(' '))
|
||||
: E('span', { class: 'dl-sub' }, 'Links will open for the people you send them to.'),
|
||||
: E('span', { class: 'dl-sub' }, _('Links will open for the people you send them to.')),
|
||||
]),
|
||||
E(
|
||||
'button',
|
||||
@@ -226,10 +231,10 @@ export function portalCard(host: SettingsHost): HTMLElement {
|
||||
class: 'dl-linkbtn',
|
||||
click: (ev: Event) => {
|
||||
details.hidden = !details.hidden;
|
||||
(ev.currentTarget as HTMLElement).textContent = details.hidden ? 'Details' : 'Hide';
|
||||
(ev.currentTarget as HTMLElement).textContent = details.hidden ? _('Details') : _('Hide');
|
||||
},
|
||||
},
|
||||
'Details',
|
||||
_('Details'),
|
||||
),
|
||||
]),
|
||||
E(
|
||||
@@ -244,17 +249,17 @@ export function portalCard(host: SettingsHost): HTMLElement {
|
||||
),
|
||||
details,
|
||||
]);
|
||||
return group('check', 'Ready to share', 'The portal’s checks from Health', [ready]);
|
||||
return group('check', _('Ready to share'), _('The portal’s checks from Health'), [ready]);
|
||||
};
|
||||
// The state pill next to the switch: none until the checks are in.
|
||||
const readyPill = (checks: PortalInfo['checks'] | null): HTMLElement => {
|
||||
if (!eff.portal_enabled || (!checks && !need.https.length)) return E('span', { hidden: true });
|
||||
if (need.https.length) return E('span', { class: 'dl-pill bad' }, 'Can’t start');
|
||||
if (need.https.length) return E('span', { class: 'dl-pill bad' }, _('Can’t start'));
|
||||
const { worst } = verdict(checks!);
|
||||
return E(
|
||||
'span',
|
||||
{ class: `dl-pill ${worst === 'ok' ? 'ok' : worst === 'error' ? 'bad' : 'warn'}` },
|
||||
worst === 'error' ? 'Needs attention' : 'Ready',
|
||||
worst === 'error' ? _('Needs attention') : _('Ready'),
|
||||
);
|
||||
};
|
||||
let readyEl = readyGroup(host.portal?.checks ?? null);
|
||||
@@ -274,31 +279,31 @@ export function portalCard(host: SettingsHost): HTMLElement {
|
||||
|
||||
const until = c && !c.self_signed && c.expires ? fmtDay(c.expires) : '';
|
||||
// Who holds the port (our own portal doesn't count), and the next one while links use an IP address.
|
||||
const listenRow = liveRow('Listening port', port, () =>
|
||||
const listenRow = liveRow(_('Listening port'), port, () =>
|
||||
portalPortHelp(port.value.trim() === '' ? eff.portal_port : Number(port.value), host.d.tcp_taken ?? [], picked.some(isIp)),
|
||||
);
|
||||
refreshPort = listenRow.refresh;
|
||||
const redirectRow = liveRow('Unknown links', redirect, () => urlHelp(redirect.value));
|
||||
const redirectRow = liveRow(_('Unknown links'), redirect, () => urlHelp(redirect.value));
|
||||
const custom = !!(s.portal_cert && s.portal_key);
|
||||
const kind = !c ? 'Portal is off' : custom ? 'Your files' : c.self_signed ? 'Self-signed' : 'Let’s Encrypt';
|
||||
const kind = !c ? _('Portal is off') : custom ? _('Your files') : c.self_signed ? _('Self-signed') : 'Let’s Encrypt';
|
||||
const certFiles = () => {
|
||||
const fc = input(s.portal_cert, { placeholder: '/etc/ssl/…/fullchain.crt' });
|
||||
const fk = input(s.portal_key, { placeholder: '/etc/ssl/…/key' });
|
||||
modal(
|
||||
'Use your own certificate',
|
||||
_('Use your own certificate'),
|
||||
[
|
||||
E('p', { class: 'dl-muted' }, 'Paths on the router. Leave both empty to pick a certificate automatically.'),
|
||||
row('Certificate file', fc),
|
||||
row('Key file', fk),
|
||||
E('p', { class: 'dl-muted' }, _('Paths on the router. Leave both empty to pick a certificate automatically.')),
|
||||
row(_('Certificate file'), fc),
|
||||
row(_('Key file'), fk),
|
||||
],
|
||||
[
|
||||
cancelButton(),
|
||||
' ',
|
||||
button(
|
||||
'Save',
|
||||
_('Save'),
|
||||
() => {
|
||||
closeModal();
|
||||
void host.save({ portal_cert: fc.value.trim(), portal_key: fk.value.trim() }, 'Certificate saved', 'portal');
|
||||
void host.save({ portal_cert: fc.value.trim(), portal_key: fk.value.trim() }, _('Certificate saved'), 'portal');
|
||||
},
|
||||
'positive',
|
||||
),
|
||||
@@ -317,10 +322,13 @@ export function portalCard(host: SettingsHost): HTMLElement {
|
||||
? missingRow(
|
||||
'lock',
|
||||
'bad',
|
||||
'HTTPS isn’t available on this router',
|
||||
`The portal needs ${need.https.join(' and ')}. It can’t start without them.`,
|
||||
_('HTTPS isn’t available on this router'),
|
||||
fmt(
|
||||
_('The portal needs %s. It can’t start without them.'),
|
||||
new Intl.ListFormat(locale(), { type: 'conjunction' }).format(need.https),
|
||||
),
|
||||
'https',
|
||||
'Install',
|
||||
_('Install'),
|
||||
)
|
||||
: '';
|
||||
const acmeRow =
|
||||
@@ -328,62 +336,70 @@ export function portalCard(host: SettingsHost): HTMLElement {
|
||||
? missingRow(
|
||||
'lock',
|
||||
'',
|
||||
'Free certificate from Let’s Encrypt',
|
||||
`ACME isn’t installed. With it the router gets a certificate${s.portal_host ? ` for ${s.portal_host}` : ''} and browsers stop warning.`,
|
||||
_('Free certificate from Let’s Encrypt'),
|
||||
s.portal_host
|
||||
? fmt(_('ACME isn’t installed. With it the router gets a certificate for %s and browsers stop warning.'), s.portal_host)
|
||||
: _('ACME isn’t installed. With it the router gets a certificate and browsers stop warning.'),
|
||||
'acme',
|
||||
'Install ACME',
|
||||
_('Install ACME'),
|
||||
)
|
||||
: '';
|
||||
const certRows = [
|
||||
E('div', { class: 'dl-row' }, [
|
||||
icon('lock'),
|
||||
E('span', { class: 'dl-row-main dl-stack' }, [
|
||||
E('b', {}, [kind, until ? E('span', { class: 'dl-faint' }, ` · until ${until}`) : '']),
|
||||
E('b', {}, [kind, until ? E('span', { class: 'dl-faint' }, ` · ${fmt(_('until %s'), until)}`) : '']),
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-sub dl-ellipsis', title: c?.path ?? '' },
|
||||
!c
|
||||
? 'Turn the portal on to see its certificate.'
|
||||
? _('Turn the portal on to see its certificate.')
|
||||
: c.self_signed
|
||||
? 'Made by the router: browsers warn until a certificate covers the address.'
|
||||
: `${custom ? 'Your files' : 'Found automatically'} · ${c.path}`,
|
||||
? _('Made by the router: browsers warn until a certificate covers the address.')
|
||||
: `${custom ? _('Your files') : _('Found automatically')} · ${c.path}`,
|
||||
),
|
||||
]),
|
||||
]),
|
||||
E('div', { class: 'dl-row' }, [
|
||||
icon('file'),
|
||||
E('span', { class: 'dl-row-main dl-stack' }, [
|
||||
E('b', {}, 'Your own files'),
|
||||
E('span', { class: 'dl-sub' }, custom ? `${s.portal_cert} · ${s.portal_key}` : 'Not set: the certificate is picked automatically.'),
|
||||
E('b', {}, _('Your own files')),
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-sub' },
|
||||
custom ? `${s.portal_cert} · ${s.portal_key}` : _('Not set: the certificate is picked automatically.'),
|
||||
),
|
||||
]),
|
||||
custom ? button('Reset', () => host.save({ portal_cert: '', portal_key: '' }, 'Automatic certificate', 'portal'), 'negative') : '',
|
||||
button(custom ? 'Change' : 'Use files', certFiles),
|
||||
custom
|
||||
? button(_('Reset'), () => host.save({ portal_cert: '', portal_key: '' }, _('Automatic certificate'), 'portal'), 'negative')
|
||||
: '',
|
||||
button(custom ? _('Change') : _('Use files'), certFiles),
|
||||
]),
|
||||
acmeRow,
|
||||
];
|
||||
|
||||
return section(
|
||||
'portal',
|
||||
'Personal portal',
|
||||
_('Personal portal'),
|
||||
[
|
||||
E('span', { class: 'dl-muted' }, 'A page where each person adds and manages their devices with their personal link.'),
|
||||
E('span', { class: 'dl-muted' }, _('A page where each person adds and manages their devices with their personal link.')),
|
||||
httpsRow ? E('div', { class: 'dl-list' }, [httpsRow]) : '',
|
||||
group('network', 'Port', 'How the portal listens (80 and 443 stay free)', [listenRow]),
|
||||
group('edit', 'Appearance', 'What people see', [redirectRow]),
|
||||
group('link', 'Addresses', 'Pick one or more; the first is the main link', [
|
||||
group('network', _('Port'), _('How the portal listens (80 and 443 stay free)'), [listenRow]),
|
||||
group('edit', _('Appearance'), _('What people see'), [redirectRow]),
|
||||
group('link', _('Addresses'), _('Pick one or more; the first is the main link'), [
|
||||
opts,
|
||||
E('div', { class: 'dl-stack gap8' }, [
|
||||
links,
|
||||
E('span', { class: 'dl-sub' }, 'Example code; each person gets their own three words.'),
|
||||
E('span', { class: 'dl-sub' }, _('Example code; each person gets their own three words.')),
|
||||
]),
|
||||
]),
|
||||
group('lock', 'Certificate', 'Used for HTTPS links', certRows),
|
||||
group('lock', _('Certificate'), _('Used for HTTPS links'), certRows),
|
||||
readyEl,
|
||||
],
|
||||
[
|
||||
E('span'),
|
||||
button(
|
||||
'Save',
|
||||
_('Save'),
|
||||
() => {
|
||||
// The help lines already say what is wrong: do not send it anyway.
|
||||
const bad = firstBad([listenRow, redirectRow]);
|
||||
@@ -399,7 +415,7 @@ export function portalCard(host: SettingsHost): HTMLElement {
|
||||
portal_port: port.value,
|
||||
portal_redirect: redirect.value.trim(),
|
||||
},
|
||||
'Saved',
|
||||
_('Saved'),
|
||||
'portal',
|
||||
);
|
||||
},
|
||||
|
||||
@@ -8,48 +8,50 @@ import { chipToggle, input, isOn, seg, setChip, sw } from '../../ui/controls';
|
||||
import { row } from '../../ui/layout';
|
||||
import { notify } from '../../ui/toast';
|
||||
import { timeHelp } from '../../netcheck';
|
||||
import { fmt } from '../../../shared/i18n';
|
||||
import { section, type SettingsHost } from './common';
|
||||
|
||||
const TARGET: [string, string][] = [
|
||||
/** The components automatic updates may install: id and chip label. */
|
||||
const targetChoices = (): [string, string][] => [
|
||||
['app', 'Dawnline'],
|
||||
['amneziawg', 'AmneziaWG'],
|
||||
['packages', 'System packages'],
|
||||
['packages', _('System packages')],
|
||||
];
|
||||
|
||||
export function updatesCard(host: SettingsHost): HTMLElement {
|
||||
const u = (host.d.effective as Record<string, any>).updates as UpdatePolicy;
|
||||
const check = sw(u.check, 'Check automatically', (v) => show(v, isOn(auto)));
|
||||
const check = sw(u.check, _('Check automatically'), (v) => show(v, isOn(auto)));
|
||||
const every = seg(
|
||||
[
|
||||
['6h', 'Every 6 h'],
|
||||
['12h', 'Every 12 h'],
|
||||
['1d', 'Daily'],
|
||||
['7d', 'Weekly'],
|
||||
['6h', _('Every 6 h')],
|
||||
['12h', _('Every 12 h')],
|
||||
['1d', _('Daily')],
|
||||
['7d', _('Weekly')],
|
||||
],
|
||||
u.interval,
|
||||
{ label: 'How often', cls: 'sm' },
|
||||
{ label: _('How often'), cls: 'sm' },
|
||||
);
|
||||
const auto = sw(u.auto, 'Install automatically', (v) => show(isOn(check), v));
|
||||
const auto = sw(u.auto, _('Install automatically'), (v) => show(isOn(check), v));
|
||||
const at = input(u.time, {
|
||||
placeholder: '04:00',
|
||||
inputmode: 'numeric',
|
||||
class: 'cbi-input-text dl-w-port dl-mono',
|
||||
'aria-label': 'Time',
|
||||
'aria-label': _('Time'),
|
||||
});
|
||||
const mode = seg(
|
||||
[
|
||||
['scheduled', 'At a set time'],
|
||||
['immediate', 'As soon as found'],
|
||||
['scheduled', _('At a set time')],
|
||||
['immediate', _('As soon as found')],
|
||||
],
|
||||
u.mode,
|
||||
{ label: 'When', cls: 'sm', onChange: (v) => (at.hidden = v !== 'scheduled') },
|
||||
{ label: _('When'), cls: 'sm', onChange: (v) => (at.hidden = v !== 'scheduled') },
|
||||
);
|
||||
at.hidden = u.mode !== 'scheduled';
|
||||
const chosen = new Set<string>(u.targets);
|
||||
const targets = E(
|
||||
'div',
|
||||
{ class: 'dl-chips-row' },
|
||||
TARGET.map(([k, t]) => {
|
||||
targetChoices().map(([k, t]) => {
|
||||
const b = chipToggle(t, chosen.has(k), () => {
|
||||
if (!chosen.delete(k)) chosen.add(k);
|
||||
setChip(b, chosen.has(k));
|
||||
@@ -57,16 +59,16 @@ export function updatesCard(host: SettingsHost): HTMLElement {
|
||||
return b;
|
||||
}),
|
||||
);
|
||||
const keep = sw(u.keep, 'Keep the previous version');
|
||||
const mirrors = sw(u.mirrors, 'GitHub mirrors');
|
||||
const everyRow = row('How often', every);
|
||||
const keep = sw(u.keep, _('Keep the previous version'));
|
||||
const mirrors = sw(u.mirrors, _('GitHub mirrors'));
|
||||
const everyRow = row(_('How often'), every);
|
||||
const autoRows = [
|
||||
row(
|
||||
'When',
|
||||
_('When'),
|
||||
E('div', { class: 'dl-hostport' }, [mode, at]),
|
||||
'A set time keeps tunnel restarts out of the evening; the run happens within an hour of it.',
|
||||
_('A set time keeps tunnel restarts out of the evening; the run happens within an hour of it.'),
|
||||
),
|
||||
row('Components', targets, 'AmneziaWG is off by default: a new kernel module restarts every tunnel.'),
|
||||
row(_('Components'), targets, _('AmneziaWG is off by default: a new kernel module restarts every tunnel.')),
|
||||
];
|
||||
const show = (c: boolean, a: boolean) => {
|
||||
everyRow.hidden = !c;
|
||||
@@ -75,37 +77,37 @@ export function updatesCard(host: SettingsHost): HTMLElement {
|
||||
show(u.check, u.auto);
|
||||
return section(
|
||||
'updates',
|
||||
'Updates',
|
||||
_('Updates'),
|
||||
[
|
||||
E(
|
||||
'span',
|
||||
{ class: 'dl-muted' },
|
||||
'How Dawnline keeps its components current. Every Dawnline update makes a backup of the settings first.',
|
||||
_('How Dawnline keeps its components current. Every Dawnline update makes a backup of the settings first.'),
|
||||
),
|
||||
row(
|
||||
'Check automatically',
|
||||
_('Check automatically'),
|
||||
check,
|
||||
'Looks for new versions in the background; Components shows what it found and the service log names it.',
|
||||
_('Looks for new versions in the background; Components shows what it found and the service log names it.'),
|
||||
),
|
||||
everyRow,
|
||||
row('Install automatically', auto, 'Downloads and installs new versions of the components below.'),
|
||||
row(_('Install automatically'), auto, _('Downloads and installs new versions of the components below.')),
|
||||
...autoRows,
|
||||
row(
|
||||
'Keep the previous version',
|
||||
_('Keep the previous version'),
|
||||
keep,
|
||||
'Saves the replaced Dawnline or AmneziaWG package on flash, so Roll back works without internet. Under 1 MB.',
|
||||
_('Saves the replaced Dawnline or AmneziaWG package on flash, so Roll back works without internet. Under 1 MB.'),
|
||||
),
|
||||
row('GitHub mirrors', mirrors, 'When GitHub is unreachable, download through mirrors. Checksums are still verified.'),
|
||||
row(_('GitHub mirrors'), mirrors, _('When GitHub is unreachable, download through mirrors. Checksums are still verified.')),
|
||||
],
|
||||
[
|
||||
E('span', { class: 'dl-sub' }, 'Run a check or an update by hand in Components.'),
|
||||
E('span', { class: 'dl-sub' }, _('Run a check or an update by hand in Components.')),
|
||||
button(
|
||||
'Save',
|
||||
_('Save'),
|
||||
() => {
|
||||
if (mode.dataset.value === 'scheduled') {
|
||||
const h = timeHelp(at.value);
|
||||
if (h.bad) {
|
||||
notify(`Time: ${h.text}`, 'warning');
|
||||
notify(fmt(_('Time: %s'), h.text), 'warning');
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -120,7 +122,7 @@ export function updatesCard(host: SettingsHost): HTMLElement {
|
||||
update_keep: isOn(keep) ? '1' : '0',
|
||||
update_mirrors: isOn(mirrors) ? '1' : '0',
|
||||
},
|
||||
'Saved',
|
||||
_('Saved'),
|
||||
'updates',
|
||||
);
|
||||
},
|
||||
|
||||
+21
-13
@@ -5,18 +5,24 @@ import { api, type Needs } from './api';
|
||||
import { attempt } from './ui/toast';
|
||||
import { confirmDialog } from './ui/modal';
|
||||
import { runOperation } from './updater/operation';
|
||||
import { fmt } from '../shared/i18n';
|
||||
|
||||
const WHAT: Record<keyof Needs, string> = {
|
||||
https: 'HTTPS for the portal',
|
||||
acme: 'ACME certificates',
|
||||
home: 'the home-like link',
|
||||
awg: 'AmneziaWG',
|
||||
};
|
||||
/** What installing a feature's packages is called: the question, then the operation's title. */
|
||||
function texts(feature: keyof Needs): [string, string] {
|
||||
const t: Record<keyof Needs, [string, string]> = {
|
||||
https: [_('Install HTTPS for the portal?'), _('Installing HTTPS for the portal')],
|
||||
acme: [_('Install ACME certificates?'), _('Installing ACME certificates')],
|
||||
home: [_('Install the home-like link?'), _('Installing the home-like link')],
|
||||
awg: [_('Install AmneziaWG?'), _('Installing AmneziaWG')],
|
||||
};
|
||||
return t[feature];
|
||||
}
|
||||
|
||||
/** Ask, then wait for the job; after it `done` runs once the service had a moment to pick the packages up. */
|
||||
async function install(what: string, label: string, body: string, done?: () => void): Promise<boolean> {
|
||||
if (!(await confirmDialog(`Install ${label}?`, body, 'Install'))) return false;
|
||||
const job = await runOperation(what, { title: `Installing ${label}` });
|
||||
async function install(what: string, feature: keyof Needs, body: string, done?: () => void): Promise<boolean> {
|
||||
const [ask, title] = texts(feature);
|
||||
if (!(await confirmDialog(ask, body, _('Install')))) return false;
|
||||
const job = await runOperation(what, { title });
|
||||
if (job?.state !== 'done') return false;
|
||||
// The service restarts to pick them up; give it a moment before reloading.
|
||||
setTimeout(() => done?.(), 4000);
|
||||
@@ -31,8 +37,10 @@ async function install(what: string, label: string, body: string, done?: () => v
|
||||
export function installAwg(done?: () => void): Promise<boolean> {
|
||||
return install(
|
||||
'amneziawg:auto',
|
||||
'AmneziaWG',
|
||||
'Dawnline installs the AmneziaWG build made for this firmware and loads it. If the network service has to restart to learn it, connections drop for a few seconds.',
|
||||
'awg',
|
||||
_(
|
||||
'Dawnline installs the AmneziaWG build made for this firmware and loads it. If the network service has to restart to learn it, connections drop for a few seconds.',
|
||||
),
|
||||
done,
|
||||
);
|
||||
}
|
||||
@@ -43,8 +51,8 @@ export async function installMissing(feature: keyof Needs, names: string[], done
|
||||
if (!names.length) return true;
|
||||
return install(
|
||||
`pkgs:${names.join(',')}`,
|
||||
WHAT[feature],
|
||||
`${names.join(', ')} from the OpenWrt feeds. Dawnline sets the rest up when they arrive.`,
|
||||
feature,
|
||||
fmt(_('%s from the OpenWrt feeds. Dawnline sets the rest up when they arrive.'), names.join(', ')),
|
||||
done,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
// stays for the replay, and the replay's timeline and shimmer. No DOM here (see ./render).
|
||||
|
||||
import type { GeoPoint, LogEvent } from '../../shared/types';
|
||||
import { locale } from '../../shared/i18n';
|
||||
|
||||
/** On one client address: from a connect or a roam to the next one, a disconnect or now. */
|
||||
export interface Stretch {
|
||||
@@ -219,14 +220,14 @@ export function ticks(range: '24h' | '7d' | '30d', now: number): [number, string
|
||||
} else if (range === '7d') {
|
||||
d.setHours(12, 0, 0, 0);
|
||||
for (; d.getTime() / 1000 <= now; d.setDate(d.getDate() + 1))
|
||||
put(d.getTime() / 1000, d.toLocaleDateString('en-GB', { weekday: 'short' }));
|
||||
put(d.getTime() / 1000, d.toLocaleDateString(locale(), { weekday: 'short' }));
|
||||
} else {
|
||||
const end = new Date(now * 1000);
|
||||
end.setHours(0, 0, 0, 0);
|
||||
for (let i = 0; i < 5; i++) {
|
||||
const w = new Date(end);
|
||||
w.setDate(end.getDate() - 7 * i);
|
||||
put(w.getTime() / 1000, w.toLocaleDateString('en-GB', { day: 'numeric', month: 'short' }));
|
||||
put(w.getTime() / 1000, w.toLocaleDateString(locale(), { day: 'numeric', month: 'short' }));
|
||||
}
|
||||
out.reverse();
|
||||
}
|
||||
@@ -234,12 +235,12 @@ export function ticks(range: '24h' | '7d' | '30d', now: number): [number, string
|
||||
}
|
||||
|
||||
/** "14:05", local. */
|
||||
export const clock = (ts: number) => new Date(ts * 1000).toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' });
|
||||
export const clock = (ts: number) => new Date(ts * 1000).toLocaleTimeString(locale(), { hour: '2-digit', minute: '2-digit' });
|
||||
|
||||
/** "Today", "Yesterday" or "Wed 14 Oct" for a moment, against the router's `now`. */
|
||||
export function dayName(ts: number, now: number): string {
|
||||
const day = (x: number) => new Date(x * 1000).toDateString();
|
||||
if (day(ts) === day(now)) return 'Today';
|
||||
if (day(ts) === day(now - 86400)) return 'Yesterday';
|
||||
return new Date(ts * 1000).toLocaleDateString('en-GB', { weekday: 'short', day: 'numeric', month: 'short' });
|
||||
if (day(ts) === day(now)) return _('Today');
|
||||
if (day(ts) === day(now - 86400)) return _('Yesterday');
|
||||
return new Date(ts * 1000).toLocaleDateString(locale(), { weekday: 'short', day: 'numeric', month: 'short' });
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import type { Device, Geo, LogEvent, Person } from '../../shared/types';
|
||||
import { E } from '../e';
|
||||
import { icon } from '../../shared/icons';
|
||||
import { ago } from '../../shared/format';
|
||||
import { fmt } from '../../shared/i18n';
|
||||
import { devicePlaces, type ConnectionMap, type MapData, type Range } from '../map';
|
||||
import {
|
||||
MOVE_MS,
|
||||
@@ -63,7 +64,7 @@ export class PlacesView {
|
||||
private endTimer = 0;
|
||||
private play = E('button', { type: 'button', class: 'dl-map-btn' });
|
||||
private chip = E('span', { class: 'dl-map-chip' });
|
||||
private stop = E('button', { type: 'button', class: 'dl-map-btn', title: 'Back to now', 'aria-label': 'Back to now' }, icon('x'));
|
||||
private stop = E('button', { type: 'button', class: 'dl-map-btn', title: _('Back to now'), 'aria-label': _('Back to now') }, icon('x'));
|
||||
private reduced = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches ?? false;
|
||||
|
||||
constructor(
|
||||
@@ -137,13 +138,13 @@ export class PlacesView {
|
||||
const row = E('div', { class: 'dl-dplace-row' }, [
|
||||
E('span', { class: `dl-dplace-n${x.online ? ' live' : ''}` }, x.online ? icon(d.device.kind) : String(x.n)),
|
||||
E('span', { class: 'dl-row-main dl-stack' }, [
|
||||
E('span', {}, [x.city || x.cc || 'Unknown city', x.org ? E('span', { class: 'dl-muted' }, ` · ${x.org}`) : '']),
|
||||
E('span', {}, [x.city || x.cc || _('Unknown city'), x.org ? E('span', { class: 'dl-muted' }, ` · ${x.org}`) : '']),
|
||||
E('span', { class: 'dl-faint' }, [
|
||||
E('span', { class: 'dl-mono' }, x.ip),
|
||||
sh != null ? ` · ${sh > 0 && sh < 0.005 ? '<1' : Math.round(sh * 100)}% of the time` : '',
|
||||
sh != null ? ` · ${fmt(_('%s%% of the time'), sh > 0 && sh < 0.005 ? '<1' : Math.round(sh * 100))}` : '',
|
||||
]),
|
||||
]),
|
||||
E('span', { class: x.online ? 'dl-dplace-now' : 'dl-faint dl-nowrap' }, x.online ? 'now' : ago(x.ts, d.now)),
|
||||
E('span', { class: x.online ? 'dl-dplace-now' : 'dl-faint dl-nowrap' }, x.online ? _('now') : ago(x.ts, d.now)),
|
||||
strip,
|
||||
]);
|
||||
row.addEventListener('mouseenter', () => this.map.hoverPlace(key));
|
||||
@@ -173,14 +174,14 @@ export class PlacesView {
|
||||
)
|
||||
: '',
|
||||
]
|
||||
: E('div', { class: 'dl-sub' }, 'No locations in this period.'),
|
||||
: E('div', { class: 'dl-sub' }, _('No locations in this period.')),
|
||||
);
|
||||
this.paintControls();
|
||||
}
|
||||
|
||||
private paintControls() {
|
||||
dom.content(this.play, icon(this.playing ? 'pause' : 'play'));
|
||||
this.play.title = this.playing ? 'Pause' : 'Replay this period';
|
||||
this.play.title = this.playing ? _('Pause', 'replay') : _('Replay this period');
|
||||
this.play.setAttribute('aria-label', this.play.title);
|
||||
// LuCI's dom.content takes one level of children: no nested arrays.
|
||||
dom.content(this.controls, this.on ? [this.play, this.chip, this.stop] : this.st.length > 1 ? [this.play] : []);
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
|
||||
import { api } from '../api';
|
||||
import { notify } from '../ui/toast';
|
||||
import { fmt } from '../../shared/i18n';
|
||||
|
||||
const EVERY = 2;
|
||||
|
||||
@@ -22,7 +23,7 @@ async function tick(): Promise<void> {
|
||||
// and RPC shapes may not match any more.
|
||||
if (r.version) {
|
||||
if (version && r.version !== version) {
|
||||
notify(`Dawnline was updated to ${r.version}: reload the page.`, 'warning', 15000);
|
||||
notify(fmt(_('Dawnline was updated to %s: reload the page.'), r.version), 'warning', 15000);
|
||||
version = null;
|
||||
} else version ??= r.version;
|
||||
}
|
||||
|
||||
@@ -64,10 +64,10 @@ export function createPoller<T>(o: PollerOptions<T>): Poller<T> {
|
||||
let d: T | null = null;
|
||||
try {
|
||||
d = await o.fetch(live);
|
||||
if (failed >= LOST_AFTER) notify('The router answers again.', 'success', 3000);
|
||||
if (failed >= LOST_AFTER) notify(_('The router answers again.'), 'success', 3000);
|
||||
failed = 0;
|
||||
} catch {
|
||||
if (++failed === LOST_AFTER) notify('The router is not answering: what you see may be out of date.', 'warning', 8000);
|
||||
if (++failed === LOST_AFTER) notify(_('The router is not answering: what you see may be out of date.'), 'warning', 8000);
|
||||
return null;
|
||||
}
|
||||
if (d == null || !seq.take(t)) return null;
|
||||
|
||||
+27
-22
@@ -3,7 +3,8 @@
|
||||
import type { Device, Person } from '../../shared/types';
|
||||
import { E } from '../e';
|
||||
import { icon } from '../../shared/icons';
|
||||
import { ACCESS_LABEL, STATE_LABEL, ago } from '../../shared/format';
|
||||
import { accessLabel, stateLabel, ago } from '../../shared/format';
|
||||
import { fmt, locale, plural } from '../../shared/i18n';
|
||||
import { attachTip } from './tooltip';
|
||||
|
||||
export function pill(tone: string, text: string, title?: string): HTMLElement {
|
||||
@@ -29,7 +30,7 @@ function ownState(p: Person): Person['state'] {
|
||||
export function statePill(p: Person): HTMLElement | '' {
|
||||
const s = ownState(p);
|
||||
if (s === 'active' || s === 'server_off') return '';
|
||||
return pill(stateTone({ ...p, state: s }), STATE_LABEL[s]);
|
||||
return pill(stateTone({ ...p, state: s }), stateLabel(s));
|
||||
}
|
||||
|
||||
/** What the person can reach, as icons: home network, internet, or both. */
|
||||
@@ -37,27 +38,30 @@ export function accessBadge(p: Person): HTMLElement {
|
||||
const kinds = p.access === 'both' ? ['lan', 'inet'] : p.access === 'lan' ? ['lan'] : ['inet'];
|
||||
const el = E(
|
||||
'span',
|
||||
{ class: 'dl-access', 'aria-label': ACCESS_LABEL[p.access] },
|
||||
{ class: 'dl-access', 'aria-label': accessLabel(p.access) },
|
||||
kinds.map((k) => E('span', { class: `dl-ibadge ${k}` }, icon(k === 'lan' ? 'home' : 'globe'))),
|
||||
);
|
||||
attachTip(el, () => [
|
||||
E('div', { class: 'dl-tip-title' }, ACCESS_LABEL[p.access]),
|
||||
E('div', { class: 'dl-tip-title' }, accessLabel(p.access)),
|
||||
p.access === 'lan' && p.services?.length
|
||||
? E('div', { class: 'dl-muted' }, `${p.services.length} home service${p.services.length === 1 ? '' : 's'} only`)
|
||||
? E('div', { class: 'dl-muted' }, plural(p.services.length, '%s home service only', '%s home services only'))
|
||||
: '',
|
||||
]);
|
||||
return el;
|
||||
}
|
||||
|
||||
/** Why a person's devices cannot connect right now, in two words. */
|
||||
const STOPPED: Partial<Record<Person['state'], string>> = {
|
||||
paused: 'Paused',
|
||||
expired: 'Access ended',
|
||||
quota: 'Data limit',
|
||||
hours: 'Outside hours',
|
||||
server_off: 'Server off',
|
||||
no_server: 'No server',
|
||||
};
|
||||
/** Why a person's devices cannot connect right now, in two words; null while they can. */
|
||||
function stoppedLabel(s: Person['state']): string | null {
|
||||
return {
|
||||
active: null,
|
||||
paused: _('Paused'),
|
||||
expired: _('Access ended'),
|
||||
quota: _('Data limit'),
|
||||
hours: _('Outside hours'),
|
||||
server_off: _('Server off'),
|
||||
no_server: _('No server'),
|
||||
}[s];
|
||||
}
|
||||
|
||||
/**
|
||||
* A device's status as coloured text, no dots (only avatars carry one). `now`
|
||||
@@ -65,12 +69,13 @@ const STOPPED: Partial<Record<Person['state'], string>> = {
|
||||
* With the person, a device that cannot come back says why ("Paused",
|
||||
* "Data limit") instead of a "Last seen" that reads like it might.
|
||||
*/
|
||||
export function deviceStatus(d: Device, now?: number, waiting = 'Not set up yet', p?: Person): HTMLElement {
|
||||
const seen = d.handshake ? `Last seen ${ago(d.handshake, now)} · ${new Date(d.handshake * 1000).toLocaleString()}` : '';
|
||||
if (d.disabled) return E('span', { class: 'dl-dstat', title: seen }, 'Disabled');
|
||||
if (d.online) return E('span', { class: 'dl-dstat ok' }, 'Connected');
|
||||
const why = p && STOPPED[p.state];
|
||||
if (why) return E('span', { class: 'dl-dstat warn', title: seen || 'Not connected yet' }, why);
|
||||
if (!d.handshake) return E('span', { class: 'dl-dstat warn', title: 'Waiting for the first connection' }, waiting);
|
||||
return E('span', { class: 'dl-dstat', title: new Date(d.handshake * 1000).toLocaleString() }, `Last seen ${ago(d.handshake, now)}`);
|
||||
export function deviceStatus(d: Device, now?: number, waiting = _('Not set up yet'), p?: Person): HTMLElement {
|
||||
const at = new Date(d.handshake * 1000).toLocaleString(locale());
|
||||
const seen = d.handshake ? `${fmt(_('Last seen %s'), ago(d.handshake, now))} · ${at}` : '';
|
||||
if (d.disabled) return E('span', { class: 'dl-dstat', title: seen }, _('Disabled'));
|
||||
if (d.online) return E('span', { class: 'dl-dstat ok' }, _('Connected'));
|
||||
const why = p && stoppedLabel(p.state);
|
||||
if (why) return E('span', { class: 'dl-dstat warn', title: seen || _('Not connected yet') }, why);
|
||||
if (!d.handshake) return E('span', { class: 'dl-dstat warn', title: _('Waiting for the first connection') }, waiting);
|
||||
return E('span', { class: 'dl-dstat', title: at }, fmt(_('Last seen %s'), ago(d.handshake, now)));
|
||||
}
|
||||
@@ -17,7 +17,7 @@ export function drawer(title: Node, body: Node, foot: Node | null, onClose: () =
|
||||
const panel = E('aside', { class: 'dl-drawer', role: 'dialog', 'aria-modal': 'true' }, [
|
||||
E('div', { class: 'dl-drawer-head' }, [
|
||||
title,
|
||||
E('button', { type: 'button', class: 'dl-drawer-x', 'aria-label': 'Close', click: () => close() }, icon('x')),
|
||||
E('button', { type: 'button', class: 'dl-drawer-x', 'aria-label': _('Close'), click: () => close() }, icon('x')),
|
||||
]),
|
||||
E('div', { class: 'dl-drawer-body' }, body),
|
||||
foot ? E('div', { class: 'dl-drawer-foot' }, foot) : '',
|
||||
|
||||
@@ -9,7 +9,7 @@ import { errorText, notify } from './toast';
|
||||
* refuse a write outside the click that started it (Safari after an await),
|
||||
* and then nothing is said — the link is on screen with its own Copy button.
|
||||
*/
|
||||
export async function copyText(text: string, what = 'Copied to clipboard', quiet = false): Promise<boolean> {
|
||||
export async function copyText(text: string, what = _('Copied to clipboard'), quiet = false): Promise<boolean> {
|
||||
try {
|
||||
if (navigator.clipboard && window.isSecureContext) {
|
||||
await navigator.clipboard.writeText(text);
|
||||
@@ -19,7 +19,7 @@ export async function copyText(text: string, what = 'Copied to clipboard', quiet
|
||||
ta.select();
|
||||
const ok = document.execCommand('copy');
|
||||
ta.remove();
|
||||
if (!ok) throw new Error('Copying is blocked here. Select the text and copy it by hand.');
|
||||
if (!ok) throw new Error(_('Copying is blocked here. Select the text and copy it by hand.'));
|
||||
}
|
||||
notify(what, 'success', 2500);
|
||||
return true;
|
||||
|
||||
@@ -46,7 +46,7 @@ export function closeModal() {
|
||||
}
|
||||
|
||||
/** "Cancel" (or another label) that closes the modal. */
|
||||
export function cancelButton(label = 'Cancel', danger = false): HTMLElement {
|
||||
export function cancelButton(label = _('Cancel'), danger = false): HTMLElement {
|
||||
return E(
|
||||
'button',
|
||||
{ class: `cbi-button ${danger ? 'cbi-button-negative' : 'cbi-button-neutral'}`, type: 'button', click: closeModal },
|
||||
@@ -54,7 +54,7 @@ export function cancelButton(label = 'Cancel', danger = false): HTMLElement {
|
||||
);
|
||||
}
|
||||
|
||||
export function confirmDialog(title: string, body: Child, confirmLabel = 'Confirm', danger = false): Promise<boolean> {
|
||||
export function confirmDialog(title: string, body: Child, confirmLabel = _('Confirm'), danger = false): Promise<boolean> {
|
||||
return new Promise((resolve) => {
|
||||
modal(title, body, [
|
||||
cancelButton(),
|
||||
|
||||
@@ -22,13 +22,14 @@ export function notify(message: Child, tone: Tone = 'info', timeout = 0) {
|
||||
const t = E('div', { class: `dl-toast ${tone}` }, [
|
||||
ic ? icon(ic) : '',
|
||||
E('span', {}, message),
|
||||
tone === 'error' ? E('button', { type: 'button', 'aria-label': 'Close', click: close }, icon('x')) : '',
|
||||
tone === 'error' ? E('button', { type: 'button', 'aria-label': _('Close'), click: close }, icon('x')) : '',
|
||||
]);
|
||||
stack.appendChild(t);
|
||||
requestAnimationFrame(() => t.classList.add('show'));
|
||||
setTimeout(close, timeout || (tone === 'error' ? 8000 : tone === 'warning' ? 5000 : 2600));
|
||||
}
|
||||
|
||||
/** A failure's message as it came: the router's own text for RPC failures. */
|
||||
export function errorText(e: unknown): string {
|
||||
return e instanceof Error ? e.message : String(e);
|
||||
}
|
||||
|
||||
@@ -2,13 +2,14 @@
|
||||
// timer and what a finished check found. Pure (no DOM, no RPC).
|
||||
|
||||
import type { UpdateJob, UpdatesStatus } from '../api';
|
||||
import { fmt, plural } from '../../shared/i18n';
|
||||
|
||||
export const NAME: Record<string, string> = {
|
||||
app: 'Dawnline',
|
||||
amneziawg: 'AmneziaWG',
|
||||
packages: 'System packages',
|
||||
pkgs: 'System packages',
|
||||
};
|
||||
/** A component's name in words; undefined for "all" and unknown ones. */
|
||||
export function componentName(comp: string): string | undefined {
|
||||
if (comp === 'app') return 'Dawnline';
|
||||
if (comp === 'amneziawg') return 'AmneziaWG';
|
||||
return comp === 'packages' || comp === 'pkgs' ? _('System packages') : undefined;
|
||||
}
|
||||
|
||||
/** "app@0.3.1" → "app"; "check:amneziawg" → "amneziawg"; "check" → "all"; "pkgs:a,b" → "pkgs". */
|
||||
export function jobComponent(what: string): string {
|
||||
@@ -49,17 +50,17 @@ export function checkVerdict(st: Pick<UpdatesStatus, 'check'>, comp: string): Ve
|
||||
const c = all[k];
|
||||
if (!c) continue;
|
||||
if (c.error) return { tone: 'warn', text: c.error };
|
||||
if (k === 'packages' && c.updates) found.push(`${c.updates} system package${c.updates === 1 ? '' : 's'}`);
|
||||
if (k === 'packages' && c.updates) found.push(plural(c.updates, '%s system package', '%s system packages'));
|
||||
else if (k !== 'packages' && c.update && c.installed && c.latest) {
|
||||
found.push(`${NAME[k]} ${c.latest}`);
|
||||
found.push(`${componentName(k)} ${c.latest}`);
|
||||
if (comp !== 'all') update = c.latest;
|
||||
}
|
||||
}
|
||||
if (found.length) return { tone: 'acc', text: `Update available: ${found.join(', ')}`, update };
|
||||
if (found.length) return { tone: 'acc', text: fmt(_('Update available: %s'), found.join(', ')), update };
|
||||
const one = list.length === 1 ? all[list[0]] : null;
|
||||
if (one?.status === 'dev') return { tone: 'acc', text: `Installed version is newer than the release (${one.latest})` };
|
||||
if (one?.status === 'dev') return { tone: 'acc', text: fmt(_('Installed version is newer than the release (%s)'), one.latest) };
|
||||
if (one?.note) return { tone: 'warn', text: one.note };
|
||||
return { tone: 'ok', text: list.length > 1 ? 'Everything is up to date' : 'Latest version is installed' };
|
||||
return { tone: 'ok', text: list.length > 1 ? _('Everything is up to date') : _('Latest version is installed') };
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -11,13 +11,13 @@ import { errorText } from '../ui/toast';
|
||||
import { forRouter, markdown, safeHref } from './markdown';
|
||||
|
||||
export async function whatsNew(component: 'app' | 'amneziawg', tag: string, title: string, build?: string) {
|
||||
const body = E('div', { class: 'dl-notes' }, E('p', { class: 'dl-muted dl-loading' }, 'Loading release notes…'));
|
||||
const body = E('div', { class: 'dl-notes' }, E('p', { class: 'dl-muted dl-loading' }, _('Loading release notes…')));
|
||||
const meta = E('div', { class: 'dl-op-head' });
|
||||
let text = '';
|
||||
modal(
|
||||
title,
|
||||
[meta, body],
|
||||
[button([icon('copy'), ' Copy'], () => copyText(text, 'Release notes copied')), ' ', cancelButton('Close')],
|
||||
[button([icon('copy'), ' ', _('Copy')], () => copyText(text, _('Release notes copied'))), ' ', cancelButton(_('Close'))],
|
||||
'wide',
|
||||
);
|
||||
try {
|
||||
@@ -26,11 +26,11 @@ export async function whatsNew(component: 'app' | 'amneziawg', tag: string, titl
|
||||
const href = safeHref(r.url);
|
||||
dom.content(meta, [
|
||||
r.published ? E('span', { class: 'dl-pill' }, fmtDay(r.published)) : '',
|
||||
r.prerelease ? E('span', { class: 'dl-pill warn' }, 'Pre-release') : '',
|
||||
r.prerelease ? E('span', { class: 'dl-pill warn' }, _('Pre-release')) : '',
|
||||
E('span', { class: 'dl-spacer' }),
|
||||
href ? E('a', { href, target: '_blank', rel: 'noopener', class: 'dl-linkbtn' }, ['On GitHub ', icon('open')]) : '',
|
||||
href ? E('a', { href, target: '_blank', rel: 'noopener', class: 'dl-linkbtn' }, [_('On GitHub'), ' ', icon('open')]) : '',
|
||||
]);
|
||||
dom.content(body, text.trim() ? markdown(text) : E('p', { class: 'dl-muted' }, 'This release has no notes.'));
|
||||
dom.content(body, text.trim() ? markdown(text) : E('p', { class: 'dl-muted' }, _('This release has no notes.')));
|
||||
} catch (e) {
|
||||
dom.content(body, E('p', { class: 'dl-muted' }, errorText(e)));
|
||||
}
|
||||
|
||||
@@ -9,7 +9,8 @@ import { button, iconButton } from '../ui/button';
|
||||
import { cancelButton, closeModal, modal } from '../ui/modal';
|
||||
import { copyText } from '../ui/files';
|
||||
import { errorText, notify } from '../ui/toast';
|
||||
import { NAME, checkVerdict, isOurJob, jobComponent, mmss, runningComponent, verText } from './jobs';
|
||||
import { fmt } from '../../shared/i18n';
|
||||
import { checkVerdict, componentName, isOurJob, jobComponent, mmss, runningComponent, verText } from './jobs';
|
||||
|
||||
export interface OpOptions {
|
||||
/** Modal title, e.g. "Updating Dawnline". */
|
||||
@@ -35,16 +36,16 @@ export async function runOperation(what: string | null, o: OpOptions, follow?: U
|
||||
const comp = follow ? runningComponent(follow) : jobComponent(what!);
|
||||
const isCheck = follow ? follow.action === 'check' : what!.startsWith('check');
|
||||
const opened = Date.now();
|
||||
const name = E('b', {}, NAME[comp] ?? (comp === 'all' ? 'All components' : 'Dawnline'));
|
||||
const name = E('b', {}, componentName(comp) ?? (comp === 'all' ? _('All components') : 'Dawnline'));
|
||||
const ver = E('span', { class: 'dl-pill dl-mono' }, o.version ?? '');
|
||||
const phase = E('span', { class: 'dl-pill info', hidden: true });
|
||||
const timer = E('span', {}, '0:00');
|
||||
const log = E('pre', { class: 'dl-log' }, 'Operation started. Waiting for log output…');
|
||||
const log = E('pre', { class: 'dl-log' }, _('Operation started. Waiting for log output…'));
|
||||
const result = E('div', {});
|
||||
const actions = E('div', { class: 'dl-op-actions' });
|
||||
let lines: string[] = [];
|
||||
const setActions = (nodes: Node[]) => dom.content(actions, nodes);
|
||||
const closeBtn = (danger = false) => cancelButton('Close', danger);
|
||||
const closeBtn = (danger = false) => cancelButton(_('Close'), danger);
|
||||
|
||||
modal(
|
||||
o.title,
|
||||
@@ -57,8 +58,8 @@ export async function runOperation(what: string | null, o: OpOptions, follow?: U
|
||||
E('span', { class: 'dl-faint dl-op-timer' }, [icon('clock'), timer]),
|
||||
]),
|
||||
E('div', { class: 'dl-op-loghead' }, [
|
||||
E('b', {}, 'Operation log'),
|
||||
iconButton('copy', 'Copy log', () => copyText(lines.join('\n'), 'Log copied')),
|
||||
E('b', {}, _('Operation log')),
|
||||
iconButton('copy', _('Copy log'), () => copyText(lines.join('\n'), _('Log copied'))),
|
||||
]),
|
||||
log,
|
||||
result,
|
||||
@@ -70,7 +71,7 @@ export async function runOperation(what: string | null, o: OpOptions, follow?: U
|
||||
E(
|
||||
'button',
|
||||
{ class: 'cbi-button cbi-button-neutral spinning', type: 'button', disabled: 'disabled' },
|
||||
isCheck ? 'Checking…' : 'Working…',
|
||||
isCheck ? _('Checking…') : _('Working…'),
|
||||
),
|
||||
]);
|
||||
|
||||
@@ -144,12 +145,12 @@ export async function runOperation(what: string | null, o: OpOptions, follow?: U
|
||||
phase.hidden = false;
|
||||
if (!job || job.state === 'running') {
|
||||
phase.className = 'dl-pill warn';
|
||||
phase.textContent = 'No answer';
|
||||
phase.textContent = _('No answer');
|
||||
dom.content(
|
||||
result,
|
||||
E('div', { class: 'dl-comp-status warn' }, [
|
||||
icon('alert'),
|
||||
E('span', {}, 'The router stopped answering. The job may still finish: reopen Components in a minute.'),
|
||||
E('span', {}, _('The router stopped answering. The job may still finish: reopen Components in a minute.')),
|
||||
]),
|
||||
);
|
||||
setActions([closeBtn()]);
|
||||
@@ -158,21 +159,25 @@ export async function runOperation(what: string | null, o: OpOptions, follow?: U
|
||||
}
|
||||
if (job.state === 'failed') {
|
||||
phase.className = 'dl-pill bad';
|
||||
phase.textContent = 'Failed';
|
||||
phase.textContent = _('Failed');
|
||||
dom.content(
|
||||
result,
|
||||
E('div', { class: 'dl-comp-status bad' }, [
|
||||
icon('x'),
|
||||
E('span', {}, [E('b', {}, job.error ?? 'Operation failed'), isCheck ? '' : '. Nothing else was changed.']),
|
||||
// The router's error may end its own sentence: one full stop either way.
|
||||
E('span', {}, [
|
||||
E('b', {}, (job.error ?? _('Operation failed')).replace(/\.$/, '')),
|
||||
isCheck ? '' : `. ${_('Nothing else was changed.')}`,
|
||||
]),
|
||||
]),
|
||||
);
|
||||
setActions([button('Copy log', () => copyText(lines.join('\n'), 'Log copied')), closeBtn(true)]);
|
||||
notify(`${NAME[comp] ?? 'Update'}: ${job.error ?? 'failed'}`, 'error');
|
||||
setActions([button(_('Copy log'), () => copyText(lines.join('\n'), _('Log copied'))), closeBtn(true)]);
|
||||
notify(`${componentName(comp) ?? _('Update', 'noun')}: ${job.error ?? _('failed')}`, 'error');
|
||||
o.onDone?.(st);
|
||||
return job;
|
||||
}
|
||||
phase.className = 'dl-pill ok';
|
||||
phase.textContent = 'Finished';
|
||||
phase.textContent = _('Finished');
|
||||
if (isCheck && st) {
|
||||
const v = checkVerdict(st, comp);
|
||||
dom.content(
|
||||
@@ -186,7 +191,7 @@ export async function runOperation(what: string | null, o: OpOptions, follow?: U
|
||||
o.onDone?.(st);
|
||||
if (v.update && o.onUpdate) {
|
||||
const s = st;
|
||||
setActions([closeBtn(), button(`Update to ${v.update}`, () => o.onUpdate!(s), 'positive')]);
|
||||
setActions([closeBtn(), button(fmt(_('Update to %s'), v.update), () => o.onUpdate!(s), 'positive')]);
|
||||
} else {
|
||||
setActions([closeBtn()]);
|
||||
// Nothing to do: the modal goes away on its own (as in the check toast).
|
||||
@@ -194,39 +199,71 @@ export async function runOperation(what: string | null, o: OpOptions, follow?: U
|
||||
}
|
||||
return job;
|
||||
}
|
||||
// The admin's translation: LuCI's web server restarts two seconds after the
|
||||
// job to read it (or forget it); the page then reloads in its new language.
|
||||
const lang = /^app:(lang:|nolang$)/.exec(job.component ?? '');
|
||||
if (lang) {
|
||||
const reload = () => {
|
||||
ui.menu?.flushCache();
|
||||
location.reload();
|
||||
};
|
||||
dom.content(
|
||||
result,
|
||||
E('div', { class: 'dl-comp-status ok' }, [
|
||||
icon('check'),
|
||||
E('span', {}, [
|
||||
E('b', {}, lang[1] === 'nolang' ? _('The translation is removed.') : _('The translation is installed.')),
|
||||
' ',
|
||||
_('Reloading the page…'),
|
||||
]),
|
||||
]),
|
||||
);
|
||||
setActions([closeBtn(), button(_('Reload now'), reload, 'positive')]);
|
||||
await sleep(4000);
|
||||
if (result.isConnected) reload();
|
||||
return job;
|
||||
}
|
||||
// Dawnline itself: rpcd and the service restart; reload the page once they answer with the new version.
|
||||
if (comp === 'app' && job.to) {
|
||||
const target = job.to;
|
||||
const msg = E('span', {}, 'Waiting for the router to restart its services…');
|
||||
const msg = E('span', {}, _('Waiting for the router to restart its services…'));
|
||||
dom.content(
|
||||
result,
|
||||
E('div', { class: 'dl-comp-status ok' }, [icon('check'), E('span', {}, [E('b', {}, `Dawnline ${target} is installed. `), msg])]),
|
||||
E('div', { class: 'dl-comp-status ok' }, [
|
||||
icon('check'),
|
||||
E('span', {}, [E('b', {}, fmt(_('Dawnline %s is installed.'), target)), ' ', msg]),
|
||||
]),
|
||||
);
|
||||
const reload = () => {
|
||||
ui.menu?.flushCache();
|
||||
location.reload();
|
||||
};
|
||||
setActions([closeBtn(), button('Reload now', reload, 'positive')]);
|
||||
notify(`Dawnline updated to ${target}`, 'success', 6000);
|
||||
setActions([closeBtn(), button(_('Reload now'), reload, 'positive')]);
|
||||
notify(fmt(_('Dawnline updated to %s'), target), 'success', 6000);
|
||||
for (let n = 1; n <= 30; n++) {
|
||||
msg.textContent = `Waiting for the router to restart its services (${n} of 30)…`;
|
||||
msg.textContent = fmt(_('Waiting for the router to restart its services (%s of 30)…'), n);
|
||||
await sleep(1500);
|
||||
const s = await api.updatesStatus().catch(() => null);
|
||||
if (s?.version === target) {
|
||||
msg.textContent = 'Services are back. Reloading…';
|
||||
msg.textContent = _('Services are back. Reloading…');
|
||||
setTimeout(reload, 800);
|
||||
return job;
|
||||
}
|
||||
}
|
||||
msg.textContent = 'Services restarted. Reload the page to use the new version.';
|
||||
msg.textContent = _('Services restarted. Reload the page to use the new version.');
|
||||
return job;
|
||||
}
|
||||
const changed = [...((job.result?.pkgs?.updated as string[]) ?? []), ...((job.result?.pkgs?.installed as string[]) ?? [])];
|
||||
const done =
|
||||
comp === 'pkgs'
|
||||
? `Updated ${[...((job.result?.pkgs?.updated as string[]) ?? []), ...((job.result?.pkgs?.installed as string[]) ?? [])].join(', ') || 'system packages'}`
|
||||
? changed.length
|
||||
? fmt(_('Updated %s'), changed.join(', '))
|
||||
: _('Updated system packages')
|
||||
: comp === 'amneziawg'
|
||||
? `AmneziaWG${job.to ? ` ${job.to}` : ''} is installed`
|
||||
: 'Operation completed';
|
||||
? job.to
|
||||
? fmt(_('AmneziaWG %s is installed'), job.to)
|
||||
: _('AmneziaWG is installed')
|
||||
: _('Operation completed');
|
||||
dom.content(result, E('div', { class: 'dl-comp-status ok' }, [icon('check'), E('span', {}, done)]));
|
||||
setActions([closeBtn()]);
|
||||
notify(done, 'success');
|
||||
|
||||
@@ -3,15 +3,15 @@
|
||||
import type { Person } from '../../shared/types';
|
||||
import { E } from '../e';
|
||||
import { icon } from '../../shared/icons';
|
||||
import { ACCESS_LABEL } from '../../shared/format';
|
||||
import { accessLabel } from '../../shared/format';
|
||||
|
||||
/** Returns the element and a getter. */
|
||||
export function accessPicker(initial: Person['access'], onChange?: (v: Person['access']) => void) {
|
||||
let value = initial;
|
||||
const opts: { v: Person['access']; ic: string; text: string }[] = [
|
||||
{ v: 'internet', ic: 'globe', text: 'Browse the internet through your router. No access to devices at home.' },
|
||||
{ v: 'lan', ic: 'home', text: 'Reach devices at home (NAS, printer, cameras). Internet stays on their own connection.' },
|
||||
{ v: 'both', ic: 'shield', text: 'Home devices and the internet, all through your router.' },
|
||||
{ v: 'internet', ic: 'globe', text: _('Browse the internet through your router. No access to devices at home.') },
|
||||
{ v: 'lan', ic: 'home', text: _('Reach devices at home (NAS, printer, cameras). Internet stays on their own connection.') },
|
||||
{ v: 'both', ic: 'shield', text: _('Home devices and the internet, all through your router.') },
|
||||
];
|
||||
const el = E(
|
||||
'div',
|
||||
@@ -29,7 +29,7 @@ export function accessPicker(initial: Person['access'], onChange?: (v: Person['a
|
||||
onChange?.(o.v);
|
||||
},
|
||||
},
|
||||
[E('span', { class: 'dl-choice-title' }, [icon(o.ic), ACCESS_LABEL[o.v]]), E('span', { class: 'dl-choice-text' }, o.text)],
|
||||
[E('span', { class: 'dl-choice-title' }, [icon(o.ic), accessLabel(o.v)]), E('span', { class: 'dl-choice-text' }, o.text)],
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -10,23 +10,32 @@ import { button, type ButtonKind } from '../ui/button';
|
||||
import { confirmDialog } from '../ui/modal';
|
||||
import { attempt } from '../ui/toast';
|
||||
import { needRow } from '../ui/layout';
|
||||
import { fmt, num } from '../../shared/i18n';
|
||||
|
||||
const FIX_LABEL: Record<string, string> = {
|
||||
apply: 'Repair',
|
||||
sync: 'Reload devices',
|
||||
restart: 'Restart service',
|
||||
netrestart: 'Restart network',
|
||||
updates: 'Open Components',
|
||||
};
|
||||
/** The button of a backend fix, by its id. */
|
||||
function fixLabel(fix: string): string {
|
||||
const labels: Record<string, string> = {
|
||||
apply: _('Repair'),
|
||||
sync: _('Reload devices'),
|
||||
restart: _('Restart service'),
|
||||
netrestart: _('Restart network'),
|
||||
updates: _('Open Components'),
|
||||
};
|
||||
return labels[fix] ?? _('Fix');
|
||||
}
|
||||
|
||||
/** Run a backend fix (a network restart asks first); the checks again, or null. */
|
||||
export async function runFix(fix: string): Promise<Health | null> {
|
||||
if (
|
||||
fix === 'netrestart' &&
|
||||
!(await confirmDialog('Restart the network?', 'Every interface restarts. Connections drop for a few seconds.', 'Restart network'))
|
||||
!(await confirmDialog(
|
||||
_('Restart the network?'),
|
||||
_('Every interface restarts. Connections drop for a few seconds.'),
|
||||
_('Restart network'),
|
||||
))
|
||||
)
|
||||
return null;
|
||||
return (await attempt(() => api.healthFix(fix), 'Done')) ?? null;
|
||||
return (await attempt(() => api.healthFix(fix), _('Done'))) ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -37,10 +46,10 @@ export function fixAction(c: HealthCheck, run: (fix: string) => void, refresh: (
|
||||
const fix = c.fix;
|
||||
if (!fix) return '';
|
||||
// install:awg installs AmneziaWG itself (the build for this firmware), the rest come from the feeds.
|
||||
if (fix.startsWith('install:')) return button('Install', () => installFeature(fix.slice(8) as keyof Needs, refresh), kind);
|
||||
if (fix.startsWith('install:')) return button(_('Install'), () => installFeature(fix.slice(8) as keyof Needs, refresh), kind);
|
||||
if (fix === 'updates')
|
||||
return E('a', { class: `cbi-button cbi-button-${kind}`, href: L.url('admin/network/dawnline/updates') }, FIX_LABEL.updates);
|
||||
return button(FIX_LABEL[fix] ?? 'Fix', () => run(fix), kind);
|
||||
return E('a', { class: `cbi-button cbi-button-${kind}`, href: L.url('admin/network/dawnline/updates') }, fixLabel(fix));
|
||||
return button(fixLabel(fix), () => run(fix), kind);
|
||||
}
|
||||
|
||||
/** The icon tile of a check's notice, by what it is about. */
|
||||
@@ -69,6 +78,7 @@ export function healthNotices(checks: HealthCheck[], run: (fix: string) => void,
|
||||
return E('div', { class: 'dl-list dl-notices' }, [
|
||||
...bad
|
||||
.slice(0, max)
|
||||
// The check's problem, title and detail come from the router.
|
||||
.map((c) =>
|
||||
needRow(
|
||||
checkIcon(c.id),
|
||||
@@ -80,7 +90,7 @@ export function healthNotices(checks: HealthCheck[], run: (fix: string) => void,
|
||||
),
|
||||
rest > 0
|
||||
? E('a', { class: 'dl-row dl-notices-more', href: L.url('admin/network/dawnline/diagnostics') }, [
|
||||
`${rest} more in Diagnostics`,
|
||||
fmt(_('%s more in Diagnostics'), num(rest)),
|
||||
E('span', { class: 'dl-spacer' }),
|
||||
'→',
|
||||
])
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import { E } from '../e';
|
||||
import { addDays, bytes, isoDay, parseDay } from '../../shared/format';
|
||||
import { attachTip } from '../ui/tooltip';
|
||||
import { locale } from '../../shared/i18n';
|
||||
|
||||
/** `today` is the router's day (YYYY-MM-DD), so the labels follow its calendar. */
|
||||
export function spark(values: number[], width = 120, height = 26, today = isoDay(new Date())): HTMLElement {
|
||||
@@ -20,10 +21,10 @@ export function spark(values: number[], width = 120, height = 26, today = isoDay
|
||||
'div',
|
||||
{ class: 'dl-tip-title' },
|
||||
back === 0
|
||||
? 'Today'
|
||||
? _('Today')
|
||||
: back === 1
|
||||
? 'Yesterday'
|
||||
: parseDay(addDays(today, -back)).toLocaleDateString('en-GB', { weekday: 'short', day: 'numeric', month: 'short' }),
|
||||
? _('Yesterday')
|
||||
: parseDay(addDays(today, -back)).toLocaleDateString(locale(), { weekday: 'short', day: 'numeric', month: 'short' }),
|
||||
),
|
||||
E('div', { class: 'dl-muted' }, bytes(v)),
|
||||
]);
|
||||
|
||||
@@ -4,10 +4,11 @@
|
||||
import type { DayUsage } from '../../shared/types';
|
||||
import { E } from '../e';
|
||||
import { bits, bytes, parseDay } from '../../shared/format';
|
||||
import { fill, fmt, locale } from '../../shared/i18n';
|
||||
import { attachTip } from '../ui/tooltip';
|
||||
import { svg } from '../ui/layout';
|
||||
|
||||
const dayLabel = (day: string) => parseDay(day).toLocaleDateString('en-GB', { day: 'numeric', month: 'short' });
|
||||
const dayLabel = (day: string) => parseDay(day).toLocaleDateString(locale(), { day: 'numeric', month: 'short' });
|
||||
|
||||
/**
|
||||
* Throughput over the last 15 minutes plus today's total. `off`: the server is
|
||||
@@ -33,7 +34,7 @@ export function speedTile(rate: [number, number, number][], now: number, today:
|
||||
`<path d="M${dl.join(' L')} L${W},${H} L0,${H}Z" class="area"/><path d="M${dl.join(' L')}" class="line"/>` +
|
||||
`<path d="M${ul.join(' L')}" class="line up"/></svg>`,
|
||||
)
|
||||
: E('div', { class: 'dl-speed-wait' }, [E('i'), off ? '' : E('span', {}, 'Collecting… 1 point a minute')]);
|
||||
: E('div', { class: 'dl-speed-wait' }, [E('i'), off ? '' : E('span', {}, _('Collecting… 1 point a minute'))]);
|
||||
const col = (label: string, ic: string, cls: string, v: number) =>
|
||||
E('div', { class: 'dl-speed-col' }, [
|
||||
E('span', { class: 'dl-sub' }, [E('span', { class: cls }, ic), ` ${label}`]),
|
||||
@@ -43,19 +44,19 @@ export function speedTile(rate: [number, number, number][], now: number, today:
|
||||
attachTip(chart, () => {
|
||||
const p = pts[pts.length - 1];
|
||||
return [
|
||||
E('div', { class: 'dl-tip-title' }, new Date(p[0] * 1000).toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' })),
|
||||
E('div', { class: 'dl-tip-title' }, new Date(p[0] * 1000).toLocaleTimeString(locale(), { hour: '2-digit', minute: '2-digit' })),
|
||||
E('div', {}, `↓ ${bits(p[2])} · ↑ ${bits(p[1])}`),
|
||||
];
|
||||
});
|
||||
return E('div', { class: 'dl-bento-tile' }, [
|
||||
E('div', { class: 'dl-bento-head' }, [
|
||||
E('span', { class: 'dl-metric-label' }, 'Speed now'),
|
||||
off ? '' : E('span', { class: 'dl-sub' }, 'last 15 min'),
|
||||
E('span', { class: 'dl-metric-label' }, _('Speed now')),
|
||||
off ? '' : E('span', { class: 'dl-sub' }, _('last 15 min')),
|
||||
]),
|
||||
E('div', { class: 'dl-speed-cols' }, [col('Download', '↓', 'dl-dn', down), col('Upload', '↑', 'dl-up', up)]),
|
||||
E('div', { class: 'dl-speed-cols' }, [col(_('Download', 'speed'), '↓', 'dl-dn', down), col(_('Upload', 'speed'), '↑', 'dl-up', up)]),
|
||||
chart,
|
||||
E('div', { class: 'dl-speed-today' }, [
|
||||
E('span', {}, ['Today ', E('b', {}, bytes(rx + tx))]),
|
||||
E('span', {}, fill(_('Today %s'), E('b', {}, bytes(rx + tx)))),
|
||||
E('span', {}, [E('span', { class: 'dl-dn' }, '↓'), ` ${bytes(tx)} `, E('span', { class: 'dl-up' }, '↑'), ` ${bytes(rx)}`]),
|
||||
]),
|
||||
]);
|
||||
@@ -75,7 +76,7 @@ export function daysTile(series: DayUsage[], note: string): HTMLElement {
|
||||
const v = vals[i];
|
||||
const bar = E('i', { class: i === days.length - 1 ? 'hi' : '', style: `height:${Math.max(4, (v / max) * 100)}%` });
|
||||
attachTip(bar, () => [
|
||||
E('div', { class: 'dl-tip-title' }, i === days.length - 1 ? `Today · ${dayLabel(d.day)}` : dayLabel(d.day)),
|
||||
E('div', { class: 'dl-tip-title' }, i === days.length - 1 ? `${_('Today')} · ${dayLabel(d.day)}` : dayLabel(d.day)),
|
||||
E('div', {}, bytes(v)),
|
||||
E('div', { class: 'dl-muted dl-mono' }, `↓ ${bytes(d.tx)} ↑ ${bytes(d.rx)}`),
|
||||
]);
|
||||
@@ -84,14 +85,14 @@ export function daysTile(series: DayUsage[], note: string): HTMLElement {
|
||||
);
|
||||
return E('div', { class: 'dl-bento-tile month' }, [
|
||||
E('div', { class: 'dl-bento-head' }, [
|
||||
E('span', {}, [E('span', { class: 'dl-metric-label' }, 'Last 30 days'), E('b', { class: 'dl-bento-total' }, bytes(total))]),
|
||||
vals[peakI] > 0 ? E('span', { class: 'dl-sub' }, `peak ${bytes(vals[peakI])} · ${dayLabel(days[peakI].day)}`) : '',
|
||||
E('span', {}, [E('span', { class: 'dl-metric-label' }, _('Last 30 days')), E('b', { class: 'dl-bento-total' }, bytes(total))]),
|
||||
vals[peakI] > 0 ? E('span', { class: 'dl-sub' }, `${fmt(_('peak %s'), bytes(vals[peakI]))} · ${dayLabel(days[peakI].day)}`) : '',
|
||||
]),
|
||||
days.length ? bars : E('p', { class: 'dl-muted' }, 'No traffic yet.'),
|
||||
days.length ? bars : E('p', { class: 'dl-muted' }, _('No traffic yet.')),
|
||||
E('div', { class: 'dl-bento-head' }, [
|
||||
E('span', { class: 'dl-sub' }, days.length ? dayLabel(days[0].day) : ''),
|
||||
E('span', { class: 'dl-sub' }, note),
|
||||
E('span', { class: 'dl-sub' }, 'today'),
|
||||
E('span', { class: 'dl-sub' }, _('today')),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
@@ -108,7 +109,7 @@ export function dayBars(series: DayUsage[]): HTMLElement {
|
||||
const bar = E('i', { class: `${vals[i] ? '' : 'zero'}${i === days.length - 1 ? ' hi' : ''}` });
|
||||
bar.style.height = `${Math.max(8, (vals[i] / max) * 100)}%`;
|
||||
attachTip(bar, () => [
|
||||
E('div', { class: 'dl-tip-title' }, i === days.length - 1 ? `Today · ${dayLabel(x.day)}` : dayLabel(x.day)),
|
||||
E('div', { class: 'dl-tip-title' }, i === days.length - 1 ? `${_('Today')} · ${dayLabel(x.day)}` : dayLabel(x.day)),
|
||||
E('div', {}, bytes(vals[i])),
|
||||
]);
|
||||
return bar;
|
||||
|
||||
+10
-2
@@ -3,7 +3,9 @@
|
||||
// throws an ApiError carrying the status and, for a plain-HTTP visitor, the
|
||||
// HTTPS twin of the link.
|
||||
|
||||
import { fmt } from '../shared/i18n';
|
||||
import { base } from './state';
|
||||
import { lang, routerText } from './i18n';
|
||||
|
||||
export class ApiError extends Error {
|
||||
constructor(
|
||||
@@ -20,7 +22,8 @@ export async function call<T>(path: string, body?: unknown): Promise<T> {
|
||||
const res = await fetch(`${base}/api/${path}`, {
|
||||
method: body === undefined ? 'GET' : 'POST',
|
||||
credentials: 'omit',
|
||||
headers: body === undefined ? {} : { 'Content-Type': 'application/json' },
|
||||
// The page's language: the router writes its messages in it when it has the translation.
|
||||
headers: body === undefined ? { 'Accept-Language': lang() } : { 'Content-Type': 'application/json', 'Accept-Language': lang() },
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
cache: 'no-store',
|
||||
});
|
||||
@@ -31,7 +34,12 @@ export async function call<T>(path: string, body?: unknown): Promise<T> {
|
||||
} catch {
|
||||
/* empty */
|
||||
}
|
||||
if (!res.ok) throw new ApiError(res.status, data?.error ?? `Request failed (${res.status})`, data?.https_url || undefined);
|
||||
if (!res.ok)
|
||||
throw new ApiError(
|
||||
res.status,
|
||||
data?.error ? routerText(data.error) : fmt(_('Request failed (%s)'), res.status),
|
||||
data?.https_url || undefined,
|
||||
);
|
||||
return data as T;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,34 +1,44 @@
|
||||
// What the demo adds to the breadcrumb: the scenario chip right after the path,
|
||||
// and a GitHub pill just before the page's QR knob (at the end where there is
|
||||
// none: a card alone). On a phone the pill would crowd out the names, so it
|
||||
// and a GitHub pill just before the page's language picker (none over a card
|
||||
// alone, which has no picker either). On a phone the pill would crowd out the names, so it
|
||||
// gives way to a button in the scenario drawer (demo.css). The portal redraws
|
||||
// the breadcrumb with the page and knows nothing of either, so both go back in
|
||||
// place after each redraw.
|
||||
// place after each redraw; a language change makes both again in it.
|
||||
|
||||
import { h, ic } from '../dom';
|
||||
import { onLang } from '../i18n';
|
||||
import { REPO } from './data';
|
||||
import { scenarioChip } from './picker';
|
||||
import type { DemoRouter } from './router';
|
||||
|
||||
export function mountCrumbs(router: DemoRouter) {
|
||||
const app = document.getElementById('app')!;
|
||||
const chip = scenarioChip(router);
|
||||
const gh = h(
|
||||
'a',
|
||||
{ class: 'dm-gh', href: REPO, target: '_blank', rel: 'noopener', 'aria-label': 'Dawnline on GitHub' },
|
||||
ic('github'),
|
||||
h('span', {}, 'GitHub'),
|
||||
);
|
||||
const make = () => ({
|
||||
chip: scenarioChip(router),
|
||||
gh: h(
|
||||
'a',
|
||||
{ class: 'dm-gh', href: REPO, target: '_blank', rel: 'noopener', 'aria-label': _('Dawnline on GitHub') },
|
||||
ic('github'),
|
||||
h('span', {}, 'GitHub'),
|
||||
),
|
||||
});
|
||||
let { chip, gh } = make();
|
||||
// Our own insertions call this again: by then both are in place and nothing moves.
|
||||
const keep = () => {
|
||||
const crumbs = app.querySelector('.crumbs');
|
||||
const path = crumbs?.querySelector('.cr-path');
|
||||
if (!crumbs || !path) return;
|
||||
if (path.nextElementSibling !== chip) path.after(chip);
|
||||
const qr = crumbs.querySelector('.cr-qr');
|
||||
if (qr && qr.previousElementSibling !== gh) qr.before(gh);
|
||||
else if (!qr && crumbs.lastElementChild !== gh) crumbs.append(gh);
|
||||
const lang = crumbs.querySelector('.cr-lang');
|
||||
if (lang && lang.previousElementSibling !== gh) lang.before(gh);
|
||||
};
|
||||
new MutationObserver(keep).observe(app, { childList: true, subtree: true });
|
||||
keep();
|
||||
// The page has redrawn its breadcrumb in the new language by now (main.ts listens first).
|
||||
onLang(() => {
|
||||
chip.remove();
|
||||
gh.remove();
|
||||
({ chip, gh } = make());
|
||||
keep();
|
||||
});
|
||||
}
|
||||
+24
-28
@@ -19,35 +19,31 @@ export interface Scenario {
|
||||
about: string;
|
||||
}
|
||||
|
||||
/** What can be tried, in the picker's groups. */
|
||||
export const GROUPS: { title: string; items: Scenario[] }[] = [
|
||||
{
|
||||
title: 'Your page',
|
||||
items: [
|
||||
{ id: 'normal', label: 'Everything works', about: 'Three devices: one online, one waiting to be set up.' },
|
||||
{ id: 'first', label: 'First visit', about: 'A fresh link with no devices yet.' },
|
||||
{ id: 'stale', label: 'Settings changed', about: 'The admin changed something: a device needs an update.' },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: 'Stopped by the admin',
|
||||
items: [
|
||||
{ id: 'quota', label: 'Out of data', about: 'The month’s limit is used up.' },
|
||||
{ id: 'hours', label: 'Outside allowed hours', about: 'Access only at certain hours of the day.' },
|
||||
{ id: 'paused', label: 'Paused by the admin', about: 'The page turns into one card.' },
|
||||
{ id: 'expired', label: 'Access ended', about: 'The end date has passed.' },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: 'Other cases',
|
||||
items: [
|
||||
{ id: 'http', label: 'Opened over plain HTTP', about: 'Settings only travel over HTTPS.' },
|
||||
{ id: 'plain', label: 'Plain WireGuard', about: 'Disguise off: any WireGuard app connects.' },
|
||||
{ id: 'full', label: 'No free slots', about: 'Every device slot is taken.' },
|
||||
],
|
||||
},
|
||||
/** What can be tried, in the picker's groups (their words are groups()). */
|
||||
const GROUPS: ScenarioId[][] = [
|
||||
['normal', 'first', 'stale'],
|
||||
['quota', 'hours', 'paused', 'expired'],
|
||||
['http', 'plain', 'full'],
|
||||
];
|
||||
export const SCENARIOS: Scenario[] = GROUPS.flatMap((g) => g.items);
|
||||
export const SCENARIOS: { id: ScenarioId }[] = GROUPS.flat().map((id) => ({ id }));
|
||||
|
||||
/** The picker's groups in the page's language: made when it draws (the language changes in place). */
|
||||
export function groups(): { title: string; items: Scenario[] }[] {
|
||||
const titles = [_('Your page'), _('Stopped by the admin'), _('Other cases')];
|
||||
const words: Record<ScenarioId, [label: string, about: string]> = {
|
||||
normal: [_('Everything works'), _('Three devices: one online, one waiting to be set up.')],
|
||||
first: [_('First visit'), _('A fresh link with no devices yet.')],
|
||||
stale: [_('Settings changed'), _('The admin changed something: a device needs an update.')],
|
||||
quota: [_('Out of data'), _('The month’s limit is used up.')],
|
||||
hours: [_('Outside allowed hours'), _('Access only at certain hours of the day.')],
|
||||
paused: [_('Paused by the admin'), _('The page turns into one card.')],
|
||||
expired: [_('Access ended'), _('The end date has passed.')],
|
||||
http: [_('Opened over plain HTTP'), _('Settings only travel over HTTPS.')],
|
||||
plain: [_('Plain WireGuard'), _('Disguise off: any WireGuard app connects.')],
|
||||
full: [_('No free slots'), _('Every device slot is taken.')],
|
||||
};
|
||||
return GROUPS.map((ids, i) => ({ title: titles[i], items: ids.map((id) => ({ id, label: words[id][0], about: words[id][1] })) }));
|
||||
}
|
||||
export const isScenario = (id: unknown): id is ScenarioId => SCENARIOS.some((s) => s.id === id);
|
||||
|
||||
/** A device as the demo keeps it; the page's Device is made from it on every answer. */
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
msgid ""
|
||||
msgstr ""
|
||||
"Project-Id-Version: Dawnline\n"
|
||||
"MIME-Version: 1.0\n"
|
||||
"Content-Type: text/plain; charset=UTF-8\n"
|
||||
"Content-Transfer-Encoding: 8bit\n"
|
||||
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "A fresh link with no devices yet."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "Access ended"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "Access only at certain hours of the day."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/portal/demo/crumbs.ts
|
||||
msgid "Dawnline on GitHub"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/portal/demo/picker.ts
|
||||
msgid "Demo"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/portal/demo/main.ts
|
||||
msgid "Demo keys connect nowhere"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "Disguise off: any WireGuard app connects."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "Every device slot is taken."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "Everything works"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "First visit"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/portal/demo/picker.ts
|
||||
msgid "How the page looks in each case. Nothing here connects."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "No free slots"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "Opened over plain HTTP"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "Other cases"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "Out of data"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "Outside allowed hours"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "Paused by the admin"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "Plain WireGuard"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "Settings changed"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "Settings only travel over HTTPS."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/portal/demo/picker.ts
|
||||
msgid "Start over"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "Stopped by the admin"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "The admin changed something: a device needs an update."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/portal/demo/picker.ts
|
||||
msgid "The demo started over"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "The end date has passed."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "The month’s limit is used up."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "The page turns into one card."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "Three devices: one online, one waiting to be set up."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/portal/demo/picker.ts
|
||||
msgid "Try a scenario"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "Your page"
|
||||
msgstr ""
|
||||
@@ -0,0 +1,129 @@
|
||||
msgid ""
|
||||
msgstr ""
|
||||
"Project-Id-Version: Dawnline\n"
|
||||
"MIME-Version: 1.0\n"
|
||||
"Content-Type: text/plain; charset=UTF-8\n"
|
||||
"Content-Transfer-Encoding: 8bit\n"
|
||||
"Language: ru\n"
|
||||
"Language-Team: Russian\n"
|
||||
"Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);\n"
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "A fresh link with no devices yet."
|
||||
msgstr "Новая ссылка, устройств пока нет."
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "Access ended"
|
||||
msgstr "Доступ закончился"
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "Access only at certain hours of the day."
|
||||
msgstr "Доступ только в определённые часы."
|
||||
|
||||
#: web/src/portal/demo/crumbs.ts
|
||||
msgid "Dawnline on GitHub"
|
||||
msgstr "Dawnline на GitHub"
|
||||
|
||||
#: web/src/portal/demo/picker.ts
|
||||
msgid "Demo"
|
||||
msgstr "Демо"
|
||||
|
||||
#: web/src/portal/demo/main.ts
|
||||
msgid "Demo keys connect nowhere"
|
||||
msgstr "Демо-ключи никуда не подключаются"
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "Disguise off: any WireGuard app connects."
|
||||
msgstr "Маскировка выключена: подойдёт любое приложение WireGuard."
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "Every device slot is taken."
|
||||
msgstr "Все места для устройств заняты."
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "Everything works"
|
||||
msgstr "Всё работает"
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "First visit"
|
||||
msgstr "Первый визит"
|
||||
|
||||
#: web/src/portal/demo/picker.ts
|
||||
msgid "How the page looks in each case. Nothing here connects."
|
||||
msgstr "Как выглядит страница в каждом случае. Ничего не подключается по-настоящему."
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "No free slots"
|
||||
msgstr "Нет свободных мест"
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "Opened over plain HTTP"
|
||||
msgstr "Открыто по обычному HTTP"
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "Other cases"
|
||||
msgstr "Другие случаи"
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "Out of data"
|
||||
msgstr "Трафик закончился"
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "Outside allowed hours"
|
||||
msgstr "Вне часов доступа"
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "Paused by the admin"
|
||||
msgstr "Доступ на паузе"
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "Plain WireGuard"
|
||||
msgstr "Обычный WireGuard"
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "Settings changed"
|
||||
msgstr "Настройки изменились"
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "Settings only travel over HTTPS."
|
||||
msgstr "Настройки передаются только по HTTPS."
|
||||
|
||||
#: web/src/portal/demo/picker.ts
|
||||
msgid "Start over"
|
||||
msgstr "Начать заново"
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "Stopped by the admin"
|
||||
msgstr "Ограничения администратора"
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "The admin changed something: a device needs an update."
|
||||
msgstr "Администратор что-то поменял: устройство нужно обновить."
|
||||
|
||||
#: web/src/portal/demo/picker.ts
|
||||
msgid "The demo started over"
|
||||
msgstr "Демо началось заново"
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "The end date has passed."
|
||||
msgstr "Дата окончания прошла."
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "The month’s limit is used up."
|
||||
msgstr "Месячный лимит исчерпан."
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "The page turns into one card."
|
||||
msgstr "Страница сворачивается в одну карточку."
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "Three devices: one online, one waiting to be set up."
|
||||
msgstr "Три устройства: одно в сети, одно ждёт настройки."
|
||||
|
||||
#: web/src/portal/demo/picker.ts
|
||||
msgid "Try a scenario"
|
||||
msgstr "Выберите сценарий"
|
||||
|
||||
#: web/src/portal/demo/data.ts
|
||||
msgid "Your page"
|
||||
msgstr "Ваша страница"
|
||||
@@ -4,11 +4,16 @@
|
||||
// picker.ts). The order of the imports is the boot order: the router owns
|
||||
// fetch before the portal loads.
|
||||
|
||||
// First: the translation globals, before anything draws.
|
||||
import { addCatalog } from '../i18n';
|
||||
import ru from './i18n/ru.po';
|
||||
import { router } from './serve';
|
||||
import '../main';
|
||||
import { toast } from '../ui/feedback';
|
||||
import { mountCrumbs } from './crumbs';
|
||||
|
||||
// The demo's own words (the scenarios, its chip and toasts), beside the portal's.
|
||||
addCatalog('ru', ru);
|
||||
mountCrumbs(router);
|
||||
|
||||
// An AmneziaVPN key would add a server that connects nowhere to the visitor's app: the demo keeps it on the page.
|
||||
@@ -18,7 +23,7 @@ document.addEventListener(
|
||||
if (!(e.target as Element).closest?.('a[href^="vpn:"]')) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
toast('Demo keys connect nowhere', true);
|
||||
toast(_('Demo keys connect nowhere'), true);
|
||||
},
|
||||
true,
|
||||
);
|
||||
@@ -11,7 +11,7 @@ import { closeSheet, head, openSheet, sub, type View } from '../ui/sheet';
|
||||
import { glass, type Tone } from '../ui/glass';
|
||||
import { toast } from '../ui/feedback';
|
||||
import { EASE_OUT, play } from '../motion';
|
||||
import { GROUPS, REPO, type Scenario, type ScenarioId } from './data';
|
||||
import { REPO, groups, type Scenario, type ScenarioId } from './data';
|
||||
import type { DemoRouter } from './router';
|
||||
|
||||
/** Each scenario's glass icon and tone (the glass set is smaller than the line icons). */
|
||||
@@ -75,9 +75,9 @@ export function scenarioChip(router: DemoRouter): HTMLElement {
|
||||
const el = h(
|
||||
'div',
|
||||
{ class: 'view' },
|
||||
head('Try a scenario'),
|
||||
sub('How the page looks in each case. Nothing here connects.'),
|
||||
...GROUPS.map((g) =>
|
||||
head(_('Try a scenario')),
|
||||
sub(_('How the page looks in each case. Nothing here connects.')),
|
||||
...groups().map((g) =>
|
||||
h('div', { class: 'dm-group' }, h('div', { class: 'lbl-s' }, g.title), h('div', { class: 'dm-list' }, ...g.items.map(row))),
|
||||
),
|
||||
h(
|
||||
@@ -85,20 +85,20 @@ export function scenarioChip(router: DemoRouter): HTMLElement {
|
||||
{ class: 'dm-foot' },
|
||||
h(
|
||||
'button',
|
||||
{ type: 'button', class: 'btn soft', onclick: () => pick(router.scenario(), 'The demo started over') },
|
||||
{ type: 'button', class: 'btn soft', onclick: () => pick(router.scenario(), _('The demo started over')) },
|
||||
ic('reset'),
|
||||
h('span', {}, 'Start over'),
|
||||
h('span', {}, _('Start over')),
|
||||
),
|
||||
h('a', { class: 'btn soft dm-gh-alt', href: REPO, target: '_blank', rel: 'noopener' }, ic('github'), h('span', {}, 'GitHub')),
|
||||
),
|
||||
);
|
||||
return { el, label: 'Try a scenario' };
|
||||
return { el, label: _('Try a scenario') };
|
||||
}
|
||||
|
||||
return h(
|
||||
'button',
|
||||
{ type: 'button', class: 'dm-chip', 'aria-haspopup': 'dialog', onclick: () => openSheet(scenarios) },
|
||||
h('span', {}, 'Demo'),
|
||||
h('span', {}, _('Demo')),
|
||||
ic('chevron', 'i'),
|
||||
);
|
||||
}
|
||||
+34
-23
@@ -4,7 +4,8 @@
|
||||
// opens on the device itself, from a code, ready to add it there.
|
||||
|
||||
import type { ClientConfig, Kind } from '../../shared/types';
|
||||
import { KIND_LABEL } from '../../shared/format';
|
||||
import { kindLabel } from '../../shared/format';
|
||||
import { fmt, num, plural } from '../../shared/i18n';
|
||||
import { ApiError, call } from '../api';
|
||||
import { h, ic } from '../dom';
|
||||
import { EASE_OUT, play } from '../motion';
|
||||
@@ -62,12 +63,12 @@ const modelReady: Promise<string> = (async () => {
|
||||
function guessName(kind: Kind): string {
|
||||
if (/iPhone/.test(UA)) return 'iPhone';
|
||||
if (IPAD) return 'iPad';
|
||||
if (/Android/.test(UA)) return MODEL || (kind === 'tablet' ? 'Android tablet' : 'Android phone');
|
||||
if (/Android/.test(UA)) return MODEL || (kind === 'tablet' ? _('Android tablet') : _('Android phone'));
|
||||
if (/CrOS/.test(UA)) return 'Chromebook';
|
||||
if (/Mac OS X/.test(UA)) return 'Mac';
|
||||
if (/Windows/.test(UA)) return 'Windows PC';
|
||||
if (/Linux/.test(UA)) return 'Linux PC';
|
||||
return KIND_LABEL[kind];
|
||||
if (/Windows/.test(UA)) return _('Windows PC');
|
||||
if (/Linux/.test(UA)) return _('Linux PC');
|
||||
return kindLabel(kind);
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -76,14 +77,18 @@ function guessName(kind: Kind): string {
|
||||
* which; picked from elsewhere it is a phone.
|
||||
*/
|
||||
type Pick = 'computer' | 'mobile' | 'router' | 'other';
|
||||
const PICK_LABEL: Record<Pick, string> = { computer: 'PC', mobile: 'Mobile', router: 'Router', other: 'Other' };
|
||||
const pickLabel = (p: Pick): string => (p === 'mobile' ? _('Mobile') : kindLabel(p));
|
||||
const pickOf = (k: Kind): Pick => (k === 'phone' || k === 'tablet' ? 'mobile' : k);
|
||||
const kindOf = (p: Pick): Kind => (p !== 'mobile' ? p : guessKind() === 'tablet' ? 'tablet' : 'phone');
|
||||
|
||||
export function startAdd() {
|
||||
const st = state();
|
||||
if (!st || st.locked) return;
|
||||
if (!st.can_add) return toast(`You have reached your limit of ${st.person.device_limit} devices`, true);
|
||||
if (!st.can_add)
|
||||
return toast(
|
||||
plural(st.person.device_limit, 'You have reached your limit of %s device', 'You have reached your limit of %s devices'),
|
||||
true,
|
||||
);
|
||||
if (secureFirst()) return;
|
||||
openSheet(vAdd);
|
||||
}
|
||||
@@ -97,26 +102,32 @@ function vAdd(): View {
|
||||
let edited = false;
|
||||
const taken = new Set(p.devices.map((d) => d.name.toLowerCase()));
|
||||
const suggest = (k: Pick) => {
|
||||
const n = k === pickOf(guessKind()) ? guessName(kindOf(k)) : k === 'mobile' ? 'Phone' : KIND_LABEL[k];
|
||||
const n = k === pickOf(guessKind()) ? guessName(kindOf(k)) : kindLabel(k === 'mobile' ? 'phone' : k);
|
||||
if (!taken.has(n.toLowerCase())) return n;
|
||||
for (let i = 2; i < 20; i++) if (!taken.has(`${n} ${i}`.toLowerCase())) return `${n} ${i}`;
|
||||
return n;
|
||||
};
|
||||
|
||||
const kinds = h('div', { class: 'kinds', role: 'radiogroup', 'aria-label': 'What is it?' });
|
||||
const kinds = h('div', { class: 'kinds', role: 'radiogroup', 'aria-label': _('What is it?') });
|
||||
kinds.style.setProperty('--n', String(picks.length));
|
||||
const tiles = picks.map((k) => {
|
||||
const t = h(
|
||||
'button',
|
||||
{ type: 'button', class: 'kind', role: 'radio', 'aria-label': PICK_LABEL[k], onclick: () => choose(k) },
|
||||
{ type: 'button', class: 'kind', role: 'radio', 'aria-label': pickLabel(k), onclick: () => choose(k) },
|
||||
h('span', { class: 'kind-tile' }, glass(k, 'blue')),
|
||||
h('span', { class: 'kind-lbl' }, PICK_LABEL[k]),
|
||||
h('span', { class: 'kind-lbl' }, pickLabel(k)),
|
||||
);
|
||||
kinds.appendChild(t);
|
||||
return t;
|
||||
});
|
||||
const input = h('input', { type: 'text', maxlength: 48, required: true, 'aria-label': 'Name', autocomplete: 'off' }) as HTMLInputElement;
|
||||
const goBtn = h('button', { class: 'go ready', type: 'submit', 'aria-label': 'Create connection' }, ic('arrow')) as HTMLButtonElement;
|
||||
const input = h('input', {
|
||||
type: 'text',
|
||||
maxlength: 48,
|
||||
required: true,
|
||||
'aria-label': _('Name'),
|
||||
autocomplete: 'off',
|
||||
}) as HTMLInputElement;
|
||||
const goBtn = h('button', { class: 'go ready', type: 'submit', 'aria-label': _('Create connection') }, ic('arrow')) as HTMLButtonElement;
|
||||
const err = h('p', { class: 'hint bad-t', hidden: true });
|
||||
const say = (msg: string) => {
|
||||
// Already showing: its words change in place.
|
||||
@@ -162,7 +173,7 @@ function vAdd(): View {
|
||||
e.preventDefault();
|
||||
const name = input.value.trim();
|
||||
if (!name) return;
|
||||
if (taken.has(name.toLowerCase())) return say('You already have a device with this name.');
|
||||
if (taken.has(name.toLowerCase())) return say(_('You already have a device with this name.'));
|
||||
void once(goBtn, async () => {
|
||||
try {
|
||||
const r = await call<{ id: string; config: ClientConfig; state: State }>('devices', { name, kind: kindOf(pick) });
|
||||
@@ -180,23 +191,23 @@ function vAdd(): View {
|
||||
'button',
|
||||
{ type: 'button', class: 'btn soft block', onclick: () => go(vLink) },
|
||||
ic('qr'),
|
||||
h('span', {}, 'Add it from the device'),
|
||||
h('span', {}, _('Add it from the device')),
|
||||
);
|
||||
const free = p.device_limit - p.devices.length;
|
||||
const el = h(
|
||||
'div',
|
||||
{ class: 'view' },
|
||||
head('Add a device'),
|
||||
sub(`${free} of ${p.device_limit} slots free`),
|
||||
head(_('Add a device')),
|
||||
sub(fmt(N_(p.device_limit, '%s of %s slot free', '%s of %s slots free'), num(free), num(p.device_limit))),
|
||||
kinds,
|
||||
hint('Phones and tablets get a smaller packet size that suits mobile networks.'),
|
||||
hint(_('Phones and tablets get a smaller packet size that suits mobile networks.')),
|
||||
form,
|
||||
err,
|
||||
h('div', { class: 'or' }, 'OR'),
|
||||
h('div', { class: 'or' }, _('OR')),
|
||||
viaLink,
|
||||
);
|
||||
el.querySelector('.hint')!.classList.add('kinds-note');
|
||||
return { el, label: 'Add a device' };
|
||||
return { el, label: _('Add a device') };
|
||||
}
|
||||
|
||||
/** The page on the device itself, ready to add it: the link as a code for its camera, and as text. */
|
||||
@@ -205,10 +216,10 @@ function vLink(): View {
|
||||
const el = h(
|
||||
'div',
|
||||
{ class: 'view' },
|
||||
head('Open on the device', { back: true }),
|
||||
sub('Point its camera at the code: your page opens there with this device ready to add.'),
|
||||
head(_('Open on the device'), { back: true }),
|
||||
sub(_('Point its camera at the code: your page opens there with this device ready to add.')),
|
||||
qrBox(link, true),
|
||||
linkRow(link),
|
||||
);
|
||||
return { el, label: 'Open on the device' };
|
||||
return { el, label: _('Open on the device') };
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
// be undone; the action's button stays busy until the router answers.
|
||||
|
||||
import type { ClientConfig, Device } from '../../shared/types';
|
||||
import { fmt } from '../../shared/i18n';
|
||||
import { call } from '../api';
|
||||
import { h, ic } from '../dom';
|
||||
import { EASE_IN, play } from '../motion';
|
||||
@@ -13,7 +14,7 @@ import { closeSheet, head, onClosed, openSheet, type View } from '../ui/sheet';
|
||||
import { secureFirst } from './secure';
|
||||
import { continueSetup } from './setup-view';
|
||||
|
||||
/** A question before something that cannot be undone: the action's icon in its colour, what happens, Cancel and the action. */
|
||||
/** A question before something that cannot be undone: the action's icon in its colour, what happens (on the left edge), Cancel and the action. */
|
||||
function ask(o: { icon: string; tone: Tone; title: string; text: string; action: string; cls: string; run: () => Promise<void> }): View {
|
||||
const ok = h(
|
||||
'button',
|
||||
@@ -26,11 +27,11 @@ function ask(o: { icon: string; tone: Tone; title: string; text: string; action:
|
||||
{ class: 'view' },
|
||||
h(
|
||||
'div',
|
||||
{ class: 'center-col ask' },
|
||||
{ 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),
|
||||
h('div', { class: 'btnrow' }, h('button', { type: 'button', class: 'btn soft', onclick: () => closeSheet() }, _('Cancel')), ok),
|
||||
),
|
||||
);
|
||||
return { el, label: o.title, asks: true };
|
||||
@@ -38,9 +39,9 @@ function ask(o: { icon: string; tone: Tone; title: string; text: string; action:
|
||||
|
||||
export function rename(d: Device) {
|
||||
openSheet(() => {
|
||||
const input = h('input', { type: 'text', maxlength: 48, 'aria-label': 'Device name', autocomplete: 'off' }) as HTMLInputElement;
|
||||
const input = h('input', { type: 'text', maxlength: 48, 'aria-label': _('Device name'), autocomplete: 'off' }) as HTMLInputElement;
|
||||
input.value = d.name;
|
||||
const save = h('button', { class: 'go', type: 'submit', 'aria-label': 'Save' }, ic('check')) as HTMLButtonElement;
|
||||
const save = h('button', { class: 'go', type: 'submit', 'aria-label': _('Save') }, ic('check')) as HTMLButtonElement;
|
||||
input.addEventListener('input', () => save.classList.toggle('ready', !!input.value.trim() && input.value.trim() !== d.name));
|
||||
const form = h('form', { class: 'field', autocomplete: 'off' }, input, save);
|
||||
form.addEventListener('submit', (e) => {
|
||||
@@ -53,7 +54,7 @@ export function rename(d: Device) {
|
||||
setState(r.state);
|
||||
onClosed(() => {
|
||||
repaint();
|
||||
toast('Renamed');
|
||||
toast(_('Renamed'));
|
||||
});
|
||||
closeSheet();
|
||||
} catch (er) {
|
||||
@@ -62,7 +63,8 @@ export function rename(d: Device) {
|
||||
});
|
||||
});
|
||||
setTimeout(() => input.select(), 60);
|
||||
return { el: h('div', { class: 'view' }, head(`Rename ${d.name}`), form), label: `Rename ${d.name}` };
|
||||
const title = fmt(_('Rename %s'), d.name);
|
||||
return { el: h('div', { class: 'view' }, head(title), form), label: title };
|
||||
});
|
||||
}
|
||||
|
||||
@@ -78,11 +80,13 @@ export function reconnect(d: Device) {
|
||||
ask({
|
||||
icon: 'refresh',
|
||||
tone: 'orange',
|
||||
title: `Reconnect ${d.name}?`,
|
||||
title: fmt(_('Reconnect %s?'), d.name),
|
||||
text: here
|
||||
? 'It gets new keys. This device is connected through its current settings: it disconnects a few seconds after you confirm. Add the new ones that open next.'
|
||||
: 'It gets new keys and its current settings stop working. Set it up again with the new ones that open next.',
|
||||
action: 'Reconnect',
|
||||
? _(
|
||||
'It gets new keys. This device is connected through its current settings: it disconnects a few seconds after you confirm. Add the new ones that open next.',
|
||||
)
|
||||
: _('It gets new keys and its current settings stop working. Set it up again with the new ones that open next.'),
|
||||
action: _('Reconnect'),
|
||||
cls: 'accent',
|
||||
run: async () => {
|
||||
try {
|
||||
@@ -103,9 +107,9 @@ export function removeDevice(d: Device) {
|
||||
ask({
|
||||
icon: 'trash',
|
||||
tone: 'red',
|
||||
title: `Remove ${d.name}?`,
|
||||
text: 'Its connection stops working at once. You can add it again later.',
|
||||
action: 'Remove',
|
||||
title: fmt(_('Remove %s?'), d.name),
|
||||
text: _('Its connection stops working at once. You can add it again later.'),
|
||||
action: _('Remove'),
|
||||
cls: 'red',
|
||||
run: async () => {
|
||||
try {
|
||||
@@ -116,7 +120,7 @@ export function removeDevice(d: Device) {
|
||||
const card = document.querySelector(`.dev[data-id="${CSS.escape(d.id)}"]`);
|
||||
const done = () => {
|
||||
repaint();
|
||||
toast('Device removed');
|
||||
toast(_('Device removed'));
|
||||
};
|
||||
if (!card) return done();
|
||||
play(
|
||||
|
||||
@@ -12,11 +12,11 @@ export function showPageCode() {
|
||||
const el = h(
|
||||
'div',
|
||||
{ class: 'view' },
|
||||
head('Open on another device'),
|
||||
sub('Point its camera at the code: this page opens there.'),
|
||||
head(_('Open on another device')),
|
||||
sub(_('Point its camera at the code: this page opens there.')),
|
||||
qrBox(url, true),
|
||||
linkRow(url),
|
||||
);
|
||||
return { el, label: 'Open on another device' };
|
||||
return { el, label: _('Open on another device') };
|
||||
});
|
||||
}
|
||||
@@ -11,20 +11,22 @@ function vSecure(url: string): View {
|
||||
const el = h(
|
||||
'div',
|
||||
{ class: 'view' },
|
||||
head('Open the link securely'),
|
||||
sub('Connection settings only travel encrypted'),
|
||||
head(_('Open the link securely')),
|
||||
sub(_('Connection settings only travel encrypted')),
|
||||
h(
|
||||
'div',
|
||||
{ class: 'center-col secure' },
|
||||
glass('lock', 'blue', 'gi xl'),
|
||||
h('p', {}, 'This page is open without encryption. To add or set up a device, open the same link over HTTPS:'),
|
||||
h('p', {}, _('This page is open without encryption. To add or set up a device, open the same link over HTTPS:')),
|
||||
),
|
||||
// The same tab: the HTTPS page replaces this one.
|
||||
h('a', { class: 'btn accent block', href: url }, ic('lock'), h('span', {}, 'Open securely')),
|
||||
hint('The browser may warn that the certificate is not trusted: it is this router’s own. Choose to continue (“Advanced” → “Proceed”).'),
|
||||
h('a', { class: 'btn accent block', href: url }, ic('lock'), h('span', {}, _('Open securely'))),
|
||||
hint(
|
||||
_('The browser may warn that the certificate is not trusted: it is this router’s own. Choose to continue (“Advanced” → “Proceed”).'),
|
||||
),
|
||||
);
|
||||
el.lastElementChild!.classList.add('secure-note');
|
||||
return { el, label: 'Open the link securely' };
|
||||
return { el, label: _('Open the link securely') };
|
||||
}
|
||||
|
||||
/** The HTTPS twin's sheet (here, or the one the router named in a refusal). */
|
||||
|
||||
@@ -5,16 +5,19 @@
|
||||
// where an app scans a code. The rules behind them are setup.ts.
|
||||
|
||||
import type { ClientConfig, Device } from '../../shared/types';
|
||||
import { fill, fmt } from '../../shared/i18n';
|
||||
import { h, ic, type Kid } from '../dom';
|
||||
import { EASE_OUT, POP, SMOOTH, play } from '../motion';
|
||||
import {
|
||||
APP_NAME,
|
||||
PLATFORM_LABEL,
|
||||
importPath,
|
||||
importSteps,
|
||||
keyFileName,
|
||||
opensKeyLinks,
|
||||
platformLabel,
|
||||
routerStore,
|
||||
scanPath,
|
||||
vpnContinue,
|
||||
storeFor,
|
||||
type AppId,
|
||||
type Platform,
|
||||
@@ -83,7 +86,7 @@ export function badge(
|
||||
/** Where the app comes from: the store (and, on Android, the APK beside it), or a line to go and get it. */
|
||||
export function storeBlock(app: AppId, os: Platform, router: boolean): Kid[] {
|
||||
const st: Store | null = router ? routerStore(app) : storeFor(app, os);
|
||||
if (!st) return [hint(`Get ${APP_NAME[app]} on the ${PLATFORM_LABEL[os]} and come back here.`)];
|
||||
if (!st) return [hint(fmt(_('Get %s on the %s and come back here.'), APP_NAME[app], platformLabel(os)))];
|
||||
// Android: the store can fail (no Google Play, or it hides the app), so the APK sits beside it.
|
||||
if (st.alt) return [h('div', { class: 'badges2' }, badge(st), badge(st.alt)), hint(st.alt.why)];
|
||||
return [badge(st)];
|
||||
@@ -106,35 +109,40 @@ export function connectKids(c: SetupCtx): Kid[] {
|
||||
// On the phone being set up, a link opens AmneziaVPN only on Android; an
|
||||
// iPhone takes the key as a .vpn file from the share sheet.
|
||||
const inHand = c.same() && hereHandheld;
|
||||
const copyKey = (ev: Event) => copy(c.key, 'Key copied', ev.currentTarget);
|
||||
const copyKey = (ev: Event) => copy(c.key, _('Key copied'), ev.currentTarget);
|
||||
const send = app === 'vpn' && inHand && !opensKeyLinks(c.pf) ? shareFile(keyFileName(c.cfg.filename), c.key) : null;
|
||||
if (app === 'vpn' && inHand && (opensKeyLinks(c.pf) || send))
|
||||
return [
|
||||
send
|
||||
? badge({ top: 'Then come back here and tap', main: 'Send to AmneziaVPN', mark: 'amnezia', onclick: () => void send() }, true)
|
||||
: badge({ href: c.key, top: 'Then come back here and tap', main: 'Open in AmneziaVPN', mark: 'amnezia' }, true),
|
||||
? badge({ top: _('Then come back here and tap'), main: _('Send to AmneziaVPN'), mark: 'amnezia', onclick: () => void send() }, true)
|
||||
: badge({ href: c.key, top: _('Then come back here and tap'), main: _('Open in AmneziaVPN'), mark: 'amnezia' }, true),
|
||||
hint(
|
||||
send ? 'Pick AmneziaVPN in the share sheet. Not there? ' : 'Nothing opened? ',
|
||||
linkBtn('Copy the key', copyKey),
|
||||
' and add it in the app.',
|
||||
...fill(
|
||||
send
|
||||
? _('Pick AmneziaVPN in the share sheet. Not there? %s and add it in the app.')
|
||||
: _('Nothing opened? %s and add it in the app.'),
|
||||
linkBtn(_('Copy the key', 'in a sentence'), copyKey),
|
||||
),
|
||||
),
|
||||
];
|
||||
if (app === 'vpn')
|
||||
if (app === 'vpn') {
|
||||
const path = importPath('vpn');
|
||||
return [
|
||||
badge({ top: 'The connection as one key', main: 'Copy the key', mark: 'copy', onclick: copyKey }, true),
|
||||
badge({ top: _('The connection as one key'), main: _('Copy the key'), mark: 'copy', onclick: copyKey }, true),
|
||||
howto([
|
||||
['Open AmneziaVPN', ''],
|
||||
['Add server › ', 'Insert key'],
|
||||
['Paste the key and connect', ''],
|
||||
[fmt(_('Open %s', 'step'), name), ''],
|
||||
[path.replace(/ → [^→]*$/, ' → '), path.replace(/^.* → /, '')],
|
||||
[vpnContinue(), ''],
|
||||
]),
|
||||
];
|
||||
}
|
||||
const share = hereHandheld ? shareFile(c.cfg.filename, c.cfg.conf) : null;
|
||||
return [
|
||||
share
|
||||
? badge(
|
||||
{
|
||||
top: c.same() ? `Straight into ${name}` : `Send it to the ${c.there}`,
|
||||
main: 'Share the file',
|
||||
top: c.same() ? fmt(_('Straight into %s'), name) : fmt(_('Send it to the %s'), c.there),
|
||||
main: _('Share the file'),
|
||||
mark: 'share',
|
||||
onclick: () => void share(),
|
||||
},
|
||||
@@ -142,8 +150,8 @@ export function connectKids(c: SetupCtx): Kid[] {
|
||||
)
|
||||
: badge(
|
||||
{
|
||||
top: 'Then import it in the app',
|
||||
main: 'Download the file',
|
||||
top: _('Then import it in the app'),
|
||||
main: _('Download the file'),
|
||||
mark: 'download',
|
||||
onclick: () => download(c.cfg.filename, c.cfg.conf),
|
||||
},
|
||||
@@ -163,23 +171,31 @@ export function sendKids(c: SetupCtx): Kid[] {
|
||||
const file = keyFileName(c.cfg.filename);
|
||||
const share = !!shareFile(file, c.key);
|
||||
return [
|
||||
h('p', { class: 'desc' }, `Send it to the ${c.there} in a message or a note, then in AmneziaVPN: Add server › Insert key.`),
|
||||
h(
|
||||
'p',
|
||||
{ class: 'desc' },
|
||||
fmt(_('Send it to the %s in a message or a note, then in AmneziaVPN: %s.'), c.there, importPath('vpn').replace(/ → /g, ' › ')),
|
||||
),
|
||||
h(
|
||||
'div',
|
||||
{ class: 'btnrow2' },
|
||||
btn('copy', 'Copy the key', (ev) => copy(c.key, 'Key copied', ev.currentTarget)),
|
||||
btn(share ? 'share' : 'download', share ? 'Share as a file' : 'Download the key', () => sendFile(file, c.key)),
|
||||
btn('copy', _('Copy the key'), (ev) => copy(c.key, _('Key copied'), ev.currentTarget)),
|
||||
btn(share ? 'share' : 'download', share ? _('Share as a file') : _('Download the key'), () => sendFile(file, c.key)),
|
||||
),
|
||||
];
|
||||
}
|
||||
const share = !!shareFile(c.cfg.filename, c.cfg.conf);
|
||||
return [
|
||||
h('p', { class: 'desc' }, `Send it to the ${c.there}, then import `, h('b', {}, c.cfg.filename), ` in ${APP_NAME[app]}.`),
|
||||
h(
|
||||
'p',
|
||||
{ class: 'desc' },
|
||||
...fill<Node | string>(_('Send it to the %s, then import %s in %s.'), c.there, h('b', {}, c.cfg.filename), APP_NAME[app]),
|
||||
),
|
||||
h(
|
||||
'div',
|
||||
{ class: 'btnrow2' },
|
||||
btn(share ? 'share' : 'download', share ? 'Share the file' : 'Download the file', () => sendFile(c.cfg.filename, c.cfg.conf)),
|
||||
btn('copy', 'Copy the configuration', (ev) => copy(c.cfg.conf, 'Configuration copied', ev.currentTarget)),
|
||||
btn(share ? 'share' : 'download', share ? _('Share the file') : _('Download the file'), () => sendFile(c.cfg.filename, c.cfg.conf)),
|
||||
btn('copy', _('Copy the configuration'), (ev) => copy(c.cfg.conf, _('Configuration copied'), ev.currentTarget)),
|
||||
),
|
||||
];
|
||||
}
|
||||
@@ -208,7 +224,7 @@ export function filePane(cfg: ClientConfig): HTMLElement {
|
||||
class: 'btn soft sm',
|
||||
onclick: () => {
|
||||
reveal = !reveal;
|
||||
eye.replaceChildren(ic(reveal ? 'x' : 'key'), h('span', {}, reveal ? 'Hide key' : 'Show key'));
|
||||
eye.replaceChildren(ic(reveal ? 'x' : 'key'), h('span', {}, reveal ? _('Hide key') : _('Show key')));
|
||||
paint();
|
||||
// A key shown comes into focus out of a blur; hidden again, the mask fades back.
|
||||
pre.querySelectorAll('.mask, .k').forEach((x) =>
|
||||
@@ -224,13 +240,13 @@ export function filePane(cfg: ClientConfig): HTMLElement {
|
||||
},
|
||||
},
|
||||
ic('key'),
|
||||
h('span', {}, 'Show key'),
|
||||
h('span', {}, _('Show key')),
|
||||
);
|
||||
const cp = h(
|
||||
'button',
|
||||
{ type: 'button', class: 'btn soft sm', onclick: (ev: Event) => copy(cfg.conf, 'Configuration copied', ev.currentTarget) },
|
||||
{ type: 'button', class: 'btn soft sm', onclick: (ev: Event) => copy(cfg.conf, _('Configuration copied'), ev.currentTarget) },
|
||||
ic('copy'),
|
||||
h('span', { class: 'lbl' }, 'Copy'),
|
||||
h('span', { class: 'lbl' }, _('Copy')),
|
||||
);
|
||||
const card = h(
|
||||
'div',
|
||||
@@ -239,16 +255,16 @@ export function filePane(cfg: ClientConfig): HTMLElement {
|
||||
'div',
|
||||
{ class: 'fc-row' },
|
||||
h('span', { class: 'filecard-ic' }, '.conf'),
|
||||
h('span', { class: 't' }, h('span', { class: 'mono' }, cfg.filename), h('span', {}, 'For computers and routers')),
|
||||
h('span', { class: 't' }, h('span', { class: 'mono' }, cfg.filename), h('span', {}, _('For computers and routers'))),
|
||||
),
|
||||
h(
|
||||
'button',
|
||||
{ type: 'button', class: 'btn accent sm block', onclick: () => sendFile(cfg.filename, cfg.conf) },
|
||||
ic(share ? 'open' : 'download'),
|
||||
h('span', {}, share ? 'Share file' : 'Download'),
|
||||
h('span', {}, share ? _('Share file') : _('Download')),
|
||||
),
|
||||
);
|
||||
const conf = accordion([{ icon: glass('file'), title: 'Configuration', body: [h('div', { class: 'confbar' }, eye, cp), pre] }], {
|
||||
const conf = accordion([{ icon: glass('file'), title: _('Configuration'), body: [h('div', { class: 'confbar' }, eye, cp), pre] }], {
|
||||
inset: true,
|
||||
});
|
||||
return h('div', { class: 'step-box' }, card, conf.el);
|
||||
@@ -265,7 +281,7 @@ export function scanLine(app: AppId): ScanLine {
|
||||
const name = h('span', { class: 'osm-p' }, APP_NAME[app]);
|
||||
const path = menuLine(scanPath(app, 'ios'), scanPath(app, 'android'));
|
||||
return {
|
||||
el: h('span', { class: 'scanline' }, h('span', {}, 'In ', name, ':'), path.el),
|
||||
el: h('span', { class: 'scanline' }, h('span', {}, ...fill(_('In %s:'), name)), path.el),
|
||||
set(a) {
|
||||
morphText(name, APP_NAME[a], undefined, { whole: true });
|
||||
path.set(scanPath(a, 'ios'), scanPath(a, 'android'));
|
||||
@@ -291,12 +307,12 @@ export function connPill(get: () => { text: string; msg: string; file: string; a
|
||||
const tip = h('span', { class: 'hp-tip', 'aria-hidden': 'true' }, tt, tm);
|
||||
const dl = h('button', { type: 'button', class: 'hp-b', onclick: () => sendFile(get().file, get().text) }, ic('download'));
|
||||
const cp = h('button', { type: 'button', class: 'hp-b' }, ic('copy'));
|
||||
const el = h('div', { class: 'hpill', role: 'group', 'aria-label': 'The connection', 'data-key': 'conn' }, dl, cp, tip);
|
||||
const el = h('div', { class: 'hpill', role: 'group', 'aria-label': _('The connection'), 'data-key': 'conn' }, dl, cp, tip);
|
||||
|
||||
let tipFor: HTMLElement | null = null;
|
||||
let tipT = 0;
|
||||
let warmUntil = 0;
|
||||
const words = (b: HTMLElement) => (b === cp && cp.classList.contains('done') ? 'Copied' : (b.getAttribute('aria-label') ?? ''));
|
||||
const words = (b: HTMLElement) => (b === cp && cp.classList.contains('done') ? _('Copied') : (b.getAttribute('aria-label') ?? ''));
|
||||
// Centred under its key, but never past the sheet's edge (× and its margin to the right).
|
||||
const centre = (b: HTMLElement, t: string) => {
|
||||
tm.textContent = t;
|
||||
@@ -401,8 +417,8 @@ export function connPill(get: () => { text: string; msg: string; file: string; a
|
||||
el,
|
||||
sync() {
|
||||
const app = get().app;
|
||||
dl.setAttribute('aria-label', `Download ${app} config`);
|
||||
cp.setAttribute('aria-label', `Copy ${app} config`);
|
||||
dl.setAttribute('aria-label', fmt(_('Download %s config'), app));
|
||||
cp.setAttribute('aria-label', fmt(_('Copy %s config'), app));
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -8,6 +8,7 @@
|
||||
// connection sits on top the whole time (wait.ts).
|
||||
|
||||
import type { ClientConfig, Device } from '../../shared/types';
|
||||
import { fmt } from '../../shared/i18n';
|
||||
import { vpnKey, vpnQrText } from '../../shared/vpnkey';
|
||||
import { ApiError, call } from '../api';
|
||||
import { h, put } from '../dom';
|
||||
@@ -115,6 +116,7 @@ export function setupView(d: Device, cfg: ClientConfig, key: string): View {
|
||||
const same = sameDevice(d.kind, pf);
|
||||
const layout: Layout = same ? 'same' : router ? 'router' : handheld ? 'away' : 'pc-away';
|
||||
const there = deviceNoun(d.kind);
|
||||
const thereOn = deviceNoun(d.kind, true);
|
||||
// A router takes AmneziaWG (or WireGuard), never AmneziaVPN.
|
||||
const choices = apps.filter((a) => !router || a.id !== 'vpn');
|
||||
let app: AppId = recallApp(d) ?? (router ? 'awg' : 'vpn');
|
||||
@@ -152,15 +154,15 @@ export function setupView(d: Device, cfg: ClientConfig, key: string): View {
|
||||
layout === 'away'
|
||||
? connPill(() => ({
|
||||
...(app === 'vpn'
|
||||
? { text: key, msg: 'Key copied', file: keyFileName(cfg.filename) }
|
||||
: { text: cfg.conf, msg: 'Configuration copied', file: cfg.filename }),
|
||||
? { text: key, msg: _('Key copied'), file: keyFileName(cfg.filename) }
|
||||
: { text: cfg.conf, msg: _('Configuration copied'), file: cfg.filename }),
|
||||
app: APP_NAME[app],
|
||||
}))
|
||||
: null;
|
||||
|
||||
/** Everything a pick changes, refilled in place. */
|
||||
function fill() {
|
||||
morphText(title1, router ? `Get ${APP_NAME[app]} on the router` : `Get ${APP_NAME[app]}`, undefined, { whole: true });
|
||||
morphText(title1, router ? fmt(_('Get %s on the router'), APP_NAME[app]) : fmt(_('Get %s'), APP_NAME[app]), undefined, { whole: true });
|
||||
morphInto(getBox, storeBlock(app, pf, router));
|
||||
// The router's file is the same for either app: it stays as it is (a folded configuration stays folded).
|
||||
if (!router) morphInto(addBox, connectKids(c));
|
||||
@@ -187,22 +189,22 @@ export function setupView(d: Device, cfg: ClientConfig, key: string): View {
|
||||
const linkThere = setupLink(pageUrl(), d.id);
|
||||
const linkBody = () => [
|
||||
handheld
|
||||
? codeRow(linkThere, [h('span', {}, 'Point its camera at the code: the link opens there.')]).el
|
||||
: h('p', { class: 'desc' }, `Open this link on the ${there} to set it up there.`),
|
||||
? codeRow(linkThere, [h('span', {}, _('Point its camera at the code: the link opens there.'))]).el
|
||||
: h('p', { class: 'desc' }, fmt(_('Open this link on the %s to set it up there.'), thereOn)),
|
||||
linkRow(linkThere),
|
||||
];
|
||||
const step1 = () => step('1', title1, [picker(), getBox]);
|
||||
const step2 = () => step('2', router ? 'Import the configuration' : 'Add the connection', [addBox]);
|
||||
const step2 = () => step('2', router ? _('Import the configuration') : _('Add the connection'), [addBox]);
|
||||
|
||||
const body = h('div', { class: 'setup' });
|
||||
if (inWebview(navigator.userAgent))
|
||||
body.appendChild(
|
||||
notice('warn', 'shield', null, 'Open this page in Safari or Chrome: the store opens from here, but the app handoff does not.'),
|
||||
notice('warn', 'shield', null, _('Open this page in Safari or Chrome: the store opens from here, but the app handoff does not.')),
|
||||
);
|
||||
if (layout === 'same') {
|
||||
// Opened, the way round folds the steps away: the device is not in hand.
|
||||
const steps = h('div', { class: 'steps-wrap' }, h('div', { class: 'steps-gap' }), step1(), step2());
|
||||
const round = accordion([{ icon: glass('link'), title: `Not on the ${there} right now?`, body: linkBody() }], {
|
||||
const round = accordion([{ icon: glass('link'), title: fmt(_('Not on the %s right now?'), thereOn), body: linkBody() }], {
|
||||
inset: true,
|
||||
onToggle: (_i, open, instant) => foldBlock(steps, open, instant),
|
||||
});
|
||||
@@ -213,8 +215,8 @@ export function setupView(d: Device, cfg: ClientConfig, key: string): View {
|
||||
body.appendChild(
|
||||
accordion(
|
||||
[
|
||||
{ icon: glass('link'), title: `Open your link on the ${there}`, body: linkBody() },
|
||||
{ icon: glass('app'), title: 'Already has the app', body: [picker(), codeBox] },
|
||||
{ icon: glass('link'), title: fmt(_('Open your link on the %s'), thereOn), body: linkBody() },
|
||||
{ icon: glass('app'), title: _('Already has the app'), body: [picker(), codeBox] },
|
||||
],
|
||||
{ inset: true, open: 1 },
|
||||
).el,
|
||||
@@ -224,8 +226,8 @@ export function setupView(d: Device, cfg: ClientConfig, key: string): View {
|
||||
body.appendChild(
|
||||
accordion(
|
||||
[
|
||||
{ icon: glass('link'), title: `Open your link on the ${there}`, body: linkBody() },
|
||||
{ icon: glass('key'), title: 'Copy or save the connection', body: [picker(), sendBox] },
|
||||
{ icon: glass('link'), title: fmt(_('Open your link on the %s'), thereOn), body: linkBody() },
|
||||
{ icon: glass('key'), title: _('Copy or save the connection'), body: [picker(), sendBox] },
|
||||
],
|
||||
{ inset: true, open: 0 },
|
||||
).el,
|
||||
@@ -248,7 +250,12 @@ export function setupView(d: Device, cfg: ClientConfig, key: string): View {
|
||||
onClosed(() => repaint());
|
||||
|
||||
const subline =
|
||||
layout === 'same' ? 'Two steps, about a minute' : router ? 'The packages and the file for OpenWrt' : `The app goes on the ${there}.`;
|
||||
const el = h('div', { class: 'view' }, head(`Set up ${d.name}`, { acts: !!pill }), sub(subline), way.el, body);
|
||||
return { el, label: `Set up ${d.name}`, acts: pill?.el ?? null };
|
||||
layout === 'same'
|
||||
? _('Two steps, about a minute')
|
||||
: router
|
||||
? _('The packages and the file for OpenWrt')
|
||||
: fmt(_('The app goes on the %s.'), there);
|
||||
const title = fmt(_('Set up %s'), d.name);
|
||||
const el = h('div', { class: 'view' }, head(title, { acts: !!pill }), sub(subline), way.el, body);
|
||||
return { el, label: title, acts: pill?.el ?? null };
|
||||
}
|
||||
@@ -5,6 +5,7 @@
|
||||
// and the sheet closes by itself onto the page.
|
||||
|
||||
import type { Device } from '../../shared/types';
|
||||
import { fmt } from '../../shared/i18n';
|
||||
import { gone, call } from '../api';
|
||||
import { h, ic } from '../dom';
|
||||
import { EASE_OUT, play } from '../motion';
|
||||
@@ -20,7 +21,7 @@ export interface Way {
|
||||
}
|
||||
|
||||
export function waitWay(d: Device): Way {
|
||||
const line = h('b', {}, 'Waiting for the connection');
|
||||
const line = h('b', {}, _('Waiting for the connection'));
|
||||
const more = h('span', { class: 'ws', hidden: true });
|
||||
const el = h(
|
||||
'div',
|
||||
@@ -38,12 +39,12 @@ export function waitWay(d: Device): Way {
|
||||
el,
|
||||
connected() {
|
||||
el.classList.add('done');
|
||||
morphText(line, `${d.name} connected`);
|
||||
morphText(line, fmt(_('%s connected'), d.name));
|
||||
},
|
||||
gaveUp() {
|
||||
el.classList.add('stopped');
|
||||
morphText(line, 'No connection yet');
|
||||
more.textContent = 'Close this and open it again to keep checking.';
|
||||
morphText(line, _('No connection yet'));
|
||||
more.textContent = _('Close this and open it again to keep checking.');
|
||||
more.hidden = false;
|
||||
play(
|
||||
line.parentElement!,
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
// The portal's languages: English (the code's) and the translations bundled
|
||||
// with it (i18n/<lang>.po, turned into lookup tables at build time). The page
|
||||
// opens in the visitor's own choice, kept in this browser, or else in the
|
||||
// first of the browser's (the system's) languages it has; the language menu in
|
||||
// the breadcrumb switches it in place. This module installs the globals _()
|
||||
// and N_() that the page and the shared code call (shared/i18n.ts), so it is
|
||||
// imported before anything that draws.
|
||||
|
||||
import type { Catalog } from '../../i18n/po';
|
||||
import ru from './i18n/ru.po';
|
||||
|
||||
export interface Lang {
|
||||
code: string;
|
||||
/** In its own language: what the menu lists. */
|
||||
name: string;
|
||||
}
|
||||
|
||||
export const LANGS: Lang[] = [
|
||||
{ code: 'en', name: 'English' },
|
||||
{ code: 'ru', name: 'Русский' },
|
||||
];
|
||||
|
||||
const catalogs: Record<string, Catalog[]> = { ru: [ru] };
|
||||
|
||||
/** Which plural form n takes (the index into the .po's msgstr[n]), by each language's gettext rule. */
|
||||
const FORMS: Record<string, (n: number) => number> = {
|
||||
en: (n) => (n !== 1 ? 1 : 0),
|
||||
ru: (n) => (n % 10 === 1 && n % 100 !== 11 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2),
|
||||
};
|
||||
|
||||
const STORE = 'dl.lang';
|
||||
|
||||
/** The language to open in: the visitor's kept choice, else the browser's first we have, else English. */
|
||||
export function pickLang(kept: string | null, browser: readonly string[]): string {
|
||||
const have = (c: string | null | undefined) => (c && LANGS.some((l) => l.code === c) ? c : null);
|
||||
return have(kept) ?? browser.map((b) => have(b.toLowerCase().split(/[-_]/)[0])).find(Boolean) ?? 'en';
|
||||
}
|
||||
|
||||
let current = 'en';
|
||||
let active: Catalog[] = [];
|
||||
const listeners: (() => void)[] = [];
|
||||
|
||||
const key = (s: string, ctx?: string) => (ctx ? `${ctx}\u0004${s}` : s);
|
||||
|
||||
function tr(s: string, ctx?: string): string {
|
||||
const k = key(s, ctx);
|
||||
for (const c of active) if (k in c.s) return c.s[k];
|
||||
return s;
|
||||
}
|
||||
|
||||
function ntr(n: number, s: string, p: string, ctx?: string): string {
|
||||
const k = key(s, ctx);
|
||||
const forms = active.find((c) => k in c.p)?.p[k];
|
||||
return forms?.[(FORMS[current] ?? FORMS.en)(n)] ?? (n === 1 ? s : p);
|
||||
}
|
||||
|
||||
export const lang = () => current;
|
||||
|
||||
/**
|
||||
* A message the router sent: in English when no translation is installed on
|
||||
* it, so the page translates the ones its catalog has (the backend's
|
||||
* portal.uc and devices.uc are in it).
|
||||
*/
|
||||
export const routerText = (msg: string) => tr(msg);
|
||||
|
||||
/** Switch the page's language; `keep`: remember it in this browser (the visitor chose it). */
|
||||
export function setLang(code: string, keep = true) {
|
||||
current = LANGS.some((l) => l.code === code) ? code : 'en';
|
||||
active = catalogs[current] ?? [];
|
||||
document.documentElement.lang = current;
|
||||
if (keep)
|
||||
try {
|
||||
localStorage.setItem(STORE, current);
|
||||
} catch {
|
||||
/* no storage: the choice lasts this visit */
|
||||
}
|
||||
listeners.forEach((f) => f());
|
||||
}
|
||||
|
||||
/** Redraw on a language change (main.ts: the page; the demo: its own parts). */
|
||||
export function onLang(f: () => void) {
|
||||
listeners.push(f);
|
||||
}
|
||||
|
||||
/** More strings for a language (the demo's own, from its catalog). */
|
||||
export function addCatalog(code: string, c: Catalog) {
|
||||
(catalogs[code] ??= []).push(c);
|
||||
if (code === current) active = catalogs[code];
|
||||
}
|
||||
|
||||
function kept(): string | null {
|
||||
try {
|
||||
return localStorage.getItem(STORE);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Object.assign(globalThis, { _: tr, N_: ntr });
|
||||
setLang(pickLang(kept(), navigator.languages?.length ? navigator.languages : [navigator.language]), false);
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
+21
-2
@@ -6,6 +6,8 @@
|
||||
// Layout: no navbar, a breadcrumb on top. Phone: "Your access" first, devices
|
||||
// under it; desktop (≥ 960px): devices left, access right and sticky.
|
||||
|
||||
// First: the translation globals, before anything draws.
|
||||
import { onLang } from './i18n';
|
||||
import { put, h } from './dom';
|
||||
import { EASE_OUT, play, publishSprings } from './motion';
|
||||
import { gone, call } from './api';
|
||||
@@ -26,6 +28,8 @@ const app = document.getElementById('app')!;
|
||||
|
||||
let parts: { notice: HTMLElement; devices: HTMLElement; access: HTMLElement } | null = null;
|
||||
let booted = false;
|
||||
/** How the page was last drawn: what a language change draws again. */
|
||||
let redraw: () => void = () => {};
|
||||
|
||||
/** The first paint comes in: the blocks rise one after the other, the sun rises behind its line. */
|
||||
function intro() {
|
||||
@@ -65,6 +69,7 @@ function intro() {
|
||||
function render(o: RepaintOpts = {}) {
|
||||
const st = state();
|
||||
if (!st) return;
|
||||
redraw = render;
|
||||
// Paused by the admin: nothing on the page works until it is resumed, so the page is the one card that says so.
|
||||
if (st.person.state === 'paused') {
|
||||
document.title = placeName();
|
||||
@@ -101,7 +106,14 @@ function only(icon: string, title: string, text: string, gone = false, tone: Ton
|
||||
function linkGone() {
|
||||
setState(null);
|
||||
closeSheet(true);
|
||||
only('key', 'This link no longer works', 'Ask for a new one.', true);
|
||||
redraw = linkGone;
|
||||
only('key', _('This link no longer works'), _('Ask for a new one.'), true);
|
||||
}
|
||||
|
||||
/** Nothing could load: the reason as the router or the browser gave it. */
|
||||
function notLoaded(why: string) {
|
||||
redraw = () => notLoaded(why);
|
||||
only('server', _('The page could not load'), why);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -130,10 +142,17 @@ async function refresh() {
|
||||
} catch (e) {
|
||||
if (gone(e)) linkGone();
|
||||
// A network hiccup: keep showing the last state (the page loads fresh data on reload).
|
||||
else if (!state()) only('server', 'The page could not load', (e as Error).message);
|
||||
else if (!state()) notLoaded((e as Error).message);
|
||||
}
|
||||
}
|
||||
|
||||
// Another language: everything is drawn again in it, the sections too (their headings are text).
|
||||
onLang(() => {
|
||||
closeMenu(true);
|
||||
parts = null;
|
||||
redraw();
|
||||
});
|
||||
|
||||
// What the keyboard does never animates.
|
||||
document.addEventListener('keydown', (e) => {
|
||||
if (e.key !== 'Escape') return;
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
// calendar of the weeks, with the admin's hours as a bar of the day.
|
||||
|
||||
import type { Person } from '../../shared/types';
|
||||
import { ACCESS_LABEL, byDeviceState, bytes, date, daysLeft, endsSoon, parseDay } from '../../shared/format';
|
||||
import { accessLabel, byDeviceState, bytes, date, daysLeft, endsSoon, parseDay } from '../../shared/format';
|
||||
import { fill, fmt, locale, num, plural } from '../../shared/i18n';
|
||||
import { h, ic, markup } from '../dom';
|
||||
import { calendar, clockOf, hoursFor, minuteAt, monthOf, stretches } from '../days';
|
||||
import { now, today, type State } from '../state';
|
||||
@@ -18,6 +19,8 @@ import { reachableFromHome } from './devices';
|
||||
const desc = (text: string) => h('p', { class: 'desc' }, text);
|
||||
/** A share of a length, as a CSS percentage. */
|
||||
const pc = (part: number, whole: number) => `${((part / whole) * 100).toFixed(2)}%`;
|
||||
/** A router day (YYYY-MM-DD) as "13 Oct", without the year. */
|
||||
const dayMonth = (d: string) => parseDay(d).toLocaleDateString(locale(), { day: 'numeric', month: 'short' });
|
||||
|
||||
/** What the access reaches, as two tiles: the home network and the internet, each in or out. */
|
||||
function reachTiles(access: Person['access']): HTMLElement {
|
||||
@@ -27,14 +30,14 @@ function reachTiles(access: Person['access']): HTMLElement {
|
||||
{ class: `reach-tile${on ? '' : ' off'}` },
|
||||
glass(icon, on ? 'blue' : 'grey', 'gi rt-ic'),
|
||||
h('b', {}, name),
|
||||
h('span', { class: 'rt-sub' }, on ? sub : 'Not included'),
|
||||
h('span', { class: 'rt-mark', 'aria-label': on ? 'Included' : 'Not included' }, ic(on ? 'check' : 'minus')),
|
||||
h('span', { class: 'rt-sub' }, on ? sub : _('Not included')),
|
||||
h('span', { class: 'rt-mark', 'aria-label': on ? _('Included') : _('Not included') }, ic(on ? 'check' : 'minus')),
|
||||
);
|
||||
return h(
|
||||
'div',
|
||||
{ class: 'reach2' },
|
||||
tile(access !== 'internet', 'home', 'Home network', 'Devices at home'),
|
||||
tile(access !== 'lan', 'globe', 'Internet', 'Through the router'),
|
||||
tile(access !== 'internet', 'home', _('Home network'), _('Devices at home')),
|
||||
tile(access !== 'lan', 'globe', _('Internet'), _('Through the router')),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -45,12 +48,12 @@ function namesAtHome(p: Person, mesh: boolean): Node[] {
|
||||
const first = named[0].hostname;
|
||||
const dot0 = first.indexOf('.');
|
||||
const domain = dot0 > 0 ? first.slice(dot0) : '';
|
||||
const pattern = h('span', { class: 'mono' }, `${_('name')}${domain}`);
|
||||
return [
|
||||
h(
|
||||
'span',
|
||||
{ class: 'lbl-s' },
|
||||
mesh ? 'Devices at home and on this VPN reach yours as ' : 'Other devices at home reach yours as ',
|
||||
h('span', { class: 'mono' }, `name${domain}`),
|
||||
...fill(mesh ? _('Devices at home and on this VPN reach yours as %s') : _('Other devices at home reach yours as %s'), pattern),
|
||||
),
|
||||
h(
|
||||
'div',
|
||||
@@ -63,8 +66,8 @@ function namesAtHome(p: Person, mesh: boolean): Node[] {
|
||||
type: 'button',
|
||||
class: 'namechip',
|
||||
title: d.name,
|
||||
'aria-label': `Copy ${d.hostname}`,
|
||||
onclick: (ev: Event) => copy(d.hostname, 'Address copied', ev.currentTarget),
|
||||
'aria-label': fmt(_('Copy %s'), d.hostname),
|
||||
onclick: (ev: Event) => copy(d.hostname, _('Address copied'), ev.currentTarget),
|
||||
},
|
||||
h('span', {}, dot > 0 ? [d.hostname.slice(0, dot), h('span', { class: 'faint' }, d.hostname.slice(dot))] : d.hostname),
|
||||
ic('copy'),
|
||||
@@ -95,12 +98,16 @@ function month(p: Person, used: number, pct: number): HTMLElement {
|
||||
const { days, day } = monthOf(today());
|
||||
const series = p.month_days ?? [];
|
||||
const max = Math.max(1, ...series);
|
||||
const short = (d: number) =>
|
||||
parseDay(`${today().slice(0, 8)}${String(d).padStart(2, '0')}`).toLocaleDateString('en-GB', { day: 'numeric', month: 'short' });
|
||||
const short = (d: number) => dayMonth(`${today().slice(0, 8)}${String(d).padStart(2, '0')}`);
|
||||
// The total, and a bar under the pointer in its place, at once: no morph while the pointer moves.
|
||||
const total = h('b', { class: 'num', 'data-t': 'm-used' }, bytes(used));
|
||||
const tail = h('span', {}, ' used');
|
||||
const read = h('span', { class: 'mread' }, total, tail);
|
||||
const read = h('span', { class: 'mread' });
|
||||
/** The month's total, or (`d`) one day's: the number in its sentence. */
|
||||
const say = (v: number, d?: number) => {
|
||||
setText(total, bytes(v));
|
||||
read.replaceChildren(...(d ? fill<Node | string>(_('%s on %s'), total, short(d)) : fill(_('%s used'), total)));
|
||||
};
|
||||
say(used);
|
||||
const bars = h('div', { class: 'mbars' });
|
||||
for (let i = 0; i < days; i++) {
|
||||
if (i >= day) {
|
||||
@@ -110,18 +117,12 @@ function month(p: Person, used: number, pct: number): HTMLElement {
|
||||
const v = series[i] ?? 0;
|
||||
const b = h('i', { class: i === day - 1 ? 'today' : '' });
|
||||
b.style.height = `${Math.max(3, Math.round((v / max) * 64))}px`;
|
||||
b.addEventListener('pointerenter', () => {
|
||||
setText(total, bytes(v));
|
||||
setText(tail, ` on ${short(i + 1)}`);
|
||||
});
|
||||
b.addEventListener('pointerleave', () => {
|
||||
setText(total, bytes(used));
|
||||
setText(tail, ' used');
|
||||
});
|
||||
b.addEventListener('pointerenter', () => say(v, i + 1));
|
||||
b.addEventListener('pointerleave', () => say(used));
|
||||
bars.appendChild(b);
|
||||
}
|
||||
// "Today" under its bar; the month's ends step aside when it comes close.
|
||||
const td = h('span', { class: 'td' }, 'Today');
|
||||
const td = h('span', { class: 'td' }, _('Today'));
|
||||
td.style.left = pc(day - 0.5, days);
|
||||
const axis = h(
|
||||
'div',
|
||||
@@ -142,7 +143,7 @@ function month(p: Person, used: number, pct: number): HTMLElement {
|
||||
h(
|
||||
'span',
|
||||
{ class: `num${p.state === 'quota' ? ' bad-t' : ''}`, 'data-t': 'm-left' },
|
||||
p.quota_limit ? `${bytes(Math.max(0, p.quota_limit - used))} left` : 'No limit',
|
||||
p.quota_limit ? fmt(_('%s left'), bytes(Math.max(0, p.quota_limit - used))) : _('No limit'),
|
||||
),
|
||||
),
|
||||
p.quota_limit ? meter(pct) : null,
|
||||
@@ -151,7 +152,9 @@ function month(p: Person, used: number, pct: number): HTMLElement {
|
||||
|
||||
/** The days left as a number over a calendar of the weeks to the end (the last day ringed). */
|
||||
function untilCal(p: Person, left: number): HTMLElement {
|
||||
const day = (d: string) => parseDay(d).toLocaleDateString('en-GB', { weekday: 'short', day: 'numeric', month: 'short' });
|
||||
const day = (d: string) => parseDay(d).toLocaleDateString(locale(), { weekday: 'short', day: 'numeric', month: 'short' });
|
||||
// The weekdays' initials, Monday first (1 Jan 2024 was a Monday).
|
||||
const weekdays = Array.from({ length: 7 }, (_x, i) => new Date(2024, 0, 1 + i, 12).toLocaleDateString(locale(), { weekday: 'narrow' }));
|
||||
const cells = calendar(today(), p.expires);
|
||||
const cal = cells
|
||||
? h(
|
||||
@@ -160,7 +163,7 @@ function untilCal(p: Person, left: number): HTMLElement {
|
||||
h(
|
||||
'div',
|
||||
{ class: 'cal-h' },
|
||||
['M', 'T', 'W', 'T', 'F', 'S', 'S'].map((x) => h('span', {}, x)),
|
||||
weekdays.map((x) => h('span', {}, x)),
|
||||
),
|
||||
h(
|
||||
'div',
|
||||
@@ -179,9 +182,9 @@ function untilCal(p: Person, left: number): HTMLElement {
|
||||
h(
|
||||
'div',
|
||||
{ class: 'until-num' },
|
||||
h('b', { class: 'num' }, String(left)),
|
||||
h('span', {}, `${left === 1 ? 'day' : 'days'} left`),
|
||||
h('span', { class: 'until-sub' }, `Ends ${day(p.expires)}`),
|
||||
h('b', { class: 'num' }, num(left)),
|
||||
h('span', {}, N_(left, 'day left', 'days left')),
|
||||
h('span', { class: 'until-sub' }, fmt(_('Ends %s'), day(p.expires))),
|
||||
),
|
||||
cal,
|
||||
);
|
||||
@@ -203,7 +206,7 @@ function hoursBar(hours: string, tzOffset: number | undefined): HTMLElement | nu
|
||||
i.style.width = pc(b - a, 1440);
|
||||
bar.appendChild(i);
|
||||
}
|
||||
const mark = h('span', { class: `hours-now${inside ? '' : ' out'}`, title: `Now, ${clockOf(at)}` });
|
||||
const mark = h('span', { class: `hours-now${inside ? '' : ' out'}`, title: fmt(_('Now, %s'), clockOf(at)) });
|
||||
mark.style.left = pc(at, 1440);
|
||||
bar.appendChild(mark);
|
||||
return h(
|
||||
@@ -212,7 +215,7 @@ function hoursBar(hours: string, tzOffset: number | undefined): HTMLElement | nu
|
||||
h(
|
||||
'div',
|
||||
{ class: 'hours-top' },
|
||||
h('span', {}, hw.yours ? 'Hours, your time' : 'Hours, router time'),
|
||||
h('span', {}, hw.yours ? _('Hours, your time') : _('Hours, router time')),
|
||||
h('b', { class: 'num' }, `${clockOf(hw.from)}–${clockOf(hw.to)}`),
|
||||
),
|
||||
bar,
|
||||
@@ -236,30 +239,30 @@ export function accessAccordion(st: State, open = 1): Accordion {
|
||||
? h(
|
||||
'span',
|
||||
{ class: 'until-val' },
|
||||
h('span', { class: 'num', 'data-t': 'until-date' }, date(p.expires).replace(/ \d{4}$/, '')),
|
||||
h('span', { class: 'num', 'data-t': 'until-date' }, dayMonth(p.expires)),
|
||||
left != null
|
||||
? h(
|
||||
'span',
|
||||
{ class: `num ${left < 0 ? 'bad-t' : endsSoon(p, left) ? 'warn-t' : 'ok-t'}`, 'data-t': 'until-left' },
|
||||
left >= 0 ? `${left} day${left === 1 ? '' : 's'}` : 'ended',
|
||||
left >= 0 ? plural(left, '%s day', '%s days') : _('ended'),
|
||||
)
|
||||
: null,
|
||||
)
|
||||
: h('span', {}, 'No end date');
|
||||
: h('span', {}, _('No end date'));
|
||||
const untilBody = [
|
||||
!p.expires ? null : left != null && left < 0 ? desc(`It ended on ${date(p.expires)}.`) : untilCal(p, left ?? 0),
|
||||
!p.expires ? null : left != null && left < 0 ? desc(fmt(_('It ended on %s.'), date(p.expires))) : untilCal(p, left ?? 0),
|
||||
p.hours ? hoursBar(p.hours, st.tz_offset) : null,
|
||||
];
|
||||
return accordion(
|
||||
[
|
||||
{
|
||||
icon: glass(p.access === 'internet' ? 'globe' : p.access === 'lan' ? 'home' : 'shield'),
|
||||
title: ACCESS_LABEL[p.access],
|
||||
title: accessLabel(p.access),
|
||||
body: [reachTiles(p.access), ...namesAtHome(p, !!st.server.device_mesh)],
|
||||
},
|
||||
{
|
||||
icon: glass('chart'),
|
||||
title: total ? 'Data used' : 'Data this month',
|
||||
title: total ? _('Data used') : _('Data this month'),
|
||||
val: h(
|
||||
'span',
|
||||
{ class: 'data-val' },
|
||||
@@ -267,23 +270,23 @@ export function accessAccordion(st: State, open = 1): Accordion {
|
||||
h(
|
||||
'span',
|
||||
{ class: 'num', 'data-t': 'data-val' },
|
||||
`${bytes(used)}${p.quota_limit ? ` / ${bytes(p.quota_limit)}` : ' · no limit'}`,
|
||||
`${bytes(used)} ${p.quota_limit ? `/ ${bytes(p.quota_limit)}` : `· ${_('no limit')}`}`,
|
||||
),
|
||||
),
|
||||
valHide: true,
|
||||
body: [
|
||||
total ? desc(`${bytes(used)} of ${bytes(p.quota_limit)} in total.`) : month(p, used, pct),
|
||||
total ? desc(fmt(_('%s of %s in total.'), bytes(used), bytes(p.quota_limit))) : month(p, used, pct),
|
||||
desc(
|
||||
!p.quota_limit
|
||||
? 'No data limit. The count starts again on the 1st.'
|
||||
? _('No data limit. The count starts again on the 1st.')
|
||||
: total
|
||||
? 'A total for your whole access, it does not reset.'
|
||||
: 'Resets on the 1st.',
|
||||
? _('A total for your whole access, it does not reset.')
|
||||
: _('Resets on the 1st.'),
|
||||
),
|
||||
],
|
||||
},
|
||||
// No end date and no hours: nothing to open, the row just says so.
|
||||
{ icon: glass('calendar'), title: 'Access until', val: untilVal, valHide: !!p.expires && (left ?? 0) >= 0, body: untilBody },
|
||||
{ icon: glass('calendar'), title: _('Access until'), val: untilVal, valHide: !!p.expires && (left ?? 0) >= 0, body: untilBody },
|
||||
],
|
||||
{ open },
|
||||
);
|
||||
@@ -293,8 +296,8 @@ export function accessAccordion(st: State, open = 1): Accordion {
|
||||
export function accessSection(): HTMLElement {
|
||||
return h(
|
||||
'section',
|
||||
{ class: 'access', id: 'access', 'aria-label': 'Your access' },
|
||||
h('div', { class: 'sec-head' }, h('h2', {}, 'Your access')),
|
||||
{ class: 'access', id: 'access', 'aria-label': _('Your access') },
|
||||
h('div', { class: 'sec-head' }, h('h2', {}, _('Your access'))),
|
||||
h('div', { class: 'acc-slot' }),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
|
||||
import type { Device, Person } from '../../shared/types';
|
||||
import { addDays, ago, byDeviceState, bytes, parseDay } from '../../shared/format';
|
||||
import { fmt, locale, num, plural } from '../../shared/i18n';
|
||||
import { h, ic } from '../dom';
|
||||
import { BOUNCY, EASE_IN, EASE_OUT, SMOOTH, play } from '../motion';
|
||||
import { now, today, type RepaintOpts, type State } from '../state';
|
||||
@@ -22,16 +23,16 @@ export const reachableFromHome = (p: Person, d: Device) => p.access !== 'interne
|
||||
|
||||
/** The status line: its class and words (short, on one line; the full wording shows on hover). */
|
||||
function statusOf(d: Device, p: Person): [string, string] {
|
||||
if (d.disabled) return ['', 'Disabled'];
|
||||
if (d.disabled) return ['', _('Disabled')];
|
||||
// The Update pill beside it says what to do.
|
||||
if (d.config_stale && d.handshake) return ['warn-t', 'Settings changed'];
|
||||
if (d.config_stale && d.handshake) return ['warn-t', _('Settings changed')];
|
||||
// Over the data limit or outside the hours the tunnel stays up but passes nothing: the app says
|
||||
// "connected", so say here why nothing works.
|
||||
if (d.online && p.state === 'quota') return ['warn-t', 'Connected, no data left'];
|
||||
if (d.online && p.state === 'hours') return ['warn-t', 'Connected, outside your hours'];
|
||||
if (d.online) return ['ok-t', 'Connected'];
|
||||
if (!d.handshake) return ['warn-t', 'Not set up yet'];
|
||||
return ['', `Last connected ${ago(d.handshake, now())}`];
|
||||
if (d.online && p.state === 'quota') return ['warn-t', _('Connected, no data left')];
|
||||
if (d.online && p.state === 'hours') return ['warn-t', _('Connected, outside your hours')];
|
||||
if (d.online) return ['ok-t', _('Connected')];
|
||||
if (!d.handshake) return ['warn-t', _('Not set up yet')];
|
||||
return ['', fmt(_('Last connected %s'), ago(d.handshake, now()))];
|
||||
}
|
||||
|
||||
function menuItems(d: Device, st: State): (MenuItem | null)[] {
|
||||
@@ -39,8 +40,8 @@ function menuItems(d: Device, st: State): (MenuItem | null)[] {
|
||||
// How devices at home reach it: only where the router actually lets them through.
|
||||
...(reachableFromHome(st.person, d)
|
||||
? [
|
||||
{ label: 'Copy IP address', icon: 'copy', run: () => copy(d.address, 'IP address copied') },
|
||||
...(d.hostname ? [{ label: 'Copy local address', icon: 'home', run: () => copy(d.hostname, 'Address copied') }] : []),
|
||||
{ label: _('Copy IP address'), icon: 'copy', run: () => copy(d.address, _('IP address copied')) },
|
||||
...(d.hostname ? [{ label: _('Copy local address'), icon: 'home', run: () => copy(d.hostname, _('Address copied')) }] : []),
|
||||
null,
|
||||
]
|
||||
: []),
|
||||
@@ -48,24 +49,24 @@ function menuItems(d: Device, st: State): (MenuItem | null)[] {
|
||||
...(d.disabled
|
||||
? []
|
||||
: [
|
||||
{ label: 'Rename', icon: 'edit', run: () => rename(d) },
|
||||
{ label: 'Reconnect', icon: 'refresh', tone: 'warn' as const, run: () => reconnect(d) },
|
||||
{ label: 'Remove', icon: 'trash', tone: 'bad' as const, run: () => removeDevice(d) },
|
||||
{ label: _('Rename'), icon: 'edit', run: () => rename(d) },
|
||||
{ label: _('Reconnect'), icon: 'refresh', tone: 'warn' as const, run: () => reconnect(d) },
|
||||
{ label: _('Remove'), icon: 'trash', tone: 'bad' as const, run: () => removeDevice(d) },
|
||||
]),
|
||||
];
|
||||
}
|
||||
|
||||
/** "Today", "Yesterday", "Tue 13 Oct": a spark bar's day, on the router's calendar. */
|
||||
function dayName(back: number): string {
|
||||
if (back === 0) return 'Today';
|
||||
if (back === 1) return 'Yesterday';
|
||||
return parseDay(addDays(today(), -back)).toLocaleDateString('en-GB', { weekday: 'short', day: 'numeric', month: 'short' });
|
||||
if (back === 0) return _('Today');
|
||||
if (back === 1) return _('Yesterday');
|
||||
return parseDay(addDays(today(), -back)).toLocaleDateString(locale(), { weekday: 'short', day: 'numeric', month: 'short' });
|
||||
}
|
||||
|
||||
/** Last 7 days as a number and bars; a bar under the pointer puts its own day in the number's place. */
|
||||
function usage(d: Device, stale: boolean): HTMLElement {
|
||||
const week = d.spark.reduce((a, b) => a + b, 0);
|
||||
const lbl = h('span', { class: 'use-lbl' }, 'Last 7 days');
|
||||
const lbl = h('span', { class: 'use-lbl' }, _('Last 7 days'));
|
||||
const val = h('span', { class: 'use-val num', 'data-t': `${d.id}:use` }, bytes(week));
|
||||
let side: HTMLElement;
|
||||
if (stale)
|
||||
@@ -74,12 +75,12 @@ function usage(d: Device, stale: boolean): HTMLElement {
|
||||
{
|
||||
type: 'button',
|
||||
class: 'upd-pill',
|
||||
'aria-label': 'Update the connection',
|
||||
title: 'Its settings changed: update the connection',
|
||||
'aria-label': _('Update the connection'),
|
||||
title: _('Its settings changed: update the connection'),
|
||||
onclick: () => reconnect(d),
|
||||
},
|
||||
ic('refresh'),
|
||||
h('span', {}, 'Update'),
|
||||
h('span', {}, _('Update')),
|
||||
);
|
||||
else {
|
||||
const max = Math.max(1, ...d.spark);
|
||||
@@ -94,7 +95,7 @@ function usage(d: Device, stale: boolean): HTMLElement {
|
||||
setText(val, bytes(v));
|
||||
});
|
||||
b.addEventListener('pointerleave', () => {
|
||||
setText(lbl, 'Last 7 days');
|
||||
setText(lbl, _('Last 7 days'));
|
||||
setText(val, bytes(week));
|
||||
});
|
||||
side.appendChild(b);
|
||||
@@ -108,15 +109,15 @@ function card(d: Device, st: State): HTMLElement {
|
||||
const locked = !!st.locked;
|
||||
// The device this page was opened from (through the tunnel): it is connected, so say which one it is instead.
|
||||
const here = st.here === d.id;
|
||||
const [cls, words] = here ? ['here-t', 'This device'] : statusOf(d, p);
|
||||
const [cls, words] = here ? ['here-t', _('This device')] : statusOf(d, p);
|
||||
const setUp = !d.handshake && !d.disabled;
|
||||
const stale = d.config_stale && !setUp && !locked && !d.disabled;
|
||||
// On one line; the exact time, or the whole wording, on hover.
|
||||
const title =
|
||||
!here && d.handshake && !d.online && !d.disabled && !d.config_stale
|
||||
? new Date(d.handshake * 1000).toLocaleString('en-GB')
|
||||
? new Date(d.handshake * 1000).toLocaleString(locale())
|
||||
: stale
|
||||
? 'Settings changed, update needed'
|
||||
? _('Settings changed, update needed')
|
||||
: words;
|
||||
const items = menuItems(d, st);
|
||||
const more =
|
||||
@@ -124,7 +125,13 @@ function card(d: Device, st: State): HTMLElement {
|
||||
? null
|
||||
: h(
|
||||
'button',
|
||||
{ type: 'button', class: 'knob more', 'aria-label': `${d.name} options`, 'aria-haspopup': 'menu', 'aria-expanded': 'false' },
|
||||
{
|
||||
type: 'button',
|
||||
class: 'knob more',
|
||||
'aria-label': fmt(_('%s options'), d.name),
|
||||
'aria-haspopup': 'menu',
|
||||
'aria-expanded': 'false',
|
||||
},
|
||||
ic('more'),
|
||||
);
|
||||
more?.addEventListener('click', () => openMenu(more, items));
|
||||
@@ -152,11 +159,11 @@ function card(d: Device, st: State): HTMLElement {
|
||||
{
|
||||
type: 'button',
|
||||
class: 'btn tint block setup-btn',
|
||||
'aria-label': `Set up ${d.name}`,
|
||||
'aria-label': fmt(_('Set up %s'), d.name),
|
||||
onclick: (ev: Event) => openSetup(d, ev.currentTarget),
|
||||
},
|
||||
ic('qr'),
|
||||
h('span', {}, 'Connect'),
|
||||
h('span', {}, _('Connect')),
|
||||
)
|
||||
: usage(d, stale),
|
||||
);
|
||||
@@ -168,25 +175,25 @@ const firstCard = (mobile: boolean) =>
|
||||
'div',
|
||||
{ class: 'dev first', 'data-id': 'first' },
|
||||
glass('plus', 'blue'),
|
||||
h('b', {}, 'Add your first device'),
|
||||
h('p', {}, 'Two steps, about a minute: get the app, then add the connection.'),
|
||||
h('b', {}, _('Add your first device')),
|
||||
h('p', {}, _('Two steps, about a minute: get the app, then add the connection.')),
|
||||
h(
|
||||
'button',
|
||||
{ type: 'button', class: 'btn accent block', onclick: startAdd },
|
||||
ic('plus'),
|
||||
h('span', {}, mobile ? 'Add this phone' : 'Add this device'),
|
||||
h('span', {}, mobile ? _('Add this phone') : _('Add this device')),
|
||||
),
|
||||
);
|
||||
|
||||
const addCard = () =>
|
||||
h('button', { type: 'button', class: 'dev add', 'data-id': 'add', onclick: startAdd }, glass('plus'), h('span', {}, 'Add device'));
|
||||
h('button', { type: 'button', class: 'dev add', 'data-id': 'add', onclick: startAdd }, glass('plus'), h('span', {}, _('Add device')));
|
||||
|
||||
/** The section, built once; `fill` puts the cards in. */
|
||||
export function devicesSection(): HTMLElement {
|
||||
return h(
|
||||
'section',
|
||||
{ class: 'devices', id: 'devices', 'aria-label': 'Your devices' },
|
||||
h('div', { class: 'sec-head' }, h('h2', {}, 'Your devices'), h('span', { class: 'aside num' })),
|
||||
{ class: 'devices', id: 'devices', 'aria-label': _('Your devices') },
|
||||
h('div', { class: 'sec-head' }, h('h2', {}, _('Your devices')), h('span', { class: 'aside num' })),
|
||||
h('div', { class: 'dgrid' }),
|
||||
h('p', { class: 'note-s limit', hidden: true }),
|
||||
);
|
||||
@@ -254,7 +261,7 @@ export function fillDevices(section: HTMLElement, st: State, o: RepaintOpts = {}
|
||||
}
|
||||
if (repainting) morphChanged(grid, said);
|
||||
const count = section.querySelector('.sec-head .aside') as HTMLElement;
|
||||
const n = `${p.devices.length} of ${p.device_limit}`;
|
||||
const n = fmt(_('%s of %s'), num(p.devices.length), num(p.device_limit));
|
||||
if (repainting) morphText(count, n);
|
||||
else count.textContent = n;
|
||||
// The admin may add devices past the limit.
|
||||
@@ -262,7 +269,11 @@ export function fillDevices(section: HTMLElement, st: State, o: RepaintOpts = {}
|
||||
const limit = section.querySelector('.limit') as HTMLElement;
|
||||
const was = limit.hidden;
|
||||
const hide = st.can_add || !!st.locked;
|
||||
limit.textContent = `You have reached your limit of ${p.device_limit} devices. Remove one to add another.`;
|
||||
limit.textContent = plural(
|
||||
p.device_limit,
|
||||
'You have reached your limit of %s device. Remove one to add another.',
|
||||
'You have reached your limit of %s devices. Remove one to add another.',
|
||||
);
|
||||
limit.getAnimations().forEach((a) => a.cancel());
|
||||
// A slot freed: the note fades the way it came, then leaves the layout.
|
||||
if (repainting && !was && hide) {
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
// The page's frame: no navbar. The page fades out under the screen's top and
|
||||
// bottom edges (the top fade only once it scrolls, so the breadcrumb at rest
|
||||
// stays crisp), and opens with a breadcrumb: the Dawnline mark, the place (the
|
||||
// server's name) and the person. The content goes in `body`.
|
||||
// server's name) and the person, then the language and this page's code. The
|
||||
// content goes in `body`.
|
||||
|
||||
import { h, ic, markup } from '../dom';
|
||||
import { placeName, state } from '../state';
|
||||
import { showPageCode } from '../flows/page-code';
|
||||
import { openMenu } from '../ui/menu';
|
||||
import { LANGS, lang, setLang } from '../i18n';
|
||||
|
||||
// The sun rises from behind the horizon once, on the visit's first paint.
|
||||
const LOGO =
|
||||
@@ -37,10 +40,28 @@ export function single(on: boolean) {
|
||||
pageEl?.classList.toggle('single', on);
|
||||
}
|
||||
|
||||
/** The language: its code and a chevron; the menu lists the languages by their own names. */
|
||||
function langPicker(): HTMLElement {
|
||||
const b = h(
|
||||
'button',
|
||||
{ type: 'button', class: 'cr-lang', 'aria-label': _('Language'), 'aria-haspopup': 'menu', 'aria-expanded': 'false' },
|
||||
h('span', {}, lang().toUpperCase()),
|
||||
ic('chevron', 'i cr-down'),
|
||||
);
|
||||
b.addEventListener('click', () =>
|
||||
openMenu(
|
||||
b,
|
||||
LANGS.map((l) => ({ label: l.name, checked: l.code === lang(), run: () => l.code !== lang() && setLang(l.code) })),
|
||||
),
|
||||
);
|
||||
return b;
|
||||
}
|
||||
|
||||
/**
|
||||
* The breadcrumb: the place, then the person (none when the link stopped
|
||||
* working); at its end, this page's code for another device, on the page
|
||||
* itself only (not over a card: paused, link gone, nothing loaded).
|
||||
* working); at its end, the language and this page's code for another
|
||||
* device, on the page itself only (not over a card: paused, link gone,
|
||||
* nothing loaded).
|
||||
*/
|
||||
export function crumbs(gone = false, card = false) {
|
||||
if (!crumbsEl) return;
|
||||
@@ -50,12 +71,13 @@ export function crumbs(gone = false, card = false) {
|
||||
h('span', { class: 'cr-mark' }, markup(LOGO)),
|
||||
h(
|
||||
'nav',
|
||||
{ class: 'cr-path', 'aria-label': 'Breadcrumb' },
|
||||
{ class: 'cr-path', 'aria-label': _('Breadcrumb') },
|
||||
place,
|
||||
p ? [ic('chevron'), h('span', { class: 'cur', 'aria-current': 'page' }, p.name)] : null,
|
||||
),
|
||||
...(card ? [] : [langPicker()]),
|
||||
...(p && !card
|
||||
? [h('button', { type: 'button', class: 'knob cr-qr', 'aria-label': 'Open on another device', onclick: showPageCode }, ic('qr'))]
|
||||
? [h('button', { type: 'button', class: 'knob cr-qr', 'aria-label': _('Open on another device'), onclick: showPageCode }, ic('qr'))]
|
||||
: []),
|
||||
);
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
import type { Person } from '../../shared/types';
|
||||
import { daysLeft, date, endsIn, endsSoon } from '../../shared/format';
|
||||
import { fmt } from '../../shared/i18n';
|
||||
import { h } from '../dom';
|
||||
import { clockOf, hoursFor } from '../days';
|
||||
import { state, today } from '../state';
|
||||
@@ -23,25 +24,26 @@ export function notice(tone: Tone, icon: string, title: string | null, sub: stri
|
||||
/** The admin's hours as the visitor reads them: "08:00–22:00 your time" (or the router's, said so). */
|
||||
export function hoursText(hours: string): string {
|
||||
const hw = hoursFor(hours, state()?.tz_offset, -new Date().getTimezoneOffset());
|
||||
if (!hw) return `${hours.replace('-', '–')} (router time)`;
|
||||
return `${clockOf(hw.from)}–${clockOf(hw.to)} ${hw.yours ? 'your time' : '(router time)'}`;
|
||||
if (!hw) return fmt(_('%s (router time)'), hours.replace('-', '–'));
|
||||
const span = `${clockOf(hw.from)}–${clockOf(hw.to)}`;
|
||||
return fmt(hw.yours ? _('%s your time') : _('%s (router time)'), span);
|
||||
}
|
||||
|
||||
/** Why the person's devices can't connect: icon, a short title, and a line that adds to it (never says it again). */
|
||||
export function stateNotice(p: Person): [string, string, string] {
|
||||
switch (p.state) {
|
||||
case 'server_off':
|
||||
return ['server', 'Server is disabled', 'Your devices can’t connect until it’s enabled again.'];
|
||||
return ['server', _('Server is disabled'), _('Your devices can’t connect until it’s enabled again.')];
|
||||
case 'no_server':
|
||||
return ['server', 'No server yet', 'You haven’t been added to one.'];
|
||||
return ['server', _('No server yet'), _('You haven’t been added to one.')];
|
||||
case 'quota':
|
||||
return ['chart', 'Out of data', 'Nothing gets through until it resets.'];
|
||||
return ['chart', _('Out of data'), _('Nothing gets through until it resets.')];
|
||||
case 'expired':
|
||||
return ['calendar', 'Access ended', 'Your devices can’t connect until it’s extended.'];
|
||||
return ['calendar', _('Access ended'), _('Your devices can’t connect until it’s extended.')];
|
||||
case 'hours':
|
||||
return ['clock', 'Outside your hours', `Open ${hoursText(p.hours)}.`];
|
||||
return ['clock', _('Outside your hours'), fmt(_('Open %s.'), hoursText(p.hours))];
|
||||
default:
|
||||
return ['pause', 'Access paused', 'Your devices can’t connect until it’s resumed.'];
|
||||
return ['pause', _('Access paused'), _('Your devices can’t connect until it’s resumed.')];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,5 +51,7 @@ export function stateNotice(p: Person): [string, string, string] {
|
||||
export function pageNotice(p: Person): HTMLElement | null {
|
||||
if (p.state !== 'active') return notice(p.state === 'quota' || p.state === 'expired' ? 'bad' : 'warn', ...stateNotice(p));
|
||||
const left = daysLeft(p.expires, today());
|
||||
return endsSoon(p, left) ? notice('warn', 'calendar', `Access ${endsIn(left as number)}`, `On ${date(p.expires)}.`) : null;
|
||||
return endsSoon(p, left)
|
||||
? notice('warn', 'calendar', fmt(_('Access %s'), endsIn(left as number)), fmt(_('On %s.'), date(p.expires)))
|
||||
: null;
|
||||
}
|
||||
Vendored
+6
@@ -0,0 +1,6 @@
|
||||
// A .po catalog imported by the portal is its lookup table, made at build time
|
||||
// (tsup.config.ts and vitest.config.ts read it with i18n/po.ts).
|
||||
declare module '*.po' {
|
||||
const catalog: import('../../i18n/po').Catalog;
|
||||
export default catalog;
|
||||
}
|
||||
+79
-54
@@ -2,6 +2,7 @@
|
||||
// is open on the device being set up. Pure: the set-up sheet (flows/) draws it.
|
||||
|
||||
import type { Kind } from '../shared/types';
|
||||
import { fmt } from '../shared/i18n';
|
||||
|
||||
export type Platform = 'ios' | 'android' | 'windows' | 'mac' | 'linux' | 'unknown';
|
||||
export type AppId = 'vpn' | 'awg' | 'wg';
|
||||
@@ -61,64 +62,67 @@ export interface Store {
|
||||
}
|
||||
|
||||
const GH_CLIENT = 'https://github.com/amnezia-vpn/amnezia-client/releases/latest';
|
||||
const APK: NonNullable<Store['alt']> = {
|
||||
href: GH_CLIENT,
|
||||
top: 'APK file on',
|
||||
const apk = (href: string): NonNullable<Store['alt']> => ({
|
||||
href,
|
||||
top: _('APK file on'),
|
||||
main: 'GitHub',
|
||||
mark: 'github',
|
||||
why: 'The APK is for phones without Google Play, or where the store hides the app.',
|
||||
};
|
||||
why: _('The APK is for phones without Google Play, or where the store hides the app.'),
|
||||
});
|
||||
|
||||
/** Where the app comes from on a platform: the store first, the official GitHub release where no store has it. */
|
||||
export function storeFor(app: AppId, platform: Platform): Store | null {
|
||||
const onAppStore = _('Download on the');
|
||||
const onPlay = _('Get it on');
|
||||
const onGitHub = _('Official release on GitHub');
|
||||
const S: Record<AppId, Partial<Record<Platform, Store>>> = {
|
||||
vpn: {
|
||||
ios: { href: 'https://apps.apple.com/app/amneziavpn/id1600529900', top: 'Download on the', main: 'App Store', mark: 'appstore' },
|
||||
ios: { href: 'https://apps.apple.com/app/amneziavpn/id1600529900', top: onAppStore, main: 'App Store', mark: 'appstore' },
|
||||
android: {
|
||||
href: 'https://play.google.com/store/apps/details?id=org.amnezia.vpn',
|
||||
top: 'Get it on',
|
||||
top: onPlay,
|
||||
main: 'Google Play',
|
||||
mark: 'googleplay',
|
||||
alt: APK,
|
||||
alt: apk(GH_CLIENT),
|
||||
},
|
||||
windows: { href: GH_CLIENT, top: 'Official release on GitHub', main: 'Download for Windows', mark: 'windows' },
|
||||
mac: { href: GH_CLIENT, top: 'Official release on GitHub', main: 'Download for Mac', mark: 'apple' },
|
||||
linux: { href: GH_CLIENT, top: 'Official release on GitHub', main: 'Download for Linux', mark: 'linux' },
|
||||
windows: { href: GH_CLIENT, top: onGitHub, main: _('Download for Windows'), mark: 'windows' },
|
||||
mac: { href: GH_CLIENT, top: onGitHub, main: _('Download for Mac'), mark: 'apple' },
|
||||
linux: { href: GH_CLIENT, top: onGitHub, main: _('Download for Linux'), mark: 'linux' },
|
||||
},
|
||||
awg: {
|
||||
ios: { href: 'https://apps.apple.com/us/app/amneziawg/id6478942365', top: 'Download on the', main: 'App Store', mark: 'appstore' },
|
||||
ios: { href: 'https://apps.apple.com/us/app/amneziawg/id6478942365', top: onAppStore, main: 'App Store', mark: 'appstore' },
|
||||
android: {
|
||||
href: 'https://play.google.com/store/apps/details?id=org.amnezia.awg',
|
||||
top: 'Get it on',
|
||||
top: onPlay,
|
||||
main: 'Google Play',
|
||||
mark: 'googleplay',
|
||||
alt: { ...APK, href: 'https://github.com/amnezia-vpn/amneziawg-android/releases' },
|
||||
alt: apk('https://github.com/amnezia-vpn/amneziawg-android/releases'),
|
||||
},
|
||||
windows: {
|
||||
href: 'https://github.com/amnezia-vpn/amneziawg-windows-client/releases',
|
||||
top: 'Official release on GitHub',
|
||||
main: 'Download for Windows',
|
||||
top: onGitHub,
|
||||
main: _('Download for Windows'),
|
||||
mark: 'windows',
|
||||
},
|
||||
mac: {
|
||||
href: 'https://apps.apple.com/us/app/amneziawg/id6478942365',
|
||||
top: 'Download on the',
|
||||
top: onAppStore,
|
||||
main: 'Mac App Store',
|
||||
mark: 'appstore',
|
||||
},
|
||||
linux: { href: 'https://github.com/amnezia-vpn/amneziawg-tools', top: 'On GitHub', main: 'amneziawg-tools', mark: 'linux' },
|
||||
linux: { href: 'https://github.com/amnezia-vpn/amneziawg-tools', top: _('On GitHub'), main: 'amneziawg-tools', mark: 'linux' },
|
||||
},
|
||||
wg: {
|
||||
ios: { href: 'https://apps.apple.com/app/wireguard/id1441195209', top: 'Download on the', main: 'App Store', mark: 'appstore' },
|
||||
ios: { href: 'https://apps.apple.com/app/wireguard/id1441195209', top: onAppStore, main: 'App Store', mark: 'appstore' },
|
||||
android: {
|
||||
href: 'https://play.google.com/store/apps/details?id=com.wireguard.android',
|
||||
top: 'Get it on',
|
||||
top: onPlay,
|
||||
main: 'Google Play',
|
||||
mark: 'googleplay',
|
||||
},
|
||||
windows: { href: 'https://www.wireguard.com/install/', top: 'Download from', main: 'wireguard.com', mark: 'windows' },
|
||||
mac: { href: 'https://apps.apple.com/app/wireguard/id1451685025', top: 'Download on the', main: 'Mac App Store', mark: 'appstore' },
|
||||
linux: { href: 'https://www.wireguard.com/install/', top: 'Install from', main: 'wireguard.com', mark: 'linux' },
|
||||
windows: { href: 'https://www.wireguard.com/install/', top: _('Download from'), main: 'wireguard.com', mark: 'windows' },
|
||||
mac: { href: 'https://apps.apple.com/app/wireguard/id1451685025', top: onAppStore, main: 'Mac App Store', mark: 'appstore' },
|
||||
linux: { href: 'https://www.wireguard.com/install/', top: _('Install from'), main: 'wireguard.com', mark: 'linux' },
|
||||
},
|
||||
};
|
||||
return S[app][platform] ?? null;
|
||||
@@ -129,12 +133,12 @@ export const routerStore = (app: AppId): Store =>
|
||||
app === 'wg'
|
||||
? {
|
||||
href: 'https://openwrt.org/docs/guide-user/services/vpn/wireguard/start',
|
||||
top: 'OpenWrt packages',
|
||||
top: _('OpenWrt packages'),
|
||||
main: 'wireguard-tools',
|
||||
mark: 'openwrt',
|
||||
}
|
||||
: // One line on a phone: the kernel module goes on top.
|
||||
{ href: 'https://openwrt.org/packages/start', top: 'OpenWrt packages + kmod', main: 'amneziawg-tools', mark: 'openwrt' };
|
||||
{ href: 'https://openwrt.org/packages/start', top: _('OpenWrt packages + kmod'), main: 'amneziawg-tools', mark: 'openwrt' };
|
||||
|
||||
/**
|
||||
* Does AmneziaVPN here open a `vpn://` link? Only the Android app registers the
|
||||
@@ -146,31 +150,45 @@ export const opensKeyLinks = (platform: Platform): boolean => platform === 'andr
|
||||
/** The key as a file for the share sheet: AmneziaVPN on iOS imports `.vpn` files (the key as text). */
|
||||
export const keyFileName = (confName: string): string => `${confName.replace(/\.conf$/i, '')}.vpn`;
|
||||
|
||||
/** A path through an app's menus: its items in order. */
|
||||
const menu = (...items: string[]) => items.join(' → ');
|
||||
|
||||
/*
|
||||
* Inside the app: where the scanner and the importer are, as each platform's
|
||||
* app words it. The WireGuard apps are the same apps as AmneziaWG (it is
|
||||
* their fork), menus included.
|
||||
* Inside the app: where the scanner and the importer are, word for word as
|
||||
* each platform's app labels them, in its own Russian when the page is in
|
||||
* Russian (every one of these apps has it). Checked against the apps'
|
||||
* sources in October 2026: wireguard-apple, wireguard-android and
|
||||
* wireguard-windows, their amneziawg forks (the same apps, menus included)
|
||||
* and amnezia-client. The context keeps the apps' words apart from the
|
||||
* portal's own. AmneziaVPN opens its "Connection" screen from the + in its
|
||||
* bottom bar (no label there); the scanner is on it on phones only.
|
||||
*/
|
||||
const TUNNEL_MENU: Partial<Record<Platform, { file: string; qr?: string }>> = {
|
||||
ios: { file: '+ → Create from file or archive', qr: '+ → Create from QR code' },
|
||||
android: { file: '+ → Import from file or archive', qr: '+ → Scan from QR code' },
|
||||
mac: { file: '+ → Import tunnel(s) from file' },
|
||||
windows: { file: 'Add Tunnel → Import tunnel(s) from file' },
|
||||
};
|
||||
function tunnelMenu(platform: Platform): { file: string; qr?: string } | undefined {
|
||||
const menus: Partial<Record<Platform, { file: string; qr?: string }>> = {
|
||||
ios: { file: menu('+', _('Create from file or archive', 'WireGuard app')), qr: menu('+', _('Create from QR code', 'WireGuard app')) },
|
||||
android: { file: menu('+', _('Import from file or archive', 'WireGuard app')), qr: menu('+', _('Scan from QR code', 'WireGuard app')) },
|
||||
mac: { file: menu('+', _('Import Tunnel(s) from File…', 'WireGuard app')) },
|
||||
windows: { file: menu(_('Add Tunnel', 'WireGuard app'), _('Import tunnel(s) from file…', 'WireGuard app')) },
|
||||
};
|
||||
return menus[platform];
|
||||
}
|
||||
|
||||
/** Where the app scans a code; a phone of either kind gets both wordings. */
|
||||
export function scanPath(app: AppId, platform: Platform = 'unknown'): string {
|
||||
if (app === 'vpn') return 'Add server → Scan QR';
|
||||
const qr = TUNNEL_MENU[platform]?.qr;
|
||||
return qr ?? `${TUNNEL_MENU.ios!.qr} (Android: ${TUNNEL_MENU.android!.qr!.replace(/^.* → /, '')})`;
|
||||
if (app === 'vpn') return menu('+', _('QR code', 'AmneziaVPN app'));
|
||||
const qr = tunnelMenu(platform)?.qr;
|
||||
return qr ?? fmt(_('%s (Android: %s)'), tunnelMenu('ios')!.qr, tunnelMenu('android')!.qr!.replace(/^.* → /, ''));
|
||||
}
|
||||
|
||||
/** Where the app takes a file (AmneziaVPN: the key). */
|
||||
/** Where the app takes a file (AmneziaVPN: the key, pasted by its Insert button); elsewhere, the Android app's words. */
|
||||
export function importPath(app: AppId, platform: Platform = 'unknown'): string {
|
||||
if (app === 'vpn') return 'Add server → Insert key';
|
||||
return TUNNEL_MENU[platform]?.file ?? 'Add tunnel → Import from file';
|
||||
if (app === 'vpn') return menu('+', _('Insert', 'AmneziaVPN app'));
|
||||
return (tunnelMenu(platform) ?? tunnelMenu('android')!).file;
|
||||
}
|
||||
|
||||
/** The last step in AmneziaVPN, once the key is in: its Continue button. */
|
||||
export const vpnContinue = () => fmt(_('Tap “%s” and connect'), _('Continue', 'AmneziaVPN app'));
|
||||
|
||||
/**
|
||||
* The file into the app, step by step: [text, the part in bold]. Linux has no
|
||||
* app, only the tools: the file goes up straight from where it was saved
|
||||
@@ -179,25 +197,22 @@ export function importPath(app: AppId, platform: Platform = 'unknown'): string {
|
||||
export function importSteps(app: AppId, platform: Platform, file: string, shared: boolean): [string, string][] {
|
||||
if (platform === 'linux')
|
||||
return [
|
||||
['Open a terminal in the folder with the file', ''],
|
||||
['Run ', `sudo ${app === 'wg' ? 'wg-quick' : 'awg-quick'} up ./${file}`],
|
||||
[_('Open a terminal in the folder with the file'), ''],
|
||||
// The command comes after the word, in bold: "Run sudo awg-quick up …".
|
||||
[`${_('Run')} `, `sudo ${app === 'wg' ? 'wg-quick' : 'awg-quick'} up ./${file}`],
|
||||
];
|
||||
const path = importPath(app, platform);
|
||||
return [
|
||||
[`Open ${APP_NAME[app]}`, ''],
|
||||
[fmt(_('Open %s', 'step'), APP_NAME[app]), ''],
|
||||
[path.replace(/ → [^→]*$/, ' → '), path.replace(/^.* → /, '')],
|
||||
[shared ? 'Confirm the import and connect' : 'Pick the file and connect', ''],
|
||||
[shared ? _('Confirm the import and connect') : _('Pick the file and connect'), ''],
|
||||
];
|
||||
}
|
||||
|
||||
export const PLATFORM_LABEL: Record<Platform, string> = {
|
||||
ios: 'iPhone / iPad',
|
||||
android: 'Android',
|
||||
windows: 'Windows',
|
||||
mac: 'Mac',
|
||||
linux: 'Linux',
|
||||
unknown: 'this device',
|
||||
};
|
||||
/** The platform in a sentence: its name, or "this device". */
|
||||
export function platformLabel(p: Platform): string {
|
||||
return { ios: 'iPhone / iPad', android: 'Android', windows: 'Windows', mac: 'Mac', linux: 'Linux', unknown: _('this device') }[p];
|
||||
}
|
||||
|
||||
/**
|
||||
* The personal link that opens straight on one device's set-up: the page then
|
||||
@@ -220,6 +235,16 @@ export const wantsAdd = (hash: string): boolean => hash === '#add';
|
||||
/**
|
||||
* "the phone", "the computer": the device being set up, in a sentence. The
|
||||
* sheet's title already names it; the lines under it do not repeat the name.
|
||||
* `on`: the word after "on the" ("open it on the phone"), which other
|
||||
* languages decline (Russian: на телефоне, but на телефон after "to the").
|
||||
*/
|
||||
export const deviceNoun = (kind: Kind): string =>
|
||||
({ phone: 'phone', tablet: 'tablet', computer: 'computer', router: 'router', other: 'device' })[kind];
|
||||
export const deviceNoun = (kind: Kind, on = false): string =>
|
||||
(on
|
||||
? {
|
||||
phone: _('phone', 'on the'),
|
||||
tablet: _('tablet', 'on the'),
|
||||
computer: _('computer', 'on the'),
|
||||
router: _('router', 'on the'),
|
||||
other: _('device', 'on the'),
|
||||
}
|
||||
: { phone: _('phone'), tablet: _('tablet'), computer: _('computer'), router: _('router'), other: _('device') })[kind];
|
||||
@@ -55,6 +55,10 @@
|
||||
height: 16px;
|
||||
color: var(--text-2);
|
||||
}
|
||||
/* An option's check, kept in its place on the others so the names line up. */
|
||||
.mi .i.off {
|
||||
visibility: hidden;
|
||||
}
|
||||
.mi.warn,
|
||||
.mi.warn .i {
|
||||
color: var(--warn);
|
||||
|
||||
@@ -81,6 +81,44 @@ body.scrolled .edge-fade.top {
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
}
|
||||
/* The language: a pill as high as the QR knob beside it, its code and a chevron that turns up while
|
||||
the menu is open. */
|
||||
.cr-lang {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
height: 32px;
|
||||
padding: 0 8px 0 12px;
|
||||
border-radius: 999px;
|
||||
background: var(--knob);
|
||||
color: var(--text);
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
letter-spacing: -0.01em;
|
||||
flex: none;
|
||||
transition:
|
||||
transform 150ms var(--ease-out),
|
||||
background-color 150ms;
|
||||
}
|
||||
.cr-lang:hover {
|
||||
background: color-mix(in srgb, var(--knob), var(--text) 6%);
|
||||
}
|
||||
.cr-lang:active {
|
||||
transform: scale(0.94);
|
||||
}
|
||||
.cr-lang[aria-expanded='true'] {
|
||||
background: color-mix(in srgb, var(--knob), var(--text) 10%);
|
||||
}
|
||||
.cr-down {
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
color: var(--text-2);
|
||||
transform: rotate(90deg);
|
||||
transition: transform 200ms var(--ease-out);
|
||||
}
|
||||
.cr-lang[aria-expanded='true'] .cr-down {
|
||||
transform: rotate(-90deg);
|
||||
}
|
||||
|
||||
/* Phones: one column, access first. From 960px: devices left, access right and sticky. The foot
|
||||
clears the bottom fade at the end of the scroll. */
|
||||
|
||||
@@ -210,7 +210,8 @@
|
||||
visibility: hidden;
|
||||
white-space: nowrap;
|
||||
}
|
||||
/* Connected: nothing is left to do here, so × and the view's buttons step away; the sheet then closes by itself. */
|
||||
/* Connected: nothing is left to do here, so × and the view's buttons step away; the sheet then closes
|
||||
by itself. A question has its own Cancel: no × beside it either. */
|
||||
.sheet .x,
|
||||
.sheet-acts {
|
||||
transition:
|
||||
@@ -221,7 +222,8 @@
|
||||
scale 240ms var(--ease-out);
|
||||
}
|
||||
.sheet.arrived .x,
|
||||
.sheet.arrived .sheet-acts {
|
||||
.sheet.arrived .sheet-acts,
|
||||
.sheet.asks .x {
|
||||
opacity: 0;
|
||||
filter: blur(3px);
|
||||
scale: 0.9;
|
||||
@@ -229,38 +231,54 @@
|
||||
}
|
||||
|
||||
/* A question before something that cannot be undone. */
|
||||
.center-col {
|
||||
.center-col,
|
||||
.ask {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.center-col {
|
||||
align-items: center;
|
||||
text-align: center;
|
||||
}
|
||||
.center-col.ask {
|
||||
padding-top: 28px;
|
||||
/* A question before something that cannot be undone (Reconnect, Remove): the icon, the question
|
||||
and what happens on the left edge, as iOS asks now, as far from the top as from the sides; the
|
||||
buttons span the sheet under them. */
|
||||
.ask {
|
||||
align-items: flex-start;
|
||||
text-align: left;
|
||||
padding-top: 24px;
|
||||
}
|
||||
.center-col.secure {
|
||||
padding-top: 4px;
|
||||
}
|
||||
.center-col .gi.xl {
|
||||
:is(.center-col, .ask) .gi.xl {
|
||||
width: 64px;
|
||||
height: 64px;
|
||||
margin: 8px 0 16px;
|
||||
}
|
||||
.center-col h3 {
|
||||
.ask .gi.xl {
|
||||
margin: 0 0 18px;
|
||||
}
|
||||
:is(.center-col, .ask) h3 {
|
||||
margin: 0;
|
||||
font-size: 20px;
|
||||
line-height: 28px;
|
||||
font-weight: 500;
|
||||
letter-spacing: -0.5px;
|
||||
}
|
||||
.center-col p {
|
||||
:is(.center-col, .ask) p {
|
||||
margin: 6px 0 22px;
|
||||
color: var(--text-2);
|
||||
font-size: 15px;
|
||||
line-height: 21px;
|
||||
}
|
||||
.center-col p {
|
||||
max-width: 30ch;
|
||||
text-wrap: balance;
|
||||
}
|
||||
.ask p {
|
||||
text-wrap: pretty;
|
||||
}
|
||||
.center-col.secure p {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
@@ -98,7 +98,12 @@ export function linkRow(url: string): HTMLElement {
|
||||
h('span', { class: 'mono' }, url.replace(/^https?:\/\//, '')),
|
||||
h(
|
||||
'button',
|
||||
{ type: 'button', class: 'knob', 'aria-label': 'Copy the link', onclick: (ev: Event) => copy(url, 'Link copied', ev.currentTarget) },
|
||||
{
|
||||
type: 'button',
|
||||
class: 'knob',
|
||||
'aria-label': _('Copy the link'),
|
||||
onclick: (ev: Event) => copy(url, _('Link copied'), ev.currentTarget),
|
||||
},
|
||||
ic('copy'),
|
||||
),
|
||||
share
|
||||
@@ -107,7 +112,7 @@ export function linkRow(url: string): HTMLElement {
|
||||
{
|
||||
type: 'button',
|
||||
class: 'knob',
|
||||
'aria-label': 'Share the link',
|
||||
'aria-label': _('Share the link'),
|
||||
onclick: () => navigator.share({ url, title: placeName() }).catch(() => undefined),
|
||||
},
|
||||
ic('share'),
|
||||
|
||||
@@ -43,7 +43,9 @@ export function toast(msg: string, bad = false) {
|
||||
|
||||
/**
|
||||
* The control that copied says so for a moment: its icon turns into a check
|
||||
* and a "Copy…" label (`.lbl`, a badge's main line) into "Copied".
|
||||
* and its "Copy…" label (`.lbl`, a badge's main line) into "Copied". Every
|
||||
* control that copies with a label says "Copy…" (in any language), so the
|
||||
* label is not read for the word.
|
||||
*/
|
||||
function copied(from: Element) {
|
||||
if (from.classList.contains('copied')) return;
|
||||
@@ -67,16 +69,16 @@ function copied(from: Element) {
|
||||
},
|
||||
);
|
||||
}
|
||||
if (label && /^Copy/.test(was)) morphText(label, 'Copied');
|
||||
if (label) morphText(label, _('Copied'));
|
||||
setTimeout(() => {
|
||||
if (check && icon) check.replaceWith(icon);
|
||||
if (label && /^Copy/.test(was)) morphText(label, was);
|
||||
if (label) morphText(label, was);
|
||||
from.classList.remove('copied');
|
||||
}, 1600);
|
||||
}
|
||||
|
||||
/** `from`: the control that copied, which then shows a check for a moment. */
|
||||
export async function copy(text: string, what = 'Copied', from?: EventTarget | null) {
|
||||
export async function copy(text: string, what = _('Copied'), from?: EventTarget | null) {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
} catch {
|
||||
@@ -85,7 +87,7 @@ export async function copy(text: string, what = 'Copied', from?: EventTarget | n
|
||||
ta.select();
|
||||
const ok = document.execCommand('copy');
|
||||
ta.remove();
|
||||
if (!ok) return toast('Copying is blocked here. Select the text and copy it by hand.', true);
|
||||
if (!ok) return toast(_('Copying is blocked here. Select the text and copy it by hand.'), true);
|
||||
}
|
||||
if (from instanceof Element) copied(from);
|
||||
toast(what);
|
||||
|
||||
@@ -1,14 +1,18 @@
|
||||
// The ⋯ menu: a small panel under (or over) its button, items with an icon,
|
||||
// a highlight that glides after the pointer and takes the item's colour
|
||||
// (orange for Reconnect, red for Remove). One at a time; it closes on a press
|
||||
// outside, on scroll, on Escape and when its button is pressed again.
|
||||
// (orange for Reconnect, red for Remove). A choice among options (the
|
||||
// language) marks the current one with a check instead of icons. One at a
|
||||
// time; it closes on a press outside, on scroll, on Escape and when its button
|
||||
// is pressed again.
|
||||
|
||||
import { h, ic } from '../dom';
|
||||
import { EASE_IN, POP, play } from '../motion';
|
||||
|
||||
export interface MenuItem {
|
||||
label: string;
|
||||
icon: string;
|
||||
/** An action's icon; an option (`checked` set) shows a check in its place, on the current one only. */
|
||||
icon?: string;
|
||||
checked?: boolean;
|
||||
tone?: 'warn' | 'bad';
|
||||
run: () => unknown;
|
||||
}
|
||||
@@ -53,14 +57,15 @@ export function openMenu(anchor: HTMLElement, all: (MenuItem | null)[]) {
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
role: 'menuitem',
|
||||
role: it.checked === undefined ? 'menuitem' : 'menuitemradio',
|
||||
'aria-checked': it.checked === undefined ? null : String(it.checked),
|
||||
class: `mi ${it.tone ?? ''}`,
|
||||
onclick: () => {
|
||||
closeMenu();
|
||||
it.run();
|
||||
},
|
||||
},
|
||||
ic(it.icon),
|
||||
it.checked === undefined ? ic(it.icon ?? '') : ic('check', it.checked ? 'i' : 'i off'),
|
||||
h('span', {}, it.label),
|
||||
);
|
||||
// The highlight comes in where the pointer is, then glides from item to item.
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
// "iPad connected"), and a menu path for another app or the other phone system
|
||||
// (`menuLine`: where the app scans, iOS "Create", Android "Scan").
|
||||
|
||||
import { fmt } from '../../shared/i18n';
|
||||
import { h, ic, markup, put, type Kid } from '../dom';
|
||||
import { EASE_IN, EASE_OUT, POP, SMOOTH, calm, play } from '../motion';
|
||||
|
||||
@@ -229,8 +230,8 @@ export function morphText(el: HTMLElement, next: string, from = textOf(el), o: M
|
||||
easing: SMOOTH.easing,
|
||||
});
|
||||
});
|
||||
const out = was.filter((_, i) => !stays.has(i));
|
||||
const inn = now.filter((_, j) => !comes.has(j));
|
||||
const out = was.filter((_x, i) => !stays.has(i));
|
||||
const inn = now.filter((_x, j) => !comes.has(j));
|
||||
// A long text keeps the same overall sweep: the steps shorten instead.
|
||||
const so = Math.min(12, 160 / Math.max(1, out.length));
|
||||
const si = Math.min(22, 260 / Math.max(1, inn.length));
|
||||
@@ -521,7 +522,7 @@ export function menuLine(ios: string, android: string): MenuLine {
|
||||
);
|
||||
|
||||
const set = (i: string, a: string) => {
|
||||
el.setAttribute('aria-label', (i === a ? i : `${i} (Android: ${a.split(' → ').pop()})`).replace(/ → /g, ' › '));
|
||||
el.setAttribute('aria-label', (i === a ? i : fmt(_('%s (Android: %s)'), i, a.split(' → ').pop())).replace(/ → /g, ' › '));
|
||||
const I = i.split(' → ');
|
||||
const A = a.split(' → ');
|
||||
const next = I.map((s, n) => cut(s, A[n] ?? s));
|
||||
|
||||
@@ -14,7 +14,7 @@ export interface View {
|
||||
el: HTMLElement;
|
||||
/** The sheet's accessible name while this view shows (its title). */
|
||||
label: string;
|
||||
/** A question (Remove, Reconnect): an alert dialog. */
|
||||
/** A question (Remove, Reconnect): an alert dialog, closed by its Cancel (no ×). */
|
||||
asks?: boolean;
|
||||
/** Its own buttons, pinned beside × while it shows. */
|
||||
acts?: HTMLElement | null;
|
||||
@@ -108,7 +108,7 @@ export function startWidth(p: WidthPlan | null) {
|
||||
/* ---------- the drawer ---------- */
|
||||
|
||||
function build() {
|
||||
closeBtn = h('button', { type: 'button', class: 'knob x', 'aria-label': 'Close', onclick: () => closeSheet() }, ic('x'));
|
||||
closeBtn = h('button', { type: 'button', class: 'knob x', onclick: () => closeSheet() }, ic('x'));
|
||||
actsEl = h('div', { class: 'sheet-acts' });
|
||||
vp = h('div', { class: 'vp' });
|
||||
scroller = h('div', { class: 'sheet-scroll' }, vp);
|
||||
@@ -122,7 +122,10 @@ function build() {
|
||||
|
||||
function label(v: View) {
|
||||
sheetEl.setAttribute('aria-label', v.label);
|
||||
// Built once, named each time: the language may have changed since.
|
||||
closeBtn.setAttribute('aria-label', _('Close'));
|
||||
sheetEl.setAttribute('role', v.asks ? 'alertdialog' : 'dialog');
|
||||
sheetEl.classList.toggle('asks', !!v.asks);
|
||||
}
|
||||
|
||||
/** The view being left (a new one, or the sheet closing) lets go of what it holds. */
|
||||
@@ -466,7 +469,7 @@ export function head(title: string, o: { back?: boolean; acts?: boolean } = {}):
|
||||
return h(
|
||||
'div',
|
||||
{ class: `vhead${o.back ? ' center' : ''}${o.acts ? ' with-acts' : ''}` },
|
||||
o.back ? h('button', { type: 'button', class: 'knob back', 'aria-label': 'Back', onclick: back }, ic('chevron')) : null,
|
||||
o.back ? h('button', { type: 'button', class: 'knob back', 'aria-label': _('Back'), onclick: back }, ic('chevron')) : null,
|
||||
h('h2', {}, title),
|
||||
);
|
||||
}
|
||||
|
||||
+51
-56
@@ -1,36 +1,41 @@
|
||||
// Formatting helpers shared by the admin UI and the portal (English only).
|
||||
// Formatting helpers shared by the admin UI and the portal, in the page's
|
||||
// language (shared/i18n.ts): units, relative times, dates, labels.
|
||||
|
||||
import type { Access, Kind, PersonState } from './types';
|
||||
import { fmt, locale, num, plural } from './i18n';
|
||||
|
||||
export function bytes(n: number): string {
|
||||
if (!n || n < 0) return '0 B';
|
||||
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
|
||||
/** A size with its unit: one decimal from 1 KB up to 100 of a unit ("1.5 GB", "120 MB"). */
|
||||
function sized(v: number, units: string[], step: number): string {
|
||||
let i = 0;
|
||||
let v = n;
|
||||
while (v >= 1024 && i < units.length - 1) {
|
||||
v /= 1024;
|
||||
while (v >= step && i < units.length - 1) {
|
||||
v /= step;
|
||||
i++;
|
||||
}
|
||||
return `${v >= 100 || i === 0 ? Math.round(v) : v.toFixed(1)} ${units[i]}`;
|
||||
return `${v >= 100 || i === 0 ? num(Math.round(v)) : num(v, 1)} ${units[i]}`;
|
||||
}
|
||||
|
||||
export function bytes(n: number): string {
|
||||
return sized(!n || n < 0 ? 0 : n, [_('B'), _('KB'), _('MB'), _('GB'), _('TB')], 1024);
|
||||
}
|
||||
|
||||
/** Bytes per second as a bit rate. */
|
||||
export function bits(bps: number): string {
|
||||
const b = bps * 8;
|
||||
if (b < 1000) return `${Math.round(b)} bit/s`;
|
||||
if (b < 1e6) return `${(b / 1e3).toFixed(b < 1e4 ? 1 : 0)} kbit/s`;
|
||||
if (b < 1e9) return `${(b / 1e6).toFixed(b < 1e7 ? 1 : 0)} Mbit/s`;
|
||||
return `${(b / 1e9).toFixed(1)} Gbit/s`;
|
||||
const units = [_('bit/s'), _('kbit/s'), _('Mbit/s'), _('Gbit/s')];
|
||||
if (b < 1000) return `${num(Math.round(b))} ${units[0]}`;
|
||||
const i = b < 1e6 ? 1 : b < 1e9 ? 2 : 3;
|
||||
const v = b / 1000 ** i;
|
||||
return `${num(v, i === 3 || v < 10 ? 1 : 0)} ${units[i]}`;
|
||||
}
|
||||
|
||||
export function ago(ts: number, now = Date.now() / 1000): string {
|
||||
if (!ts) return 'never';
|
||||
if (!ts) return _('never');
|
||||
const d = Math.max(0, Math.round(now - ts));
|
||||
if (d < 60) return 'just now';
|
||||
if (d < 3600) return `${Math.floor(d / 60)} min ago`;
|
||||
if (d < 86400) return `${Math.floor(d / 3600)} h ago`;
|
||||
if (d < 86400 * 30) return `${Math.floor(d / 86400)} d ago`;
|
||||
return new Date(ts * 1000).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' });
|
||||
if (d < 60) return _('just now');
|
||||
if (d < 3600) return fmt(_('%s min ago'), Math.floor(d / 60));
|
||||
if (d < 86400) return fmt(_('%s h ago'), Math.floor(d / 3600));
|
||||
if (d < 86400 * 30) return fmt(_('%s d ago'), Math.floor(d / 86400));
|
||||
return new Date(ts * 1000).toLocaleDateString(locale(), { day: 'numeric', month: 'short', year: 'numeric' });
|
||||
}
|
||||
|
||||
export function duration(sec: number): string {
|
||||
@@ -38,17 +43,17 @@ export function duration(sec: number): string {
|
||||
const d = Math.floor(sec / 86400);
|
||||
const h = Math.floor((sec % 86400) / 3600);
|
||||
const m = Math.floor((sec % 3600) / 60);
|
||||
if (d) return `${d}d ${h}h`;
|
||||
if (h) return `${h}h ${m}m`;
|
||||
return `${m}m`;
|
||||
if (d) return fmt(_('%sd %sh'), d, h);
|
||||
if (h) return fmt(_('%sh %sm'), h, m);
|
||||
return fmt(_('%sm'), m);
|
||||
}
|
||||
|
||||
export function clock(ts: number): string {
|
||||
const d = new Date(ts * 1000);
|
||||
const today = new Date();
|
||||
const sameDay = d.toDateString() === today.toDateString();
|
||||
const t = d.toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' });
|
||||
return sameDay ? t : `${d.toLocaleDateString('en-GB', { day: 'numeric', month: 'short' })} ${t}`;
|
||||
const t = d.toLocaleTimeString(locale(), { hour: '2-digit', minute: '2-digit' });
|
||||
return sameDay ? t : `${d.toLocaleDateString(locale(), { day: 'numeric', month: 'short' })} ${t}`;
|
||||
}
|
||||
|
||||
/* ---------- days (YYYY-MM-DD, the router's calendar) ---------- */
|
||||
@@ -67,7 +72,7 @@ export function parseDay(s: string): Date {
|
||||
/** "1 Oct 2026". A YYYY-MM-DD is a calendar day; other strings and Dates are moments. */
|
||||
export function fmtDay(d: Date | string): string {
|
||||
const v = typeof d === 'string' ? (/^\d{4}-\d{2}-\d{2}$/.test(d) ? parseDay(d) : new Date(d)) : d;
|
||||
return v.toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' });
|
||||
return v.toLocaleDateString(locale(), { day: 'numeric', month: 'short', year: 'numeric' });
|
||||
}
|
||||
|
||||
export function date(s: string): string {
|
||||
@@ -137,47 +142,37 @@ export function endsSoon(p: { expire_warn: number }, left: number | null): boole
|
||||
|
||||
/** "ends today", "ends tomorrow", "ends in 7 days" for daysLeft() > 0. */
|
||||
export function endsIn(left: number): string {
|
||||
return left <= 1 ? 'ends today' : left === 2 ? 'ends tomorrow' : `ends in ${left} days`;
|
||||
}
|
||||
|
||||
/** "1 event", "2,000 events". */
|
||||
export function plural(n: number, one: string, many = `${one}s`): string {
|
||||
return `${n.toLocaleString('en-GB')} ${n === 1 ? one : many}`;
|
||||
return left <= 1 ? _('ends today') : left === 2 ? _('ends tomorrow') : plural(left, 'ends in %s day', 'ends in %s days');
|
||||
}
|
||||
|
||||
/** Small sizes on flash and in memory: B, KB, MB. */
|
||||
export function kb(n: number): string {
|
||||
return n < 1024 ? `${n} B` : n < 1048576 ? `${(n / 1024).toFixed(n < 10240 ? 1 : 0)} KB` : `${(n / 1048576).toFixed(1)} MB`;
|
||||
if (n < 1024) return `${num(n)} ${_('B')}`;
|
||||
return n < 1048576 ? `${num(n / 1024, n < 10240 ? 1 : 0)} ${_('KB')}` : `${num(n / 1048576, 1)} ${_('MB')}`;
|
||||
}
|
||||
|
||||
export const ACCESS_LABEL: Record<Access, string> = {
|
||||
lan: 'Home network',
|
||||
internet: 'Internet',
|
||||
both: 'Home network + Internet',
|
||||
};
|
||||
|
||||
export const ACCESS_SHORT: Record<Access, string> = { lan: 'LAN', internet: 'Internet', both: 'LAN + Internet' };
|
||||
export function accessLabel(a: Access): string {
|
||||
return { lan: _('Home network'), internet: _('Internet'), both: _('Home network + Internet') }[a];
|
||||
}
|
||||
|
||||
/** In picker order. */
|
||||
export const KINDS: Kind[] = ['computer', 'phone', 'tablet', 'router', 'other'];
|
||||
|
||||
export const KIND_LABEL: Record<Kind, string> = {
|
||||
computer: 'PC',
|
||||
phone: 'Phone',
|
||||
tablet: 'Tablet',
|
||||
router: 'Router',
|
||||
other: 'Other',
|
||||
};
|
||||
export function kindLabel(k: Kind): string {
|
||||
return { computer: _('PC'), phone: _('Phone'), tablet: _('Tablet'), router: _('Router'), other: _('Other') }[k];
|
||||
}
|
||||
|
||||
export const STATE_LABEL: Record<PersonState, string> = {
|
||||
active: 'Active',
|
||||
paused: 'Paused',
|
||||
expired: 'Expired',
|
||||
quota: 'Data limit reached',
|
||||
hours: 'Outside allowed hours',
|
||||
no_server: 'No server',
|
||||
server_off: 'Server is turned off',
|
||||
};
|
||||
export function stateLabel(s: PersonState): string {
|
||||
return {
|
||||
active: _('Active'),
|
||||
paused: _('Paused'),
|
||||
expired: _('Expired'),
|
||||
quota: _('Data limit reached'),
|
||||
hours: _('Outside allowed hours'),
|
||||
no_server: _('No server'),
|
||||
server_off: _('Server is turned off'),
|
||||
}[s];
|
||||
}
|
||||
|
||||
export function initials(name: string): string {
|
||||
const parts = name.trim().split(/\s+/).filter(Boolean);
|
||||
@@ -190,8 +185,8 @@ export function initials(name: string): string {
|
||||
/** "1.2 GB of 50 GB" style quota text, or just usage when unlimited. */
|
||||
export function quotaText(used: number, quotaGb: number, period: 'month' | 'total'): string {
|
||||
const u = bytes(used);
|
||||
if (!quotaGb) return `${u} ${period === 'total' ? 'in total' : 'this month'}`;
|
||||
return `${u} of ${quotaGb} GB${period === 'total' ? '' : ' this month'}`;
|
||||
if (!quotaGb) return fmt(period === 'total' ? _('%s in total') : _('%s this month'), u);
|
||||
return fmt(period === 'total' ? _('%s of %s GB') : _('%s of %s GB this month'), u, num(quotaGb));
|
||||
}
|
||||
|
||||
export function slugify(s: string): string {
|
||||
|
||||
Vendored
+11
@@ -0,0 +1,11 @@
|
||||
// The translation globals: LuCI's own in the admin UI (cbi.js), installed by the
|
||||
// portal from its catalog (portal/i18n.ts). How to use them: shared/i18n.ts.
|
||||
|
||||
declare global {
|
||||
/** `msg` in the page's language (English when the catalog has no translation). */
|
||||
const _: (msg: string, ctx?: string) => string;
|
||||
/** `singular` or `plural` for n, by the language's plural rules (Russian has three forms). */
|
||||
const N_: (n: number, singular: string, plural: string, ctx?: string) => string;
|
||||
}
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,58 @@
|
||||
// Translation helpers for the admin UI and the portal. Text is English in the
|
||||
// code and goes through the globals _() and N_(): LuCI's own in the admin UI
|
||||
// (cbi.js, looking up the luci-i18n-dawnline-* catalog of the page's
|
||||
// language), installed by the portal from its bundled catalog (portal/i18n.ts).
|
||||
// web/i18n/extract.ts collects the strings into the catalogs; how to write them
|
||||
// is in rules/i18n.md.
|
||||
//
|
||||
// Placeholders are %s and %d, filled in order by fmt() (LuCI's
|
||||
// String.format exists only in the admin UI). Numbers and dates follow the
|
||||
// page's language: <html lang>, which LuCI sets from its language and the
|
||||
// portal from the visitor's choice.
|
||||
|
||||
/** The page's language: "en", "ru". */
|
||||
export function lang(): string {
|
||||
return (typeof document === 'undefined' ? '' : document.documentElement.lang) || 'en';
|
||||
}
|
||||
|
||||
/** The locale for Intl: English dates stay day-first (en-GB), as before translations. */
|
||||
export function locale(): string {
|
||||
const l = lang();
|
||||
return l === 'en' ? 'en-GB' : l;
|
||||
}
|
||||
|
||||
/** %s and %d replaced by the arguments in order, %% by a percent sign. */
|
||||
export function fmt(s: string, ...args: unknown[]): string {
|
||||
let i = 0;
|
||||
return s.replace(/%([%sd])/g, (_m, c: string) => (c === '%' ? '%' : String(args[i++] ?? '')));
|
||||
}
|
||||
|
||||
/** A number in the page's language: 2,000 or 2 000; `digits` fixes the decimals. */
|
||||
export function num(n: number, digits?: number): string {
|
||||
return n.toLocaleString(locale(), digits === undefined ? undefined : { minimumFractionDigits: digits, maximumFractionDigits: digits });
|
||||
}
|
||||
|
||||
/**
|
||||
* A count with its word: plural(n, '%s event', '%s events') is "1 event",
|
||||
* "2,000 events" (and "21 событие", "22 события", "25 событий" in Russian).
|
||||
* Both forms are literals: extract.ts reads them as one plural entry.
|
||||
*/
|
||||
export function plural(n: number, one: string, many: string): string {
|
||||
return fmt(N_(n, one, many), num(n));
|
||||
}
|
||||
|
||||
/**
|
||||
* A translated sentence with elements in it (a link, a <b>): the text around
|
||||
* the placeholders and the arguments, in order, as children for E() or h().
|
||||
* fill(_('Install it in %s'), link) is ['Install it in ', link].
|
||||
*/
|
||||
export function fill<T>(s: string, ...args: T[]): (string | T)[] {
|
||||
let i = 0;
|
||||
return s
|
||||
.split(/(%[%sd])/)
|
||||
.filter(Boolean)
|
||||
.map((p) => (p === '%%' ? '%' : p === '%s' || p === '%d' ? args[i++] : p));
|
||||
}
|
||||
|
||||
/** A string the router or a generated list holds (not a literal here): in the page's language when the catalog has it. */
|
||||
export const known = (s: string): string => _(s);
|
||||
@@ -93,7 +93,7 @@ export function qrSvg(text: string, margin = 3, logo = true, look: QrLook = 'pla
|
||||
`<rect x="${o}" y="${o}" width="${s}" height="${s}" rx="${s * (round ? 0.28 : 0.25)}" fill="${round ? fg : '#0a0a0a'}"/>` +
|
||||
`<g transform="translate(${o} ${o}) scale(${s / 64})">${mark(round ? bg : '#fff')}</g>`;
|
||||
}
|
||||
const open = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${size} ${size}" role="img" aria-label="QR code">`;
|
||||
const open = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${size} ${size}" role="img" aria-label="${_('QR code')}">`;
|
||||
return round
|
||||
? `${open}<rect width="${size}" height="${size}" fill="${bg}"/><path d="${d}" fill="${fg}"/>` +
|
||||
`<path d="${eyes}" fill="${fg}" fill-rule="evenodd"/>${logoTile}</svg>`
|
||||
|
||||
@@ -87,6 +87,7 @@ export interface Server {
|
||||
/** The tunnel core that serves it (see admin/cores); AmneziaWG when absent. */
|
||||
core?: string;
|
||||
/** Why the tunnel can't run: its interface name is taken by a network section Dawnline didn't make. */
|
||||
/** Why the server can't start: a whole sentence from the router, its name in it. */
|
||||
blocked?: string | null;
|
||||
ifname: string;
|
||||
port: number;
|
||||
|
||||
Reference in new issue
Block a user