Dawnline 0.14.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

- A device is renamed where its name stands on its card: a click on the
  name, Return or Space on it, or Rename in the ⋯ menu turns it into a
  field with the name selected. Return saves, and the words shimmer until
  the router answers. Esc or a click elsewhere puts the old name back. The
  rename window is gone, and the page no longer redraws under a name being
  edited
- Device names take up to 20 characters: letters of any language, digits,
  spaces and - _ . The router refuses anything else when a device is added
  or renamed, so a name can't carry symbols into configurations, file
  names or the AmneziaVPN key. The portal and the admin turn a character
  like that away as it is typed: the field shakes, its outline goes red
  and a short line says why. Suggested names (a phone's model, "Phone 2")
  are stripped of such characters and cut to fit. Names set before this
  stay as they are
- LAN Bypass: Add a device, in the portal and in the admin, has a switch
  that keeps the device's own local network (printer, TV, NAS) reachable
  while it is connected. It is off by default and stays as chosen; the
  admin's device drawer shows it. With home and internet access the switch
  says which addresses still lead to the home network
- Health warns when a server's home network is on one of the subnets home
  routers come with (192.168.0.x, 192.168.1.x and others). People with
  home access who connect from a network on the same addresses reach your
  home instead of their own, LAN Bypass or not
- The router tells when a device can't connect properly. After the problem
  lasts three minutes, the portal card and the admin drawer name it:
  can't finish connecting (the network may block it), connected but no
  data (an outdated configuration, and the card offers Reconnect), on two
  devices at once, or a connection that keeps dropping. Activity lists
  these under Problems, one line per device per hour, and says when the
  device connects normally again
- The set-up sheet's connection line follows what the device does:
  waiting, can't finish, connected, or connected but no data. The sheet
  closes by itself only once data comes through. On the device itself and
  for a router, the steps regroup to what fixes the problem: "Set it up
  again" when the handshake never finishes, "Add the connection again"
  ("Import the configuration again" for a router) when no data comes
- Set-up in the portal: a QR code too long for a camera to read gives its
  place to a code that opens the set-up link (a LAN Bypass configuration
  or a long AmneziaVPN key can be that long). A TV, box or NAS added from
  a phone gets the steps for setting up from another device. Back from
  "Open on the device" keeps the kind, LAN Bypass and the name typed. The
  packet-size note under the kinds is gone
- The portal on phones keeps its place: nothing jumps when an access row
  opens or folds, a notice comes or goes, or Safari redraws the cards. A
  reload, or coming back from the VPN app, opens where the page was. Cards
  glide to their new height, and an animation interrupted half-way goes on
  from where it is instead of snapping. A double click no longer closes
  the sheet it just opened
- In the admin, a device's drawer has its own MTU and keep-alive (empty
  means the server's), each with a Change dialog. A change touches only
  that device's configuration and restarts nothing on the router. Opening
  the drawer no longer counts as handing out the configuration: "Update
  config" stays until the new configuration is shown as a QR code,
  downloaded or copied ("Show the new configuration"). New keys set the
  device up again, as the portal's Reconnect does
- "Speed now" on a server's Overview is live: one point a second over the
  last two minutes, all there as soon as the Overview opens. The agent
  keeps those two minutes in memory and writes them out only while someone
  is looking
- Disguise values that AmneziaWG refuses or crashes on are stopped before
  they reach the kernel. That covers overlapping H1-H4, Jmin above Jmax,
  broken I1-I5 tags, padding under 12 with header protection, and more.
  Import and restore refuse them. After a hand edit in uci, the server's
  tunnel stays down and Health and the service log say why and what to do.
  Errors are full sentences in the reader's language
- The header protection key no longer shows in the status that read-only
  users can see: the Server page says only that the key is set, and each
  device's configuration still has it. The server no longer turns off
  WireGuard's protection against handshake floods (devices keep
  DisableCookies). A device can't be added with a server's own key
- An AmneziaWG update whose kernel module can't be swapped (another
  AmneziaWG interface holds the old one) no longer fails. It is installed,
  the tunnels come back on the old module, and Health and Components say
  the update starts after a reboot. On apk firmware, an install that apk
  left at the old version counts as failed. A module installed by hand is
  recorded, so after a firmware upgrade Health can tell that it is gone
- Dawnline reads only its own tunnels, each one separately. Another
  AmneziaWG interface on the router no longer slows the agent's
  once-a-second check, has its keys read or breaks Dawnline's reads. A
  portal request reads only that person's server: one process however many
  servers there are
- Fewer false disconnects: a tunnel that netifd sets up again no longer
  logs everyone as leaving and coming back, and a device with a long
  keep-alive stays online between handshakes. One configuration on two
  devices isn't logged as roaming every few seconds, and new keys end the
  old session at once. A tunnel that is missing devices is synced within a
  minute, and traffic across a tunnel restart is no longer undercounted
- Renaming a server no longer restarts its tunnel. If a tunnel's interface
  is edited outside Dawnline (LuCI, uci), the watchdog sets it up again
  with Dawnline's settings and names only the changed options. The routing
  rules for "Internet like a home device" change one at a time, new ones
  first, so traffic never falls between them. Health and the Server page
  warn when the address's AAAA record isn't this router's, or the router
  has no public IPv6: devices that prefer IPv6 fail to connect
- The README screenshots come in English and Russian; the portal's are
  taken from its demo. The demo has a switch beside × in the set-up sheet
  to show each state of the connection line. In Russian, long labels in
  the admin's wide option buttons wrap under their icon. DESIGN.md
  describes the switch, renaming on the card, the shimmer, the shake and
  how the portal scrolls. New tests cover link states, the meter, access,
  Health, firewall rules, network settings and packages
This commit is contained in:
Aemeath committed 2026-10-22 00:11:50 +03:00
1 parent 58492be021
commit dc0f159447
155 files changed
+11062 -1461

No files matched your search

+63 -4
View File
@@ -3,7 +3,19 @@
// that did not load, a server that refused its devices) as { warning }.
import type { Network, PortHold } from './netcheck';
import type { AwgCaps, AwgState, Circle, ClientConfig, DayUsage, HealthCheck, LogEvent, MeshMode, Person, Status } from '../shared/types';
import type {
AwgCaps,
AwgState,
Circle,
ClientConfig,
DayUsage,
HealthCheck,
LogEvent,
MeshMode,
Pair,
Person,
Status,
} from '../shared/types';
import { notify } from './ui/toast';
import { lang } from '../shared/i18n';
@@ -62,6 +74,44 @@ export interface EndpointProbe {
v6_only: boolean;
status: 'ok' | 'warn' | 'error';
text: string;
/** The router's public IPv6 addresses ([]: none; null: not read, the name has no IPv6). */
router6?: string[] | null;
/** The name's IPv6 addresses that are not the router's (null while router6 is). */
foreign6?: string[] | null;
/** The name has IPv6 and every address is the router's. */
here6?: boolean;
}
/** One second of the live meter: each server whose tunnel was read, [rx, tx] in bytes/s (rx = from devices, as Server.rate). */
export interface MeterPoint {
ts: number;
servers: Record<string, Pair>;
}
/**
* The live meter (rpc meter): each call keeps the router sampling for `want`
* seconds more; the first point comes about 2 s after the first call.
*/
export interface Meter {
/** Router time. */
now: number;
/** Seconds the router keeps sampling after a call. */
want: number;
/** Points it keeps: one a second, the last 2 minutes. */
keep: number;
/** The newest point's time (0: none yet); it stops moving when the agent does. */
ts: number;
/** Oldest first; only those newer than `since` when it was given. */
points: MeterPoint[];
}
/**
* A device's own link values for device_update; left out = kept. Numbers go as text: '' = the server's, keep-alive
* '0' = off. LAN Bypass stays as chosen when the device was added (the RPC takes it, the admin UI never changes it).
*/
export interface DeviceLinkPatch {
mtu?: string;
keepalive?: string;
}
export interface Backup {
@@ -400,6 +450,11 @@ async function personUpdate(id: string, patch: PersonPatch): Promise<{ person: P
const status = call<Status>('status', ['days']);
const deviceUpdateRaw = call<unknown>('device_update', ['id', 'name', 'disabled', 'mtu', 'keepalive']);
/** Rename, turn off or on, or change how a device connects; what is undefined stays as it is. */
const deviceUpdate = (id: string, name?: string, disabled?: boolean, link: DeviceLinkPatch = {}) =>
deviceUpdateRaw(id, name, disabled, link.mtu, link.keepalive);
/** One line of the service log: tunnel and service starts, stops, watchdog repairs, errors. */
export interface ServiceLogEntry {
ts: number;
@@ -433,6 +488,8 @@ export type Health = { checks: HealthCheck[] } & ServiceLog;
export const api = {
rev: call<{ rev: number; version?: string }>('rev'),
/** The live meter's points newer than `since` (0: all); polled while the Overview shows it. */
meter: call<Meter>('meter', ['since']),
personUpdate,
settingsGet: call<SettingsData>('settings_get'),
portalInfo: call<PortalInfo>('portal_info'),
@@ -501,9 +558,11 @@ export const api = {
personRegen: call<{ link: string | null; removed: number }>('person_regen', ['id', 'remove']),
personDelete: call<unknown>('person_delete', ['id']),
personUsage: call<{ person: DayUsage[]; devices: Record<string, DayUsage[]> }>('person_usage', ['id', 'days']),
deviceCreate: call<{ id: string; config: ClientConfig }>('device_create', ['person', 'name', 'kind']),
deviceConfig: call<ClientConfig>('device_config', ['id']),
deviceUpdate: call<unknown>('device_update', ['id', 'name', 'disabled']),
/** A new device; `lan_bypass` (true) keeps its own local network outside the tunnel. */
deviceCreate: call<{ id: string; config: ClientConfig }>('device_create', ['person', 'name', 'kind', 'lan_bypass']),
/** A device's configuration; `issue` (true) when it goes to the device as a code, a file or a key: only that clears "Update config". */
deviceConfig: call<ClientConfig>('device_config', ['id', 'issue']),
deviceUpdate,
deviceDelete: call<unknown>('device_delete', ['id']),
deviceRotate: call<ClientConfig>('device_rotate', ['id']),
apply: call<unknown>('apply'),
+13 -8
View File
@@ -50,14 +50,16 @@ const CONF: [string, string][] = [
/**
* The applied parameters, grouped by what they do, with a plain-language
* line per group. Collapsed by default; copyable as config lines.
* line per group. Collapsed by default; copyable as config lines. The header
* protection key stays out of the status (read-only users can read it): the
* view says there is one, and each device's file has it.
*/
function paramsView(o: Record<string, string>): HTMLElement | null {
const has = (k: string) => o[k] != null && o[k] !== '';
function paramsView(o: Record<string, string>, hpk: boolean): HTMLElement | null {
const has = (k: string) => (k === 'header_protection_key' ? hpk : o[k] != null && o[k] !== '');
const keys = CONF.filter(([k]) => has(k));
if (!keys.length) return null;
const val = (k: string, name: string) =>
E('span', { class: 'dl-pv' }, [E('i', {}, name), E('b', {}, k === 'header_protection_key' ? `${o[k].slice(0, 6)}••••` : o[k])]);
E('span', { class: 'dl-pv' }, [E('i', {}, name), E('b', {}, k === 'header_protection_key' ? _('set', 'key') : o[k])]);
const group = (title: string, ic: string, text: string, ks: string[]) => {
const present = CONF.filter(([k]) => ks.includes(k) && has(k));
return present.length
@@ -76,7 +78,10 @@ function paramsView(o: Record<string, string>): HTMLElement | null {
const signature = (o.i1 ?? '').includes('0x8580')
? _('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 conf = keys
.filter(([k]) => k !== 'header_protection_key')
.map(([k, n]) => `${n} = ${o[k]}`)
.join('\n');
const body = E('div', { class: 'dl-pgrid' }, [
group(
_('Junk packets'),
@@ -126,7 +131,7 @@ function paramsView(o: Record<string, string>): HTMLElement | null {
class: 'dl-linkbtn',
click: (ev: Event) => {
ev.preventDefault();
copyText(conf, _('Parameters copied'));
copyText(conf, hpk ? _('Parameters copied. The header protection key is in each device’s file.') : _('Parameters copied'));
},
},
_('Copy as config'),
@@ -379,7 +384,7 @@ export function settingsCard(ctx: CoreCtx, srv: Server): HTMLElement {
),
)
: '',
paramsView(srv.obf ?? {}) ?? '',
paramsView(srv.obf ?? {}, srv.hpk) ?? '',
E('div', { class: 'dl-row-end' }, [
E('span', { class: 'dl-sub' }, _('Applies at once: every AmneziaWG device imports its configuration again.')),
apply,
@@ -438,7 +443,7 @@ function overviewTile(srv: Server): HTMLElement {
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 (srv.hpk) chips.push(_('Encrypted headers'));
if (!chips.length) chips.push(m?.id === 'off' ? _('Plain WireGuard') : _('No values yet'));
return E('div', { class: 'dl-bento-tile dl-disg' }, [
E('div', { class: 'dl-bento-head' }, [
+147
View File
@@ -0,0 +1,147 @@
// A device's own link in its drawer (./device): what goes wrong with its
// connection (the agent's link state, in words about the device), its MTU and
// keep-alive with a dialog each, and LAN Bypass as it was chosen when the
// device was added. The router checks the values again
// (core.set_device_link); the help lines are ./netcheck's, the state's words
// ./events/model's.
import type { Device, DeviceLink, Person, Server } from '../shared/types';
import { E } from './e';
import { api, type DeviceLinkPatch } from './api';
import { button } from './ui/button';
import { cancelButton, closeModal, modal } from './ui/modal';
import { attempt, notify } from './ui/toast';
import { liveField } from './ui/layout';
import { deviceKeepaliveHelp, deviceMtuHelp, type Help } from './netcheck';
import { linkStateText } from './events/model';
import { fmt } from '../shared/i18n';
import { homeOf, netsLabel } from '../shared/format';
/** Status while the link fails in a named way: the state (warn) and a line on what it means; null for an unknown one. */
export function linkStatus(link: DeviceLink): HTMLElement[] | null {
const t = linkStateText(link.state);
return t ? [E('span', { class: 'dl-dstat warn' }, t.title), E('span', { class: 'dl-sub' }, t.line)] : null;
}
/** The MTU a device gets with none of its own: its server's for its kind (null when that is not known). */
function autoMtu(d: Device, srv?: Server): number | null {
if (srv) return d.kind === 'phone' || d.kind === 'tablet' ? srv.mtus.phone : srv.mtus.computer;
return d.mtu ? null : (d.mtu_used ?? null);
}
/** One value in a dialog of its own: the field with its help as it is typed, Save through device_update. */
function linkDialog(
title: string,
label: string,
input: HTMLInputElement,
help: () => Help,
patch: () => DeviceLinkPatch,
id: string,
saved: () => unknown,
) {
const field = liveField(label, input, help);
modal(
title,
[field],
[
cancelButton(),
' ',
button(
_('Save'),
async () => {
const h = field.help();
if (h.bad) {
notify(h.text, 'warning');
return;
}
if (await attempt(() => api.deviceUpdate(id, undefined, undefined, patch()), _('Saved'))) {
closeModal();
await saved();
}
},
'positive',
),
],
);
setTimeout(() => input.select(), 50);
}
/** A number field for a link value: the device's own, or empty for what it gets without one (`placeholder`). */
function numberInput(value: number | null | undefined, placeholder: string | null): HTMLInputElement {
return E('input', {
type: 'text',
class: 'cbi-input-text',
inputmode: 'numeric',
maxlength: 4,
value: value == null ? '' : String(value),
placeholder,
}) as HTMLInputElement;
}
function mtuDialog(d: Device, srv: Server | undefined, saved: () => unknown) {
const auto = autoMtu(d, srv);
const input = numberInput(d.mtu || null, auto ? fmt(_('Automatic: %s'), auto) : null);
linkDialog(
fmt(_('MTU of %s'), d.name),
'MTU',
input,
() => deviceMtuHelp(input.value),
() => ({ mtu: input.value.trim() }),
d.id,
saved,
);
}
function keepaliveDialog(d: Device, srv: Server | undefined, saved: () => unknown) {
const input = numberInput(d.keepalive, srv ? fmt(_('As the server: %s'), srv.keepalive) : null);
linkDialog(
fmt(_('Keep-alive of %s'), d.name),
_('Keep-alive'),
input,
() => deviceKeepaliveHelp(input.value),
() => ({ keepalive: input.value.trim() }),
d.id,
saved,
);
}
/**
* Details rows as [label, value]: the MTU and keep-alive its configuration
* carries, each with Change (its own dialog, then `saved`), and LAN Bypass as
* it was chosen when the device was added.
*/
export function linkRows(d: Device, p: Person, srv: Server | undefined, saved: () => unknown): [string, Node][] {
const home = homeOf(p, srv);
// Two buttons say "Change": each is named after its row for a screen reader.
const value = (v: string, from: string, name: string, change: () => void) =>
E('span', { class: 'dl-kv-act' }, [
E('span', {}, [v, from ? [' ', E('span', { class: 'dl-faint' }, from)] : '']),
E('button', { type: 'button', class: 'dl-linkbtn', 'aria-label': name, click: change }, _('Change')),
]);
const ka = d.keepalive_used;
return [
[
'MTU',
value(d.mtu_used == null ? '—' : String(d.mtu_used), d.mtu ? '' : _('automatic'), _('Change the MTU'), () =>
mtuDialog(d, srv, saved),
),
],
[
_('Keep-alive'),
value(
ka == null ? '—' : ka ? fmt(_('%s s'), ka) : _('Off'),
d.keepalive != null ? '' : _('as the server'),
_('Change the keep-alive'),
() => keepaliveDialog(d, srv, saved),
),
],
[
_('LAN Bypass'),
E('span', {}, [
!d.lan_bypass ? _('Off') : home.length ? fmt(_('On, except %s (home)'), netsLabel(home)) : _('On'),
' ',
E('span', { class: 'dl-faint' }, _('set when it was added')),
]),
],
];
}
+127 -21
View File
@@ -1,8 +1,9 @@
// Device drawer: a right-hand panel with the device's status, connection
// (QR / key / file, from its server's core), details and actions; the ⋯ menu
// on a device card; and the admin's Add device dialog.
// on a device card; and the admin's Add device dialog. Its own link (link
// state, MTU, keep-alive, LAN Bypass) is ./device-link.
import type { Device, Geo, Kind, LogEvent, Person } from '../shared/types';
import type { ClientConfig, Device, Geo, Kind, LogEvent, Person, Server } from '../shared/types';
import { E } from './e';
import { api } from './api';
import { button } from './ui/button';
@@ -12,10 +13,12 @@ import { dropdown, type MenuItem } from './ui/menu';
import { drawer } from './ui/drawer';
import { attempt, notify } from './ui/toast';
import { liveField, warnNote } from './ui/layout';
import { isOn, sw } from './ui/controls';
import { qrCode } from './ui/qr';
import { nameHelp } from './netcheck';
import { deviceNameHelp, type Help } from './netcheck';
import { deviceStatus } from './ui/badges';
import { ago, bytes, isoDay, kindLabel, KINDS, todayOf } from '../shared/format';
import { ago, bytes, defaultName, fitName, homeOf, isoDay, kindLabel, KINDS, netsLabel, todayOf } from '../shared/format';
import { guardDeviceName } from '../shared/name-guard';
import { fill, fmt, locale, num } from '../shared/i18n';
import { icon } from '../shared/icons';
import { eventBy } from './events/model';
@@ -27,6 +30,7 @@ import { onLiveChange } from './state/live';
import { ConnectionMap, rangeControl, type Range } from './map';
import { PlacesView } from './places/render';
import { personUrl } from './urls';
import { linkRows, linkStatus } from './device-link';
/** What the page that opens a device hands over. */
export interface DeviceOpts {
@@ -38,6 +42,8 @@ export interface DeviceOpts {
today?: string;
/** The device's server's core (AmneziaWG when not given). */
core?: Core;
/** The device's server: what an empty MTU or keep-alive of its own gives. */
server?: Server;
/** The page's activity log, when it keeps one: the drawer reads it instead of fetching its own. */
events?: () => LogEvent[] | null;
}
@@ -128,11 +134,38 @@ async function reopen(personId: string, deviceId: string, o: DeviceOpts) {
const p2 = st?.people.find((x) => x.id === personId);
const d2 = p2?.devices.find((x) => x.id === deviceId);
if (st && p2 && d2)
void openDevice(p2, d2, { ...o, geo: st.geo, now: st.now, today: todayOf(st.series), core: coreFor(st.servers, p2.server) });
void openDevice(p2, d2, {
...o,
geo: st.geo,
now: st.now,
today: todayOf(st.series),
core: coreFor(st.servers, p2.server),
server: st.servers.find((s) => s.id === p2.server),
});
}
/**
* The connection of a device that holds an older configuration, behind a button: showing the new one is what
* counts as giving it out (it clears "Update config"), never opening the drawer. `shown` runs once it is out.
*/
function newConfigGate(id: string, show: (cfg: ClientConfig) => Promise<HTMLElement>, shown: () => unknown): HTMLElement {
const box = E('div', { class: 'dl-row-actions' });
dom.content(
box,
button([icon('qr'), ' ', _('Show the new configuration')], async () => {
const cfg = await attempt(() => api.deviceConfig(id, true));
if (!cfg) return;
box.className = '';
dom.content(box, await show(cfg));
void shown();
}),
);
return box;
}
/** Device drawer. */
export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
// A look: only a delivery (a code, a file, a key handed to the device) clears "Update config".
const cfg = await attempt(() => api.deviceConfig(dev.id));
if (!cfg) return;
const core = o.core ?? coreOf(null);
@@ -141,8 +174,20 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
let geo = o.geo;
let now = o.now;
let today = o.today ?? isoDay(new Date());
let srv = o.server;
// Phones and tablets are set up by scanning; computers and routers by a file.
const connect = await core.connectBlock(cfg, dev.kind === 'phone' || dev.kind === 'tablet' ? 'qr' : 'file');
const block = (c: ClientConfig) => core.connectBlock(c, dev.kind === 'phone' || dev.kind === 'tablet' ? 'qr' : 'file');
// An older configuration on the device: the new one waits for a click (the inline QR code is itself a delivery).
// `relinked`: its MTU or keep-alive was just changed here, which outdates the configuration on screen even where
// the router keeps no record of what the device got (never "stale" then, e.g. after a JSON import).
let gated = dev.config_stale;
let relinked = false;
const gate = () =>
newConfigGate(dev.id, block, () => {
gated = false;
return changed();
});
const connect = gated ? gate() : await block(cfg);
const titleEl = E('div', { class: 'dl-drawer-title' });
const stats = E('div', {});
const details = E('div', {});
@@ -184,7 +229,8 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
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),
// Its link failing in a named way says so, with what it means; otherwise its usual status.
(d.link && !d.disabled && linkStatus(d.link)) || deviceStatus(d, now, _('Waiting for the first connection'), p),
]),
E('div', { class: 'dl-dstats-cell' }, [
E('span', { class: 'dl-metric-label' }, _('This month')),
@@ -202,6 +248,10 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
details,
E('div', { class: 'dl-kv2' }, [
copyRow(_('Tunnel address'), d.address),
...linkRows(d, p, srv, () => {
relinked = true;
return changed();
}).map(([k, v]) => row(k, v)),
d.hostname && p.access !== 'internet' ? copyRow(_('Local address'), d.hostname) : '',
// Where it connects from is under Locations (with the place and network); from home
// (not on the map) or without locations, here.
@@ -287,7 +337,15 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
geo = st.geo;
now = st.now;
today = todayOf(st.series);
srv = st.servers.find((s) => s.id === p2.server);
paint();
// A change made here (its MTU or keep-alive) or elsewhere left the configuration on screen behind: the new one
// waits behind the button.
if ((d.config_stale || relinked) && !gated) {
gated = true;
dom.content(connectSec, connectBody(gate()));
}
relinked = false;
view?.update({ geo: st.geo, now: st.now, person: p, device: d });
};
/** After a change made here: this drawer and the page. */
@@ -297,9 +355,10 @@ 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 input = E('input', { type: 'text', class: 'cbi-input-text', value: d.name }) as HTMLInputElement;
const said = nameGuard(input, () => nameRow.refresh());
const taken = p.devices.filter((x) => x.id !== d.id).map((x) => x.name);
const nameRow = liveField(_('Name'), input, () => nameHelp(input.value, taken, _('Shown in the portal and in the app.')));
const nameRow = liveField(_('Name'), input, () => said(deviceNameHelp(input.value, taken, _('Shown in the portal and in the app.'))));
modal(
fmt(_('Rename %s'), d.name),
[nameRow],
@@ -327,7 +386,7 @@ 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' }, [
const connectBody = (c: HTMLElement) => [
// Whether it is connected (or still waiting) is in Status above.
E('div', { class: 'dl-dsec-head' }, [E('h4', {}, _('Connect', 'section'))]),
d.config_stale
@@ -337,8 +396,9 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
),
)
: '',
connect,
]);
c,
];
const connectSec = E('section', { class: 'dl-dsec' }, connectBody(connect));
const activitySec = E('section', { class: 'dl-dsec' }, [
E('div', { class: 'dl-dsec-head' }, [
E('h4', {}, _('Activity')),
@@ -429,7 +489,8 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
/** ⋯ on a device card: quick actions (everything else is in the panel; click the card). */
export function quickMenu(anchor: HTMLElement, p: Person, d: Device, o: DeviceOpts) {
const core = o.core ?? coreOf(null);
const cfg = () => attempt(() => api.deviceConfig(d.id));
// Each of these gives the configuration out.
const cfg = () => attempt(() => api.deviceConfig(d.id, true));
const items: (MenuItem | null)[] = [
{
label: _('Show QR code'),
@@ -519,23 +580,49 @@ export function quickMenu(anchor: HTMLElement, p: Person, d: Device, o: DeviceOp
dropdown(anchor, items);
}
/**
* A device's name field guarded as the portal's are (shared/name-guard.ts): a refused character shakes the input,
* and the row's help says why until a change gets in or the field is left (Save never reads a stale reason).
* Returns what the row's help passes its own through.
*/
function nameGuard(input: HTMLInputElement, refresh: () => void): (help: Help) => Help {
let why: string | null = null;
guardDeviceName(input, input, (w) => {
why = w;
refresh();
});
input.addEventListener('blur', () => {
if (!why) return;
why = null;
refresh();
});
return (help) => (why ? { text: why, bad: true } : help);
}
/** Admin "Add device" dialog for a person; opens the new device's drawer. */
export function addDevice(person: Person, o: DeviceOpts) {
const taken = person.devices.map((x) => x.name);
// The name a type gives when none is typed: "Phone", then "Phone 2" (as the portal does).
const suggest = (k: Kind) => {
const base = kindLabel(k);
const base = defaultName(k);
let n = 1;
let name = base;
while (taken.some((t) => t.toLowerCase() === name.toLowerCase())) name = `${base} ${++n}`;
let name = fitName(base);
while (taken.some((t) => t.toLowerCase() === name.toLowerCase())) name = fitName(base, ` ${++n}`);
return name;
};
let kind: Kind = 'phone';
const nameInput = E('input', { type: 'text', class: 'cbi-input-text', placeholder: suggest(kind), maxlength: 48 }) as HTMLInputElement;
const nameInput = E('input', {
type: 'text',
class: 'cbi-input-text',
placeholder: suggest(kind),
}) as HTMLInputElement;
const said = nameGuard(nameInput, () => nameRow.refresh());
const nameRow = liveField(_('Name'), nameInput, () =>
nameInput.value.trim()
? nameHelp(nameInput.value, taken, _('Shown in the portal and in the app.'))
: { text: fmt(_('Named after its type: %s.'), suggest(kind)), bad: false },
said(
nameInput.value.trim()
? deviceNameHelp(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',
@@ -564,6 +651,8 @@ export function addDevice(person: Person, o: DeviceOpts) {
),
),
);
// LAN Bypass: off unless chosen (the person chooses it on the portal, the admin here).
const bypass = sw(false, _('LAN Bypass'));
const over = person.devices.length >= person.device_limit;
modal(
fmt(_('Add a device for %s'), person.name),
@@ -585,6 +674,23 @@ export function addDevice(person: Person, o: DeviceOpts) {
)
: '',
E('div', { class: 'dl-fld' }, [E('span', { class: 'dl-fld-label' }, _('Type')), kinds]),
// As the portal's Add a device: between the type and the name.
E('div', { class: 'cbi-value dl-live' }, [
E('div', { class: 'cbi-value-title' }, [
E('label', {}, _('LAN Bypass')),
E(
'div',
{ class: 'dl-sub' },
homeOf(person, o.server).length
? fmt(
_('The device’s local network stays reachable while connected, except %s: your home network.'),
netsLabel(homeOf(person, o.server)),
)
: _('The device’s local network stays reachable while connected.'),
),
]),
E('div', { class: 'cbi-value-field' }, bypass),
]),
nameRow,
],
[
@@ -599,7 +705,7 @@ export function addDevice(person: Person, o: DeviceOpts) {
return;
}
const name = nameInput.value.trim() || suggest(kind);
const r = await attempt(() => api.deviceCreate(person.id, name, kind));
const r = await attempt(() => api.deviceCreate(person.id, name, kind, isOn(bypass)));
if (!r) return;
closeModal();
notify(fmt(_('%s added'), name), 'success', 3000);
+6
View File
@@ -24,6 +24,8 @@ export const LOG_TEMPLATES: string[] = [
"AmneziaWG isn't running",
'Backup',
'Browsers will refuse the portal after that. Renew it with ACME, or choose another certificate in Settings.',
'Changed: %s.',
'Choose a disguise on the Server page: it replaces the values set by hand.',
'Choose another interface name in the server settings.',
'Components',
'Connections',
@@ -31,6 +33,7 @@ export const LOG_TEMPLATES: string[] = [
"Dawnline didn't stop it: the router's network restarted, someone stopped it by hand, or it failed.",
'Firewall',
'Install it in Dawnline → Components.',
'Install that AmneziaWG build in Dawnline → Components, or switch the disguise on the Server page.',
'Internet like a home device',
'MTU is now automatic',
'Missing: %s.',
@@ -71,7 +74,10 @@ export const LOG_TEMPLATES: string[] = [
'has an invalid interface name "%s"',
'installed the %s build',
'installed the %s build · %s',
"interface %s has Dawnline's settings again",
'interface %s was changed outside Dawnline',
'is kept down',
'is kept down: its disguise has values AmneziaWG cannot take',
'is kept down: its disguise needs AmneziaWG %s (installed: %s)',
'is kept down: its disguise needs AmneziaWG %s (installed: none)',
'is off',
+39 -1
View File
@@ -25,6 +25,8 @@ const CATEGORY: Record<string, LogCategory> = {
expiring: 'people',
expired_kept: 'people',
portal_blocked: 'problems',
device_failing: 'problems',
device_recovered: 'problems',
};
export const CATEGORIES: LogCategory[] = ['connections', 'people', 'problems'];
@@ -37,7 +39,7 @@ 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)'),
problems: _('Blocked portal sign-ins and devices that can’t connect properly (tunnels and services are in the service log)'),
}[c];
}
@@ -134,6 +136,42 @@ export function changedText(detail: string): string {
.join(', ');
}
/** A device's settings a device_changed event lists (its link options, "mtu, keepalive"); anything else as written. */
export function deviceChangedText(detail: string): string {
const f: Record<string, string> = { mtu: 'MTU', keepalive: _('keep-alive'), lan_bypass: _('LAN Bypass') };
return detail
.split(', ')
.map((k) => f[k] ?? k)
.join(', ');
}
/**
* A device's link failing in a named way (dawnline.link's states), said about
* the device: its title and what it means (the device drawer's Status, the
* title also in Activity). Null for a state this page does not know.
*/
export function linkStateText(state: string): { title: string; line: string } | null {
const t: Record<string, [string, string]> = {
trying: [_('Unable to complete the handshake'), _('The device’s network may be blocking the connection.')],
dropped: [_('Handshake complete, but no data'), _('This device is using an outdated configuration.')],
shared: [_('On two devices at once'), _('The same configuration connects from two places in turn. Give the other device its own.')],
unstable: [
_('Connection keeps dropping'),
_('It connects, but the connection breaks every few minutes: the network may be cutting it.'),
],
};
const w = t[state];
return w ? { title: w[0], line: w[1] } : null;
}
/** The states a device_failing event names ("trying, unstable" when two came within an hour), by their titles. */
export function linkStatesText(detail: string): string {
return detail
.split(', ')
.map((s) => linkStateText(s)?.title ?? s)
.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,
+22 -2
View File
@@ -8,7 +8,20 @@ import { E } from '../e';
import { icon } from '../../shared/icons';
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';
import {
adminName,
adminSentence,
changedText,
daysOf,
deviceChangedText,
eventBy,
linkStatesText,
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'>;
@@ -28,6 +41,8 @@ const EVENT_TONE: Record<string, string> = {
portal_blocked: 'bad',
person_changed: '',
devices_removed: 'warn',
device_failing: 'warn',
device_recovered: 'ok',
};
/** The icon in an event's tile: the device's kind for device events, else what happened. */
@@ -93,7 +108,8 @@ export function eventText(st: Pick<Status, 'people'>, e: LogEvent): Node[] {
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}`)] : [])];
// Its own link options by name ("mtu, keepalive"), as person_changed lists a person's.
return [...you(_('You changed device %s of %s'), d, b(who)), ...(detail ? [m(` · ${deviceChangedText(detail)}`)] : [])];
}
case 'device_keys':
return [...you(_('You issued new keys for device %s of %s'), devName, b(who)), m(` · ${_('it needs its new configuration')}`)];
@@ -157,6 +173,10 @@ export function eventText(st: Pick<Status, 'people'>, e: LogEvent): Node[] {
);
case 'devices_removed':
return say(_('Person %s - all devices removed, end date reached'), b(who));
case 'device_failing':
return [...say(_('Device %s has a connection problem'), wd), ...(e.detail ? [m(` · ${linkStatesText(e.detail)}`)] : [])];
case 'device_recovered':
return say(_('Device %s connects normally again'), wd);
default:
return [m(`${e.type}${e.detail ? `: ${e.detail}` : ''}`)];
}
+25
View File
@@ -2,6 +2,7 @@
// 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 { DEVICE_NAME_MAX, deviceNameFits } from '../shared/format';
import { fmt, locale, num, plural } from '../shared/i18n';
/** A network on the router, by name: an interface ("lan") or a server ("Home"). */
@@ -122,6 +123,16 @@ export function nameHelp(s: string, taken: string[] = [], good = ''): Help {
return { text: good, bad: false };
}
/**
* A device's name (util.valid_device_name): up to DEVICE_NAME_MAX of letters (any language), digits, spaces and - _ .
* (an old name from before the rule says what to change in it).
*/
export function deviceNameHelp(s: string, taken: string[] = [], good = ''): Help {
if (chars(s.trim()) > DEVICE_NAME_MAX) return { text: tooLong(DEVICE_NAME_MAX, s.trim()), bad: true };
if (!deviceNameFits(s.trim())) return { text: _('Letters, digits, spaces and - _ . only.'), bad: true };
return nameHelp(s, taken, good);
}
/** 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: tooLong(32, s), bad: true };
@@ -198,6 +209,20 @@ export function keepaliveHelp(s: string): Help {
return { text: fmt(_('Devices send a packet every %s s to keep NAT open (a little battery on phones).'), t), bad: false };
}
/** A device's own MTU (core.set_device_link): empty = automatic (the server's for its kind), else 1280–1500. */
export function deviceMtuHelp(s: string): Help {
const t = s.trim();
if (t && (!/^\d{1,4}$/.test(t) || Number(t) < 1280 || Number(t) > 1500)) return { text: _('From 1280 to 1500.'), bad: true };
return { text: _('Empty: automatic. Lower it when big pages hang on this device.'), bad: false };
}
/** A device's own keep-alive (core.set_device_link): empty = the server's, else 0–600 s (0 = off). */
export function deviceKeepaliveHelp(s: string): Help {
const t = s.trim();
if (t && (!/^\d{1,4}$/.test(t) || Number(t) > 600)) return { text: _('From 0 to 600 seconds.'), bad: true };
return { text: _('Seconds. Empty: as the server. Longer saves battery; behind some NATs it then drops.'), 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();
+24 -11
View File
@@ -14,8 +14,9 @@ import { ConnectionMap, rangeControl, type Range } from '../map';
import { personUrl } from '../urls';
import { eventRow } from '../events/render';
import { scoped } from '../state/scope';
import { repaint } from '../state/poller';
import { daysTile, speedTile } from '../widgets/tiles';
import { focusInside, repaint } from '../state/poller';
import type { LiveMeter } from '../state/meter';
import { daysTile, LiveSpeedTile } from '../widgets/tiles';
import { coreOf } from '../cores';
import { healthNotices, runFix } from '../widgets/health';
import { attempt } from '../ui/toast';
@@ -128,10 +129,13 @@ export class ServerOverview {
range: Range = 'online';
parts: Record<string, HTMLElement> = {};
healthAt = 0;
/** Speed now, live: one tile for this Overview's life, its numbers put in place each second. */
speed = new LiveSpeedTile();
/** `go` switches the Servers page to another section in place. */
/** `meter` is the Servers page's live meter (it polls it); `go` switches the page to another section in place. */
constructor(
readonly srvId: string,
private meter: LiveMeter,
private go?: (section: string, filter?: string) => void,
) {}
@@ -249,11 +253,13 @@ export class ServerOverview {
const srv = st.servers[0];
this.paintMap();
repaint(
this.parts.bento,
E('div', { class: 'dl-bento' }, [this.onlineTile(), this.speedTile(), coreOf(srv).overviewTile(srv), this.monthTile()]),
quiet,
);
// The live speed tile moves into a new bento: one is made only when it is put on the page.
if (quiet && focusInside(this.parts.bento)) this.paintSpeed();
else
dom.content(
this.parts.bento,
E('div', { class: 'dl-bento' }, [this.onlineTile(), this.speedTile(), coreOf(srv).overviewTile(srv), this.monthTile()]),
);
const att = attention(st);
repaint(
@@ -446,12 +452,19 @@ export class ServerOverview {
}
/**
* Throughput right now (from the agent's minute samples): download and
* upload side by side, the last 15 minutes as a small chart, today's total.
* Throughput right now (the live meter, one point a second): download and
* upload side by side, the last 2 minutes as a small chart, today's total.
*/
speedTile(): HTMLElement {
this.paintSpeed();
return this.speed.el;
}
/** The speed tile from the meter as it stands (the Servers page calls this with each answer). */
paintSpeed() {
if (!this.st) return;
const srv = this.st.servers[0];
return speedTile(srv?.rate ?? [], this.st.now, this.st.totals.today, srv ? !srv.enabled : false);
this.speed.update(this.meter.speed(this.srvId, Date.now()), this.st.totals.today, srv ? !srv.enabled : false);
}
/** The last 30 days, today on the right, with the peak. */
+1
View File
@@ -154,6 +154,7 @@ export class PeoplePage {
now: this.st.now,
today: this.today,
core: coreFor(this.st.servers, p.server),
server: this.st.servers.find((s) => s.id === p.server),
};
}
+2 -2
View File
@@ -17,13 +17,13 @@ import type { PersonPage } from './index';
/** Setting up a device: its QR code (key and file one tap away). */
async function showDeviceQr(page: PersonPage, d: Device) {
const cfg = await attempt(() => api.deviceConfig(d.id));
const cfg = await attempt(() => api.deviceConfig(d.id, true));
if (!cfg) return;
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));
const cfg = await attempt(() => api.deviceConfig(d.id, true));
if (!cfg) return;
if (!cfg.has_private_key) {
notify(_('This device made its own keys in the browser; its configuration only exists there.'), 'warning');
+1
View File
@@ -161,6 +161,7 @@ export class PersonPage {
now: this.st.now,
today: this.today,
core: this.core,
server: this.st.servers.find((s) => s.id === this.p.server),
events: () => this.events,
};
}
+22 -1
View File
@@ -23,6 +23,7 @@ import { defaultMethod, methodPicker } from '../disguise';
import { coreOf } from '../cores';
import { installAwg } from '../pkgs';
import { createPoller, focusInside, repaint, type Poller } from '../state/poller';
import { LiveMeter, type MeterAnswer } from '../state/meter';
import { ServerOverview } from './overview';
import { PeoplePage } from './people';
@@ -64,6 +65,9 @@ export class ServerPage {
secEl = E('div', {});
bodyEl = E('div', { class: 'dl-srvbody' });
poller?: Poller<Status>;
/** The live meter's last 2 minutes, every server's (the Overviews' Speed now), and its poller. */
meter = new LiveMeter();
meterPoller?: Poller<MeterAnswer>;
async load(): Promise<[Status, SetupDefaults | null]> {
const st = await api.status(31);
@@ -100,6 +104,23 @@ export class ServerPage {
this.ov[this.current().id]?.update(n, quiet);
},
});
// Speed now, live: one meter call a second while the Overview of a running server is on screen
// (the router keeps the last two minutes and writes them out while someone asks). A failed call is said in the tile, not in a
// second "not answering" toast beside the status poller's.
this.meterPoller?.stop();
this.meterPoller = createPoller<MeterAnswer>({
fetch: () =>
api.meter(this.meter.since(Date.now())).then(
(meter) => ({ meter }),
(e) => ({ error: errorText(e) }),
),
every: 1,
active: () => this.section === 'overview' && this.root.isConnected && this.current().enabled,
apply: (r) => {
this.meter.take(r, Date.now());
this.ov[this.current().id]?.paintSpeed();
},
});
return this.root;
}
@@ -229,7 +250,7 @@ export class ServerPage {
const body: Record<Section, () => Node> = {
overview: () => {
const ov = this.ov[srv.id];
if (!ov) return (this.ov[srv.id] = new ServerOverview(srv.id, (k, f) => this.go(k as Section, f))).mount(st);
if (!ov) return (this.ov[srv.id] = new ServerOverview(srv.id, this.meter, (k, f) => this.go(k as Section, f))).mount(st);
ov.update(st);
return ov.el;
},
+108
View File
@@ -0,0 +1,108 @@
// The live meter as the Servers page keeps it (rpc meter, polled once a
// second while an Overview is on screen): the answers merged into the last two
// minutes, and one server's part of them for its Speed now tile. No DOM and no
// RPC here: the poller is the page's (pages/server.ts), the tile widgets/tiles.
import type { Meter, MeterPoint } from '../api';
/** [ts, rx, tx] in bytes/s, as Server.rate: rx = from the devices, tx = to them. */
export type Rate = [number, number, number];
/** One call's outcome: the meter, or why there is none. */
export type MeterAnswer = { meter: Meter } | { error: string };
/** Page milliseconds after the last answer when what is kept stops counting as live: the next call asks for everything again. */
const STALE_MS = 5000;
/** Router seconds the newest point is "now": an agent that stopped leaves its last one behind. */
const FRESH_S = 5;
/** Failed calls in a row before the tile says so (one may just be slow). */
const LOST_AFTER = 3;
/**
* Answers with no points before the tile says it is collecting: the first call of a look finds none, and the
* router writes out the two minutes it kept within a second.
*/
const EARLY = 3;
/** One server's live speed, ready for the tile. */
export interface LiveSpeed {
/** Its points, oldest first. */
pts: Rate[];
/** Where each one sits across the chart: 1 is the newest point the meter has, 0 two minutes before it. */
xs: number[];
/** Bytes/s now: its newest point while that is fresh, else 0. */
rx: number;
tx: number;
/** Why the meter could not be read, once that happened a few times in a row; null otherwise. */
error: string | null;
/** No points yet, a moment after asking: the router is writing out what it kept (the tile waits without words). */
early: boolean;
}
export class LiveMeter {
private points: MeterPoint[] = [];
/** Page clock (ms) of the last answer. */
private at = 0;
/** Router clock of the last answer. */
private now = 0;
private keep = 120;
private failed = 0;
private error = '';
/** Answers in a row that left nothing kept. */
private empty = 0;
/** Still live at page time `ms`: kept points from an answer a moment ago. */
private live(ms: number): boolean {
return this.points.length > 0 && ms - this.at < STALE_MS;
}
/** What to ask for: the points after the newest one kept, or all of them (0) when nothing live is kept. */
since(ms: number): number {
return this.live(ms) ? this.points[this.points.length - 1].ts : 0;
}
/** An answer at page time `ms`: new points appended, those over two minutes behind the newest dropped. */
take(r: MeterAnswer, ms: number): void {
if ('error' in r) {
this.failed++;
this.error = r.error;
return;
}
const m = r.meter;
let kept = this.live(ms) ? this.points : [];
// The router's clock went back: its points are now behind what is kept, and asking for those after the newest
// kept would never bring them. Start over: the next call asks for everything.
if (kept.length && m.ts > 0 && m.ts < kept[kept.length - 1].ts) kept = [];
const last = kept.length ? kept[kept.length - 1].ts : 0;
const all = [...kept, ...m.points.filter((p) => p.ts > last)];
this.keep = m.keep > 1 ? m.keep : 120;
const end = all.length ? all[all.length - 1].ts : 0;
this.points = all.filter((p) => p.ts > end - this.keep);
this.empty = this.points.length ? 0 : this.empty + 1;
this.at = ms;
this.now = m.now;
this.failed = 0;
this.error = '';
}
/** Server `id`'s points at page time `ms` (none once they are not live), placed against the meter's newest point. */
speed(id: string, ms: number): LiveSpeed {
const error = this.failed >= LOST_AFTER ? this.error : null;
const live = this.live(ms) ? this.points : [];
// A second its tunnel was not read has no point of its own.
const pts = live.flatMap((p): Rate[] => (p.servers[id] ? [[p.ts, p.servers[id][0], p.servers[id][1]]] : []));
const end = live.length ? live[live.length - 1].ts : 0;
const span = this.keep - 1;
const last = pts[pts.length - 1];
// A point dated after the router's now (its clock went back) is no speed now either.
const age = last ? this.now - last[0] : -1;
const fresh = age >= 0 && age < FRESH_S;
return {
pts,
xs: pts.map((p) => 1 - (end - p[0]) / span),
rx: fresh ? last[1] : 0,
tx: fresh ? last[2] : 0,
error,
early: !live.length && this.empty < EARLY,
};
}
}
+4 -1
View File
@@ -44,5 +44,8 @@
.dl-seg button b.warn { background: var(--dl-warn-wash); color: var(--dl-warn); }
.dl-seg.sm button { padding: 2px 9px; font-size: 11px; }
.dl-seg.wide { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); border-radius: 12px; padding: 4px; }
.dl-seg.wide button { flex-direction: column; justify-content: center; padding: 8px 6px; border-radius: 9px; gap: 3px; }
/* Three equal columns: a label longer than its column (Russian "Дом и интернет") wraps under its icon instead of
running out of the button. */
.dl-seg.wide button { flex-direction: column; justify-content: center; padding: 8px 6px; border-radius: 9px; gap: 3px;
white-space: normal; text-align: center; line-height: 16px; }
.dl-seg.wide button.on { background: var(--dl-primary); color: var(--dl-primary-fg); }
+113 -28
View File
@@ -1,7 +1,8 @@
// Bento tiles shared by the server Overview and the person page: speed now
// and the last 30 days.
// (from the minute samples, or live on the Overview) and the last 30 days.
import type { DayUsage } from '../../shared/types';
import type { LiveSpeed, Rate } from '../state/meter';
import { E } from '../e';
import { bits, bytes, parseDay } from '../../shared/format';
import { fill, fmt, locale } from '../../shared/i18n';
@@ -10,37 +11,53 @@ import { svg } from '../ui/layout';
const dayLabel = (day: string) => parseDay(day).toLocaleDateString(locale(), { day: 'numeric', month: 'short' });
/** The speed chart's box (its viewBox; CSS stretches it to the tile). */
const W = 200,
H = 40;
/** The speed chart's lines through `pts` at `xs` (0–1 across): download filled, upload over it. */
function chartPaths(pts: Rate[], xs: number[]): { area: string; down: string; up: string } {
const max = Math.max(1, ...pts.map((p) => Math.max(p[1], p[2])));
const line = (k: 1 | 2) => pts.map((p, i) => `${xs[i] * W},${H - 2 - (p[k] / max) * (H - 6)}`);
const dl = line(2),
ul = line(1);
return {
area: `M${dl.join(' L')} L${xs[xs.length - 1] * W},${H} L${xs[0] * W},${H}Z`,
down: `M${dl.join(' L')}`,
up: `M${ul.join(' L')}`,
};
}
/** One of the two speeds: its arrow and label, then the value. */
const speedCol = (label: string, ic: string, cls: string, val: HTMLElement) =>
E('div', { class: 'dl-speed-col' }, [E('span', { class: 'dl-sub' }, [E('span', { class: cls }, ic), ` ${label}`]), val]);
/** Today's traffic under the chart (`today` is [rx, tx]). */
const todayParts = ([rx, tx]: [number, number]) => [
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)}`]),
];
/**
* Throughput over the last 15 minutes plus today's total. `off`: the server is
* turned off, so there is no speed to show (dashes, not zeros) and no chart.
*/
export function speedTile(rate: [number, number, number][], now: number, today: [number, number], off = false): HTMLElement {
export function speedTile(rate: Rate[], now: number, today: [number, number], off = false): HTMLElement {
const pts = rate.slice(-15);
const last = pts[pts.length - 1];
const fresh = last && now - last[0] < 180;
const down = fresh ? last[2] : 0,
up = fresh ? last[1] : 0;
const [rx, tx] = today;
const W = 200,
H = 40;
const max = Math.max(1, ...pts.map((p) => Math.max(p[1], p[2])));
const line = (k: 1 | 2) => pts.map((p, i) => `${pts.length > 1 ? (i / (pts.length - 1)) * W : W},${H - 2 - (p[k] / max) * (H - 6)}`);
const dl = line(2),
ul = line(1);
const chart =
pts.length > 1 && !off
? svg(
`<svg viewBox="0 0 ${W} ${H}" preserveAspectRatio="none" class="dl-speed-chart" aria-hidden="true">` +
`<path d="M${dl.join(' L')} L${W},${H} L0,${H}Z" class="area"/><path d="M${dl.join(' L')}" class="line"/>` +
`<path d="M${ul.join(' L')}" class="line up"/></svg>`,
)
: E('div', { class: 'dl-speed-wait' }, [E('i'), 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}`]),
off ? E('span', { class: 'dl-speed-val off' }, '—') : E('span', { class: 'dl-speed-val' }, bits(v)),
]);
if (pts.length > 1 && !off)
let chart: HTMLElement;
if (pts.length > 1 && !off) {
const d = chartPaths(
pts,
pts.map((_x, i) => i / (pts.length - 1)),
);
chart = svg(
`<svg viewBox="0 0 ${W} ${H}" preserveAspectRatio="none" class="dl-speed-chart" aria-hidden="true">` +
`<path d="${d.area}" class="area"/><path d="${d.down}" class="line"/><path d="${d.up}" class="line up"/></svg>`,
);
attachTip(chart, () => {
const p = pts[pts.length - 1];
return [
@@ -48,20 +65,88 @@ export function speedTile(rate: [number, number, number][], now: number, today:
E('div', {}, `↓ ${bits(p[2])} · ↑ ${bits(p[1])}`),
];
});
} else chart = E('div', { class: 'dl-speed-wait' }, [E('i'), off ? '' : E('span', {}, _('Collecting… 1 point a minute'))]);
const val = (v: number) => (off ? E('span', { class: 'dl-speed-val off' }, '—') : E('span', { class: 'dl-speed-val' }, bits(v)));
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('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', {}, fill(_('Today %s'), E('b', {}, bytes(rx + tx)))),
E('span', {}, [E('span', { class: 'dl-dn' }, '↓'), ` ${bytes(tx)} `, E('span', { class: 'dl-up' }, '↑'), ` ${bytes(rx)}`]),
E('div', { class: 'dl-speed-cols' }, [
speedCol(_('Download', 'speed'), '↓', 'dl-dn', val(down)),
speedCol(_('Upload', 'speed'), '↑', 'dl-up', val(up)),
]),
chart,
E('div', { class: 'dl-speed-today' }, todayParts(today)),
]);
}
/**
* Speed now, live (the server Overview): speedTile's tile, its chart the last
* 2 minutes one point a second (state/meter.ts). Built once; update() puts each
* second's numbers and lines in place. No tooltip: the numbers above the chart
* are its newest point already.
*/
export class LiveSpeedTile {
private span = E('span', { class: 'dl-sub' }, _('last 2 min'));
private down = E('span', { class: 'dl-speed-val' });
private up = E('span', { class: 'dl-speed-val' });
private chart = svg(
`<svg viewBox="0 0 ${W} ${H}" preserveAspectRatio="none" class="dl-speed-chart" aria-hidden="true">` +
`<path class="area"/><path class="line"/><path class="line up"/></svg>`,
);
private wait = E('div', { class: 'dl-speed-wait' });
/** The chart or the waiting line, whichever is in the tile. */
private shown = this.wait;
private today = E('div', { class: 'dl-speed-today' });
readonly el = E('div', { class: 'dl-bento-tile' }, [
E('div', { class: 'dl-bento-head' }, [E('span', { class: 'dl-metric-label' }, _('Speed now')), this.span]),
E('div', { class: 'dl-speed-cols' }, [
speedCol(_('Download', 'speed'), '↓', 'dl-dn', this.down),
speedCol(_('Upload', 'speed'), '↑', 'dl-up', this.up),
]),
this.wait,
this.today,
]);
/**
* This second's speed and today's traffic ([rx, tx]). `off`: the server is
* turned off (dashes, no chart); a meter that cannot be read says why in
* the chart's place, with dashes for the speeds.
*/
update(s: LiveSpeed, today: [number, number], off: boolean): void {
const none = off || !!s.error;
this.span.style.display = off ? 'none' : '';
for (const [el, v] of [
[this.down, s.tx],
[this.up, s.rx],
] as const) {
el.className = `dl-speed-val${none ? ' off' : ''}`;
el.textContent = none ? '—' : bits(v);
}
const lines = !none && s.pts.length > 1;
if (lines) {
const p = chartPaths(s.pts, s.xs);
const [area, down, up] = this.chart.querySelectorAll('path');
area.setAttribute('d', p.area);
down.setAttribute('d', p.down);
up.setAttribute('d', p.up);
} else
dom.content(this.wait, [
E('i'),
off || (s.early && !s.error)
? ''
: E('span', {}, s.error ? fmt(_("Couldn't read the live speed: %s"), s.error) : _('Collecting… 1 point a second')),
]);
const want = lines ? this.chart : this.wait;
if (want !== this.shown) {
this.shown.replaceWith(want);
this.shown = want;
}
dom.content(this.today, todayParts(today));
}
}
/** Daily traffic for the last 30 days, today on the right. */
export function daysTile(series: DayUsage[], note: string): HTMLElement {
const days = series.slice(-30);
+31 -3
View File
@@ -62,8 +62,15 @@ export interface DemoDevice {
created: number;
by: 'admin' | 'portal';
stale: boolean;
/** A set-up state the visitor picked in the sheet (way-pick.ts), held until they pick another; none: as it comes. */
way?: DemoWay;
/** When it was picked: the knocks' or the handshake's time. */
wayAt?: number;
}
/** The set-up states the visitor can hold a device in (connected is a real handshake: router.ts). */
export type DemoWay = 'waiting' | 'trying' | 'nodata';
/** The scenario's own devices, as it starts. */
export function seedDevices(s: ScenarioId, t: number, id: () => string): DemoDevice[] {
if (s === 'first') return [];
@@ -135,8 +142,12 @@ export function hoursAway(t: number): string {
export const handshakeOf = (d: DemoDevice, t: number) => (d.connectAt && t >= d.connectAt ? d.connectAt : d.hs);
function device(d: DemoDevice, t: number, st: Person['state']): Device {
const hs = handshakeOf(d, t);
// Held waiting or knocking: no handshake; no data: one handshake when it was picked, nothing after it.
const at = d.wayAt ?? t;
const hs = d.way === 'nodata' ? at : d.way ? 0 : handshakeOf(d, t);
const month = d.gb * GB;
// A stopped person's tunnels are down; the rest count as online for three minutes after a handshake.
const online = !!hs && t - hs < 180 && st !== 'paused' && st !== 'expired';
return {
id: d.id,
name: d.name,
@@ -145,8 +156,7 @@ function device(d: DemoDevice, t: number, st: Person['state']): Device {
disabled: false,
created: d.created,
created_by: d.by,
// A stopped person's tunnels are down; the rest count as online for three minutes after a handshake.
online: !!hs && t - hs < 180 && st !== 'paused' && st !== 'expired',
online,
handshake: hs,
endpoint: hs ? `203.0.113.${20 + d.n}` : '',
active: true,
@@ -158,6 +168,22 @@ function device(d: DemoDevice, t: number, st: Person['state']): Device {
hostname: `${label(d.name)}.user.lan`,
browser_key: false,
config_stale: d.stale,
lan_bypass: false,
mtu: 0,
keepalive: null,
// The server's for its kind, as the router works it out (the portal never shows it).
mtu_used: d.kind === 'phone' || d.kind === 'tablet' ? 1280 : 1368,
keepalive_used: 25,
link: null,
// The demo's devices pass data whenever they are connected: the set-up sheet sees one arrive.
setup:
d.way === 'trying'
? { state: 'trying', since: at }
: d.way === 'nodata'
? { state: 'nodata', since: at }
: online
? { state: 'flowing', since: hs }
: null,
};
}
@@ -204,6 +230,8 @@ export function pageState(s: ScenarioId, devs: DemoDevice[], t: number, secureUr
device_mesh: true,
awg_disguise: s !== 'plain',
preset: s === 'plain' ? 'off' : 'max',
// A home network as most routers come with it: LAN Bypass then says those addresses still lead home.
home: ['192.168.1.0/24'],
},
can_add: devs.length < limit,
locked: locked(s),
+153 -2
View File
@@ -1,6 +1,6 @@
/* The portal demo's stylesheet: the portal's own, then the demo's pieces in its tokens — the "Demo"
chip after the breadcrumb's path, the GitHub pill beside the page's QR knob, and the scenario
rows in the drawer. */
chip after the breadcrumb's path, the GitHub pill beside the page's QR knob, the scenario
rows in the drawer, and the set-up state switch beside the set-up sheet's ×. */
@import '../styles/index.css';
/* The path keeps its width so the chip sits right after it; the page's QR stays at the end. */
@@ -149,3 +149,154 @@
display: none;
}
}
/* The set-up state switch: a pill beside ×, gliding into its place when the device arrives. */
.dm-way {
position: absolute;
z-index: 3;
top: 22px;
display: inline-flex;
align-items: center;
gap: 7px;
height: 32px;
padding: 0 10px 0 12px;
border-radius: 999px;
background: var(--knob);
color: var(--text);
font-size: 13px;
font-weight: 500;
transition:
background-color 150ms,
transform 150ms var(--ease-out),
right var(--spring-smooth-dur) var(--spring-smooth);
}
.dm-way:hover {
background: color-mix(in srgb, var(--knob), var(--text) 6%);
}
.dm-way:active {
transform: scale(0.95);
}
.dm-way[aria-expanded='true'] {
background: color-mix(in srgb, var(--knob), var(--text) 10%);
}
.dm-way .i {
width: 14px;
height: 14px;
color: var(--text-2);
transform: rotate(90deg);
transition: transform 240ms var(--ease-out);
}
.dm-way[aria-expanded='true'] .i {
transform: rotate(-90deg);
}
.dm-way .dot,
.dm-way-pop .dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--text-3);
transition:
background-color 300ms,
opacity 150ms;
}
.dm-way .dot.warn,
.dm-way-pop .dot.warn {
background: var(--warn);
}
.dm-way .dot.ok,
.dm-way-pop .dot.ok {
background: var(--ok);
}
/* Its popup: segments in one pill frame, a step above the sheet each (white on grey in light), a tail down
to the pill, and a dark, softly blurred halo behind that fades out around it. */
.dm-way-pop {
--frame: color-mix(in srgb, var(--field), var(--knob) 55%);
--seg: color-mix(in srgb, var(--knob), var(--text) 2%);
--seg-hover: color-mix(in srgb, var(--knob), var(--text) 6%);
position: fixed;
z-index: 60;
display: flex;
gap: 3px;
padding: 3px;
border-radius: 999px;
background: var(--frame);
box-shadow: var(--pop-shadow);
}
.dm-way-pop::before {
content: '';
position: absolute;
bottom: -5px;
left: var(--tail, 50%);
width: 12px;
height: 12px;
margin-left: -6px;
border-radius: 0 0 3px 0;
background: var(--frame);
transform: rotate(45deg);
}
.dm-way-pop button {
position: relative;
display: inline-flex;
align-items: center;
gap: 6px;
height: 34px;
padding: 0 10px;
border-radius: 10px;
background: var(--seg);
color: color-mix(in srgb, var(--text-2), var(--text-3) 35%);
font-size: 12.5px;
font-weight: 500;
white-space: nowrap;
transition:
color 150ms,
background-color 150ms,
transform 150ms var(--ease-out);
}
/* The ends follow the frame: half the segment's height (a larger radius would shrink every corner). */
.dm-way-pop button:first-of-type {
border-radius: 17px 10px 10px 17px;
padding-left: 13px;
}
.dm-way-pop button:last-of-type {
border-radius: 10px 17px 17px 10px;
padding-right: 13px;
}
.dm-way-pop button:hover {
color: color-mix(in srgb, var(--text-2), var(--text) 45%);
background: var(--seg-hover);
}
.dm-way-pop button:active {
transform: scale(0.96);
}
.dm-way-pop button[aria-checked='true'] {
color: var(--text);
}
.dm-way-pop .dot {
background: currentColor;
opacity: 0.5;
}
.dm-way-pop button[aria-checked='true'] .dot,
.dm-way-pop button:hover .dot {
opacity: 1;
}
.dm-way-halo {
position: fixed;
z-index: 59;
pointer-events: none;
background: radial-gradient(closest-side, rgba(0, 0, 0, 0.6), rgba(0, 0, 0, 0.35) 55%, transparent);
-webkit-backdrop-filter: blur(3px);
backdrop-filter: blur(3px);
-webkit-mask-image: radial-gradient(closest-side, #000 60%, transparent 92%);
mask-image: radial-gradient(closest-side, #000 60%, transparent 92%);
}
@media (prefers-color-scheme: light) {
.dm-way-pop {
--frame: var(--knob);
--seg: var(--raised);
--seg-hover: color-mix(in srgb, var(--raised), var(--text) 4%);
}
.dm-way-halo {
background: radial-gradient(closest-side, rgba(0, 0, 0, 0.14), rgba(0, 0, 0, 0.07) 55%, transparent);
}
}
+24
View File
@@ -18,6 +18,10 @@ msgstr ""
msgid "Access only at certain hours of the day."
msgstr ""
#: web/src/portal/demo/way-pick.ts
msgid "Auto"
msgstr ""
#: web/src/portal/demo/crumbs.ts
msgid "Dawnline on GitHub"
msgstr ""
@@ -50,10 +54,18 @@ msgstr ""
msgid "How the page looks in each case. Nothing here connects."
msgstr ""
#: web/src/portal/demo/way-pick.ts
msgid "No data"
msgstr ""
#: web/src/portal/demo/data.ts
msgid "No free slots"
msgstr ""
#: web/src/portal/demo/way-pick.ts
msgid "Online"
msgstr ""
#: web/src/portal/demo/data.ts
msgid "Opened over plain HTTP"
msgstr ""
@@ -78,6 +90,10 @@ msgstr ""
msgid "Plain WireGuard"
msgstr ""
#: web/src/portal/demo/way-pick.ts
msgid "Set-up state"
msgstr ""
#: web/src/portal/demo/data.ts
msgid "Settings changed"
msgstr ""
@@ -122,6 +138,14 @@ msgstr ""
msgid "Try a scenario"
msgstr ""
#: web/src/portal/demo/way-pick.ts
msgid "Trying"
msgstr ""
#: web/src/portal/demo/way-pick.ts
msgid "Waiting"
msgstr ""
#: web/src/portal/demo/data.ts
msgid "Your page"
msgstr ""
+24
View File
@@ -20,6 +20,10 @@ msgstr "Доступ закончился"
msgid "Access only at certain hours of the day."
msgstr "Доступ только в определённые часы."
#: web/src/portal/demo/way-pick.ts
msgid "Auto"
msgstr "Авто"
#: web/src/portal/demo/crumbs.ts
msgid "Dawnline on GitHub"
msgstr "Dawnline на GitHub"
@@ -52,10 +56,18 @@ msgstr "Первый визит"
msgid "How the page looks in each case. Nothing here connects."
msgstr "Как выглядит страница в каждом случае. Ничего не подключается по-настоящему."
#: web/src/portal/demo/way-pick.ts
msgid "No data"
msgstr "Нет данных"
#: web/src/portal/demo/data.ts
msgid "No free slots"
msgstr "Нет свободных мест"
#: web/src/portal/demo/way-pick.ts
msgid "Online"
msgstr "В сети"
#: web/src/portal/demo/data.ts
msgid "Opened over plain HTTP"
msgstr "Открыто по обычному HTTP"
@@ -80,6 +92,10 @@ msgstr "Доступ на паузе"
msgid "Plain WireGuard"
msgstr "Обычный WireGuard"
#: web/src/portal/demo/way-pick.ts
msgid "Set-up state"
msgstr "Состояние настройки"
#: web/src/portal/demo/data.ts
msgid "Settings changed"
msgstr "Настройки изменились"
@@ -124,6 +140,14 @@ msgstr "Три устройства: одно в сети, одно ждёт н
msgid "Try a scenario"
msgstr "Выберите сценарий"
#: web/src/portal/demo/way-pick.ts
msgid "Trying"
msgstr "Попытки"
#: web/src/portal/demo/way-pick.ts
msgid "Waiting"
msgstr "Ожидание"
#: web/src/portal/demo/data.ts
msgid "Your page"
msgstr "Ваша страница"
+3 -1
View File
@@ -1,7 +1,7 @@
// The portal demo (npm run build:demo → dist/demo, a static site): the real
// portal over a router that lives in the page (serve.ts, router.ts, data.ts),
// with a scenario picker and a GitHub link in the breadcrumb (crumbs.ts,
// picker.ts). The order of the imports is the boot order: the router owns
// picker.ts) and a set-up state switch in the set-up sheet (way-pick.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.
@@ -11,10 +11,12 @@ import { router } from './serve';
import '../main';
import { toast } from '../ui/feedback';
import { mountCrumbs } from './crumbs';
import { mountWayPick } from './way-pick';
// The demo's own words (the scenarios, its chip and toasts), beside the portal's.
addCatalog('ru', ru);
mountCrumbs(router);
mountWayPick(router);
// An AmneziaVPN key would add a server that connects nowhere to the visitor's app: the demo keeps it on the page.
document.addEventListener(
+9 -4
View File
@@ -7,7 +7,7 @@
import { h, ic } from '../dom';
import { call } from '../api';
import { repaint, setState, type State } from '../state';
import { closeSheet, head, openSheet, sub, type View } from '../ui/sheet';
import { closeSheet, head, onSheetEntry, 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';
@@ -34,11 +34,16 @@ export function scenarioChip(router: DemoRouter): HTMLElement {
/** Swap the page in place: it dims away and comes back drawn from the scenario, the link saying which. */
async function pick(s: ScenarioId, done?: string) {
// The link goes on the page's own history entry, once the sheet's is stepped back off: a reload keeps the scenario.
const mark = () => {
const u = new URL(location.href);
u.searchParams.set('s', s);
history.replaceState(history.state, '', u);
};
if (onSheetEntry()) addEventListener('popstate', mark, { once: true });
else mark();
closeSheet();
router.use(s);
const u = new URL(location.href);
u.searchParams.set('s', s);
history.replaceState(history.state, '', u);
const out = play(app, [{ opacity: 1 }, { opacity: 0, filter: 'blur(4px)' }], { duration: 160, easing: EASE_OUT, fill: 'forwards' });
const st = await call<State>('state');
await out.finished;
+45 -3
View File
@@ -6,7 +6,18 @@
// itself is data.ts; serve.ts puts this router behind the page's fetch.
import type { AwgConfig, Kind } from '../../shared/types';
import { ENDPOINT, deviceLimit, isScenario, pageState, seedDevices, type DemoDevice, type ScenarioId } from './data';
import { DEVICE_NAME_MAX, validDeviceName } from '../../shared/format';
import {
ENDPOINT,
deviceLimit,
isScenario,
pageState,
seedDevices,
type DemoDevice,
type DemoWay,
type ScenarioId,
handshakeOf,
} from './data';
/** What the router remembers for this visitor. */
export interface DemoDb {
@@ -59,7 +70,6 @@ function valid(v: unknown): DemoDb | null {
}
const KINDS: Kind[] = ['computer', 'phone', 'tablet', 'router', 'other'];
const NAME_MAX = 32;
export function createRouter(o: RouterOpts) {
const clock = o.clock ?? (() => Math.floor(Date.now() / 1000));
@@ -74,6 +84,8 @@ export function createRouter(o: RouterOpts) {
let db = kept && (!o.want || kept.scenario === o.want) ? kept : seed(isScenario(o.want) ? o.want : 'normal');
const state = () => pageState(db.scenario, db.devs, clock(), o.secureUrl());
/** The device whose settings went out last: the one the set-up sheet is open for. */
let issued = '';
function needOpen() {
if (db.scenario === 'paused') refuse(403, 'Your access is paused.');
@@ -88,7 +100,7 @@ export function createRouter(o: RouterOpts) {
function checkName(v: unknown, self?: DemoDevice): string {
const name = String(v ?? '').trim();
if (!name) refuse(400, 'Give the device a name.');
if (name.length > NAME_MAX) refuse(400, `A name is at most ${NAME_MAX} characters.`);
if (!validDeviceName(name)) refuse(400, `Enter a device name: up to ${DEVICE_NAME_MAX} letters, digits, spaces and - _ .`);
if (db.devs.some((d) => d !== self && d.name.toLowerCase() === name.toLowerCase()))
refuse(409, 'You already have a device with this name.');
return name;
@@ -148,6 +160,7 @@ export function createRouter(o: RouterOpts) {
stale: false,
};
db.devs.push(d);
issued = d.id;
return { id: d.id, config: config(d), state: state() };
}
@@ -158,6 +171,7 @@ export function createRouter(o: RouterOpts) {
needHttps();
d.stale = false;
if (!d.hs && !d.connectAt) d.connectAt = soon();
issued = d.id;
return config(d);
}
@@ -172,6 +186,7 @@ export function createRouter(o: RouterOpts) {
d.hs = 0;
d.stale = false;
d.connectAt = soon();
issued = d.id;
extra = { config: config(d) };
} else if (b.action === 'delete') db.devs = db.devs.filter((x) => x !== d);
else refuse(400, 'Unknown action.');
@@ -200,6 +215,33 @@ export function createRouter(o: RouterOpts) {
return {
answer,
scenario: () => db.scenario,
/** The device being set up (its settings went out last), if it is still there. */
settingUp: () => (db.devs.some((d) => d.id === issued) ? issued : null),
/** The set-up state `id` is held in, 'auto' when none. */
wayOf: (id: string): DemoWay | 'auto' => db.devs.find((d) => d.id === id)?.way ?? 'auto',
/**
* Hold `id` in a set-up state, or let it go: 'connected' is a handshake now with data after it, 'auto' the
* demo's own timing (it connects a few seconds on, unless it already has).
*/
holdWay(id: string, w: DemoWay | 'connected' | 'auto') {
const d = db.devs.find((x) => x.id === id);
if (!d) return;
const t = clock();
delete d.way;
delete d.wayAt;
if (w === 'connected') {
d.hs = t;
d.connectAt = 0;
} else if (w === 'auto') {
if (!handshakeOf(d, t)) d.connectAt = soon();
} else {
d.way = w;
d.wayAt = t;
d.hs = 0;
d.connectAt = 0;
}
o.keep.save(db);
},
/** Start a scenario over: its own devices, nothing added. */
use(s: ScenarioId) {
db = seed(s);
+200
View File
@@ -0,0 +1,200 @@
// The demo's set-up state switch: a pill beside the set-up sheet's ×, so a visitor can see each state the way
// shows (waiting, knocks that never finish, no data, connected) without a device. Its popup is a row of segments
// in one pill frame, above the pill with a tail pointing at it and a dark halo behind. Only on the set-up view:
// another view in the same sheet (a question, a device's page) fades it out. Picking holds the device in that
// state on the demo's router and polls at once; Auto is the demo's own timing.
import { h, ic } from '../dom';
import { EASE_IN, EASE_OUT, POP, play } from '../motion';
import { morphText, setText } from '../ui/morph';
import { pollNow } from '../flows/wait';
import type { DemoWay } from './data';
import type { DemoRouter } from './router';
type Pick = DemoWay | 'connected' | 'auto';
type Tone = 'neutral' | 'warn' | 'ok';
const PICKS: [Pick, () => string, Tone][] = [
['auto', () => _('Auto'), 'neutral'],
['waiting', () => _('Waiting'), 'neutral'],
['trying', () => _('Trying'), 'warn'],
['nodata', () => _('No data'), 'warn'],
['connected', () => _('Online'), 'ok'],
];
const pick = (p: Pick) => PICKS.find((x) => x[0] === p)!;
/** The gap between the pill and the popup above it, and how far the halo reaches out (up, sideways, down). */
const GAP = 18;
const HALO = { x: 64, up: 48, down: 14 };
/** Gone from where it stands, so one leaving while it still comes in turns back from there. */
function leave(el: Element, frames: Keyframe, ms: number) {
const s = getComputedStyle(el);
el.getAnimations().forEach((a) => a.cancel());
const a = play(
el,
[
{ opacity: s.opacity, transform: s.transform, filter: s.filter },
{ opacity: 0, ...frames },
],
{
duration: ms,
easing: EASE_IN,
fill: 'forwards',
},
);
a.onfinish = () => el.remove();
}
export function mountWayPick(router: DemoRouter) {
/** What each device's pill says: what was picked here, else what the router holds it in. */
const shown = new Map<string, Pick>();
let pop: HTMLElement | null = null;
let halo: HTMLElement | null = null;
let anchor: HTMLElement | null = null;
function closePop() {
if (!pop) return;
leave(pop, { transform: 'scale(.96)', filter: 'blur(3px)' }, 120);
if (halo) leave(halo, {}, 160);
anchor?.setAttribute('aria-expanded', 'false');
pop = halo = anchor = null;
}
function openPop(pill: HTMLElement, id: string, paint: () => void) {
const now = shown.get(id) ?? router.wayOf(id);
const m = h(
'div',
{ class: 'dm-way-pop', role: 'menu' },
...PICKS.map(([p, label, tone]) =>
h(
'button',
{
type: 'button',
role: 'menuitemradio',
'aria-checked': String(p === now),
onclick: () => {
closePop();
shown.set(id, p);
router.holdWay(id, p);
paint();
pollNow();
},
},
h('span', { class: `dot ${tone}` }),
label(),
),
),
);
document.body.append(m);
// Centred over the pill, inside the sheet where it fits (else the screen), the tail on the pill's middle.
const r = pill.getBoundingClientRect();
const box = pill.closest('.sheet')?.getBoundingClientRect() ?? { left: 0, right: innerWidth };
const w = m.offsetWidth;
const mid = r.left + r.width / 2;
const lo = Math.max(12, box.left + 10);
const hi = Math.min(innerWidth - 12, box.right - 10);
const left = Math.max(lo, Math.min(mid - w / 2, hi - w));
const top = r.top - GAP - m.offsetHeight;
Object.assign(m.style, { left: `${left}px`, top: `${top}px`, transformOrigin: `${mid - left}px bottom` });
m.style.setProperty('--tail', `${mid - left}px`);
// The halo reaches up and out but stops short of the pill, which stays sharp.
const sc = h('div', { class: 'dm-way-halo' });
Object.assign(sc.style, {
left: `${left - HALO.x}px`,
top: `${top - HALO.up}px`,
width: `${w + HALO.x * 2}px`,
height: `${m.offsetHeight + HALO.up + HALO.down}px`,
});
m.before(sc);
play(sc, [{ opacity: 0 }, { opacity: 1 }], { duration: 220, easing: EASE_OUT });
play(
m,
[
{ opacity: 0, transform: 'scale(.9)', filter: 'blur(4px)' },
{ opacity: 1, transform: 'none', filter: 'none' },
],
{ duration: POP.duration, easing: POP.easing },
);
pop = m;
halo = sc;
anchor = pill;
pill.setAttribute('aria-expanded', 'true');
}
function makePill(id: string): HTMLElement {
const dot = h('span', { class: 'dot' });
const lbl = h('span', {});
const pill = h(
'button',
{ type: 'button', class: 'dm-way', 'aria-haspopup': 'menu', 'aria-expanded': 'false', 'aria-label': _('Set-up state') },
dot,
lbl,
ic('chevron', 'i'),
);
const paint = (morph = true) => {
const [, label, tone] = pick(shown.get(id) ?? router.wayOf(id));
dot.className = `dot ${tone}`;
if (morph) morphText(lbl, label());
else setText(lbl, label());
};
paint(false);
pill.addEventListener('click', () => (anchor === pill ? closePop() : (closePop(), openPop(pill, id, () => paint()))));
return pill;
}
function place() {
if (anchor && !anchor.isConnected) closePop();
const sheet = document.querySelector<HTMLElement>('.sheet-root.open .sheet');
const id = router.settingUp();
const setup = !!sheet && !!id && !!sheet.querySelector('.way') && !sheet.classList.contains('asks');
document.querySelectorAll<HTMLElement>('.dm-way:not(.gone)').forEach((el) => {
if (setup && el.parentElement === sheet && el.dataset.id === id) return;
el.classList.add('gone');
el.parentElement?.querySelectorAll<HTMLElement>('.vhead').forEach((hd) => (hd.style.paddingRight = ''));
if (anchor === el) closePop();
leave(el, { transform: 'scale(.9)', filter: 'blur(3px)' }, 160);
});
if (!sheet || !setup || !id) return;
let pill = sheet.querySelector<HTMLElement>('.dm-way:not(.gone)');
if (!pill) {
pill = makePill(id);
pill.dataset.id = id;
sheet.append(pill);
}
// Left of × and of the view's own buttons, whatever they are; into their place once the sheet hides them
// (the device arrived), gliding there as they fade.
const acts = sheet.querySelector<HTMLElement>('.sheet-acts');
const arrived = sheet.classList.contains('arrived');
const right = (arrived ? 22 : 58) + (!arrived && acts?.offsetWidth ? acts.offsetWidth + 6 : 0);
if (pill.style.right !== `${right}px`) pill.style.right = `${right}px`;
// The title keeps clear of the pill as it does of ×: a long device name ends in an ellipsis before it. Worked
// out from where the pill goes, not where it is gliding through.
const sr = sheet.getBoundingClientRect();
const scale = sr.width / sheet.offsetWidth || 1;
for (const head of sheet.querySelectorAll<HTMLElement>('.vhead')) {
const inset = (sr.right - head.getBoundingClientRect().right) / scale;
const pad = `${Math.max(0, right + pill.offsetWidth + 8 - inset)}px`;
if (head.style.paddingRight !== pad) head.style.paddingRight = pad;
}
}
new MutationObserver(place).observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['class'] });
document.addEventListener('pointerdown', (e) => {
const t = e.target as Element;
if (pop && !pop.contains(t) && !anchor?.contains(t)) closePop();
});
// Escape takes the popup only, not the sheet under it.
document.addEventListener(
'keydown',
(e) => {
if (!pop || e.key !== 'Escape') return;
e.stopPropagation();
closePop();
},
true,
);
// A wheel or a swipe closes it; the sheet's own scroll as it settles does not.
for (const ev of ['wheel', 'touchmove'])
addEventListener(ev, (e) => pop && !pop.contains(e.target as Node) && closePop(), { passive: true, capture: true });
}
+129 -44
View File
@@ -1,21 +1,27 @@
// Adding a device: what it is (four kinds; phones and tablets are one choice,
// the same apps and the same smaller packets) and its name, guessed from the
// browser when it is this device; then straight on to its set-up. Or the page
// opens on the device itself, from a code, ready to add it there.
// the same apps and the same smaller packets), whether the local network it is
// on stays reachable while connected (LAN Bypass, off unless they turn it on;
// it stays as chosen: the admin's drawer shows it, neither page changes it)
// and its name, guessed from the browser when it is this device; then straight
// on to its set-up. Or the page opens on the device itself, from a code, ready
// to add it there.
import type { ClientConfig, Kind } from '../../shared/types';
import { kindLabel } from '../../shared/format';
import { defaultName, fitName, kindLabel, netsLabel } from '../../shared/format';
import { guardDeviceName } from '../../shared/name-guard';
import { shake } from '../../shared/shake';
import { fmt, num, plural } from '../../shared/i18n';
import { ApiError, call } from '../api';
import { h, ic } from '../dom';
import { EASE_OUT, play } from '../motion';
import { SMOOTH, play } from '../motion';
import { addLink } from '../setup';
import { pageUrl, repaint, setState, state, type State } from '../state';
import { smoothCaret } from '../ui/caret';
import { linkRow, qrBox } from '../ui/codes';
import { once, toast } from '../ui/feedback';
import { badLine } from '../ui/bad-line';
import { glass } from '../ui/glass';
import { morphText } from '../ui/morph';
import { go, head, hint, openSheet, sub, type View } from '../ui/sheet';
import { go, head, openSheet, sub, type View } from '../ui/sheet';
import { secureFirst, showSecure } from './secure';
import { continueSetup } from './setup-view';
@@ -68,7 +74,7 @@ function guessName(kind: Kind): string {
if (/Mac OS X/.test(UA)) return 'Mac';
if (/Windows/.test(UA)) return _('Windows PC');
if (/Linux/.test(UA)) return _('Linux PC');
return kindLabel(kind);
return defaultName(kind);
}
/*
@@ -81,6 +87,44 @@ const pickLabel = (p: Pick): string => (p === 'mobile' ? _('Mobile') : kindLabel
const pickOf = (k: Kind): Pick => (k === 'phone' || k === 'tablet' ? 'mobile' : k);
const kindOf = (p: Pick): Kind => (p !== 'mobile' ? p : guessKind() === 'tablet' ? 'tablet' : 'phone');
/**
* What they chose so far, kept outside the view: Back from "Open on the device"
* builds the view again, and it comes back as they left it. `name`: what they
* typed (unset while the name is still the guess).
*/
interface Draft {
pick?: Pick;
bypass: boolean;
name?: string;
}
/**
* A line in a block opens or folds away: height, opacity and blur on SMOOTH, as the set-up steps fold, from
* where it is on screen (flicking the switch never snaps). The block's 1 px gap goes with it.
*/
function foldLine(el: HTMLElement, open: boolean) {
const cs = getComputedStyle(el);
const from = el.hidden
? { h: 0, o: 0, b: 4, m: -1 }
: {
h: el.getBoundingClientRect().height,
o: +cs.opacity,
b: +(cs.filter.match(/blur\(([\d.]+)px\)/)?.[1] ?? 0),
m: parseFloat(cs.marginTop) || 0,
};
el.getAnimations().forEach((a) => a.cancel());
el.hidden = false;
el.style.overflow = 'hidden';
const to = open ? { h: el.scrollHeight, o: 1, b: 0, m: 0 } : { h: 0, o: 0, b: 4, m: -1 };
const frame = (v: typeof from) => ({ height: `${v.h}px`, opacity: v.o, filter: v.b ? `blur(${v.b}px)` : 'none', marginTop: `${v.m}px` });
const a = play(el, [frame(from), frame(to)], { duration: SMOOTH.duration, easing: SMOOTH.easing, fill: 'forwards' });
a.onfinish = () => {
el.hidden = !open;
el.style.overflow = '';
a.cancel();
};
}
export function startAdd() {
const st = state();
if (!st || st.locked) return;
@@ -90,22 +134,24 @@ export function startAdd() {
true,
);
if (secureFirst()) return;
openSheet(vAdd);
const draft: Draft = { bypass: false };
openSheet(() => vAdd(draft));
}
function vAdd(): View {
function vAdd(draft: Draft): View {
const st = state()!;
const p = st.person;
// The kinds this router takes, as the four choices.
const picks = (['computer', 'mobile', 'router', 'other'] as Pick[]).filter((k) => st.kinds.some((x) => pickOf(x) === k));
let pick: Pick = picks.includes(pickOf(guessKind())) ? pickOf(guessKind()) : picks[0];
let edited = false;
const guess = picks.includes(pickOf(guessKind())) ? pickOf(guessKind()) : picks[0];
let pick: Pick = draft.pick && picks.includes(draft.pick) ? draft.pick : guess;
const taken = new Set(p.devices.map((d) => d.name.toLowerCase()));
const suggest = (k: Pick) => {
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 n = k === pickOf(guessKind()) ? guessName(kindOf(k)) : defaultName(k === 'mobile' ? 'phone' : k);
// Stripped of what the router refuses and cut to its limit, the number after it too ("Galaxy S24+ 2").
if (!taken.has(fitName(n).toLowerCase())) return fitName(n);
for (let i = 2; i < 20; i++) if (!taken.has(fitName(n, ` ${i}`).toLowerCase())) return fitName(n, ` ${i}`);
return fitName(n);
};
const kinds = h('div', { class: 'kinds', role: 'radiogroup', 'aria-label': _('What is it?') });
@@ -120,48 +166,78 @@ function vAdd(): View {
kinds.appendChild(t);
return t;
});
// With home access, the home networks still go into the tunnel: a local network on the same addresses is out
// of reach, and the row says so while LAN Bypass is on.
const home = st.server.home ?? [];
const except = home.length
? h(
'span',
{ class: 'sw-sub sw-note', hidden: !draft.bypass },
fmt(_('Except %s: those addresses lead to the home network.'), netsLabel(home)),
)
: null;
// The whole row is the switch. Built as they left it, before it is on the page: nothing slides.
const lan = h(
'button',
{
type: 'button',
class: draft.bypass ? 'swrow on' : 'swrow',
role: 'switch',
'aria-checked': String(draft.bypass),
onclick: () => {
draft.bypass = !draft.bypass;
lan.classList.toggle('on', draft.bypass);
lan.setAttribute('aria-checked', String(draft.bypass));
if (except) foldLine(except, draft.bypass);
},
},
glass('lan', 'blue'),
h(
'span',
{ class: 'sw-t' },
h('b', {}, _('LAN Bypass')),
h('span', { class: 'sw-sub' }, _('Your local network stays reachable while connected.')),
except,
),
h('span', { class: 'sw', 'aria-hidden': 'true' }),
);
const input = h('input', {
type: 'text',
maxlength: 48,
required: true,
// Not `required`: the browser's own check would stop an empty submit before the field can shake.
'aria-label': _('Name'),
autocomplete: 'off',
// Not a login: no password manager offering itself here.
'data-1p-ignore': true,
}) 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.
if (!err.hidden) return morphText(err, msg);
err.textContent = msg;
err.hidden = false;
play(
err,
[
{ opacity: 0, transform: 'translateY(-4px)' },
{ opacity: 1, transform: 'none' },
],
{ duration: 220, easing: EASE_OUT },
);
};
input.value = suggest(pick);
// The red line under the field: why a name is refused (the router's word, or the field's own as it is typed).
const { el: err, say, unsay } = badLine();
// What the router won't take never gets in: the field shakes instead (shared/name-guard.ts).
guardDeviceName(
input,
() => form,
(w) => (w ? say(w) : unsay()),
);
input.value = draft.name ?? suggest(pick);
goBtn.classList.toggle('ready', !!input.value.trim());
input.addEventListener('input', () => {
edited = true;
draft.name = input.value;
goBtn.classList.toggle('ready', !!input.value.trim());
err.hidden = true;
unsay();
});
// The Android model arrives a moment later: use it unless they started typing.
void modelReady.then(() => {
if (!edited && pick === pickOf(guessKind())) input.value = suggest(pick);
if (draft.name === undefined && pick === pickOf(guessKind())) input.value = suggest(pick);
});
// The picked tile rings itself where it stands (the ring does not travel between tiles).
function choose(k: Pick) {
pick = k;
pick = draft.pick = k;
tiles.forEach((t, i) => {
const on = picks[i] === k;
t.classList.toggle('on', on);
t.setAttribute('aria-checked', String(on));
});
if (!edited) {
if (draft.name === undefined) {
input.value = suggest(k);
goBtn.classList.add('ready');
}
@@ -169,20 +245,30 @@ function vAdd(): View {
choose(pick);
const form = h('form', { class: 'field', autocomplete: 'off' }, input, goBtn);
smoothCaret(form);
form.addEventListener('submit', (e) => {
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.'));
// Nothing to name it: the field shakes (only now, not as it empties).
if (!name) return shake(form);
if (taken.has(name.toLowerCase())) {
shake(form);
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) });
const r = await call<{ id: string; config: ClientConfig; state: State }>('devices', {
name,
kind: kindOf(pick),
lan_bypass: draft.bypass,
});
setState(r.state);
repaint({ pop: r.id });
const dev = r.state.person.devices.find((d) => d.id === r.id)!;
await continueSetup(dev, r.config);
} catch (er) {
if (er instanceof ApiError && er.httpsUrl) return showSecure(er.httpsUrl);
shake(form);
say((er as Error).message);
}
});
@@ -200,13 +286,12 @@ function vAdd(): View {
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.')),
lan,
form,
err,
h('div', { class: 'or' }, _('OR')),
viaLink,
);
el.querySelector('.hint')!.classList.add('kinds-note');
return { el, label: _('Add a device') };
}
+6 -36
View File
@@ -1,16 +1,17 @@
// A device's own actions from its ⋯ menu: Rename, Reconnect (new keys, then
// the set-up of the new ones) and Remove. A question comes before what cannot
// be undone; the action's button stays busy until the router answers.
// A device's own actions from its ⋯ menu: Reconnect (new keys, then the set-up
// of the new ones) and Remove (Rename edits the name on the card: rename.ts). A
// question comes before what cannot 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 { h } from '../dom';
import { EASE_IN, play } from '../motion';
import { repaint, setState, state, type State } from '../state';
import { once, toast } from '../ui/feedback';
import { glass, type Tone } from '../ui/glass';
import { closeSheet, head, onClosed, openSheet, type View } from '../ui/sheet';
import { closeSheet, onClosed, openSheet, type View } from '../ui/sheet';
import { secureFirst } from './secure';
import { continueSetup } from './setup-view';
@@ -37,37 +38,6 @@ function ask(o: { icon: string; tone: Tone; title: string; text: string; action:
return { el, label: o.title, asks: true };
}
export function rename(d: Device) {
openSheet(() => {
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;
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) => {
e.preventDefault();
const name = input.value.trim();
if (!name || name === d.name) return;
void once(save, async () => {
try {
const r = await call<{ state: State }>(`devices/${d.id}`, { action: 'rename', name });
setState(r.state);
onClosed(() => {
repaint();
toast(_('Renamed'));
});
closeSheet();
} catch (er) {
toast((er as Error).message, true);
}
});
});
setTimeout(() => input.select(), 60);
const title = fmt(_('Rename %s'), d.name);
return { el: h('div', { class: 'view' }, head(title), form), label: title };
});
}
/**
* Set a device up from scratch (a new phone, the app reinstalled, settings the
* admin changed): new keys, so what it holds stops working; it shows "Not set
+172
View File
@@ -0,0 +1,172 @@
// Renaming a device where its name stands on the card: a click on the name (or Rename in its ⋯ menu) turns it
// into its own input, in the name's font and place, with nothing around it but the field's caret and selection
// (ui/caret.ts), the name selected. The status line under it says how to finish. Return saves: the words shimmer
// while the router answers (ui/shimmer.ts), settle, and the card is drawn again with the new name, its status
// morphing back from the hint. Esc or a click away puts the name it had back, whatever was typed. What the router
// won't take never gets in (shared/name-guard.ts): the words shake and the status line says why in red; the
// router's own refusals (a name taken) say so the same way.
import type { Device } from '../../shared/types';
import { guardDeviceName } from '../../shared/name-guard';
import { shake } from '../../shared/shake';
import { call } from '../api';
import { h } from '../dom';
import { repaint, setState, state, type State } from '../state';
import { smoothCaret } from '../ui/caret';
import { morphText } from '../ui/morph';
import { shimmer } from '../ui/shimmer';
/** The status line's colours (page/devices.ts), and the red of a refusal. */
const TONES = ['ok-t', 'warn-t', 'here-t', 'bad-t'];
/**
* The status line says something else in another tone: its words morph and the colour turns from the one it
* had, as a repaint's status does. Only the tone classes change hands: a morph under way keeps its own.
*/
function say(stat: HTMLElement, text: string, tone: string, title = text) {
const color = getComputedStyle(stat).color;
for (const t of TONES) stat.classList.toggle(t, t === tone);
// The line is one line: a long reason (the router's own) reads in full on hover.
stat.title = title;
morphText(stat, text, undefined, { color });
}
/**
* Focus given back to the name without its ring: the browser would draw it (the last thing done was typing), but
* nobody moved there. The ring is the name's again once focus leaves it, for a Tab that does.
*/
function quietFocus(el: HTMLElement | null) {
if (!el) return;
el.classList.add('quiet');
el.addEventListener('blur', () => el.classList.remove('quiet'), { once: true });
el.focus({ preventScroll: true });
}
let editing: { id: string; cancel: () => void } | null = null;
/** A name is being edited on its card: the page is not drawn again under it. */
export const renaming = (): boolean => !!editing;
/** Edit `d`'s name on its card (`card`: its `.dev`). Another one being edited lets go first. */
export function renameOnCard(d: Device, card: HTMLElement) {
if (editing?.id === d.id) return;
editing?.cancel();
const name = card.querySelector<HTMLElement>('.dev-name');
const stat = card.querySelector<HTMLElement>('.dev-stat');
if (!name || !stat) return;
const was = { text: stat.textContent ?? '', tone: TONES.find((t) => stat.classList.contains(t)) ?? '', title: stat.title };
// How to finish, where a keyboard says it; on a touch screen its Done key saves.
const hint = matchMedia('(pointer: fine)').matches ? _('Return to save, Esc to cancel') : '';
const input = h('input', {
type: 'text',
'aria-label': _('Device name'),
autocomplete: 'off',
spellcheck: 'false',
enterkeyhint: 'done',
'data-1p-ignore': true,
}) as HTMLInputElement;
input.value = d.name;
const form = h('form', { class: 'field inline', autocomplete: 'off' }, input);
guardDeviceName(input, form, (why) => why && say(stat, why, 'bad-t'), { ring: false });
// Typing again after a refusal: the hint is back.
input.addEventListener('input', () => {
if (stat.classList.contains('bad-t')) say(stat, hint || was.text, hint ? '' : was.tone, hint ? hint : was.title);
});
// Where the name stands, in its font, with nothing around it: swapping them shows nothing but the caret.
name.after(form);
name.hidden = true;
if (hint) say(stat, hint, '');
smoothCaret(form);
// Focused in the same turn as the click or the menu's item: iOS only raises its keyboard for a focus made
// inside the tap. The whole name selected at once, and again a frame on: iOS may drop a selection made as the
// input takes focus (select() it ignores there).
input.focus();
const all = () => input.setSelectionRange(0, input.value.length);
all();
requestAnimationFrame(() => document.activeElement === input && input.selectionStart === input.selectionEnd && all());
let saving = false;
/**
* `saved`: the new name, null to let go. `back`: focus goes back to the name (Return and Esc, from a keyboard
* or the screen's Done key: a screen reader, the next Tab, carry on from it); a click or tap away leaves it
* where it went.
*/
const finish = (saved: string | null, back: boolean) => {
if (editing?.id === d.id) editing = null;
document.removeEventListener('pointerdown', away, true);
input.removeEventListener('blur', left);
if (saved) name.textContent = saved;
name.hidden = false;
form.remove();
// Saved: the hint stays for the repaint, which morphs it into the status (words and colour) as it does any
// status that changed. Let go: it turns back here.
if (!saved) say(stat, was.text, was.tone, was.title);
if (!back) return;
// After a save the card is drawn again: the name is found anew then.
if (saved)
requestAnimationFrame(() => quietFocus(document.querySelector<HTMLElement>(`.dev-name[data-t="${CSS.escape(`${d.id}:name`)}"]`)));
else quietFocus(name);
};
const refuse = (msg: string) => {
say(stat, msg, 'bad-t');
shake(form, { ring: false });
input.focus();
};
const save = async () => {
const next = input.value.trim();
if (saving) return;
// Empty: said before asking the router. The same name: nothing to save.
if (!next) return refuse(_('Give the device a name.'));
if (next === d.name) return finish(null, true);
// Another of theirs has it: said here, shorter than the router would.
const mine = state()?.person.devices ?? [];
if (mine.some((x) => x.id !== d.id && x.name.toLowerCase() === next.toLowerCase())) return refuse(_('That name is taken.'));
saving = true;
input.readOnly = true;
const stop = shimmer(form, input);
try {
const r = await call<{ state: State }>(`devices/${d.id}`, { action: 'rename', name: next });
setState(r.state);
// The words settle to solid before the field gives way to the name: nothing changes as it does.
await stop();
finish(next, true);
repaint();
} catch (e) {
await stop();
input.readOnly = false;
refuse((e as Error).message);
} finally {
saving = false;
}
};
form.addEventListener('submit', (e) => {
e.preventDefault();
void save();
});
input.addEventListener('keydown', (e) => {
if (e.key !== 'Escape' || saving) return;
e.preventDefault();
e.stopPropagation();
finish(null, true);
});
// A click away lets it go; while saving, the router's answer settles it.
const away = (e: Event) => {
if (saving || form.contains(e.target as Node)) return;
finish(null, false);
};
// Focus gone elsewhere in the page (Tab, iPad's hide-keyboard key) lets it go too. Gone from the window (another
// app, another tab) it stays: coming back, they carry on.
const left = () =>
setTimeout(() => {
if (editing?.id !== d.id || saving || !document.hasFocus() || form.contains(document.activeElement)) return;
finish(null, false);
});
input.addEventListener('blur', left);
document.addEventListener('pointerdown', away, true);
editing = { id: d.id, cancel: () => finish(null, false) };
}
+87 -34
View File
@@ -7,7 +7,7 @@
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 { EASE_IN, EASE_OUT, POP, SMOOTH, play } from '../motion';
import {
APP_NAME,
importPath,
@@ -24,7 +24,7 @@ import {
type Store,
} from '../setup';
import { accordion } from '../ui/accordion';
import { copy, download, sendFile, shareFile, swapIcon } from '../ui/feedback';
import { copy, download, sendFile, shareFile } from '../ui/feedback';
import { glass } from '../ui/glass';
import { menuLine, morphText, setText } from '../ui/morph';
import { hint } from '../ui/sheet';
@@ -200,25 +200,68 @@ export function sendKids(c: SetupCtx): Kid[] {
];
}
/** One configuration line, highlighted; private and preshared keys masked unless shown. */
function confLine(line: string, reveal: boolean): Node {
/** At rest out of sight: it keeps its place, with nothing to see, select or read out. */
function rest(el: HTMLElement | SVGElement) {
el.style.opacity = '0';
el.style.visibility = 'hidden';
}
/**
* Both looks in one place (a key and its mask, two icons): the one showing and
* the other at rest under it, so a press cross-fades them and nothing is
* rebuilt. The cell is as wide as the wider of the two.
*/
function stack(shown: HTMLElement | SVGElement, other: HTMLElement | SVGElement): HTMLElement {
const cell = h('span', {}, shown, other);
cell.style.display = 'inline-grid';
for (const x of [shown, other]) x.style.gridArea = '1 / 1';
rest(other);
return cell;
}
/**
* Shown or not: it comes into focus out of a blur, or blurs away and rests out
* of sight, from where it stands now (pressed again half-way, it turns back).
*/
function turn(el: HTMLElement | SVGElement, on: boolean, off: Keyframe) {
const s = getComputedStyle(el);
const from = { opacity: s.opacity, filter: s.filter === 'none' ? 'blur(0px)' : s.filter, transform: s.transform };
const old = el.getAnimations();
el.style.opacity = on ? '' : '0';
el.style.visibility = '';
const a = on
? play(el, [from, { opacity: 1, filter: 'blur(0px)', transform: 'none' }], { duration: 320, easing: EASE_OUT })
: play(el, [from, off], { duration: 200, easing: EASE_IN });
if (!on) a.onfinish = () => (el.style.visibility = 'hidden');
old.forEach((x) => x.cancel());
}
/** A key masked, or a mask lifted: they blur through each other. */
const SECRET_OFF: Keyframe = { opacity: 0, filter: 'blur(4px)', transform: 'none' };
/** The button's icon (a key, or × to hide it again) turns the way a copy's check comes in (ui/feedback.ts). */
const ICON_OFF: Keyframe = { opacity: 0, filter: 'blur(3px)', transform: 'scale(.6)' };
/** One configuration line, highlighted; private and preshared keys masked until shown. */
function confLine(line: string): Node {
if (/^\s*\[.+\]\s*$/.test(line)) return h('span', { class: 'sec' }, line);
const m = /^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(line);
if (!m) return document.createTextNode(line);
const secret = /^(\s*)(PrivateKey|PresharedKey)\b/.test(line);
const value = !secret ? m[2] : reveal ? h('span', { class: 'secret' }, m[2]) : h('span', { class: 'mask' }, '••••••••••••••••');
const value = secret ? stack(h('span', { class: 'mask' }, '••••••••••••••••'), h('span', { class: 'secret' }, m[2])) : m[2];
return h('span', {}, h('span', { class: 'k' }, m[1]), ' ', value);
}
/** The .conf for a router: a file card to download (or share), and the configuration folded, its keys hidden. */
export function filePane(cfg: ClientConfig): HTMLElement {
let reveal = false;
const pre = h('pre', { class: 'conf' });
const paint = () =>
pre.replaceChildren(...cfg.conf.split('\n').flatMap((l, i) => (i ? ['\n', confLine(l, reveal)] : [confLine(l, reveal)])));
paint();
const pre = h(
'pre',
{ class: 'conf' },
cfg.conf.split('\n').flatMap((l, i) => (i ? ['\n', confLine(l)] : [confLine(l)])),
);
const share = !!shareFile(cfg.filename, cfg.conf);
let icon = ic('key');
const key = ic('key') as SVGElement;
const hide = ic('x') as SVGElement;
const label = h('span', {}, _('Show key'));
const eye = h(
'button',
@@ -227,23 +270,15 @@ export function filePane(cfg: ClientConfig): HTMLElement {
class: 'btn soft sm',
onclick: () => {
reveal = !reveal;
icon = swapIcon(icon, reveal ? 'x' : 'key');
morphText(label, 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, .secret').forEach((x) =>
play(
x,
[
{ filter: 'blur(4px)', opacity: 0.4 },
{ filter: 'none', opacity: 1 },
],
{ duration: 320, easing: EASE_OUT },
),
);
// A key shown comes into focus out of a blur as its mask blurs away; hidden again, the other way round.
pre.querySelectorAll<HTMLElement>('.secret').forEach((x) => turn(x, reveal, SECRET_OFF));
pre.querySelectorAll<HTMLElement>('.mask').forEach((x) => turn(x, !reveal, SECRET_OFF));
turn(key, !reveal, ICON_OFF);
turn(hide, reveal, ICON_OFF);
},
},
icon,
stack(key, hide),
label,
);
const cp = h(
@@ -303,7 +338,9 @@ export interface ConnPill {
* Beside ×: the connection itself, to download or copy, where the sheet offers
* neither (a phone or a tablet set up from elsewhere). One tooltip for both
* keys, under them: the first waits a beat; once one is up the next comes at
* once and the tooltip glides across. Copied: a check, and the tooltip says so.
* once and the tooltip glides across (by Tab too, and back to a key while it
* still fades out), each move from where it stands. Copied: a check, and the
* tooltip says so.
*/
export function connPill(get: () => { text: string; msg: string; file: string; app: string }): ConnPill {
const tt = h('span', { class: 'tt' });
@@ -324,11 +361,22 @@ export function connPill(get: () => { text: string; msg: string; file: string; a
return Math.min(b.offsetLeft + b.offsetWidth / 2, el.offsetWidth + 46 - w / 2);
};
const at = (x: number) => `translateX(${x}px) translateX(-50%)`;
/** Where the tooltip stands now: mid-fade and mid-glide included. */
const now = (): Keyframe => {
const s = getComputedStyle(tip);
return { opacity: s.opacity, filter: s.filter === 'none' ? 'blur(0px)' : s.filter, transform: s.transform };
};
/** Its next motion takes over from where the last one stands; the last one stops once it is in place. */
const move = (frames: Keyframe[], o: KeyframeAnimationOptions) => {
const old = tip.getAnimations();
play(tip, frames, o);
old.forEach((a) => a.cancel());
};
// To another key, or back while it fades out: it glides there and comes up whole on the way.
const glideTo = (x: number) => {
const from = getComputedStyle(tip).transform;
tip.getAnimations().forEach((a) => a.cancel());
const from = now();
tip.style.transform = at(x);
play(tip, [{ transform: from }, { transform: at(x) }], { duration: SMOOTH.duration, easing: SMOOTH.easing });
move([from, { opacity: 1, filter: 'blur(0px)', transform: at(x) }], { duration: SMOOTH.duration, easing: SMOOTH.easing });
};
// Another key's words, or "Copied": what the two share slides, the rest morphs; the pill glides with it.
const reword = (t: string) => morphText(tt, t);
@@ -336,20 +384,20 @@ export function connPill(get: () => { text: string; msg: string; file: string; a
clearTimeout(tipT);
if (tipFor === b && tip.classList.contains('on')) return;
tipFor = b;
if (tip.classList.contains('on')) {
if (tip.classList.contains('on') || +getComputedStyle(tip).opacity > 0) {
const t = words(b);
tip.classList.add('on');
glideTo(centre(b, t));
return reword(t);
}
// Out of sight: it comes up under the key out of a blur.
const up = () => {
const t = words(b);
setText(tt, t);
const x = centre(b, t);
tip.getAnimations().forEach((a) => a.cancel());
tip.style.transform = at(x);
tip.classList.add('on');
play(
tip,
move(
[
{ opacity: 0, transform: `${at(x)} translateY(-3px) scale(.96)`, filter: 'blur(3px)' },
{ opacity: 1, transform: at(x), filter: 'blur(0px)' },
@@ -368,8 +416,10 @@ export function connPill(get: () => { text: string; msg: string; file: string; a
tipFor = null;
if (!tip.classList.contains('on')) return;
warmUntil = performance.now() + 500;
// It fades where it stands, mid-glide or still coming up.
const from = now();
tip.classList.remove('on');
play(tip, [{ opacity: 1 }, { opacity: 0 }], { duration: 120, easing: 'ease-out' });
move([from, { ...from, opacity: 0 }], { duration: 120, easing: 'ease-out' });
};
for (const b of [dl, cp]) {
b.addEventListener('pointerenter', (e) => {
@@ -378,7 +428,10 @@ export function connPill(get: () => { text: string; msg: string; file: string; a
b.addEventListener('focus', () => {
if (b.matches(':focus-visible')) show(b);
});
b.addEventListener('blur', hide);
// Tab from one key to the other: the focus that follows glides the tooltip across instead.
b.addEventListener('blur', (e) => {
if (!el.contains(e.relatedTarget as Node | null)) hide();
});
}
el.addEventListener('pointerleave', hide);
+146 -61
View File
@@ -2,10 +2,12 @@
// on the device itself, two steps (get the app, add the connection) with a way
// round folded under the wait; a router, its packages and the file; a phone or
// a tablet set up from elsewhere, its link as a code or the connection as a
// code for an app it has; a computer set up from elsewhere, its link or the
// connection to send there. Which app and where it comes from follow the
// code for an app it has (the link again where the key is too long for one); a
// computer, or another device added from a phone, its link or the connection
// to send there. Which app and where it comes from follow the
// server's disguise and the platform (setup.ts). The wait for the first
// connection sits on top the whole time (wait.ts).
// connection sits on top the whole time (wait.ts); on the device itself and for
// a router the steps regroup under it as it goes (can't finish, no data).
import type { ClientConfig, Device } from '../../shared/types';
import { fmt } from '../../shared/i18n';
@@ -15,7 +17,7 @@ import { h, put } from '../dom';
import { SMOOTH, play } from '../motion';
import { APP_NAME, appsFor, deviceNoun, inWebview, keyFileName, sameDevice, setupLink, type AppId } from '../setup';
import { pageUrl, platform, preset, repaint } from '../state';
import { accordion } from '../ui/accordion';
import { accordion, regrow, type Accordion } from '../ui/accordion';
import { codeRow, linkRow, type CodeRow } from '../ui/codes';
import { once, toast } from '../ui/feedback';
import { glass } from '../ui/glass';
@@ -37,7 +39,8 @@ import {
storeBlock,
type SetupCtx,
} from './setup-parts';
import { arrive, waitWay, watchFirstConnection } from './wait';
import type { WayState } from '../way';
import { follow, waitWay, watchFirstConnection } from './wait';
async function getConfig(d: Device): Promise<ClientConfig | null> {
try {
@@ -49,14 +52,17 @@ async function getConfig(d: Device): Promise<ClientConfig | null> {
}
}
/** Set up a device from its card: the configuration first (the button waits for it), then the sheet. */
export async function openSetup(d: Device, from?: EventTarget | null) {
/**
* Set up a device from its card: the configuration first (the button waits for it), then the sheet. `here`: the
* page came from the device's own set-up link, so it is open on that device (setup.ts sameDevice).
*/
export async function openSetup(d: Device, from?: EventTarget | null, here = false) {
if (secureFirst()) return;
const run = async () => {
const cfg = await getConfig(d);
if (!cfg) return;
const key = await vpnKey(cfg, cfg.server);
openSheet(() => setupView(d, cfg, key));
openSheet(() => setupView(d, cfg, key, here));
};
if (from instanceof HTMLButtonElement) await once(from, run);
else await run();
@@ -78,42 +84,104 @@ function step(n: string, title: Node | string, kids: (Node | null)[]): HTMLEleme
);
}
/** Fold a block away (height, then gone) or bring it back; `instant` without motion. */
/** A block folded away: no height, blurred out. */
const FOLDED: Keyframe = { height: '0px', opacity: 0, filter: 'blur(4px)' };
/**
* Fold a block away (height, then gone) or bring it back, from where it stands
* now: a fold turned round half-way (a double click) never jumps. What holds it
* (a row still opening) glides on to its new height with it.
* `instant` without motion.
*/
function foldBlock(el: HTMLElement, fold: boolean, instant: boolean) {
const cur = el.hidden ? 0 : el.getBoundingClientRect().height;
const cs = getComputedStyle(el);
const cur: Keyframe = el.hidden
? FOLDED
: { height: `${el.getBoundingClientRect().height}px`, opacity: cs.opacity, filter: cs.filter === 'none' ? 'blur(0px)' : cs.filter };
el.getAnimations().forEach((a) => a.cancel());
el.hidden = fold;
regrow(el.parentElement);
if (instant) {
el.hidden = fold;
el.style.overflow = '';
return;
}
el.style.overflow = 'hidden';
el.hidden = false;
const to = fold ? 0 : el.getBoundingClientRect().height;
const [a, b] = fold ? [1, 0] : [0, 1];
play(
el,
[
{ height: `${cur}px`, opacity: a, filter: `blur(${4 - a * 4}px)` },
{ height: `${to}px`, opacity: b, filter: `blur(${4 - b * 4}px)` },
],
{
duration: SMOOTH.duration,
easing: SMOOTH.easing,
},
).onfinish = () => {
const to = fold ? FOLDED : { height: `${el.getBoundingClientRect().height}px`, opacity: 1, filter: 'blur(0px)' };
play(el, [cur, to], { duration: SMOOTH.duration, easing: SMOOTH.easing }).onfinish = () => {
el.style.overflow = '';
el.hidden = fold;
};
}
/** The first control in `el` that can take focus now (shown, not disabled). */
const firstControl = (el: Element | null | undefined) =>
[...(el?.querySelectorAll<HTMLElement>('button:not([disabled]), a[href], input:not([disabled])') ?? [])].find(
(x) => x.getClientRects().length > 0,
);
/**
* The steps on the device itself or for a router, as the way goes (way.ts); the
* layouts set up from elsewhere have rows, no steps. Waiting: the steps as
* built (connected is never asked: what shows folds shut as it is, wait.ts
* follow). Can't finish: the network is the likely cause, so they fold
* into one closed row, "Set it up again". No data: only what fixes it, open in
* one row, "Add the connection again" ("Import the configuration again" for a
* router): the connection step without its number and title. A router that
* knocks has AmneziaWG on it already, so its row holds that step alone in both.
* What sits on field inside the row steps up one (accordion.css). "Not on the X
* right now?" (`round`, on the device itself) goes in both: the device is in
* hand. Focus inside what moves (a badge just used) stays in the sheet: on that
* control where it still shows, else on the first one of what holds the steps
* now. Returns whether anything changed.
*/
function regroup(body: HTMLElement, steps: HTMLElement, round: Accordion | null, router: boolean): (st: WayState) => boolean {
const [s1, s2] = [...steps.children].slice(-2) as HTMLElement[];
const gap = steps.querySelector<HTMLElement>(':scope > .steps-gap');
const head2 = [...s2.querySelectorAll<HTMLElement>(':scope > .step-n, :scope > .step-b > .step-t')];
let look: 'steps' | 'again' | 'conn' = 'steps';
let row: HTMLElement | null = null;
return (st) => {
const next = st === 'trying' ? 'again' : st === 'nodata' ? 'conn' : 'steps';
if (next === look) return false;
look = next;
// Moving a focused control out of the page and back drops its focus (to the page under the sheet).
const had = document.activeElement;
const inside = had instanceof HTMLElement && (steps.contains(had) || !!round?.el.contains(had) || !!row?.contains(had));
row?.remove();
row = null;
// The steps show whole wherever they go: opened, the way round folds them away.
round?.setOpen(-1);
if (round) round.el.hidden = next !== 'steps';
const alone = next === 'conn' || (next === 'again' && router);
for (const e of [gap, s1, ...head2]) if (e) e.hidden = alone;
if (next === 'steps') body.append(steps);
else {
const title = next === 'again' ? _('Set it up again') : router ? _('Import the configuration again') : _('Add the connection again');
row = accordion([{ icon: glass('refresh', 'blue'), title, body: [steps] }], { inset: true, open: next === 'conn' ? 0 : -1 }).el;
body.append(row);
}
if (inside) {
const to =
had.isConnected && had.getClientRects().length
? had
: next === 'again'
? row?.querySelector<HTMLElement>('.acc-head')
: firstControl(alone ? s2 : steps);
to?.focus({ preventScroll: true });
}
return true;
};
}
type Layout = 'same' | 'router' | 'away' | 'pc-away';
export function setupView(d: Device, cfg: ClientConfig, key: string): View {
export function setupView(d: Device, cfg: ClientConfig, key: string, here = false): View {
const pf = platform();
const apps = appsFor(preset());
const handheld = d.kind === 'phone' || d.kind === 'tablet';
const router = d.kind === 'router';
const same = sameDevice(d.kind, pf);
const same = sameDevice(d.kind, pf, here);
const layout: Layout = same ? 'same' : router ? 'router' : handheld ? 'away' : 'pc-away';
const there = deviceNoun(d.kind);
const thereOn = deviceNoun(d.kind, true);
@@ -135,8 +203,10 @@ export function setupView(d: Device, cfg: ClientConfig, key: string): View {
app = v;
rememberApp(d, v);
segs.forEach((x) => x.sync(v));
// The sheet glides to its new height; inside, what changed morphs (morphInto).
// The sheet glides to its new height; inside, what changed morphs (morphInto). A row still opening
// around what changed glides on to its new height, and the sheet with it.
glide(fill);
regrow(title1, getBox, addBox, codeBox, sendBox);
},
);
segs.push(s);
@@ -147,6 +217,22 @@ export function setupView(d: Device, cfg: ClientConfig, key: string): View {
const addBox = h('div', { class: 'step-box' });
const codeBox = h('div', { class: 'step-box' });
const sendBox = h('div', { class: 'step-box' });
// Not on the device: the link goes there (as a code for a phone's camera); the page there does the rest.
const linkThere = setupLink(pageUrl(), d.id);
// A connection too long for a camera (a key this browser cannot compress, a configuration with a long list of
// networks): the code is the link instead; the page there hands it over. The words follow the app picked.
const tooLong = {
text: linkThere,
words: () => [
h(
'span',
{},
app === 'vpn'
? fmt(_('The key is too long for a code. Scan this one to open your link on the %s instead.'), thereOn)
: fmt(_('The configuration is too long for a code. Scan this one to open your link on the %s instead.'), thereOn),
),
],
};
let code: CodeRow | null = null;
let scan: ScanLine | null = null;
let codeApp: AppId | null = null;
@@ -167,26 +253,27 @@ export function setupView(d: Device, cfg: ClientConfig, key: string): View {
// 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));
else if (!addBox.firstChild) put(addBox, filePane(cfg));
const text = app === 'vpn' ? vpnQrText(key) : cfg.conf;
// Another app: its words morph in place, the code changes only when it holds something else (codes.ts).
if (code && scan && code.el.isConnected) {
if (codeApp !== app) {
code.swap(text);
scan.set(app);
// The connection as a code: only a phone or a tablet set up from here shows one.
if (layout === 'away') {
const text = app === 'vpn' ? vpnQrText(key) : cfg.conf;
// Another app: its words morph in place, the code changes only when it holds something else (codes.ts).
if (code && scan && code.el.isConnected) {
if (codeApp !== app) {
code.swap(text);
scan.set(app);
}
} else {
scan = scanLine(app);
code = codeRow(text, [scan.el], tooLong);
codeBox.replaceChildren(code.el);
}
} else {
scan = scanLine(app);
code = codeRow(text, [scan.el]);
codeBox.replaceChildren(code.el);
codeApp = app;
}
codeApp = app;
morphInto(sendBox, sendKids(c));
pill?.sync();
}
fill();
// Not on the device: the link goes there (as a code for a phone's camera); the page there does the rest.
const linkThere = setupLink(pageUrl(), d.id);
const linkBody = () => [
handheld
? codeRow(linkThere, [h('span', {}, _('Point its camera at the code: the link opens there.'))]).el
@@ -201,6 +288,7 @@ export function setupView(d: Device, cfg: ClientConfig, key: string): View {
body.appendChild(
notice('warn', 'shield', null, _('Open this page in Safari or Chrome: the store opens from here, but the app handoff does not.')),
);
let shape: (st: WayState) => boolean = () => false;
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());
@@ -209,7 +297,12 @@ export function setupView(d: Device, cfg: ClientConfig, key: string): View {
onToggle: (_i, open, instant) => foldBlock(steps, open, instant),
});
body.append(round.el, steps);
} else if (layout === 'router') body.append(step1(), step2());
shape = regroup(body, steps, round, false);
} else if (layout === 'router') {
const steps = h('div', { class: 'steps-wrap' }, step1(), step2());
body.append(steps);
shape = regroup(body, steps, null, true);
}
// A phone or a tablet set up from here: its link as a code, or the connection as a code for an app it has.
else if (layout === 'away')
body.appendChild(
@@ -221,7 +314,8 @@ export function setupView(d: Device, cfg: ClientConfig, key: string): View {
{ inset: true, open: 1 },
).el,
);
// A computer set up from somewhere else: its system is not known here, so the link goes there and the page there does both steps.
// A computer set up from somewhere else, or something else (a TV, a box, a NAS) set up from a phone: its system is
// not known here, so the link goes there and the page there does both steps.
else
body.appendChild(
accordion(
@@ -233,29 +327,20 @@ export function setupView(d: Device, cfg: ClientConfig, key: string): View {
).el,
);
const way = waitWay(d);
let finished = false;
onLeave(
watchFirstConnection(
d,
() => {
if (finished) return;
finished = true;
void arrive(way, body, d);
},
way.gaveUp,
),
);
// Closed before the device connected: the page shows what the polls brought.
onClosed(() => repaint());
const subline =
const subline = sub(
layout === 'same'
? _('Two steps, about a minute')
: router
? _('The packages and the file for OpenWrt')
: fmt(_('The app goes on the %s.'), there);
: fmt(_('The app goes on the %s.'), there),
);
const way = waitWay(d);
const wait = follow(d, way, { sub: subline, rest: body, shape });
onLeave(watchFirstConnection(d, wait.seen, wait.gaveUp));
// Closed before the device connected: the page shows what the polls brought.
onClosed(() => repaint());
const title = fmt(_('Set up %s'), d.name);
const el = h('div', { class: 'view' }, head(title, { acts: !!pill }), sub(subline), way.el, body);
const el = h('div', { class: 'view' }, head(title, { acts: !!pill }), subline, way.el, body);
return { el, label: title, acts: pill?.el ?? null };
}
+319 -70
View File
@@ -1,68 +1,184 @@
// Waiting for a new device's first connection: the way from the device to the
// server (a light runs along it while the page waits), the polling behind it,
// and what happens when it comes: the way fills green and its line morphs into
// "<device> connected", the sheet's buttons step away, the steps fold shut,
// and the sheet closes by itself onto the page.
// server and what it says in each state (waiting, can't finish, connected, no
// data: way.ts reads them off the router's answer), the polling behind it, and
// the sheet around it keeping pace. Connected, the way fills green and its line
// morphs into "<device> connected", × and the sheet's buttons step away,
// everything under the way folds shut and the sheet closes by itself onto the
// page; any other state undoes that. What sits under the way in each state is
// the view's (setup-view.ts hands it over as `Around`).
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';
import { EASE_IN, EASE_OUT, calm, play } from '../motion';
import { now, repaint, setState, type State } from '../state';
import { menuOpen } from '../ui/menu';
import { morphText } from '../ui/morph';
import { morphText, setText, textOf } from '../ui/morph';
import { closeSheet, onClosed, scrollTop, settle, showing } from '../ui/sheet';
import { wayState, type WayState } from '../way';
export interface Way {
el: HTMLElement;
connected(): void;
/** Show this state: its look, its line morphing, the line under it gliding in or out or changing in place. */
set(st: WayState): void;
/** Ten minutes and nothing: the light goes out, and the way says so. */
gaveUp(): void;
}
/** The way's line and the one under it (empty: none) in a state. */
function lines(st: WayState, d: Device): [string, string] {
switch (st) {
case 'trying':
return [_('Unable to complete the handshake'), _('Your network may be blocking the connection.')];
case 'connected':
return [fmt(_('%s connected'), d.name), ''];
case 'nodata':
return [_('Handshake complete, but no data'), _('This device is using an outdated configuration.')];
case 'waiting':
return [_('Waiting for the connection'), ''];
}
}
/** The way's class in a state (setup.css). */
const LOOK: Record<WayState, string> = { waiting: '', trying: 'trying', connected: 'done', nodata: 'nodata' };
export function waitWay(d: Device): Way {
const line = h('b', {}, _('Waiting for the connection'));
const more = h('span', { class: 'ws', hidden: true });
const t = h('span', { class: 't' }, line, more);
const text = h('div', { class: 'way-text' }, t);
// The light's two loops (running, knocking) and the break at the router run all along, each showing in its own
// state (setup.css): a change of state cross-fades them where they stand instead of starting one over.
const track = h(
'span',
{ class: 'way-track' },
h('span', { class: 'way-glow' }, h('span', { class: 'run' }, h('i')), h('span', { class: 'knock' }, h('i'))),
h('span', { class: 'way-fill' }),
h('span', { class: 'way-break' }, h('i')),
);
const el = h(
'div',
{ class: 'way', role: 'status', 'aria-live': 'polite' },
h(
'div',
{ class: 'way-row' },
h('span', { class: 'way-end' }, ic(d.kind)),
h('span', { class: 'way-track' }, h('span', { class: 'way-glow' }, h('i')), h('span', { class: 'way-fill' })),
h('span', { class: 'way-end home' }, ic('server')),
),
h('div', { class: 'way-text' }, h('span', { class: 't' }, line, more)),
h('div', { class: 'way-row' }, h('span', { class: 'way-end' }, ic(d.kind)), track, h('span', { class: 'way-end home' }, ic('server'))),
text,
);
return {
el,
connected() {
el.classList.add('done');
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.');
// The lines sit centred in their block: when the second comes or goes, the block's height and the lines' place
// glide together (a FLIP of the lines), so the first never jumps to its new centre. `from` and `top`: the block's
// height and the lines' top on screen before the change.
const glide = (from: number, top: number) => {
text.getAnimations().forEach((a) => a.cancel());
t.getAnimations().forEach((a) => a.cancel());
const to = text.offsetHeight;
text.style.overflow = '';
if (from !== to) {
text.style.overflow = 'hidden';
play(text, [{ height: `${from}px` }, { height: `${to}px` }], { duration: 340, easing: EASE_OUT }).onfinish = () => {
text.style.overflow = '';
};
}
// Measured with the block held at its old height (its glide has just started), the sheet around it at its old
// size too: the lines start exactly where they stood, however the sheet is anchored and however they centre.
const dy = top - t.getBoundingClientRect().top;
if (Math.abs(dy) > 0.5) play(t, [{ transform: `translateY(${dy}px)` }, { transform: 'none' }], { duration: 340, easing: EASE_OUT });
};
/** Where the line under it shows its words on screen (mid-morph, the words it is turning into). */
const words = () => {
const r = document.createRange();
r.selectNodeContents(more.querySelector(':scope > .mt-new') ?? more);
return r.getBoundingClientRect();
};
// The line under it comes, goes and changes without the block snapping: in, it blurs in as the block opens; out,
// it blurs away first, then the block closes; another in its place, the words blur from the old into the new
// where they stand as the block glides to the new one's height. A fade under way turns round from where it is.
let says = '';
let hiding = 0;
const second = (why: string) => {
if (why === says) return;
says = why;
clearTimeout(hiding);
const shown = !more.hidden;
const cs = getComputedStyle(more);
const cur = { opacity: cs.opacity, filter: cs.filter };
if (!why) {
if (!shown) return;
more.getAnimations().forEach((a) => a.cancel());
play(more, [cur, { opacity: 0, filter: 'blur(4px)' }], { duration: 180, easing: EASE_OUT, fill: 'forwards' });
hiding = window.setTimeout(() => {
const from = text.offsetHeight;
const top = t.getBoundingClientRect().top;
more.hidden = true;
more.getAnimations().forEach((a) => a.cancel());
glide(from, top);
}, 170);
return;
}
const from = text.offsetHeight;
const top = t.getBoundingClientRect().top;
if (!shown) {
setText(more, why);
more.hidden = false;
glide(from, top);
play(
line.parentElement!,
more,
[
{ opacity: 0, filter: 'blur(4px)' },
{ opacity: 1, filter: 'none' },
],
{ duration: 280, easing: EASE_OUT },
{ duration: 300, easing: EASE_OUT, delay: 60, fill: 'backwards' },
);
return;
}
// The old words go from where they stand now, placed against the block as the glide holds it on its first frame.
const was = textOf(more);
const at = words();
setText(more, why);
glide(from, top);
morphText(more, why, was, { whole: true, at });
more.getAnimations().forEach((a) => a.cancel());
if (+cur.opacity < 1) play(more, [cur, { opacity: 1, filter: 'none' }], { duration: 300, easing: EASE_OUT });
};
const packets = (on: boolean) => {
// Those on their way out are not counted: back to no data while they fade, a fresh pair sets off.
const pk = track.querySelectorAll<HTMLElement>('.way-pkt:not(.out)');
if (on) {
// Two, half a loop apart: one is always on its way.
if (!pk.length) track.append(h('span', { class: 'way-pkt' }), h('span', { class: 'way-pkt b' }));
return;
}
// Each fades where it is, falling on (a fade from script wins over its loop's own opacity), then goes.
pk.forEach((p) => {
p.classList.add('out');
const o = getComputedStyle(p).opacity;
play(p, [{ opacity: o }, { opacity: 0 }], { duration: 200, easing: EASE_IN, fill: 'forwards' }).onfinish = () => p.remove();
});
};
return {
el,
set(st) {
el.classList.remove('trying', 'nodata', 'done', 'stopped');
if (LOOK[st]) el.classList.add(LOOK[st]);
const [a, b] = lines(st, d);
morphText(line, a);
second(b);
packets(st === 'nodata');
},
gaveUp() {
el.classList.remove('trying', 'nodata', 'done');
el.classList.add('stopped');
packets(false);
morphText(line, _('No connection yet'));
second(_('Close this and open it again to keep checking.'));
},
};
}
/**
* The first connection was seen (a fresh handshake) before the agent's watcher
* marked the device online, a second at most: ask again shortly, a few times,
* and repaint the page with the answer, so the card goes on to "Connected"
* instead of staying on "Last connected just now".
* The first connection was seen before the agent's watcher marked the device
* online, a second at most: ask again shortly, a few times, and repaint the
* page with the answer, so the card goes on to "Connected" instead of staying
* on "Last connected just now".
*/
function catchUp(id: string, tries = 4) {
window.setTimeout(async () => {
@@ -77,25 +193,33 @@ function catchUp(id: string, tries = 4) {
}, 1500);
}
/** The open set-up sheets' polls, for pollNow(). */
const pokes = new Set<() => void>();
/** Run the open set-up sheet's poll now instead of at its next turn (the demo, once its state switch moved). */
export function pollNow() {
pokes.forEach((p) => p());
}
/**
* Poll for the first connection of a device that never connected: 5 s at
* first, then slower, for ten minutes at most (then `gaveUp`), not while the
* tab is hidden (every poll is a process on the router), and never again once
* the link stopped working. `arrived` runs once. Returns the stop function.
* Poll the device being set up while its sheet is open: 5 s at first, then
* slower, for ten minutes at most (then `gaveUp`, unless it is connected: the
* sheet is closing by itself), not while the tab is hidden (every poll is a
* process on the router), and never again once the link stopped working.
* `seen` gets each new state of the way. Returns the stop function.
*/
export function watchFirstConnection(d: Device, arrived: () => void, gaveUp: () => void): () => void {
// The first connection is a handshake newer than this sheet (router clock), not `online`:
// that follows the agent's watcher, which can lag the handshake by a poll, and a device
// set up again with new keys still reports the last handshake of its old ones.
export function watchFirstConnection(d: Device, seen: (st: WayState) => void, gaveUp: () => void): () => void {
// The states count from this sheet (router clock): way.ts.
const opened = now();
let timer = 0;
let polls = 0;
let done = false;
let last: WayState = 'waiting';
const started = Date.now();
const poll = async () => {
timer = 0;
if (done) return;
if (Date.now() - started > 600_000) {
if (last !== 'connected' && Date.now() - started > 600_000) {
done = true;
gaveUp();
return;
@@ -104,12 +228,14 @@ export function watchFirstConnection(d: Device, arrived: () => void, gaveUp: ()
try {
const st = await call<State>('state');
setState(st);
// Left while it asked: the answer is the page's, not this sheet's any more.
if (done) return;
const dev = st.person.devices.find((x) => x.id === d.id);
if (dev && dev.handshake > opened) {
done = true;
arrived();
if (!dev.online) catchUp(d.id);
return;
const next = wayState(dev, opened);
if (next !== last) {
if (next === 'connected' && dev && !dev.online) catchUp(d.id);
last = next;
seen(next);
}
} catch (e) {
if (gone(e)) {
@@ -126,47 +252,170 @@ export function watchFirstConnection(d: Device, arrived: () => void, gaveUp: ()
const onVisible = () => {
if (!document.hidden && !done && !timer) void poll();
};
const poke = () => {
if (done) return;
if (timer) clearTimeout(timer);
void poll();
};
document.addEventListener('visibilitychange', onVisible);
pokes.add(poke);
schedule();
return () => {
done = true;
if (timer) clearTimeout(timer);
document.removeEventListener('visibilitychange', onVisible);
pokes.delete(poke);
};
}
const beat = (ms: number) => new Promise((r) => setTimeout(r, ms));
/** What the sheet around the way is made of (setup-view.ts). */
export interface Around {
/** The line under the sheet's title. */
sub: HTMLElement;
/** Everything under the way. */
rest: HTMLElement;
/** Give what is under the way its shape for this state, at once (the glide is here); false: nothing changed. */
shape(st: WayState): boolean;
}
/** Blocks folded away, held at nothing until they come back. */
const folded = new WeakSet<Element>();
/**
* The first connection arrived. The way fills green and says so (the sheet
* goes back up to it if it was scrolled), the buttons beside × step away; then
* everything under the way, which did its job, folds shut. Two seconds to read
* it, and the sheet closes by itself onto the page, the card ringing green.
* Fold a block away (its height and margins to nothing, blurring out) or bring
* it back, from wherever it stands now: a fold turned round half-way never jumps.
* With less motion it fades out and then is gone, its space with it (or comes
* back at once and fades in): nothing travels, and nothing keeps a blank band.
*/
export async function arrive(way: Way, rest: HTMLElement, d: Device) {
way.connected();
settle();
scrollTop();
await beat(400);
if (!showing(way.el)) return;
function fold(el: HTMLElement, away: boolean, duration: number) {
if (folded.has(el) === away) return;
if (away) folded.add(el);
else folded.delete(el);
if (calm()) {
el.getAnimations().forEach((a) => a.cancel());
if (!away) {
el.hidden = false;
play(el, [{ opacity: 0 }, { opacity: 1 }], { duration });
return;
}
play(el, [{ opacity: 1 }, { opacity: 0 }], { duration, fill: 'forwards' }).onfinish = () => {
if (folded.has(el)) el.hidden = true;
};
return;
}
el.hidden = false;
const cs = getComputedStyle(el);
const cur = {
height: `${el.getBoundingClientRect().height}px`,
marginTop: cs.marginTop,
marginBottom: cs.marginBottom,
opacity: cs.opacity,
filter: cs.filter,
};
el.getAnimations().forEach((a) => a.cancel());
const own = getComputedStyle(el);
const to = away
? { height: '0px', marginTop: '0px', marginBottom: '0px', opacity: 0, filter: 'blur(4px)' }
: {
height: `${el.getBoundingClientRect().height}px`,
marginTop: own.marginTop,
marginBottom: own.marginBottom,
opacity: 1,
filter: 'none',
};
el.style.overflow = 'hidden';
play(el, [cur, to], { duration, easing: EASE_OUT, fill: away ? 'forwards' : 'none' }).onfinish = () => {
if (!away) el.style.overflow = '';
};
}
/** The way's own gap to what is under it (18 px, setup.css) goes with it, and comes back with it. */
function gap(way: HTMLElement, away: boolean) {
const from = getComputedStyle(way).marginBottom;
way.getAnimations().forEach((a) => a.cancel());
const to = away ? '0px' : getComputedStyle(way).marginBottom;
play(way, [{ marginBottom: from }, { marginBottom: to }], { duration: 520, easing: EASE_OUT, fill: away ? 'forwards' : 'none' });
}
/** What is under the way takes another shape: it glides to its new height, and what came in blurs in. */
function reshape(a: Around, st: WayState) {
const rest = a.rest;
// From where it stands on screen (a glide under way included) to its new height.
const h0 = rest.getBoundingClientRect().height;
if (!a.shape(st)) return;
rest.getAnimations().forEach((x) => x.cancel());
const h1 = rest.getBoundingClientRect().height;
rest.style.overflow = 'hidden';
play(rest, [{ height: `${h0}px` }, { height: `${h1}px` }], { duration: 420, easing: EASE_OUT }).onfinish = () => {
rest.style.overflow = '';
};
play(
rest,
[
{ height: `${rest.offsetHeight}px`, opacity: 1, filter: 'none' },
{ height: '0px', opacity: 0, filter: 'blur(4px)' },
{ opacity: 0.4, filter: 'blur(2px)' },
{ opacity: 1, filter: 'none' },
],
{
duration: 520,
easing: EASE_OUT,
fill: 'forwards',
},
{ duration: 320, easing: EASE_OUT },
);
play(way.el, [{ marginBottom: '18px' }, { marginBottom: '0px' }], { duration: 520, easing: EASE_OUT, fill: 'forwards' });
// Reading time, not motion: the same with less motion.
await beat(2400);
// Only this sheet: not one the visitor went on to.
if (!showing(way.el)) return;
onClosed(() => repaint({ flash: d.id }));
closeSheet();
}
/** What the sheet does as the wait goes on (follow). */
export interface Following {
/** A new state of the way. */
seen(st: WayState): void;
/** Ten minutes and nothing (watchFirstConnection). */
gaveUp(): void;
}
/**
* The sheet keeps pace with the way. Connected: × and the buttons beside it
* step away, the sheet goes back up to the way if it was scrolled, everything
* under the way folds shut with the way's gap to it, and after two seconds to
* read it the sheet closes by itself onto the page, the card ringing green. Any
* other state undoes that (× comes back, what folded unfolds) and gives what is
* under the way its shape. The subtitle says what setting up takes, so it shows
* only while waiting: once the device is heard from, or the wait gives up, it
* folds away, the way then right under the head.
*/
export function follow(d: Device, way: Way, a: Around): Following {
let shut = false;
let timers: number[] = [];
const later = (ms: number, f: () => void) => timers.push(window.setTimeout(f, ms));
const seen = (st: WayState) => {
timers.forEach(clearTimeout);
timers = [];
way.set(st);
fold(a.sub, st !== 'waiting', 380);
settle(st === 'connected');
if (st === 'connected') {
scrollTop();
later(400, () => {
if (!showing(way.el)) return;
shut = true;
fold(a.rest, true, 520);
gap(way.el, true);
// Reading time, not motion: the same with less motion.
later(2400, () => {
// Only this sheet: not one the visitor went on to.
if (!showing(way.el)) return;
onClosed(() => repaint({ flash: d.id }));
closeSheet();
});
});
return;
}
if (!shut) return reshape(a, st);
// Folded while it was connected: it unfolds straight into its new shape.
shut = false;
a.shape(st);
fold(a.rest, false, 520);
gap(way.el, false);
};
return {
seen,
gaveUp() {
fold(a.sub, true, 380);
way.gaveUp();
},
};
}
+194 -18
View File
@@ -29,6 +29,10 @@ msgid_plural "%s already has %d devices. Remove one first to lower the limit to
msgstr[0] ""
msgstr[1] ""
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
msgid "%s and %s overlap: each packet type needs values of its own."
msgstr ""
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
msgid "%s can't use the network interface %s: it exists and isn't Dawnline's."
msgstr ""
@@ -51,6 +55,10 @@ msgstr[1] ""
msgid "%s h ago"
msgstr ""
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
msgid "%s has a tag that is not closed with >."
msgstr ""
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
msgid "%s has an invalid interface name \"%s\"."
msgstr ""
@@ -67,6 +75,10 @@ msgstr ""
msgid "%s is kept down."
msgstr ""
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
msgid "%s is kept down: its disguise has values AmneziaWG cannot take. %s"
msgstr ""
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
msgid "%s is kept down: its disguise needs AmneziaWG %s (installed: %s)."
msgstr ""
@@ -79,12 +91,40 @@ msgstr ""
msgid "%s left"
msgstr ""
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
msgid "%s may not contain # or a line break."
msgstr ""
#: web/src/shared/format.ts
msgid "%s min ago"
msgstr ""
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
msgid "%s must be a number or range"
msgid "%s must be a number or a range like 10-100, up to 65535."
msgstr ""
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
msgid "%s must be a number or a range like 100-200, up to 4294967295."
msgstr ""
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
msgid "%s must be a number or a range like 5-15, from 1 to 65535."
msgstr ""
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
msgid "%s must be a whole number from 0 to 65535."
msgstr ""
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
msgid "%s must be at least 12 with header protection."
msgstr ""
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
msgid "%s must be from %d to %d."
msgstr ""
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
msgid "%s must be on or off."
msgstr ""
#: web/src/portal/page/devices.ts
@@ -121,6 +161,10 @@ msgstr ""
msgid "%s your time"
msgstr ""
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
msgid "%s: <%s> is not a tag AmneziaWG apps accept: use <b 0x…> with an even number of hex digits, <r N>, <rc N> or <rd N> with N from 1 to 1000, or <t>."
msgstr ""
#: web/src/shared/format.ts
msgid "%sd %sh"
msgstr ""
@@ -186,6 +230,10 @@ msgstr ""
msgid "Add the connection"
msgstr ""
#: web/src/portal/flows/setup-view.ts
msgid "Add the connection again"
msgstr ""
#: web/src/portal/page/devices.ts
msgid "Add this device"
msgstr ""
@@ -247,6 +295,10 @@ msgstr ""
msgid "Cancel"
msgstr ""
#: web/src/portal/page/devices.ts
msgid "Can’t finish connecting"
msgstr ""
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
msgid "Circle %s: server %s does not exist."
msgstr ""
@@ -280,6 +332,10 @@ msgstr ""
msgid "Connected"
msgstr ""
#: web/src/portal/page/devices.ts
msgid "Connected, but no data"
msgstr ""
#: web/src/portal/page/devices.ts
msgid "Connected, no data left"
msgstr ""
@@ -288,6 +344,10 @@ msgstr ""
msgid "Connected, outside your hours"
msgstr ""
#: web/src/portal/page/devices.ts
msgid "Connection keeps dropping"
msgstr ""
#: web/src/portal/flows/secure.ts
msgid "Connection settings only travel encrypted"
msgstr ""
@@ -381,6 +441,14 @@ msgstr ""
msgid "Data used"
msgstr ""
#: web/src/shared/format.ts
msgid "Device"
msgstr ""
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
msgid "Device %s of %s: MTU %d is not between 1280 and 1500."
msgstr ""
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
msgid "Device %s of %s: address %s is also used by device %s of %s."
msgstr ""
@@ -401,6 +469,10 @@ msgstr ""
msgid "Device %s of %s: address (none) is not a plain IPv4 address."
msgstr ""
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
msgid "Device %s of %s: keep-alive %d is not between 0 and 600 seconds."
msgstr ""
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
msgid "Device %s of %s: the preshared key is not a key."
msgstr ""
@@ -413,6 +485,10 @@ msgstr ""
msgid "Device %s of %s: the public key is not a key."
msgstr ""
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
msgid "Device %s of %s: the public key is the server's own."
msgstr ""
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
msgid "Device %s: person %s does not exist."
msgstr ""
@@ -425,7 +501,7 @@ msgstr ""
msgid "Device limit reached (%d)."
msgstr ""
#: web/src/portal/flows/device-actions.ts
#: web/src/portal/flows/rename.ts
msgid "Device name"
msgstr ""
@@ -503,7 +579,11 @@ msgid "Ends %s"
msgstr ""
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
msgid "Enter a device name (up to 48 characters)."
msgid "Enter a device name: up to %d letters, digits, spaces and - _ ."
msgstr ""
#: web/src/portal/flows/add.ts
msgid "Except %s: those addresses lead to the home network."
msgstr ""
#: web/src/shared/format.ts
@@ -542,6 +622,14 @@ msgstr ""
msgid "Get it on"
msgstr ""
#: web/src/portal/flows/rename.ts
msgid "Give the device a name."
msgstr ""
#: web/src/portal/flows/wait.ts
msgid "Handshake complete, but no data"
msgstr ""
#: web/src/portal/flows/setup-parts.ts
msgid "Hide key"
msgstr ""
@@ -567,6 +655,10 @@ msgstr ""
msgid "Hours, your time"
msgstr ""
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
msgid "I1-I5 together must be at most 2000 characters, not %d."
msgstr ""
#: web/src/portal/page/devices.ts
msgid "IP address copied"
msgstr ""
@@ -585,6 +677,10 @@ msgstr ""
msgid "Import the configuration"
msgstr ""
#: web/src/portal/flows/setup-view.ts
msgid "Import the configuration again"
msgstr ""
#: web/src/portal/setup.ts
msgctxt "WireGuard app"
msgid "Import tunnel(s) from file…"
@@ -624,6 +720,10 @@ msgstr ""
msgid "Invalid public key."
msgstr ""
#: web/src/portal/page/devices.ts
msgid "It connects, but the connection breaks every few minutes. Another network may help."
msgstr ""
#: web/src/portal/page/access.ts
msgid "It ended on %s."
msgstr ""
@@ -636,14 +736,26 @@ msgstr ""
msgid "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."
msgstr ""
#: web/src/portal/page/devices.ts
msgid "It reaches the router, but the connection never completes. The network may be blocking it."
msgstr ""
#: web/src/portal/flows/device-actions.ts
msgid "Its connection stops working at once. You can add it again later."
msgstr ""
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
msgid "Jmin must not be larger than Jmax."
msgstr ""
#: web/src/shared/format.ts
msgid "KB"
msgstr ""
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
msgid "Keep-alive must be 0-600 seconds."
msgstr ""
#: web/src/portal/flows/setup-parts.ts
#: web/src/portal/flows/setup-view.ts
msgid "Key copied"
@@ -662,6 +774,10 @@ msgstr ""
msgid "Key generation failed."
msgstr ""
#: web/src/portal/flows/add.ts
msgid "LAN Bypass"
msgstr ""
#: web/src/portal/page/frame.ts
msgid "Language"
msgstr ""
@@ -686,6 +802,10 @@ msgstr ""
msgid "MB"
msgstr ""
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
msgid "MTU must be 1280-1500."
msgstr ""
#: web/src/shared/format.ts
msgid "Mbit/s"
msgstr ""
@@ -782,6 +902,18 @@ msgstr ""
msgid "On GitHub"
msgstr ""
#: web/src/portal/page/devices.ts
msgid "On two devices at once"
msgstr ""
#: web/src/shared/name-guard.ts
msgid "Only letters, digits, - _ ."
msgstr ""
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/devices.uc
msgid "Only the admin can change how a device connects."
msgstr ""
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/devices.uc
msgid "Only the admin can turn devices off."
msgstr ""
@@ -893,10 +1025,6 @@ msgstr ""
msgid "Phone"
msgstr ""
#: web/src/portal/flows/add.ts
msgid "Phones and tablets get a smaller packet size that suits mobile networks."
msgstr ""
#: web/src/portal/flows/setup-parts.ts
msgid "Pick AmneziaVPN in the share sheet. Not there? %s and add it in the app."
msgstr ""
@@ -943,6 +1071,10 @@ msgstr ""
msgid "Reconnect %s?"
msgstr ""
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
msgid "RejectAfterTime must be at most 180 seconds."
msgstr ""
#: web/src/portal/flows/device-actions.ts
#: web/src/portal/page/devices.ts
msgid "Remove"
@@ -956,14 +1088,10 @@ msgstr ""
msgid "Rename"
msgstr ""
#: web/src/portal/flows/device-actions.ts
#: web/src/portal/page/devices.ts
msgid "Rename %s"
msgstr ""
#: web/src/portal/flows/device-actions.ts
msgid "Renamed"
msgstr ""
#: web/src/portal/api.ts
msgid "Request failed (%s)"
msgstr ""
@@ -976,6 +1104,10 @@ msgstr ""
msgid "Resets on the 1st."
msgstr ""
#: web/src/portal/flows/rename.ts
msgid "Return to save, Esc to cancel"
msgstr ""
#: web/src/shared/format.ts
msgid "Router"
msgstr ""
@@ -984,8 +1116,8 @@ msgstr ""
msgid "Run"
msgstr ""
#: web/src/portal/flows/device-actions.ts
msgid "Save"
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
msgid "S2 must not be S1 + 56: the handshake initiation and response would have the same size."
msgstr ""
#: web/src/portal/setup.ts
@@ -1017,6 +1149,10 @@ msgstr ""
msgid "Server is turned off"
msgstr ""
#: web/src/portal/flows/setup-view.ts
msgid "Set it up again"
msgstr ""
#: web/src/portal/flows/setup-view.ts
#: web/src/portal/page/devices.ts
msgid "Set up %s"
@@ -1078,6 +1214,10 @@ msgstr ""
msgid "Tap “%s” and connect"
msgstr ""
#: web/src/portal/flows/rename.ts
msgid "That name is taken."
msgstr ""
#: web/src/portal/setup.ts
msgid "The APK is for phones without Google Play, or where the store hides the app."
msgstr ""
@@ -1094,6 +1234,10 @@ msgstr ""
msgid "The browser may warn that the certificate is not trusted: it is this router’s own. Choose to continue (“Advanced” → “Proceed”)."
msgstr ""
#: web/src/portal/flows/setup-view.ts
msgid "The configuration is too long for a code. Scan this one to open your link on the %s instead."
msgstr ""
#: web/src/portal/flows/setup-parts.ts
msgid "The connection"
msgstr ""
@@ -1102,10 +1246,18 @@ msgstr ""
msgid "The connection as one key"
msgstr ""
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
msgid "The header protection key is not a key."
msgstr ""
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
msgid "The id may use lowercase letters, digits and underscores."
msgstr ""
#: web/src/portal/flows/setup-view.ts
msgid "The key is too long for a code. Scan this one to open your link on the %s instead."
msgstr ""
#: web/src/portal/flows/setup-view.ts
msgid "The packages and the file for OpenWrt"
msgstr ""
@@ -1118,6 +1270,10 @@ msgstr ""
msgid "The person has no server."
msgstr ""
#: web/src/portal/page/devices.ts
msgid "The router can’t use what it sends: reconnect it."
msgstr ""
#: web/src/portal/flows/setup-parts.ts
msgid "Then come back here and tap"
msgstr ""
@@ -1126,10 +1282,18 @@ msgstr ""
msgid "Then import it in the app"
msgstr ""
#: web/src/portal/page/devices.ts
msgid "This connection is on two devices and they push each other out. Add the other one as its own device."
msgstr ""
#: web/src/portal/page/devices.ts
msgid "This device"
msgstr ""
#: web/src/portal/flows/wait.ts
msgid "This device is using an outdated configuration."
msgstr ""
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
msgid "This key is already in use."
msgstr ""
@@ -1163,6 +1327,10 @@ msgstr ""
msgid "Two steps, about a minute: get the app, then add the connection."
msgstr ""
#: web/src/portal/flows/wait.ts
msgid "Unable to complete the handshake"
msgstr ""
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
msgid "Unknown DNS choice."
msgstr ""
@@ -1196,6 +1364,10 @@ msgstr ""
msgid "Unknown service %s."
msgstr ""
#: web/src/shared/name-guard.ts
msgid "Up to %s characters."
msgstr ""
#: web/src/portal/ui/bars.ts
msgid "Uploaded"
msgstr ""
@@ -1268,6 +1440,14 @@ msgstr ""
msgid "Your devices can’t connect until it’s resumed."
msgstr ""
#: web/src/portal/flows/add.ts
msgid "Your local network stays reachable while connected."
msgstr ""
#: web/src/portal/flows/wait.ts
msgid "Your network may be blocking the connection."
msgstr ""
#: web/src/shared/format.ts
msgid "bit/s"
msgstr ""
@@ -1314,10 +1494,6 @@ msgstr ""
msgid "ends tomorrow"
msgstr ""
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
msgid "h1-h4 must be distinct"
msgstr ""
#: web/src/shared/format.ts
msgid "just now"
msgstr ""
+197 -21
View File
@@ -32,6 +32,10 @@ msgstr[0] "%s: уже %d устройство. Чтобы снизить лим
msgstr[1] "%s: уже %d устройства. Чтобы снизить лимит до %d, сначала удалите одно из них."
msgstr[2] "%s: уже %d устройств. Чтобы снизить лимит до %d, сначала удалите одно из них."
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
msgid "%s and %s overlap: each packet type needs values of its own."
msgstr "%s и %s пересекаются: у каждого типа пакетов должны быть свои значения."
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
msgid "%s can't use the network interface %s: it exists and isn't Dawnline's."
msgstr "Сервер %s не может использовать сетевой интерфейс %s: он уже существует и создан не Dawnline."
@@ -55,6 +59,10 @@ msgstr[2] "%s дней"
msgid "%s h ago"
msgstr "%s ч назад"
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
msgid "%s has a tag that is not closed with >."
msgstr "%s: тег не закрыт символом >."
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
msgid "%s has an invalid interface name \"%s\"."
msgstr "У сервера %s недопустимое имя интерфейса «%s»."
@@ -71,6 +79,10 @@ msgstr "%s всего"
msgid "%s is kept down."
msgstr "Сервер %s остановлен."
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
msgid "%s is kept down: its disguise has values AmneziaWG cannot take. %s"
msgstr "Сервер %s остановлен: в его маскировке есть значения, которые AmneziaWG не примет. %s"
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
msgid "%s is kept down: its disguise needs AmneziaWG %s (installed: %s)."
msgstr "Сервер %s остановлен: для его маскировки нужен AmneziaWG %s (установлен %s)."
@@ -83,13 +95,41 @@ msgstr "Сервер %s остановлен: для его маскировки
msgid "%s left"
msgstr "осталось %s"
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
msgid "%s may not contain # or a line break."
msgstr "%s не может содержать # или перенос строки."
#: web/src/shared/format.ts
msgid "%s min ago"
msgstr "%s мин назад"
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
msgid "%s must be a number or range"
msgstr "%s: нужно число или диапазон"
msgid "%s must be a number or a range like 10-100, up to 65535."
msgstr "%s: нужно число или диапазон вида 10-100, не больше 65535."
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
msgid "%s must be a number or a range like 100-200, up to 4294967295."
msgstr "%s: нужно число или диапазон вида 100-200, не больше 4294967295."
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
msgid "%s must be a number or a range like 5-15, from 1 to 65535."
msgstr "%s: нужно число или диапазон вида 5-15, от 1 до 65535."
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
msgid "%s must be a whole number from 0 to 65535."
msgstr "%s: нужно целое число от 0 до 65535."
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
msgid "%s must be at least 12 with header protection."
msgstr "%s: с защитой заголовков нужно не меньше 12."
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
msgid "%s must be from %d to %d."
msgstr "%s: от %d до %d."
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
msgid "%s must be on or off."
msgstr "%s: нужно on или off."
#: web/src/portal/page/devices.ts
msgid "%s of %s"
@@ -126,6 +166,10 @@ msgstr "%s в этом месяце"
msgid "%s your time"
msgstr "%s по вашему времени"
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
msgid "%s: <%s> is not a tag AmneziaWG apps accept: use <b 0x…> with an even number of hex digits, <r N>, <rc N> or <rd N> with N from 1 to 1000, or <t>."
msgstr "%s: тег <%s> не примут приложения AmneziaWG: используйте <b 0x…> с чётным числом шестнадцатеричных цифр, <r N>, <rc N> или <rd N> с N от 1 до 1000 либо <t>."
#: web/src/shared/format.ts
msgid "%sd %sh"
msgstr "%s д %s ч"
@@ -191,6 +235,10 @@ msgstr "Добавить с самого устройства"
msgid "Add the connection"
msgstr "Добавьте подключение"
#: web/src/portal/flows/setup-view.ts
msgid "Add the connection again"
msgstr "Добавить заново"
#: web/src/portal/page/devices.ts
msgid "Add this device"
msgstr "Добавить это устройство"
@@ -252,6 +300,10 @@ msgstr "Навигационная цепочка"
msgid "Cancel"
msgstr "Отмена"
#: web/src/portal/page/devices.ts
msgid "Can’t finish connecting"
msgstr "Не удаётся подключиться"
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
msgid "Circle %s: server %s does not exist."
msgstr "Круг %s: сервера %s нет."
@@ -285,6 +337,10 @@ msgstr "Подключить"
msgid "Connected"
msgstr "Подключено"
#: web/src/portal/page/devices.ts
msgid "Connected, but no data"
msgstr "Подключено, но данных нет"
#: web/src/portal/page/devices.ts
msgid "Connected, no data left"
msgstr "Подключено, трафик закончился"
@@ -293,6 +349,10 @@ msgstr "Подключено, трафик закончился"
msgid "Connected, outside your hours"
msgstr "Подключено, вне часов доступа"
#: web/src/portal/page/devices.ts
msgid "Connection keeps dropping"
msgstr "Связь постоянно рвётся"
#: web/src/portal/flows/secure.ts
msgid "Connection settings only travel encrypted"
msgstr "Настройки подключения передаются только в зашифрованном виде"
@@ -386,6 +446,14 @@ msgstr "Трафик за месяц"
msgid "Data used"
msgstr "Трафик всего"
#: web/src/shared/format.ts
msgid "Device"
msgstr "Устройство"
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
msgid "Device %s of %s: MTU %d is not between 1280 and 1500."
msgstr "Устройство %s (%s): MTU %d вне пределов от 1280 до 1500."
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
msgid "Device %s of %s: address %s is also used by device %s of %s."
msgstr "Устройство %s (%s): адрес %s уже занят устройством %s (%s)."
@@ -406,6 +474,10 @@ msgstr "Устройство %s (%s): адрес %s принадлежит са
msgid "Device %s of %s: address (none) is not a plain IPv4 address."
msgstr "Устройство %s (%s): нет IPv4-адреса."
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
msgid "Device %s of %s: keep-alive %d is not between 0 and 600 seconds."
msgstr "Устройство %s (%s): keep-alive %d вне пределов от 0 до 600 секунд."
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
msgid "Device %s of %s: the preshared key is not a key."
msgstr "Устройство %s (%s): общий ключ (PSK) некорректен."
@@ -418,6 +490,10 @@ msgstr "Устройство %s (%s): приватный ключ некорре
msgid "Device %s of %s: the public key is not a key."
msgstr "Устройство %s (%s): публичный ключ некорректен."
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
msgid "Device %s of %s: the public key is the server's own."
msgstr "Устройство %s (%s): публичный ключ совпадает с ключом сервера."
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
msgid "Device %s: person %s does not exist."
msgstr "Устройство %s: человека %s нет."
@@ -430,7 +506,7 @@ msgstr "Лимит устройств: от 1 до 32."
msgid "Device limit reached (%d)."
msgstr "Достигнут лимит устройств (%d)."
#: web/src/portal/flows/device-actions.ts
#: web/src/portal/flows/rename.ts
msgid "Device name"
msgstr "Имя устройства"
@@ -508,8 +584,12 @@ msgid "Ends %s"
msgstr "Закончится %s"
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
msgid "Enter a device name (up to 48 characters)."
msgstr "Введите название устройства (до 48 символов)."
msgid "Enter a device name: up to %d letters, digits, spaces and - _ ."
msgstr "Введите название устройства: до %d букв, цифр, пробелов и - _ ."
#: web/src/portal/flows/add.ts
msgid "Except %s: those addresses lead to the home network."
msgstr "Кроме %s: эти адреса ведут в домашнюю сеть."
#: web/src/shared/format.ts
msgid "Expired"
@@ -547,6 +627,14 @@ msgstr "Установите %s на роутер"
msgid "Get it on"
msgstr "Доступно в"
#: web/src/portal/flows/rename.ts
msgid "Give the device a name."
msgstr "Дайте устройству название."
#: web/src/portal/flows/wait.ts
msgid "Handshake complete, but no data"
msgstr "Рукопожатие есть, но данных нет"
#: web/src/portal/flows/setup-parts.ts
msgid "Hide key"
msgstr "Скрыть ключ"
@@ -572,6 +660,10 @@ msgstr "Часы доступа, время роутера"
msgid "Hours, your time"
msgstr "Часы доступа, ваше время"
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
msgid "I1-I5 together must be at most 2000 characters, not %d."
msgstr "I1–I5 вместе: не больше 2000 символов, сейчас %d."
#: web/src/portal/page/devices.ts
msgid "IP address copied"
msgstr "IP-адрес скопирован"
@@ -590,6 +682,10 @@ msgstr "Импорт из файла или архива"
msgid "Import the configuration"
msgstr "Импортируйте конфигурацию"
#: web/src/portal/flows/setup-view.ts
msgid "Import the configuration again"
msgstr "Импортировать заново"
#: web/src/portal/setup.ts
msgctxt "WireGuard app"
msgid "Import tunnel(s) from file…"
@@ -629,6 +725,10 @@ msgstr "Некорректный JSON."
msgid "Invalid public key."
msgstr "Недопустимый публичный ключ."
#: web/src/portal/page/devices.ts
msgid "It connects, but the connection breaks every few minutes. Another network may help."
msgstr "Устройство подключается, но связь рвётся каждые несколько минут. Может помочь другая сеть."
#: web/src/portal/page/access.ts
msgid "It ended on %s."
msgstr "Доступ закончился %s."
@@ -641,14 +741,26 @@ msgstr "Устройство получит новые ключи, а текущ
msgid "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."
msgstr "Устройство получит новые ключи. Сейчас вы подключены через его текущие настройки: через несколько секунд после подтверждения связь прервётся. Добавьте новые - они откроются следом."
#: web/src/portal/page/devices.ts
msgid "It reaches the router, but the connection never completes. The network may be blocking it."
msgstr "Устройство доходит до роутера, но подключение не завершается. Возможно, его блокирует сеть."
#: web/src/portal/flows/device-actions.ts
msgid "Its connection stops working at once. You can add it again later."
msgstr "Подключение сразу перестанет работать. Устройство можно будет добавить снова."
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
msgid "Jmin must not be larger than Jmax."
msgstr "Jmin не может быть больше Jmax."
#: web/src/shared/format.ts
msgid "KB"
msgstr "КБ"
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
msgid "Keep-alive must be 0-600 seconds."
msgstr "Keep-alive: от 0 до 600 секунд."
#: web/src/portal/flows/setup-parts.ts
#: web/src/portal/flows/setup-view.ts
msgid "Key copied"
@@ -667,6 +779,10 @@ msgstr "Не удалось создать ключ (нет случайных
msgid "Key generation failed."
msgstr "Не удалось создать ключ."
#: web/src/portal/flows/add.ts
msgid "LAN Bypass"
msgstr "Обход локальной сети"
#: web/src/portal/page/frame.ts
msgid "Language"
msgstr "Язык"
@@ -691,6 +807,10 @@ msgstr "Компьютер с Linux"
msgid "MB"
msgstr "МБ"
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
msgid "MTU must be 1280-1500."
msgstr "MTU: от 1280 до 1500."
#: web/src/shared/format.ts
msgid "Mbit/s"
msgstr "Мбит/с"
@@ -787,6 +907,18 @@ msgstr "Дата окончания - %s."
msgid "On GitHub"
msgstr "На GitHub"
#: web/src/portal/page/devices.ts
msgid "On two devices at once"
msgstr "На двух устройствах сразу"
#: web/src/shared/name-guard.ts
msgid "Only letters, digits, - _ ."
msgstr "Только буквы, цифры, - _ ."
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/devices.uc
msgid "Only the admin can change how a device connects."
msgstr "Менять настройки подключения устройства может только администратор."
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/devices.uc
msgid "Only the admin can turn devices off."
msgstr "Отключать устройства может только администратор."
@@ -898,10 +1030,6 @@ msgstr "Человек %s: сервера %s нет."
msgid "Phone"
msgstr "Телефон"
#: web/src/portal/flows/add.ts
msgid "Phones and tablets get a smaller packet size that suits mobile networks."
msgstr "У телефонов и планшетов пакеты меньше - так лучше для мобильных сетей."
#: web/src/portal/flows/setup-parts.ts
msgid "Pick AmneziaVPN in the share sheet. Not there? %s and add it in the app."
msgstr "Выберите AmneziaVPN в меню «Поделиться». Его там нет? %s и добавьте его в приложении."
@@ -948,6 +1076,10 @@ msgstr "Переподключить %s"
msgid "Reconnect %s?"
msgstr "Переподключить «%s»?"
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
msgid "RejectAfterTime must be at most 180 seconds."
msgstr "RejectAfterTime: не больше 180 секунд."
#: web/src/portal/flows/device-actions.ts
#: web/src/portal/page/devices.ts
msgid "Remove"
@@ -961,14 +1093,10 @@ msgstr "Удалить «%s»?"
msgid "Rename"
msgstr "Переименовать"
#: web/src/portal/flows/device-actions.ts
#: web/src/portal/page/devices.ts
msgid "Rename %s"
msgstr "Переименовать «%s»"
#: web/src/portal/flows/device-actions.ts
msgid "Renamed"
msgstr "Переименовано"
#: web/src/portal/api.ts
msgid "Request failed (%s)"
msgstr "Не удалось выполнить запрос (%s)"
@@ -981,6 +1109,10 @@ msgstr "Слишком большой запрос."
msgid "Resets on the 1st."
msgstr "Обнуляется 1-го числа."
#: web/src/portal/flows/rename.ts
msgid "Return to save, Esc to cancel"
msgstr "Return сохраняет, Esc отменяет"
#: web/src/shared/format.ts
msgid "Router"
msgstr "Роутер"
@@ -989,9 +1121,9 @@ msgstr "Роутер"
msgid "Run"
msgstr "Выполните"
#: web/src/portal/flows/device-actions.ts
msgid "Save"
msgstr "Сохранить"
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
msgid "S2 must not be S1 + 56: the handshake initiation and response would have the same size."
msgstr "S2 не может равняться S1 + 56: начальный и ответный пакеты рукопожатия будут одного размера."
#: web/src/portal/setup.ts
msgctxt "WireGuard app"
@@ -1022,6 +1154,10 @@ msgstr "Сервер выключен"
msgid "Server is turned off"
msgstr "Сервер выключен"
#: web/src/portal/flows/setup-view.ts
msgid "Set it up again"
msgstr "Настроить заново"
#: web/src/portal/flows/setup-view.ts
#: web/src/portal/page/devices.ts
msgid "Set up %s"
@@ -1083,6 +1219,10 @@ msgstr "Планшет"
msgid "Tap “%s” and connect"
msgstr "Нажмите «%s» и подключитесь"
#: web/src/portal/flows/rename.ts
msgid "That name is taken."
msgstr "Это имя уже занято."
#: web/src/portal/setup.ts
msgid "The APK is for phones without Google Play, or where the store hides the app."
msgstr "APK - для телефонов без Google Play или если магазин скрывает приложение."
@@ -1099,6 +1239,10 @@ msgstr "Приложение ставится на %s."
msgid "The browser may warn that the certificate is not trusted: it is this router’s own. Choose to continue (“Advanced” → “Proceed”)."
msgstr "Браузер может предупредить, что сертификату нельзя доверять: это собственный сертификат роутера. Продолжите переход («Дополнительные» → «Перейти на сайт»)."
#: web/src/portal/flows/setup-view.ts
msgid "The configuration is too long for a code. Scan this one to open your link on the %s instead."
msgstr "Конфигурация слишком длинная для QR-кода. Отсканируйте этот код, чтобы открыть свою ссылку на %s."
#: web/src/portal/flows/setup-parts.ts
msgid "The connection"
msgstr "Подключение"
@@ -1107,10 +1251,18 @@ msgstr "Подключение"
msgid "The connection as one key"
msgstr "Подключение одним ключом"
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
msgid "The header protection key is not a key."
msgstr "Ключ защиты заголовков некорректен."
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
msgid "The id may use lowercase letters, digits and underscores."
msgstr "В идентификаторе можно использовать строчные латинские буквы, цифры и подчёркивания."
#: web/src/portal/flows/setup-view.ts
msgid "The key is too long for a code. Scan this one to open your link on the %s instead."
msgstr "Ключ слишком длинный для QR-кода. Отсканируйте этот код, чтобы открыть свою ссылку на %s."
#: web/src/portal/flows/setup-view.ts
msgid "The packages and the file for OpenWrt"
msgstr "Пакеты и файл для OpenWrt"
@@ -1123,6 +1275,10 @@ msgstr "Не удалось загрузить страницу"
msgid "The person has no server."
msgstr "У человека нет сервера."
#: web/src/portal/page/devices.ts
msgid "The router can’t use what it sends: reconnect it."
msgstr "Роутер не принимает то, что отправляет устройство: переподключите его."
#: web/src/portal/flows/setup-parts.ts
msgid "Then come back here and tap"
msgstr "Затем вернитесь сюда и нажмите"
@@ -1131,10 +1287,18 @@ msgstr "Затем вернитесь сюда и нажмите"
msgid "Then import it in the app"
msgstr "Затем импортируйте его в приложении"
#: web/src/portal/page/devices.ts
msgid "This connection is on two devices and they push each other out. Add the other one as its own device."
msgstr "Это подключение стоит на двух устройствах, и они вытесняют друг друга. Добавьте второе как отдельное устройство."
#: web/src/portal/page/devices.ts
msgid "This device"
msgstr "Это устройство"
#: web/src/portal/flows/wait.ts
msgid "This device is using an outdated configuration."
msgstr "На этом устройстве устаревшая конфигурация."
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
msgid "This key is already in use."
msgstr "Этот ключ уже используется."
@@ -1168,6 +1332,10 @@ msgstr "Два шага, около минуты"
msgid "Two steps, about a minute: get the app, then add the connection."
msgstr "Два шага, около минуты: установите приложение, затем добавьте подключение."
#: web/src/portal/flows/wait.ts
msgid "Unable to complete the handshake"
msgstr "Не удаётся завершить рукопожатие"
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
msgid "Unknown DNS choice."
msgstr "Неизвестный вариант DNS."
@@ -1201,6 +1369,10 @@ msgstr "Неизвестный сервер."
msgid "Unknown service %s."
msgstr "Неизвестный сервис %s."
#: web/src/shared/name-guard.ts
msgid "Up to %s characters."
msgstr "Не больше %s символов."
#: web/src/portal/ui/bars.ts
msgid "Uploaded"
msgstr "Отправлено"
@@ -1275,6 +1447,14 @@ msgstr "Ваши устройства не подключатся, пока до
msgid "Your devices can’t connect until it’s resumed."
msgstr "Ваши устройства не подключатся, пока доступ не возобновят."
#: web/src/portal/flows/add.ts
msgid "Your local network stays reachable while connected."
msgstr "Ваша локальная сеть остаётся доступной при подключении."
#: web/src/portal/flows/wait.ts
msgid "Your network may be blocking the connection."
msgstr "Возможно, ваша сеть блокирует подключение."
#: web/src/shared/format.ts
msgid "bit/s"
msgstr "бит/с"
@@ -1323,10 +1503,6 @@ msgstr "закончится сегодня"
msgid "ends tomorrow"
msgstr "закончится завтра"
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
msgid "h1-h4 must be distinct"
msgstr "h1-h4 должны быть разными"
#: web/src/shared/format.ts
msgid "just now"
msgstr "только что"
+61 -11
View File
@@ -14,12 +14,13 @@ import { gone, call } from './api';
import { base, code, onRepaint, placeName, setState, state, type RepaintOpts, type State } from './state';
import { setupFromHash, wantsAdd } from './setup';
import { frame, crumbs, single } from './page/frame';
import { pageNotice, stateNotice } from './page/notices';
import { devicesSection, fillDevices } from './page/devices';
import { fillNotice, stateNotice } from './page/notices';
import { devicesNow, devicesSection, fillDevices } from './page/devices';
import { accessSection, fillAccess } from './page/access';
import { glass, type Tone } from './ui/glass';
import { closeMenu, menuOpen } from './ui/menu';
import { closeSheet, sheetOpen } from './ui/sheet';
import { renaming } from './flows/rename';
import { startAdd } from './flows/add';
import { openSetup } from './flows/setup-view';
@@ -34,10 +35,12 @@ let redraw: () => void = () => {};
/** The first paint comes in: the blocks rise one after the other, the sun rises behind its line. */
function intro() {
// In the order they stand on screen, top to bottom and then left to right: on a phone "Your access" comes before the devices.
const els = [...app.querySelectorAll('.crumbs, .notice, .sec-head, .dgrid > *, .note-s:not([hidden]), .acc-slot .acc-row, .gone')]
const blocks = [...app.querySelectorAll('.crumbs, .notice, .sec-head, .dgrid > *, .note-s:not([hidden]), .acc-slot .acc-row, .gone')]
.map((el) => ({ el, at: el.getBoundingClientRect() }))
.sort((a, b) => Math.round(a.at.top) - Math.round(b.at.top) || a.at.left - b.at.left)
.map((x) => x.el);
.sort((a, b) => Math.round(a.at.top) - Math.round(b.at.top) || a.at.left - b.at.left);
const els = blocks.map((x) => x.el);
// The wave starts at the first block on screen (a reload goes back deep into the page): those above it rise with it.
const above = blocks.filter((x) => x.at.bottom <= 0).length;
// Each block rises to its own opacity: a card the admin disabled is dimmed all the way, not at the end.
const own = els.map((el) => getComputedStyle(el).opacity);
els.forEach((el, i) =>
@@ -49,7 +52,7 @@ function intro() {
],
{
duration: 520,
delay: 60 + i * 40,
delay: 60 + Math.max(0, i - above) * 40,
easing: EASE_OUT,
fill: 'backwards',
},
@@ -84,18 +87,63 @@ function render(o: RepaintOpts = {}) {
single(false);
crumbs();
document.title = placeName();
// Safari lays the page out once with the new cards still empty (each is a size container, devices.css) and
// pulls the scroll up to fit that shorter page; a language change empties it all. The content keeps its height
// while it is refilled, and lets go once everything in it has its styles.
slot.style.minHeight = `${slot.offsetHeight}px`;
const fresh = !parts;
if (!parts) {
parts = { notice: h('div', { class: 'notice-slot' }), devices: devicesSection(), access: accessSection() };
put(slot, parts.notice, h('div', { class: 'cols' }, parts.devices, parts.access));
}
// Where the cards stand before anything above them changes: the notice and, on a phone, "Your access" move them too.
const devices = devicesNow(parts.devices);
// What stops the devices comes first.
put(parts.notice, pageNotice(st.person));
fillDevices(parts.devices, st, o);
fillNotice(parts.notice, st.person, !fresh);
fillAccess(parts.access, st);
if (!booted) intro();
fillDevices(parts.devices, st, o, devices);
slot.getBoundingClientRect();
slot.style.minHeight = '';
if (!booted) {
const y = keptPlace();
if (y) scrollTo(0, y);
intro();
}
}
onRepaint(render);
/*
* A phone drops a tab while the visitor is in another app (the VPN app, the App Store) and loads it again on
* return; a pull to refresh loads it again too. The browser puts the page back where it was as it loads, before
* the router has answered: the page is one empty screen then, so it stays at the top. The tab keeps the page's
* place itself, and the first paint of a reload (or of a step back onto the page) goes back there; a fresh visit
* to the link still opens at the top. Each link keeps its own (several people's links opened in one tab share the
* origin), and only the page drawn in its place has one: hidden before the router answered, or showing a card in
* place of the page, the tab keeps the place it had.
*/
const PLACE = `dl.y:${location.pathname}`;
function keepPlace() {
if (!parts) return;
try {
sessionStorage.setItem(PLACE, String(Math.round(scrollY)));
} catch {
// No storage (a private window that refuses it): a reload opens at the top.
}
}
function keptPlace(): number {
const how = (performance.getEntriesByType('navigation')[0] as PerformanceNavigationTiming | undefined)?.type;
if (how !== 'reload' && how !== 'back_forward') return 0;
try {
return Number(sessionStorage.getItem(PLACE)) || 0;
} catch {
return 0;
}
}
addEventListener('pagehide', keepPlace);
document.addEventListener('visibilitychange', () => {
if (document.hidden) keepPlace();
});
/** A card in place of the page: the link stopped working, nothing could load, or the access is paused. */
function only(icon: string, title: string, text: string, gone = false, tone: Tone = 'grey') {
parts = null;
@@ -134,14 +182,16 @@ function openFromLink() {
history.replaceState(null, '', location.pathname + location.search);
if (add) return startAdd();
const d = st.person.devices.find((x) => x.id === id);
if (d && !d.handshake && !d.disabled && !st.locked) void openSetup(d);
// Its own link: the page is open on that device.
if (d && !d.handshake && !d.disabled && !st.locked) void openSetup(d, null, true);
}
addEventListener('hashchange', openFromLink);
async function refresh() {
try {
setState(await call<State>('state'));
if (!sheetOpen() && !menuOpen()) render();
// Not under an open sheet or menu, nor a name being edited on its card.
if (!sheetOpen() && !menuOpen() && !renaming()) render();
openFromLink();
} catch (e) {
if (gone(e)) linkGone();
+5
View File
@@ -93,6 +93,11 @@ export function rubber(dist: number, dim: number): number {
return dist <= 0 || dim <= 0 ? 0 : (1 - 1 / ((dist * 0.55) / dim + 1)) * dim;
}
/** How far a pull goes for an edge to stand `d` past it: rubber() undone (a sheet taken while it settles back). */
export function unrubber(d: number, dim: number): number {
return d <= 0 || dim <= 0 ? 0 : (d * dim) / (0.55 * Math.max(1, dim - d));
}
/**
* Does a pulled sheet go away? A flick down (px/ms, as Vaul) or a pull past a
* third of its height does; a flick back up keeps it, however far it went.
+113 -8
View File
@@ -2,20 +2,23 @@
// access reaches (home and internet as two tiles, and the names devices at
// home reach this person's devices by); the data, as a ring in the head and
// the month day by day inside; and until when, as the days left over a
// calendar of the weeks, with the admin's hours as a bar of the day.
// calendar of the weeks, with the admin's hours as a bar of the day. A repaint
// keeps the rows on the page and changes what they hold in place.
import type { Pair, Person } from '../../shared/types';
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 { SMOOTH, play } from '../motion';
import { now, today, type State } from '../state';
import { accordion, type Accordion } from '../ui/accordion';
import { accordion, regrow, type Accordion } from '../ui/accordion';
import { bars, upDown } from '../ui/bars';
import { copy } from '../ui/feedback';
import { glass } from '../ui/glass';
import { morphChanged, setText, textsOf } from '../ui/morph';
import { morphChanged, morphInto, setText, textOf, textsOf } from '../ui/morph';
import { reachableFromHome } from './devices';
import { holdFoot } from './frame';
const desc = (text: string) => h('p', { class: 'desc' }, text);
/** A share of a length, as a CSS percentage. */
@@ -266,7 +269,7 @@ export function accessAccordion(st: State, open = 1): Accordion {
// 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 },
],
{ open },
{ open, hold: holdFoot },
);
}
@@ -280,13 +283,115 @@ export function accessSection(): HTMLElement {
);
}
/**
* Markup to compare: each keyed value as the words it says (one still morphing, those it turns into), less the ids
* each glass icon makes up (the same icon twice is the same).
*/
function plain(el: Element, inner = false): string {
const c = el.cloneNode(true) as Element;
const keyed = el.querySelectorAll<HTMLElement>('[data-t]');
c.querySelectorAll<HTMLElement>('[data-t]').forEach((k, i) => {
k.textContent = textOf(keyed[i]);
k.classList.remove('mt', 'mt-ib');
});
return (inner ? c.innerHTML : c.outerHTML).replace(/\bgl\d+/g, 'gl');
}
/**
* The rows on the page take the new rows' content in place, so what moves in
* them goes on (a row opening or folding, the calendar's days coming in, a
* value still morphing into the same words): keyed values in a head take their
* new words (they morph afterwards, morphChanged), a head swaps only the parts
* that changed (its click stays the row's own), and a body takes its new
* content (`refillBody`). Rows of another shape (an end date set or taken
* away) can't: null. Returns what came in whole.
*/
function refill(acc: HTMLElement, next: HTMLElement): Element[] | null {
const rows = [...acc.children] as HTMLElement[];
const news = [...next.children] as HTMLElement[];
if (rows.length !== news.length || rows.some((r, i) => r.classList.contains('still') !== news[i].classList.contains('still')))
return null;
const fresh: Element[] = [];
rows.forEach((r, i) => {
const [head, body] = [...r.children] as HTMLElement[];
const [nh, nb] = [...news[i].children] as HTMLElement[];
for (const el of head.querySelectorAll<HTMLElement>('[data-t]')) {
const n = nh.querySelector(`[data-t="${el.dataset.t}"]`);
if (n && textOf(el) !== n.textContent) setText(el, n.textContent ?? '');
}
if (head.children.length !== nh.children.length) head.replaceChildren(...nh.childNodes);
else
[...nh.children].forEach((y, k) => {
const x = head.children[k];
if (plain(x) === plain(y)) return;
// The same box (the value that hides while the row is open) keeps its own fade and takes the new content.
if (x.tagName === y.tagName && x.className === y.className) x.replaceChildren(...y.childNodes);
else x.replaceWith(y);
});
fresh.push(...refillBody(r, body, nb));
});
return fresh;
}
/** Open bodies whose days are still coming in, with what each shows once they are in. */
const waiting = new WeakMap<HTMLElement, HTMLElement>();
/**
* A row's body takes the new one's content: shut, at once; open or still
* closing, where it stands (morphInto: a crossing piece keeps its old words as
* it fades) while the row glides to its new height. The calendar's days still
* coming in finish their cascade first: the body changes once they are in, to
* what the last repaint brought. Returns what came in whole.
*/
function refillBody(r: HTMLElement, body: HTMLElement, nb: HTMLElement): Element[] {
if (waiting.has(body)) {
waiting.set(body, nb);
return [];
}
if (plain(body, true) === plain(nb, true)) return [];
if (!r.classList.contains('open') && !r.classList.contains('closing')) {
body.replaceChildren(...nb.childNodes);
return [];
}
const days = [...body.querySelectorAll('.cal-g i')].flatMap((c) => c.getAnimations());
if (days.length) {
waiting.set(body, nb);
void Promise.all(days.map((a) => a.finished.catch(() => undefined))).then(() => {
const n = waiting.get(body)!;
waiting.delete(body);
if (!r.isConnected) return;
const said = textsOf(body);
morphChanged(body, said, refillBody(r, body, n));
});
return [];
}
// Its days came in when it opened: what comes now is the change alone.
r.classList.remove('opened');
const h0 = r.getBoundingClientRect().height;
const moving = r.getAnimations().length > 0;
const came = morphInto(body, [...nb.childNodes]);
// Opening or folding still: that glide heads for the new height instead.
if (moving) regrow(body);
else {
const h1 = r.getBoundingClientRect().height;
if (Math.abs(h1 - h0) > 0.5)
play(r, [{ height: `${h0}px` }, { height: `${h1}px` }], { duration: SMOOTH.duration, easing: SMOOTH.easing });
}
return came;
}
let shown: Accordion | null = null;
/** The accordion for this state, the same row open as before. */
/** The accordion for this state, the same row open as before: the rows on the page stay when they can (`refill`). */
export function fillAccess(section: HTMLElement, st: State) {
const slot = section.querySelector('.acc-slot') as HTMLElement;
const acc = accessAccordion(st, shown ? shown.openIndex() : 1);
// The values it showed: what changed morphs from it.
const said = textsOf(section);
section.querySelector('.acc-slot')!.replaceChildren(acc.el);
if (shown) morphChanged(section, said);
shown = acc;
const had = !!shown;
const fresh = shown && slot.contains(shown.el) ? refill(shown.el, acc.el) : null;
if (!fresh) {
slot.replaceChildren(acc.el);
shown = acc;
}
if (had) morphChanged(section, said, fresh ?? []);
}
+242 -45
View File
@@ -1,29 +1,54 @@
// "Your devices": a card per device (the one this page is open on first, then
// by state), the card to add one, and the count. A repaint keeps the grid:
// cards that stay glide to their new places, a new one pops in, one that just
// cards that stay glide to their new places and heights (Connect turned into
// the week crosses where it stands), a new one pops in, one that just
// connected rings green for a moment. What a card's buttons start lives in
// flows/.
import type { Device, Person } from '../../shared/types';
import type { Device, LinkState, Person } from '../../shared/types';
import { addDays, ago, byDeviceState, 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 { BOUNCY, EASE_IN, EASE_OUT, SMOOTH, calm, play } from '../motion';
import { now, today, type RepaintOpts, type State } from '../state';
import { bars, sumDays, upDown } from '../ui/bars';
import { copy } from '../ui/feedback';
import { glass } from '../ui/glass';
import { openMenu, type MenuItem } from '../ui/menu';
import { morphChanged, morphText, setText, textsOf } from '../ui/morph';
import { appear, fadeAway, look, morphChanged, morphText, setText, textsOf, type Look } from '../ui/morph';
import { startAdd } from '../flows/add';
import { reconnect, removeDevice, rename } from '../flows/device-actions';
import { reconnect, removeDevice } from '../flows/device-actions';
import { renameOnCard } from '../flows/rename';
import { openSetup } from '../flows/setup-view';
/** The home network can open connections to it: home access, active, and the device on. */
export const reachableFromHome = (p: Person, d: Device) => p.access !== 'internet' && p.state === 'active' && !d.disabled;
/** 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] {
/** A link failing in a named way (the router's watcher held it 3 minutes): the card's line, and why. */
function linkWords(s: LinkState): [string, string] {
switch (s) {
case 'trying':
return [
_('Can’t finish connecting'),
_('It reaches the router, but the connection never completes. The network may be blocking it.'),
];
case 'dropped':
return [_('Connected, but no data'), _('The router can’t use what it sends: reconnect it.')];
case 'shared':
return [
_('On two devices at once'),
_('This connection is on two devices and they push each other out. Add the other one as its own device.'),
];
case 'unstable':
return [_('Connection keeps dropping'), _('It connects, but the connection breaks every few minutes. Another network may help.')];
}
}
/**
* The status line: its class and words (short, on one line; the full wording shows on hover), and for a link
* failing in a named way, why (its hover).
*/
function statusOf(d: Device, p: Person): [string, string, string?] {
if (d.disabled) return ['', _('Disabled')];
// The Reconnect button under it says what to do.
if (d.config_stale && d.handshake) return ['warn-t', _('Settings changed')];
@@ -31,11 +56,38 @@ function statusOf(d: Device, p: Person): [string, string] {
// "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.link) return ['warn-t', ...linkWords(d.link.state)];
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()))];
}
/**
* The card's name. One the person may change is a button too: a click, Return or Space edits it in place
* (flows/rename.ts), as Rename in the ⋯ menu does.
*/
function nameOf(d: Device, editable: boolean): HTMLElement {
const el = h('span', { class: 'dev-name', 'data-t': `${d.id}:name` }, d.name);
if (!editable) return el;
el.classList.add('can-edit');
el.setAttribute('role', 'button');
el.tabIndex = 0;
el.setAttribute('aria-label', fmt(_('Rename %s'), d.name));
el.addEventListener('click', () => renameHere(d));
el.addEventListener('keydown', (e) => {
if (e.key !== 'Enter' && e.key !== ' ') return;
e.preventDefault();
renameHere(d);
});
return el;
}
/** Edit `d`'s name on its card, wherever the card is now (ui: flows/rename.ts). */
function renameHere(d: Device) {
const card = document.querySelector<HTMLElement>(`.dev[data-id="${CSS.escape(d.id)}"]`);
if (card) renameOnCard(d, card);
}
function menuItems(d: Device, st: State): (MenuItem | null)[] {
return [
// How devices at home reach it: only where the router actually lets them through.
@@ -50,7 +102,7 @@ function menuItems(d: Device, st: State): (MenuItem | null)[] {
...(d.disabled
? []
: [
{ label: _('Rename'), icon: 'edit', run: () => rename(d) },
{ label: _('Rename'), icon: 'edit', run: () => renameHere(d) },
{ label: _('Reconnect'), icon: 'refresh', tone: 'warn' as const, run: () => reconnect(d) },
{ label: _('Remove'), icon: 'trash', tone: 'bad' as const, run: () => removeDevice(d) },
]),
@@ -91,16 +143,19 @@ 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, why] = 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.
// Connected, but nothing it sends gets through (an old configuration): new keys fix it, as changed settings.
const renew = (d.config_stale || d.link?.state === 'dropped') && !setUp && !locked && !d.disabled;
// On one line; why, the exact time, or the whole wording, on hover.
const title =
!here && d.handshake && !d.online && !d.disabled && !d.config_stale
why ??
(!here && d.handshake && !d.online && !d.disabled && !d.config_stale
? new Date(d.handshake * 1000).toLocaleString(locale())
: stale
? _('Settings changed, update needed')
: words;
: words);
const items = menuItems(d, st);
const more =
locked || !items.length
@@ -127,13 +182,17 @@ function card(d: Device, st: State): HTMLElement {
h(
'div',
{ class: 'dev-id' },
h('span', { class: 'dev-name', 'data-t': `${d.id}:name` }, d.name),
nameOf(d, !d.disabled && !locked),
h('span', { class: `dev-stat ${cls}`, title, 'data-t': `${d.id}:stat` }, words),
// Why a link fails: a pointer reads it on hover, a screen reader right after the status (a touch screen
// has neither; the card keeps its one line).
why ? h('span', { class: 'offscreen' }, why) : null,
),
more,
),
// Stopped by the admin: a device never set up has nothing to show. Its settings changed: Reconnect in
// place of its week (new keys, then set it up again), as a device not set up yet shows Connect.
// Stopped by the admin: a device never set up has nothing to show. Its settings changed, or no data gets
// through: Reconnect in place of its week (new keys, then set it up again), as a device not set up yet shows
// Connect.
setUp && locked
? null
: setUp
@@ -148,7 +207,7 @@ function card(d: Device, st: State): HTMLElement {
ic('qr'),
h('span', {}, _('Connect')),
)
: stale
: renew
? h(
'button',
{
@@ -214,13 +273,77 @@ function snapOnJump(grid: HTMLElement) {
}).observe(grid);
}
/** The cards for this state, moving from where they were. */
export function fillDevices(section: HTMLElement, st: State, o: RepaintOpts = {}) {
/** The green ring of a device that just connected (its animation's id, to find it again on a repaint). */
const RING = 'ring';
/** What a card ends in (Connect, Reconnect or its week), and which of them (a button by its words). */
const footOf = (c: Element) => c.querySelector<HTMLElement>(':scope > .dev-use, :scope > .setup-btn');
const footKind = (f: HTMLElement | null) => (!f ? '' : f.classList.contains('dev-use') ? 'use' : (f.textContent ?? ''));
/** A card as it stood before a repaint. */
interface CardWas {
el: HTMLElement;
at: DOMRect;
shows: Look;
/** What it ended in, which kind, where it stood and how it showed: one of another kind crosses. */
foot: { el: HTMLElement; kind: string; at: DOMRect; shows: Look } | null;
/** How far its green ring had faded (ms), while it still shows. */
ring: number | null;
}
/** "Your devices" as it stands: each card, and where the note under them stood (if it showed). */
export interface DevicesWas {
cards: Map<string, CardWas>;
note: DOMRect | null;
}
/** "Your devices" as it stands: read before anything above it changes (the notice; on a phone, "Your access"). */
export function devicesNow(section: HTMLElement): DevicesWas {
const note = section.querySelector('.limit') as HTMLElement;
// Not a card still fading out where it stood (laid over the grid, hidden from screen readers).
const cards = [...section.querySelectorAll<HTMLElement>('.dgrid > [data-id]:not([aria-hidden])')].map((c): [string, CardWas] => {
const f = footOf(c);
const ring = c.getAnimations().find((a) => a.id === RING);
return [
c.dataset.id!,
{
el: c,
at: c.getBoundingClientRect(),
shows: look(c),
foot: f && { el: f, kind: footKind(f), at: f.getBoundingClientRect(), shows: look(f) },
ring: ring ? Number(ring.currentTime) : null,
},
];
});
return { cards: new Map(cards), note: note.hidden ? null : note.getBoundingClientRect() };
}
/**
* The green ring of a device that just connected fades into the card's own (this device's blue one, or none);
* `from`: a ring already fading on the card a repaint rebuilt goes on from there.
*/
function ring(c: HTMLElement, from: number) {
const own = getComputedStyle(c).boxShadow;
c.animate([{ boxShadow: 'inset 0 0 0 1.5px var(--ok)' }, { boxShadow: own === 'none' ? 'inset 0 0 0 1.5px transparent' : own }], {
duration: 1800,
easing: 'ease-out',
id: RING,
}).currentTime = from;
}
/**
* The cards for this state, moving from where they were (`was`: read before
* what stands above them changed). A card that changes height (another foot, a
* row that no longer stretches it) glides to it; a foot of another kind
* crosses, the old one fading where it stood as the new one blurs in; a card
* no longer there (Add device once the last slot is taken) fades where it
* stood.
*/
export function fillDevices(section: HTMLElement, st: State, o: RepaintOpts = {}, was = devicesNow(section)) {
const p = st.person;
const grid = section.querySelector('.dgrid') as HTMLElement;
// A repaint (not the first paint, which brings everything in): what newly shows comes in too.
const repainting = grid.childElementCount > 0;
const first = new Map([...grid.querySelectorAll<HTMLElement>('[data-id]')].map((c) => [c.dataset.id, c.getBoundingClientRect()]));
// What each card said (a name, its status, its week): what changed morphs from it once the cards are in place.
const said = textsOf(grid);
// The device this page was opened from comes first.
@@ -233,8 +356,27 @@ export function fillDevices(section: HTMLElement, st: State, o: RepaintOpts = {}
else if (st.can_add && !st.locked) cards.push(addCard());
grid.classList.toggle('empty', !p.devices.length);
grid.replaceChildren(...cards);
const heights = cards.map((c) => c.getBoundingClientRect().height);
cards.forEach((c, i) => {
const w = was.cards.get(c.dataset.id!);
if (!w || c.dataset.id === o.pop) return;
const foot = footOf(c);
if ((w.foot?.kind ?? '') !== footKind(foot)) {
if (w.foot) fadeAway(w.foot.el, w.foot.at, c, w.at, w.foot.shows);
if (foot) appear(foot);
}
// What it holds is clipped to it on the way (a taller foot would hang out of it).
if (Math.abs(w.at.height - heights[i]) > 0.5) {
c.style.overflow = 'clip';
play(c, [{ height: `${w.at.height}px` }, { height: `${heights[i]}px` }], {
duration: SMOOTH.duration,
easing: SMOOTH.easing,
}).onfinish = () => (c.style.overflow = '');
}
});
// Places once the heights set off: a card under one that grows rides along with it.
for (const c of cards) {
const f = first.get(c.dataset.id);
const f = was.cards.get(c.dataset.id!)?.at;
const l = c.getBoundingClientRect();
if (c.dataset.id === o.pop)
play(
@@ -268,12 +410,16 @@ export function fillDevices(section: HTMLElement, st: State, o: RepaintOpts = {}
fill: 'backwards',
},
);
if (c.dataset.id === o.flash)
c.animate([{ boxShadow: 'inset 0 0 0 1.5px var(--ok)' }, { boxShadow: 'inset 0 0 0 1.5px transparent' }], {
duration: 1800,
easing: 'ease-out',
});
const r = c.dataset.id === o.flash ? 0 : was.cards.get(c.dataset.id!)?.ring;
if (r != null) ring(c, r);
}
const ids = new Set(cards.map((c) => c.dataset.id));
const g = grid.getBoundingClientRect();
for (const [id, w] of was.cards)
if (!ids.has(id)) {
w.el.style.height = `${w.at.height}px`;
fadeAway(w.el, w.at, grid, g, w.shows);
}
if (repainting) morphChanged(grid, said);
const count = section.querySelector('.sec-head .aside') as HTMLElement;
const n = fmt(_('%s of %s'), num(p.devices.length), num(p.device_limit));
@@ -282,38 +428,89 @@ export function fillDevices(section: HTMLElement, st: State, o: RepaintOpts = {}
// The admin may add devices past the limit.
count.classList.toggle('warn-t', p.devices.length > p.device_limit);
const limit = section.querySelector('.limit') as HTMLElement;
const was = limit.hidden;
const hide = st.can_add || !!st.locked;
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) {
const a = play(
limitNote(limit, st.can_add || !!st.locked, repainting, was.note);
}
/**
* The note that the limit is reached. It rises in under the cards when the
* last slot is taken; when one frees up it fades the way it came while its
* space folds away (on a phone it ends the page: a page scrolled to its foot
* then moves down with it instead of dropping), then leaves the layout. Each
* from where it stands, one turned back half-way included.
*/
function limitNote(limit: HTMLElement, hide: boolean, repainting: boolean, at: DOMRect | null) {
const cs = getComputedStyle(limit);
const stood = {
opacity: cs.opacity,
filter: cs.filter,
transform: cs.transform,
height: `${limit.offsetHeight}px`,
marginTop: cs.marginTop,
};
const prior = limit.getAnimations();
const shown = !limit.hidden;
if (repainting && hide && shown) {
const fade = play(
limit,
[
{ opacity: 1, filter: 'none' },
{ opacity: 0, filter: 'blur(4px)' },
{ opacity: stood.opacity, filter: stood.filter, transform: stood.transform },
{ opacity: 0, filter: 'blur(4px)', transform: stood.transform },
],
{ duration: 200, easing: EASE_IN, fill: 'forwards' },
{ duration: 200 * +stood.opacity, easing: EASE_IN, fill: 'forwards' },
);
a.onfinish = () => {
// With less motion nothing folds: it fades, then is gone with its space.
const fold = calm()
? null
: play(
limit,
[
{ height: stood.height, marginTop: stood.marginTop },
{ height: '0px', marginTop: '0px' },
],
{ duration: SMOOTH.duration, easing: SMOOTH.easing, fill: 'forwards' },
);
prior.forEach((a) => a.cancel());
(fold ?? fade).onfinish = () => {
limit.hidden = true;
a.cancel();
fade.cancel();
fold?.cancel();
};
} else {
prior.forEach((a) => a.cancel());
limit.hidden = hide;
if (repainting && was && !hide)
play(
limit,
[
{ opacity: 0, transform: 'translateY(6px)', filter: 'blur(4px)' },
{ opacity: 1, transform: 'none', filter: 'none' },
],
{ duration: 420, easing: EASE_OUT },
);
}
if (!repainting || hide) return glideFrom(limit, at);
if (!shown)
play(
limit,
[
{ opacity: 0, transform: 'translateY(6px)', filter: 'blur(4px)' },
{ opacity: 1, transform: 'none', filter: 'none' },
],
{ duration: 420, easing: EASE_OUT },
);
// Folding away when it was needed again: it opens back from where it stood.
else if (prior.length)
play(
limit,
[
stood,
{ opacity: 1, filter: 'none', transform: 'none', height: `${limit.offsetHeight}px`, marginTop: getComputedStyle(limit).marginTop },
],
{ duration: SMOOTH.duration, easing: SMOOTH.easing },
);
glideFrom(limit, at);
}
/** The note, shown before and still in the page, glides from where it stood as the cards do (one came in above it). */
function glideFrom(limit: HTMLElement, at: DOMRect | null) {
if (!at || limit.hidden) return;
const dy = at.top - limit.getBoundingClientRect().top;
if (Math.abs(dy) > 0.5)
play(limit, [{ translate: `0 ${dy}px` }, { translate: '0 0' }], { duration: SMOOTH.duration, easing: SMOOTH.easing });
}
+31 -1
View File
@@ -2,9 +2,11 @@
// 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, then the language and this page's code. The
// content goes in `body`.
// content goes in `body`, which holds its height while a fold near the page's
// foot takes the scroll down with it (`holdFoot`).
import { h, ic, markup } from '../dom';
import { EASE_OUT, SOFT, play } from '../motion';
import { placeName, state } from '../state';
import { showPageCode } from '../flows/page-code';
import { openMenu } from '../ui/menu';
@@ -35,6 +37,34 @@ export function frame(app: HTMLElement): HTMLElement {
return bodyEl;
}
/**
* The page keeps its height while something in it takes a shorter shape (an
* access row folding): with no scroll anchoring (base.css), a page scrolled
* near its foot would drop to its new end on the frame that shape is measured.
* Held at what the scroll needs, it lets go once the new shape is known (what
* this returns), on an ease that never overshoots, so the scroll follows the
* fold down frame by frame and stops at the new foot. Still tall enough, it
* lets go at once.
*/
export function holdFoot(): () => void {
const body = bodyEl;
if (!body) return () => {};
// Read as it stands (a hold still letting go included), then taken over.
const r = body.getBoundingClientRect();
// Tall enough for the page's foot to stay at the bottom of the screen: the scroll and the screen, less what is
// above the body and under it.
const need = innerHeight - r.top - (document.documentElement.scrollHeight - scrollY - r.bottom);
body.getAnimations().forEach((a) => a.cancel());
body.style.minHeight = `${need}px`;
return () => {
const last = body.lastElementChild;
const end = last ? last.getBoundingClientRect().bottom - body.getBoundingClientRect().top : 0;
body.style.minHeight = '';
if (end < need - 0.5)
play(body, [{ minHeight: `${need}px` }, { minHeight: `${end}px` }], { duration: SOFT.duration, easing: EASE_OUT });
};
}
/** One card in place of the page (the link gone, nothing loaded, access paused): it and the breadcrumb sit in the middle of the screen. */
export function single(on: boolean) {
pageEl?.classList.toggle('single', on);
+26 -2
View File
@@ -1,14 +1,18 @@
// What stops the person's devices, said once at the top of the page: paused,
// ended, out of data, outside the hours, the server off or missing, or access
// ending soon. A notice wears its tone (orange or red) in its tint.
// ending soon. A notice wears its tone (orange or red) in its tint. On a
// repaint it comes, goes or changes in place while its slot glides to its new
// height, so the page under it moves instead of jumping.
import type { Person } from '../../shared/types';
import { daysLeft, date, endsIn, endsSoon } from '../../shared/format';
import { fmt } from '../../shared/i18n';
import { h } from '../dom';
import { h, put } from '../dom';
import { SMOOTH, play } from '../motion';
import { clockOf, hoursFor } from '../days';
import { state, today } from '../state';
import { glass } from '../ui/glass';
import { appear, morphInto } from '../ui/morph';
export type Tone = 'warn' | 'bad';
@@ -55,3 +59,23 @@ export function pageNotice(p: Person): HTMLElement | null {
? notice('warn', 'calendar', fmt(_('Access %s'), endsIn(left as number)), fmt(_('On %s.'), date(p.expires)))
: null;
}
/**
* The page's notice in its slot. On a repaint one that comes blurs in, one that
* goes fades where it stood, one that changes morphs in place (ui/morph.ts),
* and the slot glides from its height on screen to the new one (the slot holds
* the notice's margin and clips it on the way: page.css).
*/
export function fillNotice(slot: HTMLElement, p: Person, repainting: boolean) {
const n = pageNotice(p);
if (!repainting) return put(slot, n);
const h0 = slot.getBoundingClientRect().height;
// A notice that was there (one fading out lies over the slot, hidden from screen readers).
const had = !!slot.querySelector(':scope > .notice:not([aria-hidden])');
slot.getAnimations().forEach((a) => a.cancel());
morphInto(slot, n);
if (n && !had) appear(n);
const h1 = slot.getBoundingClientRect().height;
if (Math.abs(h1 - h0) > 0.5)
play(slot, [{ height: `${h0}px` }, { height: `${h1}px` }], { duration: SMOOTH.duration, easing: SMOOTH.easing });
}
+9 -3
View File
@@ -26,12 +26,18 @@ export function platformOf(ua: string, touchPoints = 0): Platform {
/** A browser inside another app (Telegram, Instagram…): vpn:// and the share sheet do not work there. */
export const inWebview = (ua: string): boolean => /Telegram|FBAN|FBAV|Instagram|VKClient|Line\//i.test(ua);
/** Is the page open on the device being set up? A router never is; an unknown platform never counts. */
export function sameDevice(kind: Kind, platform: Platform): boolean {
/**
* Is the page open on the device being set up? A router never is; an unknown
* platform never counts. Something else (a TV, a box, a NAS) counts when the
* page came from its own set-up link (`here`: it is open there, an Android TV
* included) or on a computer's system: added from a phone, it is not the
* phone in hand.
*/
export function sameDevice(kind: Kind, platform: Platform, here = false): boolean {
if (kind === 'router' || platform === 'unknown') return false;
if (kind === 'phone' || kind === 'tablet') return platform === 'ios' || platform === 'android';
if (kind === 'computer') return platform === 'windows' || platform === 'mac' || platform === 'linux';
return true;
return here || platform === 'windows' || platform === 'mac' || platform === 'linux';
}
export interface AppChoice {
+2 -1
View File
@@ -11,7 +11,8 @@ export interface State {
person: Person;
/** device_mesh: devices with home access reach each other through the tunnel. */
/** awg_disguise: false = plain WireGuard, any WireGuard app connects. */
server: { name?: string; endpoint: string; device_mesh?: boolean; awg_disguise?: boolean; preset?: Preset };
/** home: the home networks a device with LAN Bypass still sends into the tunnel (home and internet access). */
server: { name?: string; endpoint: string; device_mesh?: boolean; awg_disguise?: boolean; preset?: Preset; home?: string[] };
/** The device this page was opened from (through the tunnel), if any. */
here?: string | null;
can_add: boolean;
+33 -4
View File
@@ -84,7 +84,7 @@
align-items: center;
gap: 8px;
}
.acc-row.open .acc-val.hide-open {
.acc-row.open > .acc-head > .acc-val.hide-open {
opacity: 0;
filter: blur(4px);
transform: translateX(8px);
@@ -97,15 +97,17 @@
transform: rotate(90deg);
transition: transform var(--spring-soft-dur, 470ms) var(--spring-soft, ease);
}
.acc-row.open .acc-chev {
/* Only the row's own head and body: a row inside an open row keeps its own state (the router's
"Configuration" inside "Set it up again"). */
.acc-row.open > .acc-head > .acc-chev {
transform: rotate(-90deg);
}
.acc-body {
display: none;
padding: 0 8px 16px 40px;
}
.acc-row.open .acc-body,
.acc-row.closing .acc-body {
.acc-row.open > .acc-body,
.acc-row.closing > .acc-body {
display: flex;
flex-direction: column;
gap: 12px;
@@ -128,6 +130,33 @@
.acc.inset .seg {
background: color-mix(in srgb, var(--knob) 65%, var(--field));
}
/* Steps inside an inset row ("Set it up again") sit on field: their badges step up as the picker
does, and one step more on hover. */
.acc.inset .badge {
background: color-mix(in srgb, var(--knob) 65%, var(--field));
}
.acc.inset .badge:hover {
background: var(--knob);
}
/* The router's file step inside an inset row: its card, its inset "Configuration" row and what
that row opens step up one the same way; its buttons one more, and one more again on hover. */
.acc.inset .filecard,
.acc.inset .acc.inset .acc-row {
background: color-mix(in srgb, var(--knob) 65%, var(--field));
}
.acc.inset .acc.inset .acc-row:not(.open):not(.still):hover {
background: var(--knob);
}
.acc.inset .filecard-ic,
.acc.inset .acc.inset .btn.soft {
background: color-mix(in srgb, var(--knob), var(--text) 6%);
}
.acc.inset .acc.inset .btn.soft:hover {
background: color-mix(in srgb, var(--knob), var(--text) 12%);
}
.acc.inset .acc.inset .conf {
background: var(--knob);
}
@media (prefers-reduced-motion: reduce) {
.acc-chev {
+4
View File
@@ -8,6 +8,10 @@ html {
-webkit-text-size-adjust: 100%;
/* The page keeps its width when a sheet locks the scroll: no sideways jump behind the scrim. */
scrollbar-gutter: stable;
/* No scroll anchoring: on a phone "Your access" shows above the devices but comes after them in the page
(main.ts), so the browser would hold "Your devices" still while an access row opens or folds, and pull a page
scrolled less than the fold to the very top. A row grows and folds in place; a repaint glides what moves. */
overflow-anchor: none;
}
body {
margin: 0;
+245 -6
View File
@@ -1,6 +1,7 @@
/* The controls every part uses: round knobs, buttons (and their busy orb), the field with its
go button, the icon picker, the kinds with their ring, badges, hints and menu paths, the link row,
QR codes and the row that puts a code beside its words. */
go button and its own caret and selection, the icon picker, the kinds with their ring, the option
row with its switch, badges, hints and menu paths, the link row, QR codes and the row that puts a
code beside its words. */
.knob {
width: 32px;
@@ -199,7 +200,7 @@
gap: 12px;
padding: 0 4px 0 16px;
overflow: hidden;
transition: box-shadow 200ms var(--ease-out);
transition: box-shadow var(--spring-smooth-dur, 524ms) var(--spring-smooth, ease);
}
.field:focus-within {
box-shadow: inset 0 0 0 1.5px color-mix(in srgb, var(--text) 16%, transparent);
@@ -228,8 +229,8 @@
place-items: center;
flex: none;
transition:
background-color 200ms var(--ease-out),
color 200ms var(--ease-out),
background-color var(--spring-smooth-dur, 524ms) var(--spring-smooth, ease),
color var(--spring-smooth-dur, 524ms) var(--spring-smooth, ease),
transform 200ms var(--ease-out);
}
.go .i {
@@ -247,6 +248,142 @@
cursor: not-allowed;
}
/* The field's own caret (ui/caret.ts): the input's is hidden, ours glides to where the next letter
goes. As macOS draws it (Sonoma, NSTextInsertionIndicator): the accent, a 2 px capsule the line's
height, on for 0.6 s and off for 0.6 s with a soft fade either way; solid while typing, blinking
again 0.5 s after the last key. */
.field.own-caret {
position: relative;
}
.field.own-caret input {
caret-color: transparent;
}
.caret {
position: absolute;
left: 0;
top: 50%;
width: 2px;
height: 20px;
margin-top: -10px;
border-radius: 1px;
background: var(--accent);
pointer-events: none;
opacity: 0;
transition: opacity 100ms linear;
will-change: transform;
}
.caret.on {
opacity: 1;
}
.caret.on.blink {
animation: caret-blink 1.2s ease-in-out infinite;
}
@keyframes caret-blink {
0%,
38% {
opacity: 1;
}
50%,
88% {
opacity: 0;
}
100% {
opacity: 1;
}
}
/* Where the caret measures the text: the input's font, out of sight. */
.caret-mirror {
position: absolute;
left: -9999px;
top: 0;
visibility: hidden;
white-space: pre;
}
/* With a mouse or trackpad, an iOS-style selection: the native one is see-through (the text keeps
its colour) and ours is drawn under the text, an accent wash a little taller than the line with a
handle at each end (2 px, the knob on top at the start and under it at the end). They fade in as
a selection starts and out as it collapses. */
.field.own-sel input {
position: relative;
z-index: 1;
}
.field.own-sel input::selection {
background: transparent;
color: var(--text);
}
.caret-sel {
position: absolute;
left: 0;
top: 50%;
height: 22px;
margin-top: -11px;
border-radius: 4px;
background: color-mix(in srgb, var(--accent) 26%, transparent);
pointer-events: none;
opacity: 0;
transition: opacity 140ms linear;
}
.caret-hd {
position: absolute;
z-index: 2;
left: 0;
top: 50%;
width: 2px;
height: 22px;
margin-top: -11px;
border-radius: 1px;
background: var(--accent);
pointer-events: none;
opacity: 0;
transition: opacity 140ms linear;
}
.caret-hd::after {
content: '';
position: absolute;
left: 50%;
width: 9px;
height: 9px;
margin-left: -4.5px;
border-radius: 50%;
background: var(--accent);
}
.caret-hd.s::after {
top: -7px;
}
.caret-hd.e::after {
bottom: -7px;
}
.field.selecting .caret-sel,
.field.selecting .caret-hd {
opacity: 1;
}
/* Words on their way to the router (ui/shimmer.ts): the input's own are hidden under a copy that dims and lets a
light band sweep across it, the band the words' colour over a muted base; the caret steps aside meanwhile. */
.field.saving input {
color: transparent;
}
.field.saving .caret {
opacity: 0 !important;
animation: none !important;
}
.shim-clip {
position: absolute;
z-index: 2;
overflow: hidden;
pointer-events: none;
}
.shim {
--shim-high: var(--text);
--shim-base: color-mix(in oklab, var(--text) 38%, var(--raised));
position: absolute;
top: 0;
white-space: pre;
-webkit-background-clip: text;
background-clip: text;
color: transparent;
}
/* The icon picker (skiper21's tabs): icons only, the picked one widens and shows its name. */
.seg {
position: relative;
@@ -398,6 +535,98 @@
font-size: 11.5px;
}
}
/* An option with a switch (Add a device's LAN Bypass): a field-coloured block on the raised sheet,
its glass icon grey while off, the whole row the switch. Hover tints it; it does not shrink. */
.swrow {
width: 100%;
display: flex;
align-items: center;
gap: 12px;
padding: 12px 12px 12px 14px;
border-radius: 16px;
background: var(--field);
color: var(--text);
text-align: left;
user-select: none;
-webkit-user-select: none;
transition: background-color 200ms;
}
.swrow:hover {
background: color-mix(in srgb, var(--field), var(--knob) 50%);
}
.kinds + .swrow {
margin: 16px 0 12px;
}
.swrow .gi {
width: 28px;
height: 28px;
flex: none;
transition:
filter var(--spring-smooth-dur, 524ms) var(--spring-smooth, ease),
opacity var(--spring-smooth-dur, 524ms) var(--spring-smooth, ease);
}
.swrow:not(.on) .gi {
filter: grayscale(1);
opacity: 0.55;
}
.sw-t {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 1px;
}
.sw-t b {
font-size: 15px;
line-height: 22px;
font-weight: 500;
letter-spacing: -0.015em;
}
.sw-sub {
font-size: 13px;
line-height: 18px;
color: var(--text-2);
}
/* The switch: a knob-coloured track on the field, the accent when on. Held down, the knob reaches
halfway toward where it goes (as iOS switches do: off it stretches to the right, on to the left);
let go and it finishes the move. */
.sw {
position: relative;
flex: none;
width: 44px;
height: 26px;
border-radius: 999px;
background: var(--knob);
transition: background-color var(--spring-smooth-dur, 524ms) var(--spring-smooth, ease);
}
.sw::after {
content: '';
position: absolute;
top: 3px;
left: 3px;
width: 20px;
height: 20px;
border-radius: 10px;
background: var(--text-2);
transition:
transform var(--spring-smooth-dur, 524ms) var(--spring-smooth, ease),
width var(--spring-smooth-dur, 524ms) var(--spring-smooth, ease),
background-color var(--spring-smooth-dur, 524ms) var(--spring-smooth, ease);
}
.swrow.on .sw {
background: var(--accent);
}
.swrow.on .sw::after {
transform: translateX(18px);
background: var(--accent-ink);
}
.swrow:active .sw::after {
width: 27px;
}
.swrow.on:active .sw::after {
transform: translateX(11px);
}
.or {
display: flex;
align-items: center;
@@ -499,6 +728,11 @@
line-height: 18px;
color: var(--text-2);
}
/* A hint that says what is wrong (under a name field): red, over the hint's own grey (this file comes after
base.css's .bad-t). */
.hint.bad-t {
color: var(--bad);
}
.hint a,
.hint button {
color: var(--accent);
@@ -595,7 +829,8 @@
width: 100%;
height: 100%;
}
/* A code swapping for another: the old one lies over the new one while it fades. */
/* A code swapping for another: the old one lies over the new one while it fades, and one turned back to while it
fades up again where it lies. */
.qrbox > svg.old {
position: absolute;
inset: 0;
@@ -657,4 +892,8 @@
opacity: 1;
filter: none;
}
/* The caret stands still: a blink is motion the visitor asked to be spared. */
.caret.on.blink {
animation: none;
}
}
+40
View File
@@ -72,6 +72,46 @@
.dev-stat.here-t {
color: var(--accent);
}
/* Why a name it was given won't do (flows/rename.ts). */
.dev-stat.bad-t {
color: var(--bad);
}
/* A name the person may change (flows/rename.ts): it hugs its words, a faint wash under the pointer says it can
be clicked; editing, it gives way to its own input in the same font and place, with nothing around it but the
field's caret and selection. */
.dev-name.can-edit {
align-self: flex-start;
max-width: calc(100% + 12px);
margin: 0 -6px;
padding: 0 6px;
border-radius: 8px;
cursor: text;
outline: none;
transition: background-color 150ms var(--ease-out);
}
.dev-name.can-edit:hover {
background: color-mix(in srgb, var(--raised), var(--text) 6%);
}
/* Not when an edit gave focus back to it (flows/rename.ts): only reached with Tab. */
.dev-name.can-edit:focus-visible:not(.quiet) {
box-shadow: 0 0 0 2px color-mix(in srgb, var(--accent) 60%, transparent);
}
.field.inline,
.field.inline:focus-within {
height: 30px;
margin: -4px -6px;
padding: 0 6px;
gap: 0;
border-radius: 8px;
background: none;
box-shadow: none;
overflow: visible;
}
.field.inline input {
font: 500 16px/22px var(--font);
letter-spacing: -0.02em;
}
.dev-use {
margin-top: auto;
background: var(--field);
+6
View File
@@ -176,6 +176,12 @@ body.scrolled .edge-fade.top {
line-height: 18px;
}
/* The notice's slot holds its margin (flow-root) and clips it while its height glides, so a notice that comes or
goes is uncovered or folded away instead of hanging over what follows (page/notices.ts). */
.notice-slot {
display: flow-root;
overflow-y: clip;
}
/* A notice wears its tone: the fill tinted, the rim a little stronger. */
.notice {
display: flex;
+156 -8
View File
@@ -1,6 +1,7 @@
/* The set-up sheet: the numbered steps, the way from the device to the server while the page waits
(and its line morphing into "<device> connected"), the .conf for a router, and the scan line that
speaks for both phone systems. */
(its line morphing into "<device> connected", and how it looks when the device can't finish
connecting or connects with no data), the .conf for a router, and the scan line that speaks for
both phone systems. */
.setup {
display: flex;
@@ -21,6 +22,10 @@
.step + .step {
margin-top: 20px;
}
/* No data: the connection step alone in its row (flows/setup-view.ts regroup). */
.step[hidden] + .step {
margin-top: 0;
}
.step-n {
width: 24px;
height: 24px;
@@ -108,8 +113,22 @@
}
.way-glow {
overflow: hidden;
}
/* Running and knocking are two loops that never stop: a state fades its own in and the other out where
each stands (a new animation-name would start over at 0%, off the track, in one frame). Connected, no
data and given up show neither. */
.way-glow > span {
position: absolute;
inset: 0;
transition: opacity 200ms var(--ease-out);
}
.way.trying .run,
.way.done .run,
.way.nodata .run,
.way.stopped .run,
.way:not(.trying) .knock {
opacity: 0;
}
.way-glow i {
position: absolute;
inset: 0;
@@ -134,19 +153,26 @@
.way.done .way-fill {
clip-path: inset(0);
}
.way.done .way-glow,
.way.stopped .way-glow {
opacity: 0;
}
.way.done .way-end {
color: var(--ok);
background: var(--ok-soft);
}
.way.done .way-end.home {
.way.done .way-end.home,
.way.nodata .way-end.home {
transition-delay: 600ms;
}
/* The router's icon pops as the green gets there: it dips to .6 first (from rest to rest, on the way's
curve), so it starts from its own size, and springs back on BOUNCY's own curve and time from 600 ms,
with its colour. */
.way.done .way-end.home .i {
animation: way-pop 420ms var(--spring-bouncy, ease) 600ms backwards;
animation:
way-dip 120ms cubic-bezier(0.45, 0, 0.55, 1) 480ms,
way-pop var(--spring-bouncy-dur, 572ms) var(--spring-bouncy, ease) 600ms;
}
@keyframes way-dip {
to {
transform: scale(0.6);
}
}
@keyframes way-pop {
from {
@@ -191,6 +217,121 @@
color: var(--ok);
}
/* Can't finish: the light runs almost to the router and falls back, a break flashes at the router,
and the router's end turns orange. */
.way-glow .knock i {
background: linear-gradient(90deg, transparent 32%, var(--warn) 50%, transparent 68%);
animation: way-knock 1.8s cubic-bezier(0.45, 0, 0.55, 1) infinite;
}
@keyframes way-knock {
0% {
transform: translateX(-70%);
}
48% {
transform: translateX(34%);
}
62% {
transform: translateX(26%);
opacity: 1;
}
86%,
100% {
transform: translateX(-70%);
opacity: 0;
}
}
/* The break flashes all along on the knock's beat (both start with the way) and fades in and out with
can't finish, from whatever it shows. */
.way-break {
position: absolute;
right: -2px;
top: -5px;
width: 2px;
height: 18px;
opacity: 0;
transition: opacity 200ms var(--ease-out);
}
.way.trying .way-break {
opacity: 1;
}
.way-break i {
position: absolute;
inset: 0;
border-radius: 2px;
background: var(--warn);
transform: rotate(18deg);
animation: way-break 1.8s cubic-bezier(0.45, 0, 0.55, 1) infinite;
}
@keyframes way-break {
0%,
40% {
opacity: 0.25;
transform: rotate(18deg) scaleY(0.7);
}
50% {
opacity: 1;
transform: rotate(18deg) scaleY(1.15);
}
70%,
100% {
opacity: 0.25;
transform: rotate(18deg) scaleY(0.7);
}
}
.way.trying .way-end.home {
color: var(--warn);
background: color-mix(in srgb, var(--warn) 14%, transparent);
}
.way.trying .way-text b,
.way.nodata .way-text b {
color: var(--warn);
}
/* No data: the way is green (it connects), but a packet falls through on its way to the router. */
.way.nodata .way-fill {
clip-path: inset(0);
}
.way.nodata .way-end {
color: var(--ok);
background: var(--ok-soft);
}
.way-pkt {
position: absolute;
top: 50%;
left: 0;
width: 8px;
height: 8px;
margin-top: -4px;
border-radius: 50%;
background: var(--warn);
box-shadow: 0 0 10px color-mix(in srgb, var(--warn) 70%, transparent);
opacity: 0;
animation: way-drop 2.2s cubic-bezier(0.45, 0, 0.55, 1) infinite;
}
.way-pkt.b {
animation-delay: 1.1s;
}
@keyframes way-drop {
0% {
left: 0;
opacity: 0;
transform: none;
}
8% {
opacity: 1;
}
46% {
left: 48%;
opacity: 1;
transform: none;
}
66%,
100% {
left: 54%;
opacity: 0;
transform: translateY(16px) scale(0.5);
}
}
/* The .conf for a router: a file card, and the configuration folded with its keys masked. */
.filecard {
display: flex;
@@ -315,4 +456,11 @@
.way.done .way-end.home .i {
animation: none;
}
/* Still frames: the break stands at the router, and no packet falls. */
.way-break i {
animation: none;
}
.way-pkt {
display: none;
}
}
+5 -5
View File
@@ -1,5 +1,6 @@
/* The sheet: a drawer floating at the bottom on every width, × and a view's own buttons pinned in its
corner, the views inside (head, line under it), and the question look (Remove, Reconnect). */
/* The sheet: a drawer floating at the bottom of a phone, a dialog in the middle of a computer, × and a view's
own buttons pinned in its corner, the views inside (head, line under it), and the question look (Remove,
Reconnect). */
/* Closed, the sheet is out of the page (display, not visibility): each open computes its styles
afresh. Hidden by visibility, Chromium could keep the inherited "hidden" on the views' box after a
@@ -60,6 +61,8 @@
right: 22px;
top: 22px;
}
/* The viewport: as tall as its view, give or take the gap or overhang under the view while it glides to a new height
(ui/sheet.ts); what does not fit yet, and a view on its way out, is clipped. */
.vp {
position: relative;
overflow: hidden;
@@ -116,9 +119,6 @@
max-width: 32ch;
text-wrap: balance;
}
.kinds-note {
margin: 14px 2px 16px;
}
.view > .hint.bad-t {
margin-top: 8px;
}
+122 -27
View File
@@ -3,8 +3,12 @@
// and its own corners. One row open at a time. A row with nothing to open is a
// plain head: no chevron, no click. Inside the sheet it tells the sheet first,
// so a code that comes into view gets its width. A row the person opens is
// `.opened` until it closes: what enters inside it (the calendar's days) keys on
// that, so a repaint that rebuilds the row open doesn't play it again.
// `.opened` until it has shut: what enters inside it (the calendar's days) keys
// on that, so a repaint that rebuilds the row open doesn't play it again, and a
// row opened again before it has shut carries on. A click mid-way (a double
// click) turns every row and body back from where it stands, and a row around
// them glides on with them (`regrow`, which the set-up sheet also uses when a
// pick changes a row still opening); the sheet follows its view by itself.
import { h, ic } from '../dom';
import { EASE_IN, SOFT, play } from '../motion';
@@ -41,9 +45,79 @@ const PROPS = [
'borderBottomRightRadius',
] as const;
/** A body not showing (display: none) stands where an opening one starts. */
const HIDDEN: Keyframe = { opacity: 0, filter: 'blur(2px)' };
/** A body's new fade takes over from the one under way, which stops once the new one is in place. */
function fade(body: HTMLElement, frames: Keyframe[], o: KeyframeAnimationOptions) {
const old = body.getAnimations();
play(body, frames, o);
old.forEach((a) => a.cancel());
}
/** What a keyframe holds besides the properties it animates. */
const META = new Set(['offset', 'computedOffset', 'easing', 'composite']);
const kebab = (p: string) => p.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`);
/**
* Content changed under a glide still heading for a height it measured before
* (a row opening, a fold coming back): each element from `from` up whose
* height glides to what its content gives it carries on from where it stands
* to what its content gives it now, on its own curve, so it neither clips what
* grew nor jumps when the glide ends. A row closing (its height is its head's,
* not its content's) or a fold shutting keeps its end. Called with what changed
* in its end shape, before that moves. The heights are taken at the sheet's end
* width (a dense code widening it).
*/
export function regrow(...from: (Element | null | undefined)[]) {
const runs: { el: HTMLElement; a: Animation; t: CSSNumberish | null; cur: Keyframe; to: Keyframe }[] = [];
const widths: { a: Animation; t: CSSNumberish | null }[] = [];
const seen = new Set<Element>();
for (const start of from)
for (let el: Element | null | undefined = start; el && !seen.has(el); el = el.parentElement) {
seen.add(el);
if (!(el instanceof HTMLElement) || el.classList.contains('closing')) continue;
for (const a of el.getAnimations()) {
const ks = a.playState === 'running' && a.effect instanceof KeyframeEffect ? a.effect.getKeyframes() : [];
const end = ks[ks.length - 1];
if (end && ('width' in end || 'maxWidth' in end)) widths.push({ a, t: a.currentTime });
if (!end?.height || end.height === '0px') continue;
const cs = getComputedStyle(el);
const cur: Keyframe = {};
const to: Keyframe = {};
for (const p of Object.keys(end))
if (!META.has(p)) {
cur[p] = cs.getPropertyValue(kebab(p));
to[p] = end[p];
}
runs.push({ el, a, t: a.currentTime, cur, to });
}
}
if (!runs.length) return;
// Measured with every glide lifted, the widths too; those not aimed anew go on from where they were.
[...runs, ...widths].forEach((r) => r.a.cancel());
const ends = runs.map((r) => getComputedStyle(r.el).height);
for (const w of widths) {
w.a.play();
w.a.currentTime = w.t;
}
runs.forEach((r, i) => {
r.a.play();
// Its content gives it the height it was heading for: it carries on as it was.
if (Math.abs(parseFloat(ends[i]) - parseFloat(String(r.to.height))) < 0.5) r.a.currentTime = r.t;
else (r.a.effect as KeyframeEffect).setKeyframes([r.cur, { ...r.to, height: ends[i] }]);
});
}
export function accordion(
items: AccItem[],
o: { inset?: boolean; open?: number; onToggle?: (i: number, open: boolean, instant: boolean) => void } = {},
o: {
inset?: boolean;
open?: number;
onToggle?: (i: number, open: boolean, instant: boolean) => void;
/** On the page: holds its height as a click reshapes the rows; what it returns lets go once their new shape is measured. */
hold?: () => () => void;
} = {},
): Accordion {
const acc = h('div', { class: `acc${o.inset ? ' inset' : ''}` });
const rows = items.map((it, i) => {
@@ -87,43 +161,57 @@ export function accordion(
};
const aria = () =>
rows.forEach((x) => x.querySelector('button.acc-head')?.setAttribute('aria-expanded', String(x.classList.contains('open'))));
/** A row shows its body while open and while it closes (`.closing`). */
const shows = (x: HTMLElement) => x.classList.contains('open') || x.classList.contains('closing');
/** Where a body's fade stands now, mid-fade included. */
const faded = (x: HTMLElement): Keyframe => {
if (!shows(x)) return HIDDEN;
const cs = getComputedStyle(bodyOf(x));
return { opacity: cs.opacity, filter: cs.filter === 'none' ? 'blur(0px)' : cs.filter };
};
function toggle(r: HTMLElement) {
const before = rows.map(read);
const fades = rows.map(faded);
const release = o.hold?.();
rows.forEach((x) => x.getAnimations().forEach((a) => a.cancel()));
rows.forEach((x) =>
bodyOf(x)
.getAnimations()
.forEach((a) => a.cancel()),
);
const willOpen = !r.classList.contains('open');
const closing = rows.filter((x) => x.classList.contains('open') && (x === r || willOpen));
// Every row showing its body shuts, still closing from a click before included, but the one that opens.
const closing = rows.filter((x) => shows(x) && !(x === r && willOpen));
rows.forEach((x) => {
x.classList.remove('closing');
if (x !== r) x.classList.remove('open', 'opened');
if (x !== r) x.classList.remove('open');
});
r.classList.toggle('open', willOpen);
r.classList.toggle('opened', willOpen);
if (willOpen) r.classList.add('opened');
corners();
const plan = planWidth();
const after = rows.map(read);
release?.();
// The row this accordion sits in glides on to its new height with them (the sheet follows its view by itself).
regrow(acc.parentElement);
rows.forEach((x, i) => {
const after = read(x);
if (!PROPS.some((p) => before[i][p] !== after[p])) return;
// Shut: what enters inside it plays again the next time it opens.
const shut = () => {
x.classList.remove('closing');
if (!x.classList.contains('open')) x.classList.remove('opened');
};
if (!PROPS.some((p) => before[i][p] !== after[i][p])) return shut();
if (closing.includes(x)) x.classList.add('closing');
play(x, [before[i], after], { duration: SOFT.duration, easing: SOFT.easing }).onfinish = () => x.classList.remove('closing');
play(x, [before[i], after[i]], { duration: SOFT.duration, easing: SOFT.easing }).onfinish = shut;
});
closing.forEach((x) =>
play(bodyOf(x), [{ opacity: 1 }, { opacity: 0, filter: 'blur(2px)' }], { duration: 160, easing: EASE_IN, fill: 'forwards' }),
);
if (willOpen)
play(
bodyOf(r),
[
{ opacity: 0, filter: 'blur(2px)' },
{ opacity: 1, filter: 'blur(0px)' },
],
{ duration: 300, easing: 'cubic-bezier(0,0,.58,1)' },
);
// Each body fades on from where it stands (a double click turns it back), over what is left of its way.
closing.forEach((x) => {
const f = fades[rows.indexOf(x)];
fade(bodyOf(x), [f, { opacity: 0, filter: 'blur(2px)' }], { duration: 160 * Number(f.opacity), easing: EASE_IN, fill: 'forwards' });
});
if (willOpen) {
const f = fades[rows.indexOf(r)];
fade(bodyOf(r), [f, { opacity: 1, filter: 'blur(0px)' }], {
duration: 300 * (1 - Number(f.opacity)),
easing: 'cubic-bezier(0,0,.58,1)',
});
}
startWidth(plan);
aria();
o.onToggle?.(rows.indexOf(r), willOpen, false);
@@ -134,7 +222,14 @@ export function accordion(
el: acc,
openIndex: () => rows.findIndex((x) => x.classList.contains('open')),
setOpen(i) {
rows.forEach((x, k) => x.classList.toggle('open', k === i && !x.classList.contains('still')));
rows.forEach((x, k) => {
// Without motion: whatever was under way stops where it was going.
[x, bodyOf(x)].forEach((e) => e.getAnimations().forEach((a) => a.cancel()));
const open = k === i && !x.classList.contains('still');
x.classList.toggle('open', open);
x.classList.remove('closing');
if (!open) x.classList.remove('opened');
});
corners();
aria();
rows.forEach((x, k) => o.onToggle?.(k, x.classList.contains('open'), true));
+69
View File
@@ -0,0 +1,69 @@
// The red line under a name field (Add a device, Rename): why the name is refused, the router's word or the
// field's own as it is typed (shared/name-guard.ts). It comes and goes without the sheet snapping: in, it rises in
// as the sheet glides open; out, it blurs away first, then the sheet glides shut. Either way it turns back from
// where it stands on screen. A view already swapped out (the answer came late) changes alone: the sheet's height is
// the new view's. Another reason while it shows: its words change in place.
import { h } from '../dom';
import { EASE_IN, EASE_OUT, play } from '../motion';
import { morphText, setText, textOf } from './morph';
import { glide, showing } from './sheet';
/** Away and shown. */
const GONE: Keyframe = { opacity: 0, transform: 'translateY(-4px)', filter: 'blur(4px)' };
const SHOWN: Keyframe = { opacity: 1, transform: 'none', filter: 'none' };
export interface BadLine {
el: HTMLElement;
say: (msg: string) => void;
unsay: () => void;
}
export function badLine(): BadLine {
const err = h('p', { class: 'hint bad-t', hidden: true });
const reflow = (change: () => void) => (showing(err) ? glide(change) : change());
let fade: Animation | null = null;
let hiding = 0;
const now = (): Keyframe => {
const s = getComputedStyle(err);
return { opacity: s.opacity, transform: s.transform, filter: s.filter };
};
// The new fade takes over from the old one once it is in place (nothing paints between).
const fadeTo = (from: Keyframe, to: Keyframe, o: KeyframeAnimationOptions) => {
const was = fade;
fade = play(err, [from, to], o);
was?.cancel();
};
const say = (msg: string) => {
if (err.hidden) {
reflow(() => {
setText(err, msg);
err.hidden = false;
});
return fadeTo(GONE, SHOWN, { duration: 220, easing: EASE_OUT });
}
// Already showing: its words change in place. On its way out, it comes back from where it stands as they do.
const from = hiding ? now() : null;
morphText(err, msg);
if (!from) return;
clearTimeout(hiding);
hiding = 0;
fadeTo(from, SHOWN, { duration: 220, easing: EASE_OUT });
};
const unsay = () => {
if (err.hidden || hiding) return;
const from = now();
// A morph under way ends where it was going: its end would cancel the fade.
setText(err, textOf(err));
fadeTo(from, GONE, { duration: 180, easing: EASE_IN, fill: 'forwards' });
hiding = window.setTimeout(() => {
hiding = 0;
reflow(() => {
err.hidden = true;
fade?.cancel();
fade = null;
});
}, 170);
};
return { el: err, say, unsay };
}
+8 -4
View File
@@ -39,14 +39,18 @@ function hand(btn: HTMLElement, next: Animation[]) {
}
export function busyOn(btn: HTMLElement) {
btn.querySelector(':scope > .orb')?.remove();
const parts = content(btn);
const from = parts.map(now);
const orb = h('span', { class: 'orb', 'aria-hidden': 'true' }, h('i'), h('i'));
btn.append(orb);
// An orb still on its way out (pressed again right after an answer) turns back from where it stands, at once.
const was = btn.querySelector<HTMLElement>(':scope > .orb');
const orb = was ?? h('span', { class: 'orb', 'aria-hidden': 'true' }, h('i'), h('i'));
if (!was) btn.append(orb);
btn.classList.add('busy');
btn.setAttribute('aria-busy', 'true');
hand(btn, [...parts.map((p, i) => play(p, [from[i], GONE], OUT)), play(orb, [ORB_GONE, SHOWN], IN)]);
hand(btn, [
...parts.map((p, i) => play(p, [from[i], GONE], OUT)),
play(orb, [was ? now(was) : ORB_GONE, SHOWN], was ? { ...IN, delay: 0 } : IN),
]);
}
export function busyOff(btn: HTMLElement) {
+270
View File
@@ -0,0 +1,270 @@
// The name fields' own caret and, with a mouse or trackpad, their own selection
// (`smoothCaret` on a `.field`). The caret glides to where the next letter goes
// and blinks as macOS draws it; a selection is an accent wash with a handle at
// each end, as iOS draws it, growing out of the caret and fading back into it.
// The input stays the browser's own (typing, IME, its native selection, made
// see-through): this only draws over it. On a touch screen the system draws its
// own selection and handles, so ours stays off and the caret steps aside while
// one shows. The look is in styles/controls.css; like the rest of the page this
// writes styles through `el.style` only (the CSP drops style attributes).
//
// Places come from a hidden mirror with the input's own font: the width of the
// text up to a position, less how far the input has scrolled. The pure parts
// (`glideStep`, `places`) are what the tests run.
import { h } from '../dom';
import { calm } from '../motion';
/** One edge that glides: where it is, how fast it moves, where it goes. */
export interface Glide {
x: number;
v: number;
t: number;
}
/** The frame the glide is tuned to, in ms. */
const FRAME = 16.67;
/**
* Move a glide on by `frames` frames (after bencho.dev's one-time code, a softer pull: per frame
* v += (t − x)·0.12, v ·= 0.62, x += v; 90% of the way in ~134 ms, about 2% over, no stretch).
* At most 2.5 frames at once; after a long gap (a hidden tab) it is simply there. False once it
* rests, then exactly on its target.
*/
export function glideStep(g: Glide, frames: number): boolean {
if (frames > 15) {
g.x = g.t;
g.v = 0;
return false;
}
const dt = Math.min(2.5, Math.max(0, frames));
g.v += (g.t - g.x) * 0.12 * dt;
g.v *= Math.pow(0.62, dt);
g.x += g.v * dt;
if (Math.abs(g.t - g.x) < 0.05 && Math.abs(g.v) < 0.05) {
g.x = g.t;
g.v = 0;
return false;
}
return true;
}
/** What an input shows now, as `places` reads it. */
export interface FieldText {
value: string;
/** The selection (equal: a caret), and which end the caret is at. */
start: number;
end: number;
backward: boolean;
/** The input's box in the field: its left edge and width, and how far its text has scrolled. */
left: number;
width: number;
scroll: number;
}
/** Where the caret and a selection's ends go, in px from the field's left edge. */
export interface Places {
caret: number;
start: number;
end: number;
/** A selection, not just a caret. */
range: boolean;
}
/**
* The places for `f`, with `measure` the width of a text in the input's font. A selection that
* runs past the input's edges (a long name, scrolled) stops at them: the wash never covers the
* go button.
*/
export function places(f: FieldText, measure: (text: string) => number): Places {
const x = (i: number) => Math.min(f.left + f.width, Math.max(f.left, f.left + measure(f.value.slice(0, i)) - f.scroll));
const start = x(f.start);
const end = f.end === f.start ? start : x(f.end);
return { caret: f.backward ? start : end, start, end, range: f.start !== f.end };
}
/** The input's font, as the mirror needs it to measure the same widths. */
const FONT = ['fontFamily', 'fontSize', 'fontWeight', 'letterSpacing', 'fontFeatureSettings', 'fontVariationSettings'] as const;
/**
* Give the input of `field` (a `.field`) the glide caret and, with a fine pointer, the selection.
* Call it once, as the field is built (it measures only once the field is on the page).
*/
export function smoothCaret(field: HTMLElement) {
const input = field.querySelector('input');
if (!input) return;
const fine = matchMedia('(pointer: fine)').matches;
field.classList.add('own-caret');
if (fine) field.classList.add('own-sel');
const wash = h('span', { class: 'caret-sel' });
const h0 = h('span', { class: 'caret-hd s' });
const h1 = h('span', { class: 'caret-hd e' });
const caret = h('span', { class: 'caret' });
const mirror = h('span', { class: 'caret-mirror', 'aria-hidden': 'true' });
field.append(wash, h0, h1, caret, mirror);
// In the field's own px: while the sheet scales in (the rename field selects its text then), the
// box on screen is smaller than the one the caret is drawn in.
const measure = (text: string) => {
mirror.textContent = text;
const shown = field.getBoundingClientRect().width;
return mirror.getBoundingClientRect().width * (shown ? field.offsetWidth / shown : 1);
};
const now = (): Places =>
places(
{
value: input.value,
start: input.selectionStart ?? 0,
end: input.selectionEnd ?? 0,
backward: input.selectionDirection === 'backward',
left: input.offsetLeft,
width: input.clientWidth,
scroll: input.scrollLeft,
},
measure,
);
const glide = (): Glide => ({ x: 0, v: 0, t: 0 });
const cur = glide();
const s0 = glide();
const s1 = glide();
const all = [cur, s0, s1];
const jump = (g: Glide, x: number) => {
g.x = g.t = x;
g.v = 0;
};
let selecting = false;
const focused = () => document.activeElement === input;
const draw = () => {
caret.style.transform = `translateX(${(cur.x - 1).toFixed(2)}px)`;
wash.style.transform = `translateX(${Math.min(s0.x, s1.x).toFixed(2)}px)`;
wash.style.width = `${Math.abs(s1.x - s0.x).toFixed(2)}px`;
h0.style.transform = `translateX(${(s0.x - 1).toFixed(2)}px)`;
h1.style.transform = `translateX(${(s1.x - 1).toFixed(2)}px)`;
};
// One loop for the three edges; it stops when all of them rest.
let raf = 0;
let last = 0;
const step = (t: number) => {
const frames = last ? (t - last) / FRAME : 1;
last = t;
let busy = false;
for (const g of all) if (glideStep(g, frames)) busy = true;
draw();
raf = busy ? requestAnimationFrame(step) : 0;
if (!raf) last = 0;
};
const follow = () => {
// Less motion: everything is where it goes at once.
if (calm()) {
all.forEach((g) => jump(g, g.t));
return draw();
}
if (!raf) raf = requestAnimationFrame(step);
};
let first = true;
let rest = 0;
let faded = 0;
let fading = false;
let pressedAt = 0;
const place = () => {
if (!focused()) {
clearTimeout(rest);
caret.classList.remove('on', 'blink');
field.classList.remove('selecting');
selecting = false;
return draw();
}
if (first) {
// Measured here, not when built: a field not on the page yet has no font to copy.
const cs = getComputedStyle(input);
for (const k of FONT) mirror.style[k] = cs[k];
}
const p = now();
if (first) {
all.forEach((g) => jump(g, p.start));
first = false;
}
if (p.range && fine) {
// Selecting: the wash grows out of where the caret is, and the caret steps aside. A wash still fading from
// the last selection turns back instead and glides from its old ends to the new ones.
if (!selecting) {
clearTimeout(faded);
if (!fading) {
s0.x = s1.x = cur.x;
s0.v = s1.v = 0;
}
fading = false;
}
selecting = true;
s0.t = p.start;
s1.t = p.end;
cur.t = p.caret;
field.classList.add('selecting');
caret.classList.remove('on', 'blink');
} else if (p.range) {
// A touch screen: the system's own selection shows.
caret.classList.remove('on', 'blink');
return;
} else {
// Collapsed: the wash fades where it stands, and its ends join the caret once it is gone.
// A click puts the caret where it was clicked at once, as macOS does; typing and the arrows glide.
if (selecting) {
field.classList.remove('selecting');
clearTimeout(faded);
fading = true;
faded = window.setTimeout(() => {
fading = false;
if (selecting) return;
jump(s0, cur.t);
jump(s1, cur.t);
draw();
}, 160);
} else if (!fading) {
jump(s0, p.start);
jump(s1, p.start);
}
selecting = false;
if (performance.now() - pressedAt < 400) jump(cur, p.caret);
else cur.t = p.caret;
// Solid while it moves or they type, blinking again half a second after.
caret.classList.add('on');
caret.classList.remove('blink');
clearTimeout(rest);
rest = window.setTimeout(() => {
if (focused()) caret.classList.add('blink');
}, 500);
}
follow();
};
// After the event: by then the browser has moved its own caret.
let queued = 0;
const soon = () => {
if (!queued)
queued = requestAnimationFrame(() => {
queued = 0;
place();
});
};
for (const ev of ['pointerdown', 'pointerup']) input.addEventListener(ev, () => (pressedAt = performance.now()));
for (const ev of ['input', 'keydown', 'keyup', 'pointerup', 'select', 'scroll']) input.addEventListener(ev, soon);
input.addEventListener('pointermove', (e) => {
if (e.buttons) soon();
});
// A selection made any other way (the keyboard's, a double click, the page's own select()).
const onSelect = () => {
if (focused()) soon();
};
input.addEventListener('focus', () => {
first = true;
document.addEventListener('selectionchange', onSelect);
soon();
});
input.addEventListener('blur', () => {
document.removeEventListener('selectionchange', onSelect);
soon();
});
}
+128 -39
View File
@@ -2,71 +2,165 @@
// link as text with Copy and Share. Codes follow the theme: the night look
// (light dots on black) on a dark one, the same dots dark on white on a light
// one, redrawn in place when the system's theme changes. A dense code (an
// AmneziaVPN key) fills its row; the sheet widens for it (ui/sheet.ts).
// AmneziaVPN key) fills its row; the sheet widens for it (ui/sheet.ts). A code
// too long for a camera gives its place to a stand-in (the device's set-up link).
import { denseQr, qrSvg } from '../../shared/qr';
import { h, ic } from '../dom';
import { EASE_IN, EASE_OUT, play } from '../motion';
import { denseQr, qrSvg, scannable } from '../../shared/qr';
import { h, ic, markup } from '../dom';
import { EASE_IN, EASE_OUT, SMOOTH, play } from '../motion';
import { placeName } from '../state';
import { copy } from './feedback';
const LIGHT = matchMedia('(prefers-color-scheme: light)');
const look = () => (LIGHT.matches ? 'day' : 'night');
function paint(box: HTMLElement, text: string) {
box.dataset.qr = text;
box.classList.toggle('dense', denseQr(text));
/** The code for `text` in the theme's look, tagged with what it says. */
function drawn(text: string): SVGSVGElement {
const svg = markup(qrSvg(text, 3, true, look())) as SVGSVGElement;
svg.dataset.qr = text;
return svg;
}
/** The box shows `svg` (or is about to): its size, and the sheet's width, follow that code. */
function holds(box: HTMLElement, svg: SVGSVGElement) {
box.dataset.qr = svg.dataset.qr;
box.classList.toggle('dense', denseQr(svg.dataset.qr!));
box.classList.toggle('light', LIGHT.matches);
box.innerHTML = qrSvg(text, 3, true, look());
// The modules across: how wide the sheet must be for a camera to read it.
box.dataset.mods = String((box.firstElementChild as SVGSVGElement | null)?.viewBox.baseVal.width ?? 0);
box.dataset.mods = String(svg.viewBox.baseVal.width);
}
export function qrBox(text: string, big = false): HTMLElement {
const box = h('div', { class: `qrbox${big ? ' big' : ''}` });
paint(box, text);
const svg = drawn(text);
box.append(svg);
holds(box, svg);
return box;
}
// Each code is redrawn in the other look where it stands: a cross-fade under way carries on.
LIGHT.addEventListener('change', () =>
document.querySelectorAll<HTMLElement>('.qrbox[data-qr]').forEach((b) => {
// Mid cross-fade a box holds two codes: the old one goes, the new one is drawn again.
b.querySelector('svg.old')?.remove();
paint(b, b.dataset.qr!);
b.querySelectorAll<SVGSVGElement>(':scope > svg[data-qr]').forEach((s) => s.replaceChildren(...drawn(s.dataset.qr!).childNodes));
b.classList.toggle('light', LIGHT.matches);
}),
);
/** Where an element's fade stands now, mid-fade included. */
function now(el: Element): Keyframe {
const s = getComputedStyle(el);
return { opacity: s.opacity, filter: s.filter === 'none' ? 'blur(0px)' : s.filter };
}
export interface CodeRow {
el: HTMLElement;
/** Another code in the same place: it comes in over the old one, which then goes; new words too, if given (else they stay, to change in place). */
swap(next: string, words?: Node[]): void;
}
/** A code and its words: side by side, or a dense code full width with the words under it. */
export function codeRow(text: string, words: Node[]): CodeRow {
const box = qrBox(text);
let shown = h('div', { class: 'words' }, words);
/** What a code row shows instead of a code a camera cannot read: another code, and words that say why (made each time it shows). */
export interface StandIn {
text: string;
words: () => Node[];
}
/**
* A code and its words: side by side, or a dense code full width with the
* words under it. With a stand-in, a code too long to scan shows the stand-in
* and its words; the row's own words come back with a code that fits.
*/
export function codeRow(text: string, words: Node[], standIn?: StandIn): CodeRow {
const instead = (t: string) => !!standIn && !scannable(t);
let own = words;
let out = instead(text);
const box = qrBox(out ? standIn!.text : text);
let shown = h('div', { class: 'words' }, out ? standIn!.words() : own);
const side = h('div', { class: 'side' }, shown);
const el = h('div', { class: `coderow${box.classList.contains('dense') ? ' stacked' : ''}` }, box, side);
/**
* Another code in the box: it comes in under the one showing, which lies over
* it and goes after it, so the place is never empty. Nothing on screen changes
* its place in the stack: the codes lie in the box in the order they paint (the
* one in flow first, under the rest). A swap under way carries on from where
* each code stands; a code turned back to fades up again where it lies, what
* lies over it going, and what lies under it goes once it shows whole. A code
* of the other size (dense or not) takes the box from its size on screen to its
* own on SMOOTH, the codes in it scaling with it, while the sheet glides the
* rest (glide() in ui/sheet.ts).
*/
let sizing: Animation | null = null;
/** The codes on their way out: a later swap leaves their fade as it is. */
const going = new WeakSet<Element>();
const cross = (code: string) => {
const svgs = [...box.querySelectorAll<SVGSVGElement>(':scope > svg')];
const op = new Map(svgs.map((s) => [s, +getComputedStyle(s).opacity]));
const cs = getComputedStyle(box);
const r0 = box.getBoundingClientRect();
// Its corners as they look now: a resize under way scales them with the box.
const round0 = parseFloat(cs.borderTopLeftRadius) * new DOMMatrix(cs.transform).a;
const neu = svgs.find((s) => s.dataset.qr === code) ?? drawn(code);
const at = svgs.indexOf(neu);
// A new code goes under them all; one still in the box stays where it lies.
if (at < 0) box.prepend(neu);
const over = svgs.slice(at + 1).filter((s) => !going.has(s));
const under = svgs.slice(0, Math.max(0, at));
const fades = [neu, ...over].flatMap((s) => s.getAnimations());
going.delete(neu);
holds(box, neu);
el.classList.toggle('stacked', box.classList.contains('dense'));
const o0 = op.get(neu) ?? 0;
play(neu, [{ opacity: o0 }, { opacity: 1 }], { duration: 200 * (1 - o0), easing: EASE_OUT }).onfinish = () => {
// Whole: what lies under it, hidden now, goes, and it takes the box's flow under what still fades over it.
under.forEach((s) => s.remove());
neu.classList.remove('old');
};
// What lies over it goes from how it shows, where it lies (the code that showed, over the new one); one already going goes on.
over.forEach((s) => {
s.classList.add('old');
going.add(s);
play(s, [{ opacity: op.get(s)! }, { opacity: 0 }], {
duration: 220 * op.get(s)!,
delay: 110,
easing: EASE_IN,
fill: 'both',
}).onfinish = () => s.remove();
});
fades.forEach((a) => a.cancel());
sizing?.cancel();
sizing = null;
const r1 = box.getBoundingClientRect();
const sx = r0.width / r1.width;
const sy = r0.height / r1.height;
// Not on screen (a folded row): nothing to watch move.
if (r0.width && r1.width && (Math.abs(sx - 1) > 0.005 || Math.abs(sy - 1) > 0.005))
sizing = play(
box,
[
{ transform: `scale(${sx}, ${sy})`, transformOrigin: '0 0', borderRadius: `${round0 / sx}px` },
{ transform: 'none', transformOrigin: '0 0', borderRadius: getComputedStyle(box).borderTopLeftRadius },
],
{ duration: SMOOTH.duration, easing: SMOOTH.easing },
);
};
return {
el,
swap(next, nextWords) {
if (nextWords) own = nextWords;
const was = out;
out = instead(next);
const code = out ? standIn!.text : next;
// The same code for another app (AmneziaWG and WireGuard take one file): only the words change.
const oldSvg = box.dataset.qr === next ? null : box.querySelector('svg');
if (oldSvg) {
paint(box, next);
el.classList.toggle('stacked', box.classList.contains('dense'));
const newSvg = box.querySelector('svg')!;
oldSvg.classList.add('old');
box.appendChild(oldSvg);
// The new code comes in first, the old one goes after it: the place is never empty.
play(newSvg, [{ opacity: 0 }, { opacity: 1 }], { duration: 200, easing: EASE_OUT });
play(oldSvg, [{ opacity: 1 }, { opacity: 0 }], { duration: 220, delay: 110, easing: EASE_IN, fill: 'forwards' }).onfinish = () =>
oldSvg.remove();
}
if (!nextWords) return;
if (box.dataset.qr !== code) cross(code);
// The stand-in's words stay while they say the same (they may follow what it stands in for); the row's own
// come back with a code that fits.
let put = out ? standIn!.words() : (nextWords ?? (was ? own : null));
if (out && was && put!.map((n) => n.textContent).join('') === shown.textContent) put = null;
if (!put) return;
const oldWords = shown;
shown = h('div', { class: 'words' }, nextWords);
// From where they stand: words still coming in (a pick right after a pick) go from there.
const from = now(oldWords);
const fades = oldWords.getAnimations();
shown = h('div', { class: 'words' }, put);
side.appendChild(shown);
oldWords.classList.add('old');
play(
@@ -77,14 +171,9 @@ export function codeRow(text: string, words: Node[]): CodeRow {
],
{ duration: 220, easing: EASE_OUT },
);
play(
oldWords,
[
{ opacity: 1, filter: 'blur(0px)' },
{ opacity: 0, filter: 'blur(3px)' },
],
{ duration: 200, delay: 90, easing: EASE_IN, fill: 'forwards' },
).onfinish = () => oldWords.remove();
play(oldWords, [from, { opacity: 0, filter: 'blur(3px)' }], { duration: 200, delay: 90, easing: EASE_IN, fill: 'both' }).onfinish =
() => oldWords.remove();
fades.forEach((a) => a.cancel());
},
};
}
+20 -11
View File
@@ -12,13 +12,22 @@ let slot: HTMLElement | null = null;
let shown: HTMLElement | null = null;
let timer = 0;
const leave = (t: HTMLElement, frames: Keyframe[], ms: number) =>
(play(t, frames, { duration: ms, easing: EASE_IN, fill: 'forwards' }).onfinish = () => t.remove());
/** A toast goes from where it stands: one still rising (a new one took its place) goes from there. */
function leave(t: HTMLElement, to: Keyframe, ms: number) {
const s = getComputedStyle(t);
const a = play(t, [{ opacity: s.opacity, transform: s.transform, filter: s.filter }, to], {
duration: ms,
easing: EASE_IN,
fill: 'forwards',
});
t.getAnimations().forEach((x) => x !== a && x.cancel());
a.onfinish = () => t.remove();
}
/** One toast at a time: a new one sends the last away first. */
export function toast(msg: string, bad = false) {
slot ??= document.body.appendChild(h('div', { class: 'toasts' }));
if (shown) leave(shown, [{ opacity: 1 }, { opacity: 0, transform: 'scale(.96)', filter: 'blur(4px)' }], 140);
if (shown) leave(shown, { opacity: 0, transform: 'scale(.96)', filter: 'blur(4px)' }, 140);
const t = h('div', { class: `toast${bad ? ' bad' : ''}`, role: 'status' }, ic(bad ? 'alert' : 'check'), h('span', {}, msg));
slot.appendChild(t);
shown = t;
@@ -37,13 +46,13 @@ export function toast(msg: string, bad = false) {
timer = window.setTimeout(() => {
if (shown !== t) return;
shown = null;
leave(t, [{ opacity: 1 }, { opacity: 0, transform: 'translateY(6px) scale(.96)', filter: 'blur(4px)' }], 180);
leave(t, { opacity: 0, transform: 'translateY(6px) scale(.96)', filter: 'blur(4px)' }, 180);
}, 2400);
}
/** An icon that changes in place: the new one pops in where the old one stood. */
export function swapIcon(icon: Element, name: string): Element {
const next = ic(name, icon.getAttribute('class') ?? 'i');
/** An icon that changes in place: the new one (by name, or one to put back) pops in where the old one stood. */
export function swapIcon(icon: Element, to: string | Element): Element {
const next = typeof to === 'string' ? ic(to, icon.getAttribute('class') ?? 'i') : to;
icon.replaceWith(next);
play(
next,
@@ -61,9 +70,9 @@ export function swapIcon(icon: Element, name: string): Element {
/**
* The control that copied says so for a moment: its icon turns into a check
* 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.
* and its "Copy…" label (`.lbl`, a badge's main line) into "Copied", then both
* turn back the way they came. 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;
@@ -74,7 +83,7 @@ function copied(from: Element) {
const check = icon ? swapIcon(icon, 'check') : null;
if (label) morphText(label, _('Copied'));
setTimeout(() => {
if (check && icon) check.replaceWith(icon);
if (check && icon) swapIcon(check, icon);
if (label) morphText(label, was);
from.classList.remove('copied');
}, 1600);
+5
View File
@@ -121,6 +121,11 @@ const GL: Record<string, Shape> = {
f: '<rect x="2.5" y="6" width="13.5" height="16" rx="3.2"/>',
d: '<path d="M6.2 11h6.5M6.2 14.5h6.5M6.2 18h4"/>',
},
lan: {
b: '<circle cx="16" cy="8" r="6"/>',
f: '<rect x="2.5" y="7.5" width="14.5" height="14.5" rx="4.2"/>',
d: '<rect x="8.3" y="10.4" width="2.9" height="2.6" rx=".7"/><rect x="5.2" y="16.4" width="2.9" height="2.6" rx=".7"/><rect x="11.4" y="16.4" width="2.9" height="2.6" rx=".7"/><path d="M9.75 13v1.8M6.65 16.4v-1.6h6.2v1.6"/>',
},
};
/** The AmneziaVPN mark without its own svg: drawn on the "app" pane. */
+21 -7
View File
@@ -34,11 +34,22 @@ export function closeMenu(now = false) {
m.remove();
return;
}
play(m, [{ opacity: 1 }, { opacity: 0, transform: 'scale(.96)', filter: 'blur(3px)' }], {
duration: 120,
easing: EASE_IN,
fill: 'forwards',
}).onfinish = () => m.remove();
// From where it stands: one closed while it still pops in (a scroll, a second press) goes from there.
const s = getComputedStyle(m);
const a = play(
m,
[
{ opacity: s.opacity, transform: s.transform, filter: s.filter },
{ opacity: 0, transform: 'scale(.96)', filter: 'blur(3px)' },
],
{
duration: 120,
easing: EASE_IN,
fill: 'forwards',
},
);
m.getAnimations().forEach((x) => x !== a && x.cancel());
a.onfinish = () => m.remove();
}
/** `items`: null is a separator, kept only between items. */
@@ -68,9 +79,12 @@ export function openMenu(anchor: HTMLElement, all: (MenuItem | null)[]) {
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.
// The highlight comes in where the pointer is, then glides from item to item. Whether it shows is read off the
// screen: one still fading out (the pointer left and came back) turns back and glides from where it stands;
// only one gone altogether is placed at once.
b.addEventListener('pointerenter', () => {
hl.className = `menu-hl${hl.style.opacity === '1' ? ' moving' : ''} ${it.tone ?? ''}`;
const seen = +getComputedStyle(hl).opacity > 0.01;
hl.className = `menu-hl${seen ? ' moving' : ''} ${it.tone ?? ''}`;
hl.style.transform = `translateY(${b.offsetTop - 6}px)`;
hl.style.opacity = '1';
});
+328 -105
View File
@@ -4,7 +4,9 @@
// through `morphText`: a card's name and status after a repaint, the counts and
// values, a label that says "Copied", a line that says what happened (the way:
// "iPad connected"), and a menu path for another app or the other phone system
// (`menuLine`: where the app scans, iOS "Create", Android "Scan").
// (`menuLine`: where the app scans, iOS "Create", Android "Scan"). Turned again
// half-way, a morph or a refill goes on from what shows: words still coming in
// leave from as far as they came, what was leaving keeps leaving.
import { fmt } from '../../shared/i18n';
import { h, ic, markup, put, type Kid } from '../dom';
@@ -23,6 +25,22 @@ const runs = new WeakMap<HTMLElement, Run>();
/** What `el` says: while it morphs, what it is turning into. */
export const textOf = (el: HTMLElement): string => runs.get(el)?.text ?? el.textContent ?? '';
/** How something shows: its opacity and blur, part of the way while a fade or a morph runs. */
export interface Look {
opacity: number;
filter: string;
}
const SHOWN: Look = { opacity: 1, filter: 'blur(0px)' };
const settled = (s: Look) => s.opacity > 0.99 && (s.filter === 'none' || s.filter === 'blur(0px)');
/** How `el` shows now (on the page: a detached element has no style), with the words a whole-word morph brings in. */
export function look(el: Element): Look {
const cs = getComputedStyle(el);
const words = el.querySelector(':scope > .mt-new');
const ws = words && getComputedStyle(words);
return { opacity: +cs.opacity * (ws ? +ws.opacity : 1), filter: cs.filter === 'none' && ws ? ws.filter : cs.filter };
}
/** Where `el`'s words sit (their own box, not the element's). */
function wordsBox(el: HTMLElement): DOMRect {
const r = document.createRange();
@@ -30,6 +48,13 @@ function wordsBox(el: HTMLElement): DOMRect {
return r.getBoundingClientRect();
}
/** Where a text's glyphs stand (only as high as the font, not the line). */
function glyphs(n: Node): DOMRect {
const r = document.createRange();
r.selectNodeContents(n);
return r.getBoundingClientRect();
}
/** Where each character of `el`'s plain text starts, from the first (kerning and all). */
function spacing(el: HTMLElement): number[] {
const node = el.firstChild;
@@ -54,10 +79,11 @@ function spacing(el: HTMLElement): number[] {
function space(box: Element, at: number[]) {
const kids = [...box.children] as HTMLElement[];
if (!kids.length) return;
const start = kids[0].getBoundingClientRect().left;
kids.forEach((c, i) => {
if (!i || at[i] === undefined) return;
const dx = start + at[i] - c.getBoundingClientRect().left;
// Against the first letter as it stands now: in a centred line every nudge moves the whole run
// by half of it, the first letter too, and a start read once would let the nudges add up.
const dx = kids[0].getBoundingClientRect().left + at[i] - c.getBoundingClientRect().left;
if (Math.abs(dx) > 0.01) c.style.marginLeft = `${dx}px`;
});
}
@@ -105,6 +131,20 @@ export function setText(el: HTMLElement, text: string) {
el.textContent = text;
}
/**
* A morph under way on `el`, taken out as it shows: the words it brings in (and where they stand), and all still
* leaving (one turned again before has more than one).
*/
function lift(el: HTMLElement): { words: HTMLElement; at: DOMRect; going: HTMLElement[] } | null {
const words = el.querySelector<HTMLElement>(':scope > .mt-new');
if (!words) return null;
const going = [...el.querySelectorAll<HTMLElement>(':scope > .mt-old')];
const at = wordsBox(words);
words.remove();
going.forEach((g) => g.remove());
return { words, at, going };
}
export interface MorphOpts {
/** The words change as a whole instead: the old blur away where they stood as the new come in. */
whole?: boolean;
@@ -116,6 +156,10 @@ export interface MorphOpts {
* words go from there, and the width does not glide.
*/
at?: DOMRect;
/** How the old words show, against `el` (they were still coming in when the caller rebuilt them): they leave from there. */
shows?: Look;
/** The old words' colour, where `el` took another with the new ones (a status turned green): they keep it, the new turn from it. */
color?: string;
}
/**
@@ -125,14 +169,21 @@ export interface MorphOpts {
* The old letters keep to the edge
* that stays put while the width changes (the start of a line, the end of a
* value on the right, the middle of a centred line). Done, it holds plain text
* again: a box that ends in an ellipsis keeps it.
* again: a box that ends in an ellipsis keeps it. Turned again half-way, the
* words that were coming in leave from as far as they came (a letter both
* texts keep slides on from where it is), and those leaving go on leaving.
*/
export function morphText(el: HTMLElement, next: string, from = textOf(el), o: MorphOpts = {}) {
const { whole = false, at } = o;
const run = runs.get(el);
// Asked again for what it is already turning into: the morph under way goes on.
if (run && from === run.text && next === run.text) return;
// Placed by the caller, the width does not glide: what follows is moved by the caller too.
const glide = (o.glide ?? true) && !at;
// Interrupted mid-way: the width carries on from where it is on screen, not from where that morph was going.
const midway = runs.has(el) ? el.getBoundingClientRect().width : null;
// Interrupted mid-way: the width carries on from where it is on screen, not from where that morph was going,
// and what shows of it is taken out as it stands.
const midway = run ? el.getBoundingClientRect() : null;
const live = run && from === run.text && !calm() && el.getClientRects().length ? lift(el) : null;
finish(el);
// Nothing to watch move: no motion asked for, or not on screen (a folded row, a closed sheet).
if (from === next || calm() || !el.getClientRects().length) {
@@ -145,8 +196,8 @@ export function morphText(el: HTMLElement, next: string, from = textOf(el), o: M
const flow = whole && cs.display === 'inline';
if (cs.display === 'inline' && !whole) el.classList.add('mt-ib');
if (cs.position === 'static') el.classList.add('mt');
let r0: DOMRect | null = null;
let t0 = at ?? null;
let r0: DOMRect | null = live ? midway : null;
let t0 = live?.at ?? at ?? null;
let at0: number[] = [];
if (!t0) {
el.textContent = from;
@@ -157,15 +208,25 @@ export function morphText(el: HTMLElement, next: string, from = textOf(el), o: M
el.textContent = next;
const r1 = el.getBoundingClientRect();
const at1 = spacing(el);
const w0 = midway ?? r0?.width ?? r1.width;
const w0 = midway?.width ?? r0?.width ?? r1.width;
const glides = glide && !flow && !!r0 && Math.abs(r1.width - w0) > 0.5;
const edge = !glides || !r0 || Math.abs(r1.left - r0.left) < 0.5 ? 'start' : Math.abs(r1.right - r0.right) < 0.5 ? 'end' : 'middle';
const neu = h('span', { class: whole ? 'mt-new w' : 'mt-new' }, whole ? next : letters(next));
const old = h('span', { class: whole ? 'mt-old w' : 'mt-old', 'aria-hidden': 'true' }, whole ? from : letters(from));
// The old words: those that were coming in, as they show, or the old text built afresh.
const old = live?.words ?? h('span', { class: whole ? 'mt-old w' : 'mt-old' }, whole ? from : letters(from));
old.classList.replace('mt-new', 'mt-old');
old.setAttribute('aria-hidden', 'true');
// Whole words wrap as they did: the old ones keep the width they took.
if (whole) old.style.width = `${t0.width + 1}px`;
if (old.classList.contains('w')) old.style.width = `${t0.width + 1}px`;
el.replaceChildren(neu, old);
// What was still leaving goes on leaving where it is.
if (live) el.append(...live.going);
if (o.color) {
old.style.color = o.color;
const c1 = getComputedStyle(el).color;
if (c1 !== o.color) play(neu, [{ color: o.color }, { color: c1 }], { duration: 280, easing: EASE_OUT });
}
// Held at the plain text's width until the letters turn back into it, so what follows never steps.
if (glides)
play(el, [{ width: `${w0}px` }, { width: `${r1.width}px` }], {
@@ -186,18 +247,28 @@ export function morphText(el: HTMLElement, next: string, from = textOf(el), o: M
};
const x0 = edge === 'end' ? t0.right - r2.right : edge === 'middle' ? (t0.left + t0.right - r2.left - r2.right) / 2 : t0.left - r2.left;
place(x0, t0.top - r2.top);
// Then onto the old words exactly: the box's top is not the text's (the line's leading sits above it).
const t2 = wordsBox(old);
// Then onto the old words exactly: the box's top is not the text's (the line's leading sits above it), nor is a
// letter's (a box of its own, a line high): built afresh, the first letter's glyphs go where the text's stood.
const first = !live && old.querySelector('i')?.firstChild;
const t2 = first ? glyphs(first) : wordsBox(old);
place(x0 + t0.left - t2.left, t0.top - r2.top + t0.top - t2.top);
if (whole) {
// How the old words show: those that were coming in as far as they came.
const s0 = live ? look(old) : (o.shows ?? SHOWN);
/** The old words go as one, from how they show. */
const leave = () => {
const prior = old.getAnimations();
play(
old,
[
{ opacity: 1, filter: 'blur(0px)' },
{ opacity: s0.opacity, filter: s0.filter },
{ opacity: 0, filter: 'blur(4px)' },
],
{ duration: 180, easing: EASE_IN, fill: 'forwards' },
{ duration: 180 * s0.opacity, easing: EASE_IN, fill: 'forwards' },
);
prior.forEach((a) => a.cancel());
};
if (whole) {
leave();
play(
neu,
[
@@ -211,26 +282,36 @@ export function morphText(el: HTMLElement, next: string, from = textOf(el), o: M
return;
}
space(neu, at1);
space(old, at0);
if (!live) space(old, at0);
// The letters both texts keep slide from where they stood to where they go, on the width's spring;
// the old ones' places in the overlay stay empty.
const was = [...old.children] as HTMLElement[];
// the old ones' places in the overlay stay empty. Old words that came whole have no letters to keep.
const was = old.classList.contains('w') ? [] : ([...old.children] as HTMLElement[]);
const now = [...neu.children] as HTMLElement[];
const pairs = kept([...from], [...next]);
const pairs = was.length ? kept([...from], [...next]) : [];
const stays = new Set(pairs.map(([i]) => i));
const comes = new Set(pairs.map(([, j]) => j));
pairs.forEach(([i, j]) => {
const a = was[i].getBoundingClientRect();
const b = now[j].getBoundingClientRect();
// A letter still rising when the morph turned comes along from as far as it rose.
const s = live ? look(was[i]) : s0;
was[i].style.visibility = 'hidden';
if (Math.abs(a.left - b.left) > 0.5 || Math.abs(a.top - b.top) > 0.5)
play(now[j], [{ transform: `translate(${a.left - b.left}px, ${a.top - b.top}px)` }, { transform: 'none' }], {
duration: SMOOTH.duration,
easing: SMOOTH.easing,
});
const moves = Math.abs(a.left - b.left) > 0.5 || Math.abs(a.top - b.top) > 0.5;
const shows = settled(s) ? null : s;
if (moves || shows)
play(
now[j],
[
{ transform: `translate(${a.left - b.left}px, ${a.top - b.top}px)`, ...shows },
{ transform: 'none', ...(shows && SHOWN) },
],
{ duration: SMOOTH.duration, easing: SMOOTH.easing },
);
});
const out = was.filter((_x, i) => !stays.has(i));
// Turned half-way, the old words leave as one: each of their letters is somewhere on its own way.
const out = live ? [] : was.filter((_x, i) => !stays.has(i));
if (live) leave();
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));
@@ -239,7 +320,7 @@ export function morphText(el: HTMLElement, next: string, from = textOf(el), o: M
play(
c,
[
{ opacity: 1, filter: 'blur(0px)', transform: 'none' },
{ opacity: s0.opacity, filter: s0.filter, transform: 'none' },
{ opacity: 0, filter: 'blur(4px)', transform: 'translateY(-0.45em)' },
],
{ duration: 220, delay: i * so, easing: EASE_IN, fill: 'forwards' },
@@ -260,17 +341,32 @@ export function morphText(el: HTMLElement, next: string, from = textOf(el), o: M
runs.set(el, { text: next, timer: window.setTimeout(() => finish(el), ends) });
}
/** The keyed texts under `root` (`data-t`), before a repaint rebuilds them. */
export function textsOf(root: ParentNode): Map<string, string> {
return new Map([...root.querySelectorAll<HTMLElement>('[data-t]')].map((el) => [el.dataset.t!, textOf(el)]));
/** What a keyed text said, and in which colour. */
export interface Said {
text: string;
color: string;
}
/** After the repaint: each keyed text that changed morphs from what it said. */
export function morphChanged(root: ParentNode, was: Map<string, string>) {
/** The keyed texts under `root` (`data-t`), before a repaint rebuilds them. */
export function textsOf(root: ParentNode): Map<string, Said> {
return new Map(
[...root.querySelectorAll<HTMLElement>('[data-t]')].map((el) => [
el.dataset.t!,
{ text: textOf(el), color: getComputedStyle(el).color },
]),
);
}
/**
* After the repaint: each keyed text that changed morphs from what it said (one already turning into it goes on).
* `fresh`: what a refill brought in whole (morphInto), its words with it: the old words fade where they stood.
*/
export function morphChanged(root: ParentNode, was: Map<string, Said>, fresh: Element[] = []) {
root.querySelectorAll<HTMLElement>('[data-t]').forEach((el) => {
const before = was.get(el.dataset.t!);
const now = el.textContent ?? '';
if (before !== undefined && before !== now) morphText(el, now, before);
const now = textOf(el);
if (!before || before.text === now || runs.has(el) || fresh.some((f) => f.contains(el))) return;
morphText(el, now, before.text, { color: before.color });
});
}
@@ -283,11 +379,87 @@ interface Piece {
/** Where its words stand (a morph under way: the words it is turning into). */
words: DOMRect | null;
node: Node;
/** How it shows: part of the way while it still comes in. */
shows: Look;
}
/** What can fade out where it stood. */
type Drawn = HTMLElement | SVGElement;
const isDrawn = (n: Node): n is Drawn => n instanceof HTMLElement || n instanceof SVGElement;
/** A piece as something that can fade where it stood: bare words go into a span of their own. */
const drawn = (n: Node): Drawn => (isDrawn(n) ? n : h('span', {}, n));
/** Its tag and classes, less a morph's own (a piece still changing is the same piece). */
const kindOf = (el: Element) => `${el.tagName}.${[...el.classList].filter((c) => c !== 'mt' && c !== 'mt-ib').join(' ')}`;
/** A drawing as markup, less the ids each build makes up (a glass icon's gradients): the same icon twice is the same. */
const drawing = (el: Element) => el.outerHTML.replace(/\bgl\d+/g, 'gl');
/** What fades out where it stood (`fadeAway`), each with the element it is laid over. */
const fading = new Map<Element, Element>();
/** How many fade over each element, and those made a positioned box for them. */
const holding = new WeakMap<Element, number>();
const boxed = new WeakSet<Element>();
/** Inside something already fading out (under `box`): it goes with it. */
function within(el: Element, box: Element): boolean {
for (let p = el.parentElement; p && p !== box; p = p.parentElement) if (fading.has(p)) return true;
return false;
}
function hold(host: Element) {
const n = holding.get(host) ?? 0;
if (!n && getComputedStyle(host).position === 'static') {
host.classList.add('mt');
boxed.add(host);
}
holding.set(host, n + 1);
}
/** The last to fade over `host` is gone: a box made positioned for them is static again. */
function release(host: Element) {
const n = (holding.get(host) ?? 1) - 1;
holding.set(host, n);
if (!n && boxed.delete(host)) host.classList.remove('mt');
}
/**
* `e`, which stood at `at` on screen, fades out there, laid over `host` (which
* stood at `from`): a piece a refill crossed or left out (morphInto), a card's
* old foot (page/devices.ts). One already fading only moves over its new host
* and goes on; another starts from how it showed (`shows`: it may still have
* been coming in), over what is left of its way.
*/
export function fadeAway(e: Drawn, at: DOMRect, host: Element, from: DOMRect, shows: Look = SHOWN) {
const over = fading.get(e);
if (over) release(over);
hold(host);
fading.set(e, host);
e.style.position = 'absolute';
e.style.margin = '0';
e.style.left = `${at.left - from.left - host.clientLeft}px`;
e.style.top = `${at.top - from.top - host.clientTop}px`;
e.style.right = '';
e.style.translate = '';
e.style.width = `${at.width}px`;
e.style.pointerEvents = 'none';
e.setAttribute('aria-hidden', 'true');
host.appendChild(e);
if (over) return;
const prior = e.getAnimations();
const a = play(
e,
[
{ opacity: shows.opacity, filter: shows.filter },
{ opacity: 0, filter: 'blur(4px)' },
],
{ duration: 180 * shows.opacity, easing: EASE_IN, fill: 'forwards' },
);
prior.forEach((x) => x.cancel());
// Gone, or stopped by whatever stops what moves around it: it was leaving either way.
a.onfinish = a.oncancel = () => {
const last = fading.get(e);
if (!last) return;
fading.delete(e);
release(last);
e.remove();
};
}
function pieces(box: Element): Map<string, Piece> {
const out = new Map<string, Piece>();
const walk = (n: Node, path: string) =>
@@ -298,58 +470,121 @@ function pieces(box: Element): Map<string, Piece> {
const r = document.createRange();
r.selectNodeContents(c);
const at = r.getBoundingClientRect();
out.set(p, { kind: '#text', text: c.textContent, svg: '', at, words: at, node: c });
out.set(p, { kind: '#text', text: c.textContent, svg: '', at, words: at, node: c, shows: SHOWN });
}
return;
}
if (!(c instanceof Element)) return;
// What is on its way out already (crossed by a refill before, words a morph lifts away) goes on by itself.
if (!(c instanceof Element) || fading.has(c) || c.classList.contains('mt-old')) return;
const svg = c instanceof SVGElement ? drawing(c) : '';
const words = c instanceof HTMLElement && !svg ? wordsBox(c.querySelector<HTMLElement>(':scope > .mt-new') ?? c) : null;
out.set(p, { kind: kindOf(c), text: c instanceof HTMLElement ? textOf(c) : '', svg, at: c.getBoundingClientRect(), words, node: c });
out.set(p, {
kind: kindOf(c),
text: c instanceof HTMLElement ? textOf(c) : '',
svg,
at: c.getBoundingClientRect(),
words,
node: c,
shows: look(c),
});
if (!svg) walk(c, p);
});
walk(box, '');
return out;
}
/** Something with nothing to change from comes in through a blur. */
const appear = (el: Element) =>
/**
* `el` glides back to its place from `(dx, dy)` away, on SMOOTH. A transform
* does nothing to words in a line (an inline box): those move by a relative
* offset instead, theirs only for the glide.
*/
function shift(el: Element, dx: number, dy: number) {
const o = { duration: SMOOTH.duration, easing: SMOOTH.easing };
if (!(el instanceof HTMLElement) || getComputedStyle(el).display !== 'inline')
return play(el, [{ transform: `translate(${dx}px, ${dy}px)` }, { transform: 'none' }], o);
const own = el.style.position;
if (getComputedStyle(el).position === 'static') el.style.position = 'relative';
const a = play(
el,
[
{ left: `${dx}px`, top: `${dy}px` },
{ left: '0px', top: '0px' },
],
o,
);
a.onfinish = a.oncancel = () => (el.style.position = own);
return a;
}
/**
* Something with nothing to change from comes in through a blur, to its own
* opacity (a part the stylesheet dims stays dimmed); `shows`: it was on its way
* in already, and goes on from as far as it came.
*/
export function appear(el: Element, shows?: Look) {
const own = +getComputedStyle(el).opacity;
const o0 = shows?.opacity ?? 0;
play(
el,
[
{ opacity: 0, filter: 'blur(4px)' },
{ opacity: 1, filter: 'blur(0px)' },
{ opacity: o0, filter: shows?.filter ?? 'blur(4px)' },
{ opacity: own, filter: 'blur(0px)' },
],
{ duration: 280, delay: 60, easing: EASE_OUT, fill: 'backwards' },
{ duration: 280 * Math.min(1, Math.max(0, own - o0) / (own || 1)), delay: shows ? 0 : 60, easing: EASE_OUT, fill: 'backwards' },
);
}
/**
* `box` refilled with `kids` and nothing blinks: what is the same stays still;
* a piece in the same place with other words blurs from the old words into the
* new where it stands; a drawing that changed comes in through a blur; a piece
* that changed its kind or its height (another block, a list that wraps over
* more lines) crosses whole, the old one blurring out exactly where it stood as
* the new one blurs in, and so does what is gone. A piece that kept its kind
* and size but moved glides from where it stood. Places are taken against the
* box, which its sheet moves as a whole; an old piece fades inside its own
* parent's new self (the same kind, in the same place), so it keeps its look.
* new where it stands (a keyed text, `data-t`, is left to morphChanged, which
* letter-morphs it from what it said); a piece that changed its kind, its
* height (another block, a list that wraps over more lines) or its drawing
* crosses whole, the old one blurring out exactly where it stood as the new one
* blurs in, and so does what is gone. A piece that kept its kind and size but
* moved glides from where it stood. Places are taken against the box, which its
* sheet moves as a whole; an old piece fades inside its own parent's new self
* (the same kind, in the same place), so it keeps its look. Refilled again
* half-way, what was fading goes on fading where it is, and what was still
* coming in goes on from as far as it came. Returns what came in whole.
*/
export function morphInto(box: HTMLElement, kids: Kid) {
export function morphInto(box: HTMLElement, kids: Kid): Element[] {
const was = pieces(box);
const box0 = box.getBoundingClientRect();
// What is on its way out already, with what it sat in: it goes on over that one's new self.
const going = [...fading.keys(), ...box.querySelectorAll('.mt-old')]
.filter((g): g is Drawn => box.contains(g) && !within(g, box) && isDrawn(g))
.map((g) => ({ g, at: g.getBoundingClientRect(), over: g.parentElement, shows: fading.has(g) ? undefined : look(g) }));
const pathOf = new Map([...was].map(([p, w]) => [w.node, p]));
put(box, kids);
if (!was.size || calm()) return;
/** The new element at each place. */
const placed = new Map<string, Element>();
const carry = () =>
going.forEach(({ g, at, over, shows }) => {
const p = over && pathOf.get(over);
const host = p && placed.get(p);
const w = p && was.get(p);
if (host && w && w.at && w.kind === kindOf(host)) fadeAway(g, at, host, w.at, shows);
else fadeAway(g, at, box, box0, shows);
});
if (!was.size || calm()) {
carry();
return [];
}
const box1 = box.getBoundingClientRect();
/** Where something that stood at `r` in the box's old place stands now, the pieces having glided back there. */
const here = (r: DOMRect | null) => r && new DOMRect(r.left - box0.left + box1.left, r.top - box0.top + box1.top, r.width, r.height);
const morphs: (() => void)[] = [];
/** An old piece, where it stood, the new parent it fades in and where that parent stood. */
const ghosts: [Element, DOMRect, Element, DOMRect][] = [];
/** An old piece, where it stood, the new parent it fades in, where that parent stood, and how the piece showed. */
const ghosts: [Drawn, DOMRect, Element, DOMRect, Look][] = [];
const seen = new Set<string>();
/** What comes in whole. */
const came: Element[] = [];
const cross = (el: Element, w: Piece | undefined, path: string) => {
const host = el.parentElement;
const from = path ? was.get(path)?.at : box0;
if (w?.at && w.node instanceof Element) ghosts.push(host && from ? [w.node, w.at, host, from] : [w.node, w.at, box, box0]);
if (w?.at) ghosts.push(host && from ? [drawn(w.node), w.at, host, from, w.shows] : [drawn(w.node), w.at, box, box0, w.shows]);
came.push(el);
morphs.push(() => appear(el));
};
/** Moves `el` from where it stood (`at`, in the box's old place) to where it is, less what its parent already carries. */
@@ -359,8 +594,7 @@ export function morphInto(box: HTMLElement, kids: Kid) {
const dy = at.top - box0.top - (r.top - box1.top);
const ox = dx - carried[0];
const oy = dy - carried[1];
if (Math.abs(ox) > 0.5 || Math.abs(oy) > 0.5)
play(el, [{ transform: `translate(${ox}px, ${oy}px)` }, { transform: 'none' }], { duration: SMOOTH.duration, easing: SMOOTH.easing });
if (Math.abs(ox) > 0.5 || Math.abs(oy) > 0.5) shift(el, ox, oy);
return [dx, dy];
};
const walk = (n: Node, path: string, carried: [number, number]) =>
@@ -370,75 +604,58 @@ export function morphInto(box: HTMLElement, kids: Kid) {
const w = was.get(p);
if (c.nodeType === Node.TEXT_NODE) {
const t = c.textContent ?? '';
if (!t.trim() || (w?.kind === '#text' && w.text === t)) return;
if (!t.trim()) return;
// Words: a bare word before, or one the last refill put in a span of its own (it is still that word).
const said = w && (w.kind === '#text' || (w.node instanceof HTMLElement && !w.node.children.length)) ? w.text : null;
const coming = w && w.shows.opacity < 0.99 ? w.shows : null;
if (said === t && !coming) return;
// A bare word among elements goes into a span of its own, so it can change (and glide from where its words were).
const s = h('span', {}, t);
c.replaceWith(s);
if (said === null || Math.max(t.length, said.length) > 40) return cross(s, w, path);
if (w?.at) glideFrom(s, w.at, carried);
morphs.push(() =>
w?.kind === '#text' && t.length <= 40 && w.text.length <= 40
? morphText(s, t, w.text, { whole: true, at: here(w.words) ?? undefined })
: appear(s),
said === t ? appear(s, coming!) : morphText(s, t, said, { whole: true, at: here(w!.words) ?? undefined, shows: w!.shows }),
);
return;
}
if (!(c instanceof Element)) return;
placed.set(p, c);
const r = c.getBoundingClientRect();
if (!w || w.kind !== kindOf(c) || (w.at && Math.abs(w.at.height - r.height) > 1 && !(c instanceof SVGElement)))
const svg = c instanceof SVGElement;
if (!w || w.kind !== kindOf(c) || (svg ? w.svg !== drawing(c) : !!w.at && Math.abs(w.at.height - r.height) > 1))
return cross(c, w, path);
// The same piece somewhere else in the box: it glides there (what it holds rides along, plus its own move).
const own = w.at ? glideFrom(c, w.at, carried) : carried;
if (c instanceof SVGElement) {
if (w.svg !== drawing(c)) morphs.push(() => appear(c));
// Still coming in when the box was refilled: it goes on from as far as it came.
const rest = +getComputedStyle(c).opacity;
const coming = Math.abs(w.shows.opacity - rest) > 0.01 ? w.shows : null;
if (svg) {
if (coming) morphs.push(() => appear(c, coming));
return;
}
if (!c.children.length && c instanceof HTMLElement) {
const t = c.textContent ?? '';
if (t !== w.text)
morphs.push(() =>
t.length <= 40 && w.text.length <= 40
? morphText(c, t, w.text, { whole: true, at: here(w.words) ?? undefined })
: cross(c, w, path),
);
if (t === w.text || c.dataset.t) {
if (coming) morphs.push(() => appear(c, coming));
} else if (t.length <= 40 && w.text.length <= 40) {
// The old words leave from how they showed, against the element that holds them now.
const shows = { opacity: Math.min(1, w.shows.opacity / (rest || 1)), filter: w.shows.filter };
morphs.push(() => morphText(c, t, w.text, { whole: true, at: here(w.words) ?? undefined, shows }));
} else cross(c, w, path);
return;
}
if (coming) morphs.push(() => appear(c, coming));
walk(c, p, own);
});
walk(box, '', [0, 0]);
// What the new box no longer has goes the same way.
for (const [p, w] of was)
if (!seen.has(p) && p.lastIndexOf('/') === 0 && w.at && w.node instanceof Element) ghosts.push([w.node, w.at, box, box0]);
for (const [p, w] of was) if (!seen.has(p) && p.lastIndexOf('/') === 0 && w.at) ghosts.push([drawn(w.node), w.at, box, box0, w.shows]);
morphs.forEach((m) => m());
// The old pieces that cross go from exactly where they stood in their parent (which glides from where it stood).
const hosts = new Map<Element, number>();
for (const [, , host] of ghosts) {
if (!hosts.has(host) && getComputedStyle(host).position === 'static') host.classList.add('mt');
hosts.set(host, (hosts.get(host) ?? 0) + 1);
}
for (const [g, at, host, from] of ghosts) {
const e = g as HTMLElement;
e.style.position = 'absolute';
e.style.margin = '0';
e.style.left = `${at.left - from.left - host.clientLeft}px`;
e.style.top = `${at.top - from.top - host.clientTop}px`;
e.style.width = `${at.width}px`;
e.style.pointerEvents = 'none';
e.setAttribute('aria-hidden', 'true');
host.appendChild(e);
play(
e,
[
{ opacity: 1, filter: 'blur(0px)' },
{ opacity: 0, filter: 'blur(4px)' },
],
{ duration: 180, easing: EASE_IN, fill: 'forwards' },
).onfinish = () => {
e.remove();
const n = hosts.get(host)! - 1;
hosts.set(host, n);
if (!n) host.classList.remove('mt');
};
}
for (const [g, at, host, from, shows] of ghosts) fadeAway(g, at, host, from, shows);
carry();
return came;
}
/** The Android robot's head; its eyes take the colour of what it sits on. */
@@ -502,15 +719,21 @@ export function menuLine(ios: string, android: string): MenuLine {
};
const MARK = { width: '1.05em', marginRight: '0.25em' };
const markOut = (m: HTMLElement) =>
(play(
/** The mark shrinks away from where it stands (one still growing in turns back), over what is left of its width. */
const markOut = (m: HTMLElement) => {
const cs = getComputedStyle(m);
const left = Math.min(1, parseFloat(cs.width) / (1.05 * parseFloat(cs.fontSize)) || 0);
const prior = m.getAnimations();
play(
m,
[
{ opacity: 1, filter: 'blur(0px)', ...MARK },
{ opacity: cs.opacity, filter: cs.filter, width: cs.width, marginRight: cs.marginRight },
{ opacity: 0, filter: 'blur(3px)', width: '0px', marginRight: '0px' },
],
{ duration: 220, easing: EASE_IN, fill: 'forwards' },
).onfinish = () => m.remove());
{ duration: 220 * left, easing: EASE_IN, fill: 'forwards' },
).onfinish = () => m.remove();
prior.forEach((a) => a.cancel());
};
const markIn = (m: HTMLElement) =>
play(
m,
+76 -20
View File
@@ -19,6 +19,26 @@ export interface IconSeg<T extends string> {
sync(v: T): void;
}
/** Where a name stands on screen: its width of `full` (its words' whole width), and its opacity. */
export interface LabelAt {
width: number;
full: number;
opacity: number;
}
/**
* How a name fades on a pick, from where it stands (ms): the picked one blurs
* in (280, a beat after the pill sets off), the others fold (220); a fade
* turned back half-way runs only the share of its way it has left, and a name
* already folded has nothing to do (0).
*/
export function labelFade(at: LabelAt, picked: boolean): { duration: number; delay: number } {
const opacity = Math.min(1, Math.max(0, at.opacity));
if (picked) return { duration: 280 * (1 - opacity), delay: 70 * (1 - opacity) };
const left = Math.max(opacity, at.full > 0 ? Math.min(1, at.width / at.full) : 0);
return { duration: left > 0.01 ? 220 * left : 0, delay: 0 };
}
export function iconSeg<T extends string>(items: SegItem<T>[], value: T, onPick: (v: T) => void): IconSeg<T> {
const pill = h('span', { class: 'seg-pill' });
const el = h('div', { class: 'seg appseg', role: 'tablist' }, pill);
@@ -59,32 +79,68 @@ export function iconSeg<T extends string>(items: SegItem<T>[], value: T, onPick:
const cs = getComputedStyle(pill);
const l0 = parseFloat(cs.left) || 0;
const r0 = parseFloat(cs.right) || 0;
// Each item's share as it stands, and its basis (a narrow picker gives a picked item more: controls.css).
const g0 = btns.map((b) => parseFloat(getComputedStyle(b).flexGrow) || 0);
const oldL = labelOf(btns[from]);
const oldW = oldL.getBoundingClientRect().width;
[...btns, ...btns.map(labelOf)].forEach((x) => x.getAnimations().forEach((a) => a.cancel()));
const f0 = btns.map((b) => getComputedStyle(b).flexBasis);
// Every name from where it stands too: a pick turned back half-way (or an item still folding from the one
// before) goes on from there, so neither a name nor the icon beside it jumps.
const labels = btns.map(labelOf);
const now = labels.map((l) => {
const s = getComputedStyle(l);
return { width: l.getBoundingClientRect().width, opacity: +s.opacity, filter: s.filter, marginLeft: s.marginLeft };
});
[...btns, ...labels].forEach((x) => x.getAnimations().forEach((a) => a.cancel()));
value = v;
mark();
// The picked name's whole width, as it will stand once its item has its share.
const w1 = labels[to].getBoundingClientRect().width;
btns.forEach((b, i) => {
const g1 = i === to ? 1 : 0;
if (g0[i] !== g1) play(b, [{ flexGrow: g0[i] }, { flexGrow: g1 }], { duration: SMOOTH.duration, easing: SMOOTH.easing });
const f1 = getComputedStyle(b).flexBasis;
if (g0[i] !== g1 || f0[i] !== f1)
play(
b,
[
{ flexGrow: g0[i], flexBasis: f0[i] },
{ flexGrow: g1, flexBasis: f1 },
],
{ duration: SMOOTH.duration, easing: SMOOTH.easing },
);
});
labels.forEach((l, i) => {
const n = now[i];
const fade = labelFade({ ...n, full: l.scrollWidth }, i === to);
if (i !== to) {
// It folds (its blur, if it was still coming in, stays while it fades).
if (fade.duration)
play(
l,
[
{ opacity: n.opacity, maxWidth: `${n.width}px`, marginLeft: n.marginLeft, filter: n.filter },
{ opacity: 0, maxWidth: '0px', marginLeft: '-8px', filter: n.filter },
],
{ duration: fade.duration, easing: 'ease-out' },
);
return;
}
// The picked name opens with its item's share, inside the pill, and blurs in.
play(
l,
[
{ maxWidth: `${n.width}px`, marginLeft: n.marginLeft },
{ maxWidth: `${w1}px`, marginLeft: '0px' },
],
{ duration: SMOOTH.duration, easing: SMOOTH.easing },
);
play(
l,
[
{ opacity: n.opacity, filter: n.opacity ? n.filter : 'blur(4px)' },
{ opacity: 1, filter: 'none' },
],
{ ...fade, easing: EASE_OUT, fill: 'backwards' },
);
});
play(
oldL,
[
{ opacity: 1, maxWidth: `${oldW}px`, marginLeft: '0px' },
{ opacity: 0, maxWidth: '0px', marginLeft: '-8px' },
],
{ duration: 220, easing: 'ease-out' },
);
play(
labelOf(btns[to]),
[
{ opacity: 0, filter: 'blur(4px)' },
{ opacity: 1, filter: 'none' },
],
{ duration: 280, delay: 70, easing: EASE_OUT, fill: 'backwards' },
);
// The stretch: the leading edge follows the quick spring, the trailing edge the smooth one.
const right = to > from;
const lead = calm() ? SMOOTH : LEAD;
+180 -85
View File
@@ -1,12 +1,13 @@
// The sheet: one drawer floating at the bottom of the screen, on phones and
// desktops alike. It holds a stack of views (go/back), glides to each view's
// height, widens on a desktop for a dense QR code until the code gets its
// pixels, pins a view's own buttons beside ×, and closes by ×, the scrim, a
// The sheet: a drawer at the bottom of a phone's screen, a dialog in the
// middle of a computer's. It holds a stack of views (go/back), glides to each
// view's height, widens on a desktop for a dense QR code until the code gets
// its pixels, pins a view's own buttons beside ×, and closes by ×, the scrim, a
// pull down on its header, Escape, or the phone's back button (it is a history
// entry). Views are built by the flows; this module only moves them.
// entry). A flow that comes while it is on its way out opens once it is gone.
// Views are built by the flows; this module only moves them.
import { h, ic } from '../dom';
import { BOUNCY, DRAWER, EASE_IN, EASE_OUT, SMOOTH, SOFT, dismisses, play, rubber } from '../motion';
import { BOUNCY, DRAWER, EASE_IN, EASE_OUT, SMOOTH, SOFT, dismisses, play, rubber, unrubber } from '../motion';
import { closeMenu } from './menu';
/** A view: its root, and what the sheet reads from it. */
@@ -32,11 +33,19 @@ let vp: HTMLElement;
let stack: ViewFactory[] = [];
let closed: (() => void) | null = null;
let left: (() => void) | null = null;
/** A flow that came while the sheet was on its way out (an answer after Cancel): it opens once the sheet is gone. */
let next: ViewFactory | null = null;
let ownsHistory = false;
let returnFocus: HTMLElement | null = null;
/** Until then clicks in a sheet just opened are the second half of the double click that opened it. */
let quietUntil = 0;
export const sheetOpen = () => !!root?.classList.contains('open');
/** What runs on `el` and moves one of `props`: stopped or waited for without touching the rest. */
const running = (el: Element, ...props: string[]) =>
el.getAnimations().filter((a) => (a.effect as KeyframeEffect | null)?.getKeyframes().some((k) => props.some((p) => p in k)));
/* ---------- width: a dense code scans from a screen at about 3 px a module ---------- */
const SHEET_W = 400;
@@ -56,8 +65,9 @@ export interface WidthPlan {
/**
* The width the sheet needs now, set at once so whatever measures the new
* layout (an accordion, the height glide) measures it at the final width; the
* plan then animates there on the same spring (`startWidth`), so nothing snaps.
* layout (an accordion) measures it at the final width; the plan then animates
* there on the same spring (`startWidth`), so nothing snaps. The sheet's own
* height follows its view through the glide (`glideHeight`).
*/
export function planWidth(): WidthPlan | null {
if (!root || !sheetOpen()) return null;
@@ -81,10 +91,7 @@ export function planWidth(): WidthPlan | null {
if (Math.abs(want - sheetW) < 8) return reveal ? { from: want, want, reveal } : null;
const from = parseFloat(getComputedStyle(sheetEl).maxWidth) || sheetW;
sheetW = want;
sheetEl
.getAnimations()
.filter((a) => (a.effect as KeyframeEffect | null)?.getKeyframes().some((k) => 'maxWidth' in k))
.forEach((a) => a.cancel());
running(sheetEl, 'maxWidth').forEach((a) => a.cancel());
sheetEl.style.maxWidth = `${want}px`;
return { from, want, reveal };
}
@@ -115,6 +122,17 @@ function build() {
sheetEl = h('div', { class: 'sheet', role: 'dialog', 'aria-modal': 'true' }, closeBtn, actsEl, scroller);
scrim = h('div', { class: 'scrim', onclick: () => closeSheet() });
root = h('div', { class: 'sheet-root', 'aria-hidden': 'true' }, scrim, sheetEl);
// The second click of a double click lands on what the first one opened: the scrim would close the sheet again,
// a question's button would answer it.
root.addEventListener(
'click',
(e) => {
if (performance.now() >= quietUntil) return;
e.preventDefault();
e.stopPropagation();
},
true,
);
document.body.appendChild(root);
new ResizeObserver(() => startWidth(planWidth())).observe(vp);
pullToClose();
@@ -148,6 +166,11 @@ export function onClosed(fn: () => void) {
export function openSheet(factory: ViewFactory) {
if (!root) build();
closeMenu(true);
if (root.dataset.closing) {
// Still on its way out: the new flow opens once it is gone, as it would have a moment later.
next = factory;
return;
}
leave();
if (sheetOpen()) {
// Already open: the new flow takes the place of the old one, history and all.
@@ -156,6 +179,7 @@ export function openSheet(factory: ViewFactory) {
return;
}
returnFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null;
quietUntil = performance.now() + 320;
stack = [factory];
closed = null;
sheetW = SHEET_W;
@@ -194,6 +218,9 @@ export function openSheet(factory: ViewFactory) {
if (!ownsHistory) {
try {
history.pushState({ sheet: true }, '');
// The sheet's own entry never moves the page: left behind once the sheet closes, a step forward onto it (Safari's
// swipe in from the right edge) would put the page back where it stood when the sheet opened.
history.scrollRestoration = 'manual';
ownsHistory = true;
} catch {
/* no history */
@@ -203,63 +230,91 @@ export function openSheet(factory: ViewFactory) {
/** `now`: gone at once (Escape: what the keyboard does never animates). */
export function closeSheet(now = false) {
if (!sheetOpen() || root.dataset.closing) return;
if (!sheetOpen()) return;
if (root.dataset.closing) {
// Escape while it goes, or the link stopped working: gone at once, and nothing opens after it.
if (now) {
next = null;
gone();
}
return;
}
leave();
if (ownsHistory) {
ownsHistory = false;
history.back();
}
document.body.classList.remove('locked');
const done = () => {
root.classList.remove('open');
root.setAttribute('aria-hidden', 'true');
delete root.dataset.closing;
sheetEl.style.transform = '';
scrim.style.opacity = '';
sheetEl.getAnimations().forEach((a) => a.cancel());
scrim.getAnimations().forEach((a) => a.cancel());
vp.getAnimations().forEach((a) => a.cancel());
vp.replaceChildren();
actsEl.replaceChildren();
sheetEl.classList.remove('arrived');
sheetEl.style.maxWidth = '';
sheetW = SHEET_W;
stack = [];
if (returnFocus?.isConnected) returnFocus.focus({ preventScroll: true });
returnFocus = null;
const f = closed;
closed = null;
f?.();
};
if (now) return done();
if (now) return gone();
root.dataset.closing = '1';
const from = getComputedStyle(sheetEl).transform;
sheetEl.getAnimations().forEach((a) => a.cancel());
// From where it stands: a dialog still coming up leaves from its present fade, blur and scale.
const cs = getComputedStyle(sheetEl);
const at = cs.transform;
const op = cs.opacity;
const blur = cs.filter === 'none' ? 'blur(0px)' : cs.filter;
const dim = getComputedStyle(scrim).opacity;
running(sheetEl, 'transform', 'opacity').forEach((a) => a.cancel());
scrim.getAnimations().forEach((a) => a.cancel());
play(
scrim,
[{ opacity: getComputedStyle(scrim).opacity }, { opacity: 0 }],
[{ opacity: dim }, { opacity: 0 }],
wide() ? { duration: 120, easing: EASE_IN, fill: 'forwards' } : { duration: 320, easing: 'ease-out', fill: 'forwards' },
);
const at = from === 'none' ? 'none' : from;
// A dialog goes the way a ⋯ menu does, quick and soft into its centre; the drawer goes down past the edge.
play(
sheetEl,
wide()
? [
{ opacity: 1, transform: at, filter: 'blur(0px)' },
{ opacity: op, transform: at, filter: blur },
{ opacity: 0, transform: `${at === 'none' ? '' : at} scale(.96)`.trim(), filter: 'blur(3px)' },
]
: [{ transform: at }, { transform: 'translateY(calc(100% + 40px))' }],
wide() ? { duration: 120, easing: EASE_IN, fill: 'forwards' } : { duration: 420, easing: DRAWER, fill: 'forwards' },
).onfinish = done;
).onfinish = gone;
}
// The phone's back button closes the sheet instead of leaving the page.
/** The sheet is out of the page: emptied, focus back on what opened it, then whatever waited for it. */
function gone() {
// Nothing a view holds (a poll) outlives the sheet.
leave();
root.classList.remove('open');
root.setAttribute('aria-hidden', 'true');
delete root.dataset.closing;
sheetEl.style.transform = '';
scrim.style.opacity = '';
sheetEl.getAnimations().forEach((a) => a.cancel());
scrim.getAnimations().forEach((a) => a.cancel());
vp.replaceChildren();
actsEl.replaceChildren();
sheetEl.classList.remove('arrived');
sheetEl.style.maxWidth = '';
sheetW = SHEET_W;
stack = [];
if (returnFocus?.isConnected) returnFocus.focus({ preventScroll: true });
returnFocus = null;
const f = closed;
closed = null;
f?.();
const n = next;
next = null;
if (n) openSheet(n);
}
/** On the history entry a sheet pushed (openSheet): closing it steps back to the page's own. */
export const onSheetEntry = () => !!(history.state as { sheet?: boolean } | null)?.sheet;
// The phone's back button closes the sheet instead of leaving the page. A sheet's entry is current only while its
// sheet is open: one left behind (a reload with a sheet open, a step forward onto it) is stepped back off at once, so
// Back from there leaves the page instead of putting it back where it stood when that sheet opened.
addEventListener('popstate', () => {
if (!sheetOpen()) return;
if (!sheetOpen()) {
if (onSheetEntry()) history.back();
return;
}
ownsHistory = false;
closeSheet();
});
if (onSheetEntry()) history.back();
/** A view's own buttons beside ×: pinned with it while the sheet scrolls, they come and go with the view. */
function setActs(v: View, anim = true) {
@@ -301,17 +356,38 @@ function setActs(v: View, anim = true) {
}
}
/**
* The viewport glides from `h0`, its height on screen, to its view's: as a gap under the view that closes, or an
* overhang the viewport clips, so what changes inside meanwhile (a row opening, a fold, a poll) carries the sheet's
* edge along instead of landing when the glide ends.
*/
function glideHeight(view: Element | null, h0: number, o: KeyframeAnimationOptions) {
if (!view) return;
running(view, 'marginBottom').forEach((a) => a.cancel());
const d = h0 - vp.getBoundingClientRect().height;
if (Math.abs(d) > 1) play(view, [{ marginBottom: `${d}px` }, { marginBottom: '0px' }], o);
}
/** Another view in the open sheet: the old one fades out over the new one, the sheet glides to its height. */
function swapView(v: View) {
label(v);
setActs(v);
sheetEl.classList.remove('arrived');
const old = [...vp.children] as HTMLElement[];
const h0 = vp.getBoundingClientRect().height;
vp.getAnimations().forEach((a) => a.cancel());
old.forEach((o) => {
// What goes stays where it stands on screen while the scroll goes back to the top under it (the viewport clips it);
// a view already on its way out keeps its own fade.
const st = scroller.scrollTop;
const views = [...vp.children] as HTMLElement[];
const tops = views.map((o) => (o.classList.contains('leaving') ? parseFloat(o.style.top) || 0 : 0) - st);
const old = views.filter((o) => !o.classList.contains('leaving'));
// It fades from how it shows: one still coming in (Back right after a step) goes from as far as it came.
const shown = old.map((o) => {
const cs = getComputedStyle(o);
return { opacity: cs.opacity, transform: cs.transform, filter: cs.filter };
});
views.forEach((o, i) => {
o.classList.add('leaving');
Object.assign(o.style, { position: 'absolute', left: '0', right: '0', top: '0', pointerEvents: 'none' });
Object.assign(o.style, { position: 'absolute', left: '0', right: '0', top: `${tops[i]}px`, pointerEvents: 'none' });
o.inert = true;
});
vp.appendChild(v.el);
@@ -319,25 +395,17 @@ function swapView(v: View) {
v.el.style.pointerEvents = 'none';
setTimeout(() => (v.el.style.pointerEvents = ''), 320);
scroller.scrollTop = 0;
const plan = planWidth();
const h1 = v.el.getBoundingClientRect().height;
play(vp, [{ height: `${h0}px` }, { height: `${h1}px` }], { duration: 360, easing: 'cubic-bezier(.25,1,.5,1)' });
startWidth(plan);
old.forEach(
(o) =>
(play(
o,
[
{ opacity: 1, transform: 'none', filter: 'none' },
{ opacity: 0, transform: 'scale(.96)', filter: 'blur(2px)' },
],
{
duration: 200,
easing: 'cubic-bezier(.2,0,0,1)',
fill: 'forwards',
},
).onfinish = () => o.remove()),
);
startWidth(planWidth());
glideHeight(v.el, h0, { duration: 360, easing: 'cubic-bezier(.25,1,.5,1)' });
old.forEach((o, i) => {
const prior = o.getAnimations();
play(o, [shown[i], { opacity: 0, transform: 'scale(.96)', filter: 'blur(2px)' }], {
duration: 200 * +shown[i].opacity,
easing: 'cubic-bezier(.2,0,0,1)',
fill: 'forwards',
}).onfinish = () => o.remove();
prior.forEach((a) => a.cancel());
});
play(
v.el,
[
@@ -355,14 +423,14 @@ function swapView(v: View) {
/** Further into a flow (Add → Open on the device). */
export function go(factory: ViewFactory) {
if (!sheetOpen()) return openSheet(factory);
if (!sheetOpen() || root.dataset.closing) return openSheet(factory);
leave();
stack.push(factory);
swapView(factory());
}
export function back() {
if (stack.length < 2) return;
if (stack.length < 2 || root.dataset.closing) return;
leave();
stack.pop();
swapView(stack[stack.length - 1]());
@@ -375,19 +443,17 @@ export function back() {
*/
export function glide(change: () => void, focus: (Element | null | undefined)[] = []) {
if (!sheetOpen()) return change();
const h0 = vp.getBoundingClientRect().height;
vp.getAnimations().forEach((a) => a.cancel());
const view = vp.lastElementChild;
// As it all stands on screen, the sheet's own glides under way included.
const was = new Map<Element, DOMRect>();
view?.querySelectorAll('*').forEach((e) => {
if (!(e instanceof SVGElement) || e instanceof SVGSVGElement) was.set(e, e.getBoundingClientRect());
});
const h0 = vp.getBoundingClientRect().height;
change();
const plan = planWidth();
const h1 = vp.getBoundingClientRect().height;
if (Math.abs(h1 - h0) > 1) play(vp, [{ height: `${h0}px` }, { height: `${h1}px` }], { duration: SMOOTH.duration, easing: SMOOTH.easing });
startWidth(plan);
// Measured with the sheet back at its old size (its glides have just started): only what moved inside it moves.
startWidth(planWidth());
glideHeight(view, h0, { duration: SMOOTH.duration, easing: SMOOTH.easing });
// Measured with the sheet back at its size on screen (its glides have just started): only what moved inside it moves.
const moved = new Set<Element>();
for (const [e, r] of was) {
if (!e.isConnected || !r.width || !r.height) continue;
@@ -401,7 +467,13 @@ export function glide(change: () => void, focus: (Element | null | undefined)[]
let p = e.parentElement;
while (p && p !== view && !moved.has(p)) p = p.parentElement;
if (p && p !== view) continue;
play(e, [{ transform: `translate(${dx}px, ${dy}px)` }, { transform: 'none' }], { duration: SMOOTH.duration, easing: SMOOTH.easing });
// Added to a glide still under way (a quick second pick), which runs on to its end underneath: both rects held
// its offset, so this is only the new move, and nothing it had left to go is dropped.
play(e, [{ transform: `translate(${dx}px, ${dy}px)` }, { transform: 'none' }], {
duration: SMOOTH.duration,
easing: SMOOTH.easing,
composite: 'add',
});
}
for (const el of focus)
if (el)
@@ -415,9 +487,12 @@ export function glide(change: () => void, focus: (Element | null | undefined)[]
);
}
/** The view's job is done (a device connected): ×, and the view's own buttons, step away. */
export function settle() {
sheetEl?.classList.add('arrived');
/**
* The view's job is done (a device connected): ×, and the view's own buttons, step away. `false`: it turned out
* not to be (the device left that state): they come back.
*/
export function settle(done = true) {
sheetEl?.classList.toggle('arrived', done);
}
/** The sheet scrolls back to the top (a device connected under a scrolled sheet). */
@@ -428,12 +503,27 @@ export const showing = (el: Element) => sheetOpen() && vp.contains(el) && !el.cl
/* ---------- pull down by the header to close ---------- */
/** The dim a pull alone leaves: it fades as the sheet goes down. */
const dimAt = (dy: number) => Math.max(0, 1 - Math.max(0, dy) / 420);
function pullToClose() {
let drag: { y: number; t: number; dy: number; v: number } | null = null;
// `y`: where the finger would stand with the sheet at rest; `y0`: where the sheet was taken; `off`: how far the dim
// was then from what the pull alone gives (a sheet taken while it still opens).
let drag: { y: number; t: number; dy: number; v: number; y0: number; off: number } | null = null;
sheetEl.addEventListener('pointerdown', (e) => {
const t = e.target as Element;
if (!t.closest('.vhead') || t.closest('button, a, input')) return;
drag = { y: e.clientY, t: performance.now(), dy: 0, v: 0 };
// Not while it leaves, nor while a dialog pops up: its fade and blur ride the same animation as its scale.
if (root.dataset.closing || running(sheetEl, 'opacity').length) return;
// Taken where it stands (still rising, or settling back from the last pull), and the dim with it.
const y0 = new DOMMatrixReadOnly(getComputedStyle(sheetEl).transform).m42;
const o = +getComputedStyle(scrim).opacity;
running(sheetEl, 'transform').forEach((a) => a.cancel());
scrim.getAnimations().forEach((a) => a.cancel());
if (y0) sheetEl.style.transform = `translateY(${y0}px)`;
if (o !== 1) scrim.style.opacity = String(o);
const raw = y0 < 0 ? -unrubber(-y0, sheetEl.offsetHeight) : y0;
drag = { y: e.clientY - raw, t: performance.now(), dy: y0, v: 0, y0, off: o - dimAt(y0) };
sheetEl.setPointerCapture(e.pointerId);
});
sheetEl.addEventListener('pointermove', (e) => {
@@ -446,17 +536,22 @@ function pullToClose() {
drag.dy = dy;
drag.t = t;
sheetEl.style.transform = `translateY(${dy}px)`;
scrim.style.opacity = String(Math.max(0, 1 - Math.max(0, dy) / 420));
scrim.style.opacity = String(Math.min(1, Math.max(0, dimAt(dy) + drag.off)));
});
const end = () => {
if (!drag) return;
const { dy, v } = drag;
const { dy, v, y0 } = drag;
drag = null;
if (dismisses(dy, v, sheetEl.offsetHeight)) return closeSheet();
// A touch that never moved (on a sheet still rising) only lets it settle.
if (dy !== y0 && dismisses(dy, v, sheetEl.offsetHeight)) return closeSheet();
// Back to rest from where the pull left it, the dim with it on the same spring.
const from = sheetEl.style.transform;
const dim = getComputedStyle(scrim).opacity;
sheetEl.style.transform = '';
scrim.style.opacity = '';
if (dy !== 0) play(sheetEl, [{ transform: from }, { transform: 'none' }], { duration: SMOOTH.duration, easing: SMOOTH.easing });
const o = { duration: SMOOTH.duration, easing: SMOOTH.easing };
if (dy !== 0) play(sheetEl, [{ transform: from }, { transform: 'none' }], o);
if (+dim !== 1) play(scrim, [{ opacity: dim }, { opacity: 1 }], o);
};
sheetEl.addEventListener('pointerup', end);
sheetEl.addEventListener('pointercancel', end);
+151
View File
@@ -0,0 +1,151 @@
// A light sweeping across a field's words while they are on their way to the router (a device's name being
// saved), as an assistant's "thinking" line does: a copy of the words laid exactly over the input's dims, and a
// band with a bell-shaped falloff crosses it again and again with a rest between. Stopping holds the band where it
// is and fades the words back to their colour around it; only then does the copy go, so the input's own words
// (or what takes their place) show with nothing changing. The band is the words' own colour over a muted base
// (styles/controls.css, `.shim`). With less motion asked for it only dims and comes back.
import { h } from '../dom';
import { calm } from '../motion';
/** A cubic-bezier easing as a function of progress (0..1). */
function bezier(x1: number, y1: number, x2: number, y2: number): (x: number) => number {
const at = (a: number, b: number, t: number) => 3 * a * t * (1 - t) ** 2 + 3 * b * t * t * (1 - t) + t ** 3;
return (x) => {
let lo = 0;
let hi = 1;
for (let i = 0; i < 24; i++) {
const mid = (lo + hi) / 2;
if (at(x1, x2, mid) < x) lo = mid;
else hi = mid;
}
return at(y1, y2, (lo + hi) / 2);
};
}
const STANDARD = bezier(0.2, 0, 0, 1);
const linear = (x: number) => x;
/** One value that moves; a new move of it stops the old one first. */
class Value {
v: number;
private stop: (() => void) | null = null;
constructor(
v: number,
private paint: () => void,
) {
this.v = v;
}
/** To `to` over `ms` (after `delay`), from where it is: true once there, false if stopped first. */
to(to: number, ms: number, ease: (x: number) => number, delay = 0): Promise<boolean> {
this.halt();
return new Promise((done) => {
let t0 = 0;
let from = this.v;
const step = (now: number) => {
if (!t0) {
t0 = now + delay;
from = this.v;
}
const k = ms <= 0 ? 1 : Math.min(1, Math.max(0, (now - t0) / ms));
if (now >= t0) {
this.v = from + (to - from) * ease(k);
this.paint();
}
if (k < 1) raf = requestAnimationFrame(step);
else {
this.stop = null;
done(true);
}
};
let raf = requestAnimationFrame(step);
this.stop = () => {
cancelAnimationFrame(raf);
this.stop = null;
done(false);
};
});
}
halt() {
this.stop?.();
}
}
/** Half the band's width in em, and its falloff as [offset, strength]. */
const BAND = 2.2;
const FALLOFF = [
[-1, 0],
[-0.5, 0.5],
[-0.2, 0.9],
[0, 1],
[0.2, 0.9],
[0.5, 0.5],
[1, 0],
] as const;
const pct = (x: number) => `${(x * 100).toFixed(1)}%`;
/** The band at sweep `t` (0: left of the words, 1: right of them) over a base `settle` of the way to solid. */
function image(t: number, settle: number): string {
const base = `color-mix(in oklab, var(--shim-high) ${pct(settle)}, var(--shim-base))`;
const stops = FALLOFF.map(
([o, k]) =>
`color-mix(in oklab, var(--shim-high) ${pct(k)}, ${base}) calc(${(t * 100).toFixed(2)}% + ${((2 * t - 1 + o) * BAND).toFixed(3)}em)`,
);
return `linear-gradient(90deg, ${base}, ${stops.join(', ')}, ${base})`;
}
/** The input's font, for a copy of its words that has to sit exactly on them. */
const FONT = ['fontFamily', 'fontSize', 'fontWeight', 'letterSpacing', 'fontFeatureSettings', 'fontVariationSettings'] as const;
/** Seconds for one sweep across the words, and the rest between sweeps (a share of it). */
const SWEEP = 1.8;
const REST = 0.32;
/** How long the words take to fade back to their colour once the answer is in, in ms. */
const SETTLE = 480;
/**
* Start the shimmer over `input` (inside `field`, which it marks `.saving`). Returns the stop, which resolves
* once the words are solid again and the copy is gone.
*/
export function shimmer(field: HTMLElement, input: HTMLInputElement): () => Promise<void> {
const cs = getComputedStyle(input);
// The copy sits in a box the input's size and is clipped to it, scrolled as the input is: a name longer than
// the field shows the same part, never more.
const copy = h('span', { class: 'shim' }, input.value);
const clip = h('span', { class: 'shim-clip', 'aria-hidden': 'true' }, copy);
for (const k of FONT) copy.style[k] = cs[k];
Object.assign(clip.style, {
left: `${input.offsetLeft}px`,
top: `${input.offsetTop}px`,
width: `${input.clientWidth}px`,
height: `${input.offsetHeight}px`,
});
Object.assign(copy.style, { left: `${-input.scrollLeft}px`, lineHeight: `${input.offsetHeight}px` });
const still = calm();
const paint = () => (copy.style.backgroundImage = image(sweep.v, settle.v));
// Solid at first, exactly the input's words: the swap shows nothing, then it dims.
const sweep = new Value(0, paint);
const settle = new Value(1, paint);
paint();
field.append(clip);
field.classList.add('saving');
field.setAttribute('aria-busy', 'true');
let running = !still;
const pass = async (delay: number) => {
if (!running) return;
if (sweep.v >= 1) sweep.v = 0;
if (await sweep.to(1, SWEEP * 1000 * (1 - sweep.v), linear, delay * 1000)) void pass(SWEEP * REST);
};
void pass(0.12);
void settle.to(0, still ? 0 : 240, STANDARD);
return async () => {
// The band stops where it is and the words fade back to their colour around it: nothing races off.
running = false;
sweep.halt();
await settle.to(1, still ? 0 : SETTLE, STANDARD);
field.classList.remove('saving');
field.removeAttribute('aria-busy');
clip.remove();
};
}
+25
View File
@@ -0,0 +1,25 @@
// What the set-up sheet's way shows, read off the device in the router's last
// answer (`setup` on every device view: the agent's watcher's; without the
// agent the router counts a session that lives as data flowing): waiting,
// can't finish (its knocks reach the router, no handshake follows), connected
// (a handshake since the sheet opened, and data coming through), no data (a
// handshake since then, but nothing in except handshakes and keep-alives: an
// outdated configuration). Pure: flows/wait.ts polls for it and draws it.
import type { Device } from '../shared/types';
export type WayState = 'waiting' | 'trying' | 'connected' | 'nodata';
/**
* The way's state for `d` (undefined: no longer in the answer), `opened` being when the sheet opened (router
* clock). Arrival is data flowing, not the first handshake, so no data shows instead of the sheet closing; a
* handshake from before the sheet is not this set-up's. Knocks that never finish show whenever they come. Anything
* else (the device gone offline, quiet, or removed) is plain waiting.
*/
export function wayState(d: Device | undefined, opened: number): WayState {
if (!d) return 'waiting';
if (d.setup?.state === 'trying') return 'trying';
if (d.handshake <= opened) return 'waiting';
if (d.setup?.state === 'flowing') return 'connected';
return d.setup?.state === 'nodata' ? 'nodata' : 'waiting';
}
+83 -1
View File
@@ -1,7 +1,7 @@
// 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 type { Access, Kind, Person, PersonState, Server } from './types';
import { fmt, locale, num, plural } from './i18n';
/** A size with its unit: one decimal from 1 KB up to 100 of a unit ("1.5 GB", "120 MB"). */
@@ -155,6 +155,73 @@ export function accessLabel(a: Access): string {
return { lan: _('Home network'), internet: _('Internet'), both: _('Home network + Internet') }[a];
}
/** The longest name a device takes, in characters (the router's DEVICE_NAME_MAX, util.uc). */
export const DEVICE_NAME_MAX = 20;
/**
* Past ASCII, the blocks a device's name doesn't take: symbols, punctuation, arrows, maths, emoji and invisibles
* (the router refuses the same, util.uc NAME_SYMBOLS). Code point ranges, both ends in.
*/
const NAME_SYMBOLS: [number, number][] = [
[0x80, 0xbf],
[0xd7, 0xd7],
[0xf7, 0xf7],
[0x2000, 0x2bff],
[0x3000, 0x303f],
[0xd800, 0xf8ff],
[0xfe00, 0xfe0f],
[0xfe30, 0xfe4f],
[0xfeff, 0xfeff],
[0xfff0, 0xffff],
[0x1f000, 0x1fbff],
[0xe0000, 0xe007f],
];
const ASCII_NAME = /^[A-Za-z0-9 ._-]$/;
const LETTER = /^[\p{L}\p{M}\p{N}]$/u;
/**
* One character a device's name may hold: a letter of any language (with its marks) or a digit, a space, - _ or
* . (the router checks the ASCII ones and refuses the symbol blocks past it; this also asks Unicode it is a letter).
*/
export function deviceNameChar(ch: string): boolean {
const cp = ch.codePointAt(0) ?? 0;
if (cp < 0x80) return ASCII_NAME.test(ch);
return !NAME_SYMBOLS.some(([a, b]) => cp >= a && cp <= b) && LETTER.test(ch);
}
/** `s` could still become a device's name as it is typed: only those characters, no more than DEVICE_NAME_MAX. */
export function deviceNameFits(s: string): boolean {
const chars = [...s];
return chars.length <= DEVICE_NAME_MAX && chars.every(deviceNameChar);
}
/** A device's name the router takes: not blank, and it fits (spaces around are trimmed). */
export const validDeviceName = (s: string): boolean => !!s.trim() && deviceNameFits(s.trim());
/**
* A name made up for a device (its kind, the phone's model), as the router takes it: what it refuses stripped
* ("Galaxy S24+" → "Galaxy S24"), cut to fit with `suffix` after it ("Phone 2"), not left ending in a space.
* Nothing left: the kind-less "Device".
*/
export function fitName(base: string, suffix = ''): string {
const clean =
[...base]
.map((c) => (deviceNameChar(c) ? c : ' '))
.join('')
.replace(/\s+/g, ' ')
.trim() || _('Device');
const cut = [...clean]
.slice(0, Math.max(1, DEVICE_NAME_MAX - [...suffix].length))
.join('')
.trimEnd();
return cut + suffix;
}
/** The name a device of kind `k` gets when nobody gives it one, in the page's language: "Phone", "Device". */
export function defaultName(k: Kind): string {
return k === 'other' ? _('Device') : kindLabel(k);
}
/** In picker order. */
export const KINDS: Kind[] = ['computer', 'phone', 'tablet', 'router', 'other'];
@@ -207,3 +274,18 @@ export function byDeviceState<T extends { online: boolean; handshake: number; di
.sort((a, b) => rank(a[0]) - rank(b[0]) || a[1] - b[1])
.map(([d]) => d);
}
/** Networks as people read them: a /24 as its first three numbers and x ("10.0.1.x"), others as they are. */
export function netsLabel(nets: string[]): string {
return nets.map((n) => (n.endsWith('.0/24') ? `${n.slice(0, -5)}.x` : n)).join(', ');
}
/**
* The home networks a device of `p` with LAN Bypass still sends into the tunnel: with home and internet access,
* the server's home networks they reach (all of them, or the ones picked for them). None otherwise.
*/
export function homeOf(p: Person, srv: Server | undefined): string[] {
if (p.access !== 'both' || !srv) return [];
const pick = p.home_nets ?? [];
return srv.home.filter((h) => !pick.length || pick.includes(h.dev)).flatMap((h) => h.nets);
}
+59
View File
@@ -0,0 +1,59 @@
// A device's name as it is typed, in the portal and the admin: what the router would refuse never gets in. A
// character it doesn't take (letters of any language, digits, spaces and - _ . only) or one past DEVICE_NAME_MAX is turned
// away as it is typed, pasted or dropped, `field` shakes and `tell` gets a short reason for the field's red line,
// then null once a change gets in. Nothing is asked of the router for it. Emptying the field is fine as it
// happens: a submit says so. The router checks the same on its own (util.uc): this only spares the round trip.
import { DEVICE_NAME_MAX, deviceNameChar, deviceNameFits } from './format';
import { fmt, num } from './i18n';
import { shake } from './shake';
/** Why `next` doesn't fit, short enough for a card's status line: a character it doesn't take, else its length. */
function why(next: string): string {
return [...next].every(deviceNameChar) ? fmt(_('Up to %s characters.'), num(DEVICE_NAME_MAX)) : _('Only letters, digits, - _ .');
}
/**
* Call it as the input is built, before its own `input` listeners: a refused change is undone before they see it.
* `field`: what shakes (a getter, for a field built after its input); the input itself by default. `look`: as
* shake() takes it (no red ring for a field drawn without one).
*/
export function guardDeviceName(
input: HTMLInputElement,
field: HTMLElement | (() => HTMLElement) = input,
tell: (why: string | null) => void = () => {},
look: { ring?: boolean } = {},
) {
const box = () => (typeof field === 'function' ? field() : field);
let last = input.value;
input.addEventListener('beforeinput', (e) => {
last = input.value;
// Deleting is always fine; typing through an IME is checked once it lands (it can't be refused mid-way).
if (e.inputType.startsWith('delete') || e.isComposing || e.inputType === 'insertCompositionText') return;
const text = e.data ?? e.dataTransfer?.getData('text/plain') ?? '';
const s = input.selectionStart ?? input.value.length;
const end = input.selectionEnd ?? s;
const next = input.value.slice(0, s) + text + input.value.slice(end);
if (deviceNameFits(next)) return;
e.preventDefault();
shake(box(), look);
tell(why(next));
});
// What got in anyway (an IME's letters, autofill): back to what it was, caret where it stood. Deleting stays
// (an old name the rules came after is shortened a letter at a time).
input.addEventListener('input', (e) => {
const deleting = e instanceof InputEvent && e.inputType.startsWith('delete');
if (deleting || deviceNameFits(input.value)) {
last = input.value;
tell(null);
return;
}
const next = input.value;
const at = Math.min(input.selectionStart ?? last.length, last.length);
input.value = last;
input.setSelectionRange(at, at);
e.stopImmediatePropagation();
shake(box(), look);
tell(why(next));
});
}
+34 -3
View File
@@ -27,6 +27,39 @@ const ROUND: Record<'night' | 'day', [bg: string, fg: string]> = { night: [NIGHT
/** Long content: fewer modules matter more than the mark. */
export const denseQr = (text: string): boolean => text.length > 300;
/** The last code made: qrSvg right after qrFits on the same text does not make it again. */
let made: { text: string; qr: ReturnType<typeof qrcode> } | null = null;
/** The code for a text, at the level qrSvg draws it with; throws when no version holds the text. */
function make(text: string) {
if (made?.text === text) return made.qr;
const qr = qrcode(0, denseQr(text) ? 'L' : 'H');
qr.addData(text, 'Byte');
qr.make();
made = { text, qr };
return qr;
}
/** Does the text fit in a code at all? Version 40 holds 2953 bytes at level L; past that the library throws. */
export function qrFits(text: string): boolean {
try {
make(text);
return true;
} catch {
return false;
}
}
/**
* Past about 1.6 KB (version 29-L, 133 modules) a code on a phone's screen is
* too fine for another phone's camera, even before it stops fitting at all
* (an AmneziaVPN key on Maximum without compression is about 3.3 KB).
*/
const SCAN_MAX = 1600;
/** Can a camera read this text from a code on a screen? */
export const scannable = (text: string): boolean => text.length <= SCAN_MAX && qrFits(text);
const n2 = (v: number) => +v.toFixed(2);
/** A rounded rectangle as a sub-path. */
function rrect(x: number, y: number, w: number, h: number, r: number): string {
@@ -41,9 +74,7 @@ export function qrSvg(text: string, margin = 3, logo = true, look: QrLook = 'pla
// The night and day looks draw the same round dots and eyes; only their colours differ.
const round = look !== 'plain';
const [bg, fg] = round ? ROUND[look] : ['#fff', '#000'];
const qr = qrcode(0, dense ? 'L' : 'H');
qr.addData(text, 'Byte');
qr.make();
const qr = make(text);
const n = qr.getModuleCount();
const size = n + margin * 2;
// A centred, module-aligned hole for the mark (same parity as n).
+52
View File
@@ -0,0 +1,52 @@
// The field shake for a name it won't take (iOS's wrong passcode): a damped swing sideways, about four times in
// half a second, from wherever a shake under way has it, so another one starts over without a jump; and its
// outline goes red at once and fades back to what it is. Only their own animations are touched (the field's
// transitions go on). With less motion asked for it doesn't move; the outline still says it. Used by the portal
// and the admin both (shared/name-guard.ts).
const FRAMES = 30;
const SWING = Array.from({ length: FRAMES + 1 }, (_, i) => {
const t = i / FRAMES;
return 14 * Math.exp(-4.2 * t) * Math.sin(t * Math.PI * 2 * 3.6);
});
/** How long the outline stays red, then how long it takes to fade back, in ms. */
const RED_HOLD = 700;
const RED_FADE = 800;
/**
* The outline red at once (a 1.5 px ring: inside the portal's field, as its focus ring is; around the admin's
* input), then back to whatever the field shows now, focused or not. Another one starts red again.
*/
function redden(el: HTMLElement) {
el.getAnimations()
.filter((a) => a.id === 'redden')
.forEach((a) => a.cancel());
const cs = getComputedStyle(el);
const inset = el.classList.contains('field') ? 'inset ' : '';
const red = `${inset}0 0 0 1.5px ${cs.getPropertyValue('--bad').trim() || '#e5484d'}`;
const all = RED_HOLD + RED_FADE;
// No last frame: it fades into the field's own ring as it is then, a focus ring still coming in included.
el.animate(
[
{ boxShadow: red, offset: 0 },
{ boxShadow: red, offset: RED_HOLD / all, easing: 'cubic-bezier(0.23, 1, 0.32, 1)' },
],
{ duration: all, id: 'redden' },
);
}
/** `ring: false` for a field drawn without one (a name edited in place on its card): it only moves. */
export function shake(el: HTMLElement, o: { ring?: boolean } = {}) {
if (o.ring !== false) redden(el);
if (typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches) return;
const tr = getComputedStyle(el).transform;
const from = tr && tr !== 'none' ? new DOMMatrix(tr).m41 : 0;
el.getAnimations()
.filter((a) => a.id === 'shake')
.forEach((a) => a.cancel());
el.animate(
SWING.map((x, i) => ({ transform: `translateX(${(i === 0 ? from : x).toFixed(2)}px)` })),
{ duration: 520, easing: 'linear', id: 'shake' },
);
}
+51
View File
@@ -5,6 +5,35 @@ export type Kind = 'computer' | 'phone' | 'tablet' | 'router' | 'other';
export type PersonState = 'active' | 'paused' | 'expired' | 'quota' | 'hours' | 'no_server' | 'server_off';
export type Pair = [number, number]; // [rx, tx] from the router's point of view
/**
* A device's link failing in a named way (the agent's watcher), shown once it
* held 3 minutes: trying (it knocks, never finishes connecting), shared (one
* configuration on two devices), dropped (connected, but the router drops
* what it sends), unstable (the connection keeps breaking).
*/
export type LinkState = 'trying' | 'shared' | 'dropped' | 'unstable';
export interface DeviceLink {
state: LinkState;
/** When it began (router clock). */
since: number;
}
/**
* What a device's link does right now, without that hold, for the set-up
* sheet: trying (its initiations reach the router, no handshake follows),
* flowing (online, data came in during this session), nodata (online for
* 15 s with nothing but handshakes and keepalives in, and the router
* answering what it dropped: an old address in its configuration).
*/
export type SetupState = 'trying' | 'flowing' | 'nodata';
export interface DeviceSetup {
state: SetupState;
/** When the watcher first saw it (router clock). */
since: number;
}
export interface Device {
id: string;
name: string;
@@ -25,6 +54,23 @@ export interface Device {
browser_key: boolean;
/** Its configuration changed (networks, DNS, keys...) since it was last shown or downloaded. */
config_stale: boolean;
// How it connects (set by the admin, LAN Bypass also by the person when adding it).
/** LAN Bypass: its own local network stays outside the tunnel (chosen when it was added). */
lan_bypass: boolean;
/** Its own MTU; 0 = the server's (automatic by kind and disguise). */
mtu: number;
/** Its own keep-alive in seconds (0 = off); null = the server's. */
keepalive: number | null;
/** The MTU and keep-alive its configuration carries now; null without a server. */
mtu_used: number | null;
keepalive_used: number | null;
/** Its link failing in a named way; null when it is not. */
link: DeviceLink | null;
/**
* What its link does right now (the set-up sheet); null for none of these. Without the router's agent a session
* that lives counts as flowing (nobody tells data from a bare handshake then).
*/
setup: DeviceSetup | null;
}
export interface Person {
@@ -122,7 +168,10 @@ export interface Server {
/** The newest handshake from a public address that is not the router's own (0: never). */
reached?: number;
online: number;
/** The disguise parameters, without the header protection key: only device configurations carry it. */
obf: Record<string, string>;
/** The disguise has a header protection key (AmneziaWG 3.1). */
hpk: boolean;
}
export interface DayUsage {
@@ -182,6 +231,8 @@ export interface AwgCaps {
kmod?: string | null;
/** The two differ: a feature counts only when both have it. */
mismatch?: boolean;
/** An installed kernel module waits for a reboot (kmod is the one that runs until then). */
pending?: boolean;
}
/** Whether AmneziaWG can run here: tools and kernel module installed, the module loaded, netifd's proto handler present. */
+12 -4
View File
@@ -4,14 +4,19 @@
import type { ClientConfig } from './types';
/**
* What a parameter the server does not set reads as. S3 and S4 stay empty: the
* app names a key "AmneziaWG (version 2)" when either is there (awgVersionOf in
* amnezia-client), and every platform skips an empty one.
*/
const DEFAULTS: Record<string, string> = {
jc: '0',
jmin: '0',
jmax: '0',
s1: '0',
s2: '0',
s3: '0',
s4: '0',
s3: '',
s4: '',
h1: '1',
h2: '2',
h3: '3',
@@ -94,8 +99,11 @@ export function amneziaJson(cfg: ClientConfig, description: string): Record<stri
description,
hostName: host,
};
if (a.dns[0]) out.dns1 = a.dns[0];
if (a.dns[1]) out.dns2 = a.dns[1];
// Without a dns2 the app adds its own (Cloudflare by default), which bypasses the home DNS: one server goes in as both.
if (a.dns[0]) {
out.dns1 = a.dns[0];
out.dns2 = a.dns[1] || a.dns[0];
}
return out;
}