Files
dawnline/web/src/admin/pages/person/limits.ts
T
Aemeath 2f2aaf6c34
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
Dawnline 0.11.0
- 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)
2026-10-20 19:33:52 +03:00

359 lines
13 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Person page: Access & limits — what they reach, then the tiles (devices,
// circle, end date, data, hours). Every choice applies at once.
import type { Person } from '../../../shared/types';
import { E } from '../../e';
import { notify } from '../../ui/toast';
import { seg } from '../../ui/controls';
import { button } from '../../ui/button';
import { cancelButton, closeModal, modal } from '../../ui/modal';
import { liveField } from '../../ui/layout';
import { quotaHelp } from '../../netcheck';
import { attachTip } from '../../ui/tooltip';
import { icon } from '../../../shared/icons';
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';
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$/;
function endTile(page: PersonPage): HTMLElement {
const p = page.p;
const today = page.today;
const left = daysLeft(p.expires, today);
const dateInput = E('input', {
type: 'date',
class: 'dl-date-hidden',
value: p.expires,
tabindex: '-1',
'aria-hidden': 'true',
}) as HTMLInputElement;
dateInput.addEventListener(
'change',
() => 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 }, fmt(_('Access until %s'), date(next)));
};
const ext = (
[
['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
// focus first, so the page's background refresh leaves this tile (and the open picker) alone.
const pick = E('span', { class: 'dl-datechip' }, [
E(
'button',
{
type: 'button',
class: 'dl-chipbtn',
click: () => {
dateInput.focus({ preventScroll: true });
try {
dateInput.showPicker();
} catch {
/* focused is the best this browser offers */
}
},
},
[icon('calendar'), p.expires ? date(p.expires) : _('Date')],
),
dateInput,
]);
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')),
p.expires
? E(
'span',
{ class: left != null && left < 0 ? 'dl-bad' : endsSoon(p, left) ? 'dl-warn' : 'dl-ok' },
left != null && left < 0 ? _('ended') : plural(left ?? 0, '%s day left', '%s days left'),
)
: 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('div', { class: 'dl-tile2-foot' }, [
E(
'span',
{ class: 'dl-muted' },
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',
{
href: '#',
click: (ev: Event) => {
ev.preventDefault();
endSettings(page);
},
},
_('Change'),
),
]),
]);
}
function dataTile(page: PersonPage): HTMLElement {
const p = page.p;
const used = p.quota_used || p.month[0] + p.month[1];
const pct = p.quota_limit ? Math.min(100, (p.quota_used / p.quota_limit) * 100) : 0;
const 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%') }) : '',
]);
(bar.firstChild as HTMLElement).style.width = `${pct}%`;
if (p.quota_limit)
attachTip(bar, () => [
E('div', { class: 'dl-tip-title' }, fmt(_('%s%% used'), num(pct, 1))),
E(
'div',
{ class: 'dl-muted' },
`${fmt(_('%s of %s'), bytes(p.quota_used), bytes(p.quota_limit))} · ${fmt(_('%s left'), bytes(Math.max(0, p.quota_limit - p.quota_used)))}`,
),
E('div', { class: 'dl-faint' }, _('Alert at 90%')),
]);
const period = seg(
[
['month', _('Monthly')],
['total', _('Total')],
],
p.quota_period,
{ label: _('Data limit period'), cls: 'sm', optimistic: false, onChange: (v) => page.patch({ quota_period: v }) },
);
const presets = [10, 50, 100].map((gb) =>
E(
'button',
{
type: 'button',
class: `dl-chipbtn${p.quota_gb === gb ? ' on' : ''}`,
click: () => page.patch({ quota_gb: String(gb) }, fmt(_('Data limit %s GB'), num(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'),
),
);
presets.push(
E(
'button',
{
type: 'button',
class: 'dl-chipbtn',
click: () => {
const inp = E('input', {
type: 'number',
class: 'cbi-input-text dl-w-port',
min: 0,
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'));
modal(
_('Data limit'),
[row],
[
cancelButton(),
' ',
button(
_('Save'),
async () => {
const h = row.help();
if (h.bad) {
notify(h.text, 'warning');
return;
}
const v = inp.value.trim();
if (
await page.patch({ quota_gb: v }, v && Number(v) > 0 ? fmt(_('Data limit %s GB'), num(Number(v))) : _('No data limit'))
)
closeModal();
},
'positive',
),
],
);
setTimeout(() => inp.select(), 50);
},
},
_('Custom'),
),
);
return E('div', { class: 'dl-tile2' }, [
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' }, ` ${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_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 ? 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'));
},
},
_('+10 GB this month'),
),
])
: '',
E('div', { class: 'dl-tile2-foot' }, [
E('span', { class: 'dl-muted' }, fmt(_('%s in total'), bytes(p.total[0] + p.total[1]))),
E(
'button',
{
type: 'button',
class: 'dl-linkbtn danger',
click: () => resetUsageDialog('person', p.id, p.name, () => setTimeout(() => page.refresh(), 300)),
},
_('Reset usage'),
),
]),
]);
}
/**
* Allowed hours. The times save when the focus leaves them (or on Enter), not
* on every change: a half-typed time would otherwise be saved and the tile
* repainted under the cursor. Both are checked first.
*/
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', '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 }, fmt(_('Allowed %s–%s'), from.value, to.value));
};
times.addEventListener('focusout', (ev: FocusEvent) => {
if (!times.contains(ev.relatedTarget as Node | null)) commit();
});
for (const t of [from, to])
t.addEventListener('keydown', (ev: KeyboardEvent) => {
if (ev.key === 'Enter') {
ev.preventDefault();
commit();
}
});
const sw = E(
'button',
{
type: 'button',
role: 'switch',
'aria-checked': hoursOn ? 'true' : 'false',
class: `dl-switch${hoursOn ? ' on' : ''}`,
'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'));
sw.classList.add('on');
sw.setAttribute('aria-checked', 'true');
label.textContent = _('Set the hours, then press Enter');
tile.appendChild(times);
from.focus();
},
},
E('i'),
);
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]),
sw,
]),
hoursOn ? times : '',
]);
return tile;
}
export function limitsPart(page: PersonPage): HTMLElement {
const p = page.p;
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'),
],
]),
p.access,
{
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'))]),
E('div', { class: 'dl-panel' }, [
E('div', { class: 'dl-stack gap8' }, [
E('span', { class: 'dl-tile2-label' }, _('Can reach')),
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) : '',
]),
E('div', { class: 'dl-tiles2' }, [devTile(page), circleTile(page), endTile(page), dataTile(page), hoursTile(page)]),
]),
]);
}