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

- Add V2RayTun to a device's set-up on Android: its awg:// link as a code and to copy, in the portal and in the admin (phones, tablets and other devices), with the server's IP, which its Android app needs; not with the Maximum disguise. Its Windows app is ready but stays off until it gives the tunnel the server's DNS.
- Portal: show V2RayTun's Telegram channel beside Google Play.
- Make WireGuard part of AmneziaWG's choice when the disguise is off: the same file and code, both apps named in the steps, WireGuard's store a tap away; a router still picks its package.
- Portal: Reconnect asks again what the device is and about LAN Bypass, and LAN Bypass switches from a device's ⋯ menu, in a group of its own between the copy actions and Rename, Reconnect, Remove (the keys stay; the device takes its updated configuration).
- Turn LAN Bypass on by default for new devices, in the portal and the admin.
- Portal: an app's name too long for the picker fades at its edge and glides to its end on hover or tap; two store buttons stack where they do not fit side by side; the month chart's "Today" stays inside its axis.
- Write to the router's system log by level (Settings → Logs & history → System log: errors, warnings, normal, verbose): the service starting and stopping, every apply with its time, network, firewall, nftables and peer changes, changed settings and portal errors, in English whatever the admin's language, with keys masked.
- Activity: say what a device's change on the portal was (LAN Bypass on or off, its type).
- Demo: build again after a force-pushed main instead of failing on the commit that is gone.
This commit is contained in:
Aemeath committed 2026-11-05 13:56:20 +03:00
1 parent 18e3013047
commit f8130e39a8
65 files changed
+2066 -338

No files matched your search

+3 -1
View File
@@ -62,6 +62,8 @@ export interface DemoDevice {
created: number;
by: 'admin' | 'portal';
stale: boolean;
/** LAN Bypass (unset: off). */
bypass?: 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. */
@@ -168,7 +170,7 @@ 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,
lan_bypass: !!d.bypass,
mtu: 0,
keepalive: null,
// The server's for its kind, as the router works it out (the portal never shows it).
+14 -1
View File
@@ -1,5 +1,5 @@
// The demo's router: portal.uc's API (state, add a device, its settings,
// rename / reconnect / remove) answered from the demo's own devices, which it
// rename / reconnect / LAN Bypass / remove) answered from the demo's own devices, which it
// keeps per visitor. The refusals are the router's (paused, ended, plain HTTP,
// no free slot, a name taken). Nothing is installed and no tunnel exists: the
// keys are random and the server's address never resolves. The page state
@@ -158,6 +158,7 @@ export function createRouter(o: RouterOpts) {
created: clock(),
by: 'portal',
stale: false,
bypass: b.lan_bypass === true,
};
db.devs.push(d);
issued = d.id;
@@ -182,12 +183,24 @@ export function createRouter(o: RouterOpts) {
if (b.action === 'rename') d.name = checkName(b.name, d);
else if (b.action === 'reconnect') {
needHttps();
// What it is and LAN Bypass change with the keys, as on the router.
if (typeof b.kind === 'string') {
if (!KINDS.includes(b.kind as Kind)) refuse(400, 'Unknown device type.');
d.kind = b.kind as Kind;
}
if (typeof b.lan_bypass === 'boolean') d.bypass = b.lan_bypass;
// New keys: the old handshake no longer counts, the device connects again once set up.
d.hs = 0;
d.stale = false;
d.connectAt = soon();
issued = d.id;
extra = { config: config(d) };
} else if (b.action === 'bypass') {
needHttps();
if (typeof b.on !== 'boolean') refuse(400, 'Unknown action.');
// The keys stay; the configuration it holds is out of date until it takes the updated one.
d.bypass = b.on as boolean;
d.stale = true;
} else if (b.action === 'delete') db.devs = db.devs.filter((x) => x !== d);
else refuse(400, 'Unknown action.');
return { ok: true, ...extra, state: state() };
+12 -103
View File
@@ -1,40 +1,29 @@
// Adding a device: what it is (four kinds; phones and tablets are one choice,
// 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.
// on stays reachable while connected (LAN Bypass, on unless they turn it off;
// Reconnect and the card's ⋯ menu change it later: device-actions.ts) 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 kinds and the switch are device-form.ts.
import type { ClientConfig, Kind } from '../../shared/types';
import { defaultName, fitName, netsLabel, pickLabel, pickOf, PICKS, type KindPick } from '../../shared/format';
import { defaultName, fitName, pickOf, PICKS, type KindPick } 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 { 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 { go, head, openSheet, sub, type View } from '../ui/sheet';
import { secureFirst, showSecure } from './secure';
import { IPAD, UA, guessKind, kindOf, kindTiles, lanSwitch } from './device-form';
import { continueSetup } from './setup-view';
// Best guess at the device this page is open on (the browser never tells its real name).
const UA = navigator.userAgent;
const IPAD = /iPad/.test(UA) || (/Macintosh/.test(UA) && navigator.maxTouchPoints > 1);
function guessKind(): Kind {
if (IPAD || /Tablet/i.test(UA) || (/Android/.test(UA) && !/Mobile/.test(UA))) return 'tablet';
if (/Android|iPhone|Mobile/i.test(UA)) return 'phone';
return 'computer';
}
/** Samsung model codes → names people know (S and A series; the code stays in brackets). */
const GALAXY: [RegExp, string][] = [
[/^SM-S93/, 'Galaxy S25'],
@@ -77,9 +66,6 @@ function guessName(kind: Kind): string {
return defaultName(kind);
}
// Mobile is a tablet when this page is open on one (see KindPick).
const kindOf = (p: KindPick): 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
@@ -91,33 +77,6 @@ interface Draft {
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;
@@ -127,7 +86,7 @@ export function startAdd() {
true,
);
if (secureFirst()) return;
const draft: Draft = { bypass: false };
const draft: Draft = { bypass: true };
openSheet(() => vAdd(draft));
}
@@ -147,53 +106,8 @@ function vAdd(draft: Draft): View {
return fitName(n);
};
const kinds = h('div', { class: 'kinds', role: 'radiogroup', 'aria-label': _('What is it?') });
kinds.style.setProperty('--n', String(picks.length));
const tiles = picks.map((k) => {
const t = h(
'button',
{ type: 'button', class: 'kind', role: 'radio', 'aria-label': pickLabel(k), onclick: () => choose(k) },
h('span', { class: 'kind-tile' }, glass(k, 'blue')),
h('span', { class: 'kind-lbl' }, pickLabel(k)),
);
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 kinds = kindTiles(picks, (k) => choose(k));
const lan = lanSwitch(draft.bypass, st.server.home ?? [], (on) => (draft.bypass = on));
const input = h('input', {
type: 'text',
// Not `required`: the browser's own check would stop an empty submit before the field can shake.
@@ -222,14 +136,9 @@ function vAdd(draft: Draft): View {
void modelReady.then(() => {
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: KindPick) {
pick = draft.pick = k;
tiles.forEach((t, i) => {
const on = picks[i] === k;
t.classList.toggle('on', on);
t.setAttribute('aria-checked', String(on));
});
kinds.set(k);
if (draft.name === undefined) {
input.value = suggest(k);
goBtn.classList.add('ready');
@@ -278,7 +187,7 @@ function vAdd(draft: Draft): View {
{ class: '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,
kinds.el,
lan,
form,
err,
+78 -28
View File
@@ -1,19 +1,22 @@
// 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.
// A device's own actions from its ⋯ menu: Reconnect (new keys, what it is and
// LAN Bypass asked again, then the set-up of the new ones), LAN Bypass on or
// off (the same keys, then the set-up of the updated configuration) 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 { pickOf, PICKS, type KindPick } from '../../shared/format';
import { fmt } from '../../shared/i18n';
import { call } from '../api';
import { h } from '../dom';
import { h, ic } 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, onClosed, openSheet, type View } from '../ui/sheet';
import { closeSheet, head, onClosed, openSheet, sub, type View } from '../ui/sheet';
import { kindOf, kindTiles, lanSwitch } from './device-form';
import { secureFirst } from './secure';
import { continueSetup } from './setup-view';
import { continueSetup, openSetup } from './setup-view';
/** A question before something that cannot be undone: the action's icon in its colour, what happens (on the left edge), Cancel and the action. */
function ask(o: { icon: string; tone: Tone; title: string; text: string; action: string; cls: string; run: () => Promise<void> }): View {
@@ -41,35 +44,82 @@ function ask(o: { icon: string; tone: Tone; title: string; text: string; action:
/**
* 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
* up yet" until it connects with the new configuration, which the sheet goes on to.
* up yet" until it connects with the new configuration, which the sheet goes on
* to. The sheet asks again what it is and about LAN Bypass, as Add a device does
* (device-form.ts), as they stand now; the name stays.
*/
export function reconnect(d: Device) {
if (secureFirst()) return;
const here = state()?.here === d.id;
openSheet(() =>
ask({
icon: 'refresh',
tone: 'orange',
title: fmt(_('Reconnect %s?'), d.name),
text: here
openSheet(() => vReconnect(d));
}
function vReconnect(d: Device): View {
const st = state()!;
const here = st.here === d.id;
// The kinds this router takes, as the four choices; what it is now ringed.
const picks = PICKS.filter((k) => st.kinds.some((x) => pickOf(x) === k));
let pick: KindPick = picks.includes(pickOf(d.kind)) ? pickOf(d.kind) : picks[0];
let bypass = d.lan_bypass;
const kinds = kindTiles(picks, (k) => (pick = k));
kinds.set(pick);
const lan = lanSwitch(bypass, st.server.home ?? [], (on) => (bypass = on));
const run = async () => {
try {
const r = await call<{ config: ClientConfig; state: State }>(`devices/${d.id}`, {
action: 'reconnect',
kind: kindOf(pick, d.kind),
lan_bypass: bypass,
});
setState(r.state);
repaint();
await continueSetup(r.state.person.devices.find((x) => x.id === d.id) ?? { ...d, handshake: 0 }, r.config);
} catch (er) {
toast((er as Error).message, true);
}
};
const go = h(
'button',
{ type: 'button', class: 'btn warn block', onclick: (ev: Event) => once(ev.currentTarget as HTMLButtonElement, run) },
ic('refresh'),
h('span', {}, _('Reconnect')),
);
const title = fmt(_('Reconnect %s'), d.name);
const el = h(
'div',
{ class: 'view' },
head(title),
sub(
here
? _(
'It gets new keys. This device is connected through its current settings: it disconnects a few seconds after you confirm. Add the new ones that open next.',
)
: _('It gets new keys and its current settings stop working. Set it up again with the new ones that open next.'),
action: _('Reconnect'),
cls: 'accent',
run: async () => {
try {
const r = await call<{ config: ClientConfig; state: State }>(`devices/${d.id}`, { action: 'reconnect' });
setState(r.state);
repaint();
await continueSetup(r.state.person.devices.find((x) => x.id === d.id) ?? { ...d, handshake: 0 }, r.config);
} catch (er) {
toast((er as Error).message, true);
}
},
}),
),
kinds.el,
lan,
go,
);
return { el, label: title };
}
/**
* LAN Bypass on or off from the ⋯ menu: the keys stay, the device needs its
* updated configuration (its own local network in or out of the tunnel is in
* there), so its set-up opens on it.
*/
export async function toggleBypass(d: Device) {
if (secureFirst()) return;
const on = !d.lan_bypass;
try {
const r = await call<{ state: State }>(`devices/${d.id}`, { action: 'bypass', on });
setState(r.state);
repaint();
toast(on ? _('LAN Bypass is on: add the updated connection') : _('LAN Bypass is off: add the updated connection'));
const dev = r.state.person.devices.find((x) => x.id === d.id);
if (dev) await openSetup(dev);
} catch (er) {
toast((er as Error).message, true);
}
}
export function removeDevice(d: Device) {
+129
View File
@@ -0,0 +1,129 @@
// What a device is and how it connects, as Add a device and Reconnect ask it:
// the kinds as four tiles (phones and tablets are one choice, the same apps and
// the same smaller packets) and LAN Bypass, the whole row a switch.
import type { Kind } from '../../shared/types';
import { netsLabel, pickLabel, pickOf, type KindPick } from '../../shared/format';
import { fmt } from '../../shared/i18n';
import { h } from '../dom';
import { SMOOTH, play } from '../motion';
import { glass } from '../ui/glass';
export const UA = navigator.userAgent;
export const IPAD = /iPad/.test(UA) || (/Macintosh/.test(UA) && navigator.maxTouchPoints > 1);
/** Best guess at the kind of device this page is open on (the browser never tells). */
export function guessKind(): Kind {
if (IPAD || /Tablet/i.test(UA) || (/Android/.test(UA) && !/Mobile/.test(UA))) return 'tablet';
if (/Android|iPhone|Mobile/i.test(UA)) return 'phone';
return 'computer';
}
/** The kind a pick keeps: Mobile is a tablet when this page is open on one, or when the device was one already (`was`). */
export function kindOf(p: KindPick, was?: Kind): Kind {
if (was && pickOf(was) === p) return was;
return p !== 'mobile' ? p : guessKind() === 'tablet' ? 'tablet' : 'phone';
}
/**
* 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 interface KindTiles {
el: HTMLElement;
/** Ring this one (the ring does not travel between tiles: the picked tile rings itself where it stands). */
set(k: KindPick): void;
}
/** The kinds a router takes, as tiles; `onPick` on a tap, after the ring moved. */
export function kindTiles(picks: KindPick[], onPick: (k: KindPick) => void): KindTiles {
const el = h('div', { class: 'kinds', role: 'radiogroup', 'aria-label': _('What is it?') });
el.style.setProperty('--n', String(picks.length));
const set = (k: KindPick) =>
tiles.forEach((t, i) => {
const on = picks[i] === k;
t.classList.toggle('on', on);
t.setAttribute('aria-checked', String(on));
});
const tiles = picks.map((k) => {
const t = h(
'button',
{
type: 'button',
class: 'kind',
role: 'radio',
'aria-label': pickLabel(k),
onclick: () => {
set(k);
onPick(k);
},
},
h('span', { class: 'kind-tile' }, glass(k, 'blue')),
h('span', { class: 'kind-lbl' }, pickLabel(k)),
);
el.appendChild(t);
return t;
});
return { el, set };
}
/**
* LAN Bypass, the whole row the switch, built as it is (`on`) before it is on
* the page: nothing slides. 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 it is on.
*/
export function lanSwitch(on: boolean, home: string[], onChange: (on: boolean) => void): HTMLElement {
const except = home.length
? h('span', { class: 'sw-sub sw-note', hidden: !on }, fmt(_('Except %s: those addresses lead to the home network.'), netsLabel(home)))
: null;
const row = h(
'button',
{
type: 'button',
class: on ? 'swrow on' : 'swrow',
role: 'switch',
'aria-checked': String(on),
onclick: () => {
on = !on;
row.classList.toggle('on', on);
row.setAttribute('aria-checked', String(on));
if (except) foldLine(except, on);
onChange(on);
},
},
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' }),
);
return row;
}
+106 -23
View File
@@ -10,6 +10,7 @@ import { h, ic, type Kid } from '../dom';
import { EASE_IN, EASE_OUT, POP, SMOOTH, play } from '../motion';
import {
APP_NAME,
appName,
importPath,
importSteps,
keyFileName,
@@ -18,6 +19,7 @@ import {
routerStore,
scanPath,
vpnContinue,
v2rTunnelMode,
storeFor,
type AppId,
type Platform,
@@ -29,14 +31,14 @@ import { glass } from '../ui/glass';
import { menuLine, morphText, setText } from '../ui/morph';
import { hint } from '../ui/sheet';
export const APP_ICON: Record<AppId, string> = { vpn: 'amnezia', awg: 'amneziawg', wg: 'wireguard' };
export const APP_ICON: Record<AppId, string> = { vpn: 'amnezia', awg: 'amneziawg', v2r: 'v2raytun', wg: 'wireguard' };
/** The app a device was set up with last time, so the sheet reopens on it. */
const memo = (d: Device) => `dl.app.${d.id}`;
export function recallApp(d: Device): AppId | null {
try {
const v = localStorage.getItem(memo(d));
return v === 'vpn' || v === 'awg' || v === 'wg' ? v : null;
return v === 'vpn' || v === 'awg' || v === 'v2r' || v === 'wg' ? v : null;
} catch {
return null;
}
@@ -49,11 +51,17 @@ export function rememberApp(d: Device, app: AppId) {
}
}
/** What the steps work with: the device, its configuration, the key, and the choices made. */
/** What the steps work with: the device, its configuration, the key, the link, and the choices made. */
export interface SetupCtx {
d: Device;
cfg: ClientConfig;
key: string;
/** The connection as V2RayTun's awg:// link (shared/awglink.ts). */
link: string;
/** The link names the server by an IP in place of its name (false: the address is an IP already, or did not resolve). */
byIp: boolean;
/** The disguise is off and this is no router: AmneziaWG's choice is WireGuard's too (setup.ts appName). */
wgToo: boolean;
/** The platform this page is open on. */
pf: Platform;
/** "the phone": the device in a sentence. */
@@ -83,13 +91,26 @@ function badge(
return h('a', { class: cls, href: st.href, target: app ? null : '_blank', rel: 'noopener noreferrer' }, inner);
}
/** Where the app comes from: the store (and, on Android, the APK beside it), or a line to go and get it. */
export function storeBlock(app: AppId, os: Platform, router: boolean): Kid[] {
/**
* Where the app comes from: the store (and, on Android, the APK beside it), or
* a line to go and get it. With the disguise off (`wgToo`), a line under
* AmneziaWG's says WireGuard takes the connection too, its name a link to its
* store here.
*/
export function storeBlock(app: AppId, os: Platform, router: boolean, wgToo = false): Kid[] {
const st: Store | null = router ? routerStore(app) : storeFor(app, os);
if (!st) return [hint(fmt(_('Get %s on the %s and come back here.'), APP_NAME[app], platformLabel(os)))];
const wg = wgToo && app === 'awg' && !router ? wgLine(os) : null;
if (!st) return [hint(fmt(_('Get %s on the %s and come back here.'), appName(app, wgToo && !router), platformLabel(os)))];
// Android: the store can fail (no Google Play, or it hides the app), so the APK sits beside it.
if (st.alt) return [h('div', { class: 'badges2' }, badge(st), badge(st.alt)), hint(st.alt.why)];
return [badge(st)];
if (st.alt) return [h('div', { class: 'badges2' }, badge(st), badge(st.alt)), hint(st.alt.why), wg];
return [badge(st), wg];
}
/** "WireGuard works too, if it is already there": the name links to its store on this platform. */
function wgLine(os: Platform): HTMLElement {
const st = storeFor('wg', os);
const name = st ? h('a', { href: st.href, target: '_blank', rel: 'noopener noreferrer' }, APP_NAME.wg) : h('b', {}, APP_NAME.wg);
return hint(...fill<Node | string>(_('%s works too, if it is already there: the disguise is off.'), name));
}
const howto = (steps: [string, string][]) =>
@@ -101,10 +122,42 @@ const howto = (steps: [string, string][]) =>
const linkBtn = (label: string, run: (ev: Event) => void) => h('button', { type: 'button', onclick: run }, label);
/** Step 2: a link for AmneziaVPN, the file for the others, in the words of where they go. */
/** V2RayTun has the server by its IP, not its name: once the router's address changes, the connection goes stale. The IP itself stays off the page. */
const byIpWords = () =>
_('V2RayTun reaches the server by its IP address, not its hostname: if the address changes, add the connection again.');
/** V2RayTun takes the connection as a link from the clipboard: copied, then "+ › Import config from Clipboard". */
function v2rKids(c: SetupCtx): Kid[] {
// The words of the app on this device when the page is open on it (Windows has its own); else Android's.
const os = c.same() ? c.pf : 'unknown';
const path = importPath('v2r', os);
const win = os === 'windows';
return [
badge(
{
top: _('The connection as one link'),
main: _('Copy the link'),
mark: 'copy',
onclick: (ev) => copy(c.link, _('Link copied'), ev.currentTarget),
},
true,
),
howto([
[fmt(_('Open %s', 'step'), APP_NAME.v2r), ''],
[path.replace(/ → [^→]*$/, ' → '), path.replace(/^.* → /, '')],
// On Windows AmneziaWG runs in its Tunnel mode (the Mode switch on its main screen), which needs administrator rights.
win ? [fmt(_('Switch to %s mode and connect', 'step'), v2rTunnelMode()), ''] : [_('Connect', 'step'), ''],
]),
win ? hint(_('V2RayTun needs administrator rights for this mode: it offers to restart with them.')) : null,
c.byIp ? hint(byIpWords()) : null,
];
}
/** Step 2: a link for AmneziaVPN and V2RayTun, the file for the others, in the words of where they go. */
export function connectKids(c: SetupCtx): Kid[] {
const app = c.app();
const name = APP_NAME[app];
const name = appName(app, c.wgToo);
if (app === 'v2r') return v2rKids(c);
const hereHandheld = c.pf === 'ios' || c.pf === 'android';
// On the phone being set up, a link opens AmneziaVPN only on Android; an
// iPhone takes the key as a .vpn file from the share sheet.
@@ -141,7 +194,12 @@ export function connectKids(c: SetupCtx): Kid[] {
share
? badge(
{
top: c.same() ? fmt(_('Straight into %s'), name) : fmt(_('Send it to the %s'), c.there),
// Two apps' names do not fit the badge's small line: "the app" then.
top: c.same()
? c.wgToo && app === 'awg'
? _('Straight into the app')
: fmt(_('Straight into %s'), name)
: fmt(_('Send it to the %s'), c.there),
main: _('Share the file'),
mark: 'share',
onclick: () => void share(),
@@ -158,15 +216,29 @@ export function connectKids(c: SetupCtx): Kid[] {
true,
),
// In the words of the app where the file goes: the phone in hand, or the computer's system.
howto(importSteps(app, c.pf, c.cfg.filename, !!share && c.same())),
howto(importSteps(app, c.pf, c.cfg.filename, !!share && c.same(), c.wgToo)),
];
}
/** A computer set up from elsewhere: the connection to send there, as the key or the file. */
/** A computer (or a TV, a box) set up from elsewhere: the connection to send there, as the key, the link or the file. */
export function sendKids(c: SetupCtx): Kid[] {
const app = c.app();
const btn = (icon: string, label: string, run: (ev: Event) => void) =>
h('button', { type: 'button', class: 'btn soft sm', onclick: run }, ic(icon), h('span', { class: 'lbl' }, label));
if (app === 'v2r')
return [
h(
'p',
{ class: 'desc' },
fmt(_('Send it to the %s in a message or a note, then in V2RayTun: %s.'), c.there, importPath('v2r').replace(/ → /g, ' › ')),
),
h(
'div',
{ class: 'btnrow2' },
btn('copy', _('Copy the link'), (ev) => copy(c.link, _('Link copied'), ev.currentTarget)),
),
c.byIp ? hint(byIpWords()) : null,
];
if (app === 'vpn') {
const file = keyFileName(c.cfg.filename);
const share = !!shareFile(file, c.key);
@@ -189,7 +261,7 @@ export function sendKids(c: SetupCtx): Kid[] {
h(
'p',
{ class: 'desc' },
...fill<Node | string>(_('Send it to the %s, then import %s in %s.'), c.there, h('b', {}, c.cfg.filename), APP_NAME[app]),
...fill<Node | string>(_('Send it to the %s, then import %s in %s.'), c.there, h('b', {}, c.cfg.filename), appName(app, c.wgToo)),
),
h(
'div',
@@ -315,15 +387,26 @@ export interface ScanLine {
set(app: AppId): void;
}
/** "In AmneziaWG: + › Create from QR code", with both phone systems' wording where they differ. */
export function scanLine(app: AppId): ScanLine {
const name = h('span', { class: 'osm-p' }, APP_NAME[app]);
/**
* "In AmneziaWG: + › Create from QR code", with both phone systems' wording
* where they differ ("In AmneziaWG or WireGuard:" with the disguise off,
* `wgToo`: the same code and menus). For V2RayTun, where the link names the
* server by its IP (`byIp`), a line under it says what that means.
*/
export function scanLine(app: AppId, byIp = false, wgToo = false): ScanLine {
const name = h('span', { class: 'osm-p' }, appName(app, wgToo));
const path = menuLine(scanPath(app, 'ios'), scanPath(app, 'android'));
const note = byIp ? hint(byIpWords()) : null;
const shows = (a: AppId) => {
if (note) note.hidden = a !== 'v2r';
};
shows(app);
return {
el: h('span', { class: 'scanline' }, h('span', {}, ...fill(_('In %s:'), name)), path.el),
el: h('div', { class: 'scanwrap' }, h('span', { class: 'scanline' }, h('span', {}, ...fill(_('In %s:'), name)), path.el), note),
set(a) {
morphText(name, APP_NAME[a], undefined, { whole: true });
morphText(name, appName(a, wgToo), undefined, { whole: true });
path.set(scanPath(a, 'ios'), scanPath(a, 'android'));
shows(a);
},
};
}
@@ -342,7 +425,7 @@ export interface ConnPill {
* 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 {
export function connPill(get: () => { text: string; msg: string; file: string; app: string; link?: boolean }): ConnPill {
const tt = h('span', { class: 'tt' });
const tm = h('span', { class: 'tt-m' });
const tip = h('span', { class: 'hp-tip', 'aria-hidden': 'true' }, tt, tm);
@@ -473,9 +556,9 @@ export function connPill(get: () => { text: string; msg: string; file: string; a
return {
el,
sync() {
const app = get().app;
dl.setAttribute('aria-label', fmt(_('Download %s config'), app));
cp.setAttribute('aria-label', fmt(_('Copy %s config'), app));
const { app, link } = get();
dl.setAttribute('aria-label', link ? fmt(_('Download %s link'), app) : fmt(_('Download %s config'), app));
cp.setAttribute('aria-label', link ? fmt(_('Copy %s link'), app) : fmt(_('Copy %s config'), app));
},
};
}
+26 -9
View File
@@ -11,11 +11,12 @@
import type { ClientConfig, Device } from '../../shared/types';
import { fmt } from '../../shared/i18n';
import { awgLink } from '../../shared/awglink';
import { vpnKey, vpnQrText } from '../../shared/vpnkey';
import { ApiError, call } from '../api';
import { h, put } from '../dom';
import { SMOOTH, play } from '../motion';
import { APP_NAME, appsFor, deviceNoun, inWebview, keyFileName, sameDevice, setupLink, type AppId } from '../setup';
import { APP_NAME, appsFor, appsOn, deviceNoun, inWebview, keyFileName, sameDevice, setupLink, type AppId } from '../setup';
import { pageUrl, platform, preset, repaint } from '../state';
import { accordion, regrow } from '../ui/accordion';
import { codeRow, linkRow, type CodeRow } from '../ui/codes';
@@ -124,11 +125,22 @@ function setupView(d: Device, cfg: ClientConfig, key: string, here = false): Vie
const layout: Layout = same ? 'same' : router ? 'router' : handheld ? 'away' : 'pc-away';
const there = deviceNoun(d.kind);
const thereOn = deviceNoun(d.kind, true);
// A router takes AmneziaWG (or WireGuard), never AmneziaVPN.
const choices = apps.filter((a) => !router || a.id !== 'vpn');
let app: AppId = recallApp(d) ?? (router ? 'awg' : 'vpn');
// A router takes AmneziaWG or WireGuard, never AmneziaVPN; elsewhere WireGuard is AmneziaWG's choice; V2RayTun
// is for Android and Windows (setup.ts appsOn).
const choices = appsOn(d.kind, apps, same ? pf : null);
// AmneziaWG first, as the picker lists it; a device set up before opens on the app it was set up with.
let app: AppId = recallApp(d) ?? 'awg';
if (!choices.some((a) => a.id === app)) app = choices[0].id;
const c: SetupCtx = { d, cfg, key, pf, there, app: () => app, same: () => same };
// V2RayTun takes the server by its IP (shared/awglink.ts): only when the address is a name do the words say what that means.
const ip = cfg.amnezia.host_ip;
// Its Windows app resolves the name itself (amneziawg-windows, before the tunnel starts): there the link keeps
// the name, so a new address at home does not break it, and nothing needs saying.
const named = same && pf === 'windows';
const link = awgLink(cfg.conf, cfg.server, named ? null : ip);
const byIp = !named && !!ip && ip !== cfg.amnezia.host.replace(/^\[(.*)\]$/, '$1');
// The disguise off: WireGuard takes AmneziaWG's file and code (one choice, both names; a router keeps both packages).
const wgToo = preset() === 'off' && !router;
const c: SetupCtx = { d, cfg, key, link, byIp, wgToo, pf, there, app: () => app, same: () => same };
// The pickers and the boxes a pick changes live across repaints: a pick only
// refills what it changes, so the pills glide and nothing else in the sheet moves.
@@ -178,9 +190,13 @@ function setupView(d: Device, cfg: ClientConfig, key: string, here = false): Vie
const pill =
layout === 'away'
? connPill(() => ({
// V2RayTun: its link, copied or as a .txt. Its "Import config from locally" takes a file line by line,
// each line a link: a .conf does not import that way (and its server's name would not connect either).
...(app === 'vpn'
? { text: key, msg: _('Key copied'), file: keyFileName(cfg.filename) }
: { text: cfg.conf, msg: _('Configuration copied'), file: cfg.filename }),
: app === 'v2r'
? { text: link, msg: _('Link copied'), file: cfg.filename.replace(/\.conf$/i, '.txt'), link: true }
: { text: cfg.conf, msg: _('Configuration copied'), file: cfg.filename }),
app: APP_NAME[app],
}))
: null;
@@ -188,13 +204,14 @@ function setupView(d: Device, cfg: ClientConfig, key: string, here = false): Vie
/** Everything a pick changes, refilled in place. */
function fill() {
morphText(title1, router ? fmt(_('Get %s on the router'), APP_NAME[app]) : fmt(_('Get %s'), APP_NAME[app]), undefined, { whole: true });
morphInto(getBox, storeBlock(app, pf, router));
morphInto(getBox, storeBlock(app, pf, router, wgToo));
// 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));
// 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;
// V2RayTun scans its link: a .conf would come in named by the clock, the link carries the server's name.
const text = app === 'vpn' ? vpnQrText(key) : app === 'v2r' ? link : 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) {
@@ -202,7 +219,7 @@ function setupView(d: Device, cfg: ClientConfig, key: string, here = false): Vie
scan.set(app);
}
} else {
scan = scanLine(app);
scan = scanLine(app, byIp, wgToo);
code = codeRow(text, [scan.el], tooLong);
codeBox.replaceChildren(code.el);
}
+107 -8
View File
@@ -157,10 +157,18 @@ msgstr[1] ""
msgid "%s options"
msgstr ""
#: web/src/portal/setup.ts
msgid "%s or %s"
msgstr ""
#: web/src/shared/format.ts
msgid "%s this month"
msgstr ""
#: web/src/portal/flows/setup-parts.ts
msgid "%s works too, if it is already there: the disguise is off."
msgstr ""
#: web/src/portal/page/notices.ts
msgid "%s your time"
msgstr ""
@@ -299,6 +307,10 @@ msgstr ""
msgid "Can’t finish connecting"
msgstr ""
#: web/src/portal/setup.ts
msgid "Channel on"
msgstr ""
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
msgid "Circle %s: server %s does not exist."
msgstr ""
@@ -328,6 +340,11 @@ msgstr ""
msgid "Connect"
msgstr ""
#: web/src/portal/flows/setup-parts.ts
msgctxt "step"
msgid "Connect"
msgstr ""
#: web/src/portal/page/devices.ts
msgid "Connected"
msgstr ""
@@ -374,6 +391,10 @@ msgstr ""
msgid "Copy %s config"
msgstr ""
#: web/src/portal/flows/setup-parts.ts
msgid "Copy %s link"
msgstr ""
#: web/src/portal/page/devices.ts
msgid "Copy IP address"
msgstr ""
@@ -404,6 +425,7 @@ msgid "Copy the key"
msgstr ""
#: web/src/portal/flows/page-code.ts
#: web/src/portal/flows/setup-parts.ts
#: web/src/portal/ui/codes.ts
msgid "Copy the link"
msgstr ""
@@ -539,6 +561,10 @@ msgstr ""
msgid "Download %s config"
msgstr ""
#: web/src/portal/flows/setup-parts.ts
msgid "Download %s link"
msgstr ""
#: web/src/portal/setup.ts
msgid "Download for Linux"
msgstr ""
@@ -587,7 +613,7 @@ msgstr ""
msgid "Enter a device name: up to %d letters, digits, spaces and - _ ."
msgstr ""
#: web/src/portal/flows/add.ts
#: web/src/portal/flows/device-form.ts
msgid "Except %s: those addresses lead to the home network."
msgstr ""
@@ -673,6 +699,21 @@ msgctxt "WireGuard app"
msgid "Import Tunnel(s) from File…"
msgstr ""
#: web/src/portal/setup.ts
msgctxt "V2RayTun app"
msgid "Import config from Clipboard"
msgstr ""
#: web/src/portal/setup.ts
msgctxt "V2RayTun app"
msgid "Import config from QRcode"
msgstr ""
#: web/src/portal/setup.ts
msgctxt "V2RayTun app"
msgid "Import from clipboard"
msgstr ""
#: web/src/portal/setup.ts
msgctxt "WireGuard app"
msgid "Import from file or archive"
@@ -775,10 +816,19 @@ msgstr ""
msgid "Key generation failed."
msgstr ""
#: web/src/portal/flows/add.ts
#: web/src/portal/flows/device-form.ts
#: web/src/portal/page/devices.ts
msgid "LAN Bypass"
msgstr ""
#: web/src/portal/flows/device-actions.ts
msgid "LAN Bypass is off: add the updated connection"
msgstr ""
#: web/src/portal/flows/device-actions.ts
msgid "LAN Bypass is on: add the updated connection"
msgstr ""
#: web/src/portal/page/frame.ts
msgid "Language"
msgstr ""
@@ -792,6 +842,8 @@ msgid "Last connected %s"
msgstr ""
#: web/src/portal/flows/page-code.ts
#: web/src/portal/flows/setup-parts.ts
#: web/src/portal/flows/setup-view.ts
#: web/src/portal/ui/codes.ts
msgid "Link copied"
msgstr ""
@@ -892,10 +944,18 @@ msgstr ""
msgid "OR"
msgstr ""
#: web/src/portal/page/devices.ts
msgid "Off"
msgstr ""
#: web/src/portal/setup.ts
msgid "Official release on GitHub"
msgstr ""
#: web/src/portal/page/devices.ts
msgid "On"
msgstr ""
#: web/src/portal/page/notices.ts
msgid "On %s."
msgstr ""
@@ -979,6 +1039,10 @@ msgstr ""
msgid "OpenWrt packages + kmod"
msgstr ""
#: web/src/portal/setup.ts
msgid "Or, with wireguard-tools,"
msgstr ""
#: web/src/shared/format.ts
msgid "Other"
msgstr ""
@@ -1061,14 +1125,11 @@ msgstr ""
msgid "Reconnect"
msgstr ""
#: web/src/portal/flows/device-actions.ts
#: web/src/portal/page/devices.ts
msgid "Reconnect %s"
msgstr ""
#: web/src/portal/flows/device-actions.ts
msgid "Reconnect %s?"
msgstr ""
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
msgid "RejectAfterTime must be at most 180 seconds."
msgstr ""
@@ -1131,6 +1192,10 @@ msgstr ""
msgid "Send it to the %s in a message or a note, then in AmneziaVPN: %s."
msgstr ""
#: web/src/portal/flows/setup-parts.ts
msgid "Send it to the %s in a message or a note, then in V2RayTun: %s."
msgstr ""
#: web/src/portal/flows/setup-parts.ts
msgid "Send it to the %s, then import %s in %s."
msgstr ""
@@ -1189,6 +1254,10 @@ msgstr ""
msgid "Straight into %s"
msgstr ""
#: web/src/portal/flows/setup-parts.ts
msgid "Straight into the app"
msgstr ""
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
msgid "Subnet must look like 10.77.0.0/24."
msgstr ""
@@ -1197,6 +1266,11 @@ msgstr ""
msgid "Subnet overlaps %s."
msgstr ""
#: web/src/portal/flows/setup-parts.ts
msgctxt "step"
msgid "Switch to %s mode and connect"
msgstr ""
#: web/src/shared/format.ts
msgid "TB"
msgstr ""
@@ -1241,6 +1315,10 @@ msgstr ""
msgid "The connection as one key"
msgstr ""
#: web/src/portal/flows/setup-parts.ts
msgid "The connection as one link"
msgstr ""
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
msgid "The header protection key is not a key."
msgstr ""
@@ -1315,6 +1393,11 @@ msgstr ""
msgid "Too many changes in a short time. Try again in a few minutes."
msgstr ""
#: web/src/portal/setup.ts
msgctxt "V2RayTun app"
msgid "Tunnel"
msgstr ""
#: web/src/portal/flows/setup-view.ts
msgid "Two steps, about a minute"
msgstr ""
@@ -1339,6 +1422,10 @@ msgstr ""
msgid "Unknown circle."
msgstr ""
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
msgid "Unknown device type."
msgstr ""
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/devices.uc
msgid "Unknown device."
@@ -1368,6 +1455,18 @@ msgstr ""
msgid "Uploaded"
msgstr ""
#: web/src/portal/flows/setup-parts.ts
msgid "V2RayTun needs administrator rights for this mode: it offers to restart with them."
msgstr ""
#: web/src/portal/flows/setup-parts.ts
msgid "V2RayTun reaches the server by its IP address, not its hostname: if the address changes, add the connection again."
msgstr ""
#: web/src/portal/setup.ts
msgid "V2RayTun’s own channel: news and updates of the app."
msgstr ""
#: web/src/portal/flows/wait.ts
msgid "Waiting for the connection"
msgstr ""
@@ -1376,7 +1475,7 @@ msgstr ""
msgid "Warning must be 0-60 days."
msgstr ""
#: web/src/portal/flows/add.ts
#: web/src/portal/flows/device-form.ts
msgid "What is it?"
msgstr ""
@@ -1440,7 +1539,7 @@ msgstr ""
msgid "Your devices can’t connect until it’s resumed."
msgstr ""
#: web/src/portal/flows/add.ts
#: web/src/portal/flows/device-form.ts
msgid "Your local network stays reachable while connected."
msgstr ""
+107 -8
View File
@@ -162,10 +162,18 @@ msgstr[2] "Свободно %s из %s мест"
msgid "%s options"
msgstr "Действия с устройством %s"
#: web/src/portal/setup.ts
msgid "%s or %s"
msgstr "%s или %s"
#: web/src/shared/format.ts
msgid "%s this month"
msgstr "%s в этом месяце"
#: web/src/portal/flows/setup-parts.ts
msgid "%s works too, if it is already there: the disguise is off."
msgstr "Подойдёт и %s, если он уже стоит: маскировка выключена."
#: web/src/portal/page/notices.ts
msgid "%s your time"
msgstr "%s по вашему времени"
@@ -304,6 +312,10 @@ msgstr "Отмена"
msgid "Can’t finish connecting"
msgstr "Не удаётся подключиться"
#: web/src/portal/setup.ts
msgid "Channel on"
msgstr "Канал в"
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
msgid "Circle %s: server %s does not exist."
msgstr "Круг %s: сервера %s нет."
@@ -333,6 +345,11 @@ msgstr "Подтвердите импорт и подключитесь"
msgid "Connect"
msgstr "Подключить"
#: web/src/portal/flows/setup-parts.ts
msgctxt "step"
msgid "Connect"
msgstr "Подключитесь"
#: web/src/portal/page/devices.ts
msgid "Connected"
msgstr "Подключено"
@@ -379,6 +396,10 @@ msgstr "Скопировать %s"
msgid "Copy %s config"
msgstr "Скопировать конфигурацию %s"
#: web/src/portal/flows/setup-parts.ts
msgid "Copy %s link"
msgstr "Скопировать ссылку %s"
#: web/src/portal/page/devices.ts
msgid "Copy IP address"
msgstr "Скопировать IP-адрес"
@@ -409,6 +430,7 @@ msgid "Copy the key"
msgstr "Скопируйте ключ"
#: web/src/portal/flows/page-code.ts
#: web/src/portal/flows/setup-parts.ts
#: web/src/portal/ui/codes.ts
msgid "Copy the link"
msgstr "Скопировать ссылку"
@@ -544,6 +566,10 @@ msgstr "Скачать"
msgid "Download %s config"
msgstr "Скачать конфигурацию %s"
#: web/src/portal/flows/setup-parts.ts
msgid "Download %s link"
msgstr "Скачать ссылку %s"
#: web/src/portal/setup.ts
msgid "Download for Linux"
msgstr "Скачать для Linux"
@@ -592,7 +618,7 @@ msgstr "Закончится %s"
msgid "Enter a device name: up to %d letters, digits, spaces and - _ ."
msgstr "Введите название устройства: до %d букв, цифр, пробелов и - _ ."
#: web/src/portal/flows/add.ts
#: web/src/portal/flows/device-form.ts
msgid "Except %s: those addresses lead to the home network."
msgstr "Кроме %s: эти адреса ведут в домашнюю сеть."
@@ -678,6 +704,21 @@ msgctxt "WireGuard app"
msgid "Import Tunnel(s) from File…"
msgstr "Импорт туннелей из файла…"
#: web/src/portal/setup.ts
msgctxt "V2RayTun app"
msgid "Import config from Clipboard"
msgstr "Импорт из буфера обмена"
#: web/src/portal/setup.ts
msgctxt "V2RayTun app"
msgid "Import config from QRcode"
msgstr "Импорт из QR-кода"
#: web/src/portal/setup.ts
msgctxt "V2RayTun app"
msgid "Import from clipboard"
msgstr "Импорт из буфера обмена"
#: web/src/portal/setup.ts
msgctxt "WireGuard app"
msgid "Import from file or archive"
@@ -780,10 +821,19 @@ msgstr "Не удалось создать ключ (нет случайных
msgid "Key generation failed."
msgstr "Не удалось создать ключ."
#: web/src/portal/flows/add.ts
#: web/src/portal/flows/device-form.ts
#: web/src/portal/page/devices.ts
msgid "LAN Bypass"
msgstr "Обход локальной сети"
#: web/src/portal/flows/device-actions.ts
msgid "LAN Bypass is off: add the updated connection"
msgstr "Обход локальной сети выключен: добавьте обновлённое подключение"
#: web/src/portal/flows/device-actions.ts
msgid "LAN Bypass is on: add the updated connection"
msgstr "Обход локальной сети включён: добавьте обновлённое подключение"
#: web/src/portal/page/frame.ts
msgid "Language"
msgstr "Язык"
@@ -797,6 +847,8 @@ msgid "Last connected %s"
msgstr "В сети %s"
#: web/src/portal/flows/page-code.ts
#: web/src/portal/flows/setup-parts.ts
#: web/src/portal/flows/setup-view.ts
#: web/src/portal/ui/codes.ts
msgid "Link copied"
msgstr "Ссылка скопирована"
@@ -897,10 +949,18 @@ msgstr "Сейчас %s"
msgid "OR"
msgstr "ИЛИ"
#: web/src/portal/page/devices.ts
msgid "Off"
msgstr "Выкл."
#: web/src/portal/setup.ts
msgid "Official release on GitHub"
msgstr "Официальная версия на GitHub"
#: web/src/portal/page/devices.ts
msgid "On"
msgstr "Вкл."
#: web/src/portal/page/notices.ts
msgid "On %s."
msgstr "Дата окончания - %s."
@@ -984,6 +1044,10 @@ msgstr "Пакеты OpenWrt"
msgid "OpenWrt packages + kmod"
msgstr "Пакеты OpenWrt + kmod"
#: web/src/portal/setup.ts
msgid "Or, with wireguard-tools,"
msgstr "Или через wireguard-tools:"
#: web/src/shared/format.ts
msgid "Other"
msgstr "Другое"
@@ -1066,14 +1130,11 @@ msgstr "QR-код"
msgid "Reconnect"
msgstr "Переподключить"
#: web/src/portal/flows/device-actions.ts
#: web/src/portal/page/devices.ts
msgid "Reconnect %s"
msgstr "Переподключить %s"
#: web/src/portal/flows/device-actions.ts
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 секунд."
@@ -1136,6 +1197,10 @@ msgstr "Отправить на %s"
msgid "Send it to the %s in a message or a note, then in AmneziaVPN: %s."
msgstr "Отправьте его на %s в сообщении или заметке, затем в AmneziaVPN: %s."
#: web/src/portal/flows/setup-parts.ts
msgid "Send it to the %s in a message or a note, then in V2RayTun: %s."
msgstr "Отправьте её на %s в сообщении или заметке, затем в V2RayTun: %s."
#: web/src/portal/flows/setup-parts.ts
msgid "Send it to the %s, then import %s in %s."
msgstr "Отправьте его на %s, затем импортируйте %s в %s."
@@ -1194,6 +1259,10 @@ msgstr "Показать ключ"
msgid "Straight into %s"
msgstr "Сразу в %s"
#: web/src/portal/flows/setup-parts.ts
msgid "Straight into the app"
msgstr "Сразу в приложение"
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
msgid "Subnet must look like 10.77.0.0/24."
msgstr "Подсеть указывается так: 10.77.0.0/24."
@@ -1202,6 +1271,11 @@ msgstr "Подсеть указывается так: 10.77.0.0/24."
msgid "Subnet overlaps %s."
msgstr "Подсеть пересекается с %s."
#: web/src/portal/flows/setup-parts.ts
msgctxt "step"
msgid "Switch to %s mode and connect"
msgstr "Включите режим «%s» и подключитесь"
#: web/src/shared/format.ts
msgid "TB"
msgstr "ТБ"
@@ -1246,6 +1320,10 @@ msgstr "Подключение"
msgid "The connection as one key"
msgstr "Подключение одним ключом"
#: web/src/portal/flows/setup-parts.ts
msgid "The connection as one link"
msgstr "Подключение одной ссылкой"
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
msgid "The header protection key is not a key."
msgstr "Ключ защиты заголовков некорректен."
@@ -1320,6 +1398,11 @@ msgstr "Сегодня"
msgid "Too many changes in a short time. Try again in a few minutes."
msgstr "Слишком много изменений за короткое время. Попробуйте ещё раз через несколько минут."
#: web/src/portal/setup.ts
msgctxt "V2RayTun app"
msgid "Tunnel"
msgstr "Туннель"
#: web/src/portal/flows/setup-view.ts
msgid "Two steps, about a minute"
msgstr "Два шага, около минуты"
@@ -1344,6 +1427,10 @@ msgstr "Неизвестное действие."
msgid "Unknown circle."
msgstr "Неизвестный круг."
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
msgid "Unknown device type."
msgstr "Неизвестный тип устройства."
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/devices.uc
msgid "Unknown device."
@@ -1373,6 +1460,18 @@ msgstr "Не больше %s символов."
msgid "Uploaded"
msgstr "Отправлено"
#: web/src/portal/flows/setup-parts.ts
msgid "V2RayTun needs administrator rights for this mode: it offers to restart with them."
msgstr "Для этого режима V2RayTun нужны права администратора: приложение предложит перезапуститься с ними."
#: web/src/portal/flows/setup-parts.ts
msgid "V2RayTun reaches the server by its IP address, not its hostname: if the address changes, add the connection again."
msgstr "V2RayTun подключается к серверу по IP-адресу, а не по доменному имени: если адрес сменится, добавьте подключение заново."
#: web/src/portal/setup.ts
msgid "V2RayTun’s own channel: news and updates of the app."
msgstr "Канал самого V2RayTun: новости и обновления приложения."
#: web/src/portal/flows/wait.ts
msgid "Waiting for the connection"
msgstr "Ждём подключения"
@@ -1381,7 +1480,7 @@ msgstr "Ждём подключения"
msgid "Warning must be 0-60 days."
msgstr "Предупреждать можно за 0–60 дней."
#: web/src/portal/flows/add.ts
#: web/src/portal/flows/device-form.ts
msgid "What is it?"
msgstr "Что это за устройство?"
@@ -1447,7 +1546,7 @@ msgstr "Ваши устройства не подключатся, пока до
msgid "Your devices can’t connect until it’s resumed."
msgstr "Ваши устройства не подключатся, пока доступ не возобновят."
#: web/src/portal/flows/add.ts
#: web/src/portal/flows/device-form.ts
msgid "Your local network stays reachable while connected."
msgstr "Ваша локальная сеть остаётся доступной при подключении."
+18 -8
View File
@@ -123,16 +123,26 @@ function month(p: Person, used: number, pct: number): HTMLElement {
say(-1);
const chart = bars(series, 'bars-month', 64, days - day);
readBars(chart, _('Your data this month'), say);
// "Today" under its bar; the month's ends step aside when it comes close.
// "Today" under its bar, kept inside the axis; the month's ends step aside where it comes within 6 px of
// either of them, measured (the words' widths follow the language and the axis the screen). Until the first
// measure, which comes before the first paint: under its bar, and the ends by the day.
const td = h('span', { class: 'td' }, _('Today'));
td.style.left = pc(day - 0.5, days);
const axis = h(
'div',
{ class: 'month-axis' },
h('span', { class: day <= 4 ? 'hide' : '' }, short(1)),
td,
h('span', { class: day >= days - 3 ? 'hide' : '' }, short(days)),
);
const first = h('span', { class: day <= 4 ? 'hide' : '' }, short(1));
const last = h('span', { class: day >= days - 3 ? 'hide' : '' }, short(days));
const axis = h('div', { class: 'month-axis' }, first, td, last);
const fit = () => {
const room = axis.clientWidth;
const w = td.offsetWidth;
if (!room || !w) return;
const x = Math.min(Math.max(((day - 0.5) / days) * room, w / 2), room - w / 2);
td.style.left = `${x}px`;
first.classList.toggle('hide', x - w / 2 < first.offsetWidth + 6);
last.classList.toggle('hide', x + w / 2 > room - last.offsetWidth - 6);
};
// The axis on another width (a phone turned, the card's columns), or the words on theirs (the font arrived).
const ro = new ResizeObserver(fit);
for (const x of [axis, td, first, last]) ro.observe(x);
// With a limit not yet reached: the pace lately (the devices' last 7 days, so the month's first days have one
// too) and when the limit fills at it, orange within a week.
const pace = paceOf(
+5 -1
View File
@@ -17,7 +17,7 @@ import { glass } from '../ui/glass';
import { openMenu, type MenuItem } from '../ui/menu';
import { appear, fadeAway, look, morphChanged, morphText, setText, textsOf, type Look } from '../ui/morph';
import { startAdd } from '../flows/add';
import { reconnect, removeDevice } from '../flows/device-actions';
import { reconnect, removeDevice, toggleBypass } from '../flows/device-actions';
import { renameOnCard } from '../flows/rename';
import { openSetup } from '../flows/setup-view';
@@ -108,6 +108,10 @@ function menuItems(d: Device, st: State): (MenuItem | null)[] {
...(d.disabled
? []
: [
// A setting in a group of its own: on or off now, under it; a tap switches it and opens the set-up of the
// updated configuration. Then what is done to the device itself.
{ label: _('LAN Bypass'), icon: 'ethernet', sub: d.lan_bypass ? _('On') : _('Off'), run: () => toggleBypass(d) },
null,
{ 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) },
+101 -13
View File
@@ -3,13 +3,14 @@
import type { Kind } from '../shared/types';
import { fmt } from '../shared/i18n';
import { V2R_WINDOWS } from '../shared/flags';
export type Platform = 'ios' | 'android' | 'windows' | 'mac' | 'linux' | 'unknown';
export type AppId = 'vpn' | 'awg' | 'wg';
export type AppId = 'vpn' | 'awg' | 'v2r' | 'wg';
/** The server's disguise generation as the portal sees it. */
export type Preset = 'off' | 'balanced' | 'max' | 'legacy';
export const APP_NAME: Record<AppId, string> = { vpn: 'AmneziaVPN', awg: 'AmneziaWG', wg: 'WireGuard' };
export const APP_NAME: Record<AppId, string> = { vpn: 'AmneziaVPN', awg: 'AmneziaWG', v2r: 'V2RayTun', wg: 'WireGuard' };
/** The platform the page is open on. iPadOS Safari calls itself a Mac; touch points tell. */
export function platformOf(ua: string, touchPoints = 0): Platform {
@@ -45,17 +46,50 @@ export interface AppChoice {
name: string;
}
/** The apps that connect to a server with this disguise, the recommended one first; any WireGuard app without one. */
/**
* The apps that connect to a server with this disguise, in the picker's order:
* the tunnel apps first (AmneziaWG; any WireGuard app without a disguise), then
* AmneziaVPN and V2RayTun. The sheet opens on the first, AmneziaWG (flows/setup-view.ts).
* V2RayTun runs AmneziaWG 2.0 (amneziawg-go 0.2.16 on Android, 0.2.18 on
* Windows), not 3.1: Maximum leaves it out.
*/
export function appsFor(preset: Preset): AppChoice[] {
const out: AppChoice[] = [
{ id: 'vpn', name: APP_NAME.vpn },
{ id: 'awg', name: APP_NAME.awg },
];
const out: AppChoice[] = [{ id: 'awg', name: APP_NAME.awg }];
if (preset === 'off') out.push({ id: 'wg', name: APP_NAME.wg });
out.push({ id: 'vpn', name: APP_NAME.vpn });
if (preset !== 'max') out.push({ id: 'v2r', name: APP_NAME.v2r });
return out;
}
type Mark = 'appstore' | 'googleplay' | 'windows' | 'apple' | 'linux' | 'openwrt' | 'github' | 'site';
/**
* The apps a device can take. A router takes AmneziaWG or WireGuard (its
* packages, one choice each). Anything else takes WireGuard under AmneziaWG's
* choice (the same file, code and menus: appName says both). V2RayTun has AmneziaWG in its Android app (phones, tablets,
* Android TV) and its Windows app, not on iOS, macOS or Linux (`os`: the
* device's own system where the page is open on it, else null). A phone or
* something else set up from elsewhere may be on Android; a computer only
* where the page is open on it under Windows (its link opens it there), and
* only while Windows is on (`windows`, shared/flags.ts V2R_WINDOWS).
*/
export function appsOn(kind: Kind, apps: AppChoice[], os: Platform | null = null, windows = V2R_WINDOWS): AppChoice[] {
return apps.filter((a) => {
if (kind === 'router') return a.id !== 'vpn' && a.id !== 'v2r';
if (a.id === 'wg') return false;
if (a.id !== 'v2r') return true;
if (os === 'android' || (windows && os === 'windows')) return true;
return os === null && kind !== 'computer';
});
}
/**
* An app's name in a sentence: with the disguise off (`wgToo`), AmneziaWG's
* choice is WireGuard's too ("AmneziaWG or WireGuard"), as their apps take the
* same file and code through the same menus.
*/
export const appName = (app: AppId, wgToo = false): string =>
wgToo && app === 'awg' ? fmt(_('%s or %s'), APP_NAME.awg, APP_NAME.wg) : APP_NAME[app];
type Mark = 'appstore' | 'googleplay' | 'windows' | 'apple' | 'linux' | 'openwrt' | 'github' | 'telegram' | 'site';
export interface Store {
href: string;
@@ -63,11 +97,19 @@ export interface Store {
top: string;
main: string;
mark: Mark;
/** A second source shown beside the first, where the store can fail (Android). */
/** A second source shown beside the first: where the store can fail (Android), or the app's own channel. */
alt?: { href: string; top: string; main: string; mark: Mark; why: string };
}
const GH_CLIENT = 'https://github.com/amnezia-vpn/amnezia-client/releases/latest';
/** V2RayTun's channel (linked from v2raytun.com): its news and updates, beside its store. */
const v2rChannel = (): NonNullable<Store['alt']> => ({
href: 'https://t.me/v2raytun',
top: _('Channel on'),
main: 'Telegram',
mark: 'telegram',
why: _('V2RayTun’s own channel: news and updates of the app.'),
});
const apk = (href: string): NonNullable<Store['alt']> => ({
href,
top: _('APK file on'),
@@ -118,6 +160,24 @@ export function storeFor(app: AppId, platform: Platform): Store | null {
},
linux: { href: 'https://github.com/amnezia-vpn/amneziawg-tools', top: _('On GitHub'), main: 'amneziawg-tools', mark: 'linux' },
},
v2r: {
android: {
href: 'https://play.google.com/store/apps/details?id=com.v2raytun.android',
top: onPlay,
main: 'Google Play',
mark: 'googleplay',
// Its site's Android download is this store page too: the channel goes beside it.
alt: v2rChannel(),
},
// The installer the official site (v2raytun.com) links to.
windows: {
href: 'https://storage.v2raytun.com/v2RayTun_Setup.exe',
top: _('Download from'),
main: 'v2raytun.com',
mark: 'windows',
alt: v2rChannel(),
},
},
wg: {
ios: { href: 'https://apps.apple.com/app/wireguard/id1441195209', top: onAppStore, main: 'App Store', mark: 'appstore' },
android: {
@@ -179,16 +239,42 @@ function tunnelMenu(platform: Platform): { file: string; qr?: string } | undefin
return menus[platform];
}
/*
* V2RayTun, read from its apps in November 2026 (its sources are closed).
* Android 5.26.83: the + at the top of its server list (menu_main); both items
* hand the text to one importer, which takes an amneziawg:// or awg:// link or a .conf.
* Windows (the Flutter app of v2RayTun_Setup.exe, read from its Dart snapshot):
* a + (tooltip "Import") at the top of the connection screen opens Import from
* clipboard, Type manually, Import from file, Import from QR code (an image
* file) and Import from phone. The clipboard takes an awg:// link (its parser
* refuses the amneziawg:// scheme) or a whole .conf;
* "Import from file" offers .txt and .json only and reads them line by line,
* a link a line. AmneziaWG runs there in its Tunnel mode (or Proxy + Tunnel),
* picked under "Mode" on the same screen.
*/
const v2rScan = () => menu('+', _('Import config from QRcode', 'V2RayTun app'));
const v2rImport = (platform: Platform) =>
menu('+', platform === 'windows' ? _('Import from clipboard', 'V2RayTun app') : _('Import config from Clipboard', 'V2RayTun app'));
/** V2RayTun's mode AmneziaWG needs on Windows, in its own words (it restarts as administrator for it). */
export const v2rTunnelMode = () => _('Tunnel', 'V2RayTun app');
/** Where the app scans a code; a phone of either kind gets both wordings. */
export function scanPath(app: AppId, platform: Platform = 'unknown'): string {
if (app === 'vpn') return menu('+', _('QR code', 'AmneziaVPN app'));
if (app === 'v2r') return v2rScan();
const qr = tunnelMenu(platform)?.qr;
return qr ?? fmt(_('%s (Android: %s)'), tunnelMenu('ios')!.qr, tunnelMenu('android')!.qr!.replace(/^.* → /, ''));
}
/** Where the app takes a file (AmneziaVPN: the key, pasted by its Insert button); elsewhere, the Android app's words. */
/**
* Where the app takes the connection: a file, or what is copied (AmneziaVPN:
* the key, pasted by its Insert button; V2RayTun: the link, from the
* clipboard); elsewhere, the Android app's words.
*/
export function importPath(app: AppId, platform: Platform = 'unknown'): string {
if (app === 'vpn') return menu('+', _('Insert', 'AmneziaVPN app'));
if (app === 'v2r') return v2rImport(platform);
return (tunnelMenu(platform) ?? tunnelMenu('android')!).file;
}
@@ -198,18 +284,20 @@ export const vpnContinue = () => fmt(_('Tap “%s” and connect'), _('Continue'
/**
* The file into the app, step by step: [text, the part in bold]. Linux has no
* app, only the tools: the file goes up straight from where it was saved
* (its name is a valid interface name, see tunnel_name on the router).
* (its name is a valid interface name, see tunnel_name on the router); with
* the disguise off (`wgToo`) wireguard-tools' wg-quick takes it too.
*/
export function importSteps(app: AppId, platform: Platform, file: string, shared: boolean): [string, string][] {
export function importSteps(app: AppId, platform: Platform, file: string, shared: boolean, wgToo = false): [string, string][] {
if (platform === 'linux')
return [
[_('Open a terminal in the folder with the file'), ''],
// The command comes after the word, in bold: "Run sudo awg-quick up …".
[`${_('Run')} `, `sudo ${app === 'wg' ? 'wg-quick' : 'awg-quick'} up ./${file}`],
...(wgToo && app === 'awg' ? ([[`${_('Or, with wireguard-tools,')} `, `sudo wg-quick up ./${file}`]] as [string, string][]) : []),
];
const path = importPath(app, platform);
return [
[fmt(_('Open %s', 'step'), APP_NAME[app]), ''],
[fmt(_('Open %s', 'step'), appName(app, wgToo)), ''],
[path.replace(/ → [^→]*$/, ' → '), path.replace(/^.* → /, '')],
[shared ? _('Confirm the import and connect') : _('Pick the file and connect'), ''],
];
+50 -2
View File
@@ -97,6 +97,15 @@
.btn.red:hover {
background: color-mix(in srgb, var(--bad) 82%, transparent);
}
/* Reconnect: the warn colour it has in the ⋯ menu and on the card's status. Dark ink: white on it reads at 2.3:1. */
.btn.warn {
background: var(--warn);
color: #241300;
font-weight: 600;
}
.btn.warn:hover {
background: color-mix(in srgb, var(--warn) 82%, transparent);
}
/* Waiting for the router: the button keeps its size, its content blurs away and an orb comes up in
its place (ui/busy.ts runs the change). The orb is B4 Converge from aicss.dev's Orbs, at its own
28px stage and twice its speed: one circle walks a triangle, sharp at each corner and smaller,
@@ -510,12 +519,43 @@
opacity: 1;
margin-left: 0;
}
/* A name wider than its place (ui/seg.ts marquee): it fades to nothing at the edge it runs past, the right one
at its start, the left one at its end, the fade sliding across as the name glides. */
@property --fade-l {
syntax: '<length>';
inherits: false;
initial-value: 0px;
}
@property --fade-r {
syntax: '<length>';
inherits: false;
initial-value: 0px;
}
.appseg .seg-l {
-webkit-mask-image: linear-gradient(to right, transparent, #000 var(--fade-l), #000 calc(100% - var(--fade-r)), transparent);
mask-image: linear-gradient(to right, transparent, #000 var(--fade-l), #000 calc(100% - var(--fade-r)), transparent);
transition:
--fade-l 320ms var(--ease-out),
--fade-r 320ms var(--ease-out);
}
.appseg .seg-l.clip {
--fade-r: 18px;
}
.appseg .seg-l.clip.end {
--fade-l: 18px;
--fade-r: 0px;
}
.appseg .seg-t {
display: inline-block;
}
/* Three apps on a phone: the icons take less room, so the picked one's name fits whole. */
.appseg {
container-type: inline-size;
}
/* The pill takes the narrow width too: a container query reaches only what is inside the track, never the track
itself, so --b is set on the pill (on .appseg it would stay 56 and the pill fall short of its item). */
@container (max-width: 300px) {
.appseg {
.appseg .seg-pill {
--b: 44px;
}
.appseg .seg-b {
@@ -770,11 +810,19 @@
background: var(--accent-soft);
color: var(--accent);
}
/* Two side by side while each has room for its words on one line (a store's name never wraps); else one under
the other. */
.badges2 {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
grid-template-columns: repeat(auto-fit, minmax(min(100%, 150px), 1fr));
gap: 8px;
}
.badges2 .b-top,
.badges2 .b-main {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.badges2 .badge {
padding: 0 10px;
gap: 10px;
+6
View File
@@ -439,6 +439,12 @@
align-items: baseline;
column-gap: 0.3em;
}
/* The scan line and, for V2RayTun reached by IP, the line under it. */
.scanwrap {
display: flex;
flex-direction: column;
gap: 6px;
}
.scanline .osm {
white-space: nowrap;
}
+98 -5
View File
@@ -5,7 +5,8 @@
// they stay right while the sheet around them changes width. At rest the pill
// stands where CSS puts it (its item's place among the others: controls.css), so
// a sheet changing width, a phone turned, carry it along with nothing to watch;
// only a pick moves it from here.
// only a pick moves it from here. A name wider than its place fades out at
// the edge it runs past and glides to its end on hover (marquee()).
import { h, ic } from '../dom';
import { EASE_OUT, LEAD, SMOOTH, calm, play } from '../motion';
@@ -42,21 +43,104 @@ export function labelFade(at: LabelAt, picked: boolean): { duration: number; del
return { duration: left > 0.01 ? 220 * left : 0, delay: 0 };
}
/** How fast a name too long for its place glides to its end (px/s): slow enough to read along. */
const GLIDE_SPEED = 40;
/** In and out of the glide, gently at both ends. */
const GLIDE_EASE = 'cubic-bezier(.45, 0, .55, 1)';
interface Marquee {
/** Glide to the name's end, or back to its start (`now`: at once). */
go(end: boolean, now?: boolean): void;
/** At the start, at once (another item picked). */
reset(): void;
/** At the end: back; at the start: to the end (a tap on the picked item, where there is no hover). */
toggle(): void;
}
/**
* A name in its place (`l`, its words the inline block inside): wider than
* the place, it is `.clip` and fades to nothing at the edge it runs past
* (controls.css); at its end (`.end`) the fade moves to the other edge. It
* glides from where it stands, at GLIDE_SPEED, a beat after the pointer comes.
*/
function marquee(l: HTMLElement): Marquee {
const t = l.firstElementChild as HTMLElement;
let atEnd = false;
/** The glide under way, if any. */
let glide: Animation | null = null;
const over = () => Math.max(0, t.offsetWidth - l.clientWidth);
/** To the end or the start, from where it stands; `delay` before it sets off (a beat on hover, none to follow a moved end). */
function go(end: boolean, now = false, delay = end ? 240 : 0) {
const o = end ? over() : 0;
atEnd = end && o > 0;
l.classList.toggle('end', atEnd);
const from = new DOMMatrix(getComputedStyle(t).transform).m41;
t.getAnimations().forEach((a) => a.cancel());
glide = null;
t.style.transform = o ? `translateX(${-o}px)` : '';
const dist = Math.abs(-o - from);
if (now || dist < 0.5) return;
const a = play(t, [{ transform: `translateX(${from}px)` }, { transform: `translateX(${-o}px)` }], {
duration: Math.max(420, (dist / GLIDE_SPEED) * 1000),
delay,
easing: GLIDE_EASE,
fill: 'backwards',
});
glide = a;
// The place changed while it glided (a pick still opening it, the sheet still gliding to its width): on to
// the end it has now, from where it landed, without a jump.
a.onfinish = () => {
if (glide !== a) return;
glide = null;
if (atEnd && Math.abs(over() - o) > 0.5) go(true, false, 0);
};
}
// Its place changes (a pick opens or folds it, the sheet changes width): clipped or not. At its end and still,
// it glides to where the end is now (back to the start if it fits); a glide under way corrects when it lands.
new ResizeObserver(() => {
l.classList.toggle('clip', over() > 0.5);
if (atEnd && !glide) go(true, false, 0);
}).observe(l);
return { go, reset: () => go(false, true), toggle: () => go(!atEnd) };
}
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);
// A touch has no hover: a tap on the picked item glides its name instead.
let touch = false;
const btns = items.map((it) => {
const b = h(
'button',
{ type: 'button', class: 'seg-b', role: 'tab', 'aria-label': it.label, title: it.label, onclick: () => pick(it.value) },
{
type: 'button',
class: 'seg-b',
role: 'tab',
'aria-label': it.label,
title: it.label,
onclick: () => (it.value === value ? touch && marquees[btns.indexOf(b)].toggle() : pick(it.value)),
},
ic(it.icon),
h('span', { class: 'seg-l' }, it.label),
h('span', { class: 'seg-l' }, h('span', { class: 'seg-t' }, it.label)),
);
b.dataset.v = it.value;
b.addEventListener('pointerdown', (e) => (touch = e.pointerType !== 'mouse'));
// The picked item's name glides to its end while the pointer (or the keyboard's focus) is on it.
b.addEventListener('pointerenter', (e) => {
if (e.pointerType === 'mouse' && b.classList.contains('on')) marquees[btns.indexOf(b)].go(true);
});
b.addEventListener('pointerleave', (e) => {
if (e.pointerType === 'mouse') marquees[btns.indexOf(b)].go(false);
});
b.addEventListener('focus', () => {
if (b.matches(':focus-visible') && b.classList.contains('on')) marquees[btns.indexOf(b)].go(true);
});
b.addEventListener('blur', () => marquees[btns.indexOf(b)].go(false));
el.appendChild(b);
return b;
});
const labelOf = (b: HTMLElement) => b.querySelector('.seg-l') as HTMLElement;
const marquees = btns.map((b) => marquee(labelOf(b)));
const mark = () =>
btns.forEach((b) => {
const on = b.dataset.v === value;
@@ -102,10 +186,18 @@ export function iconSeg<T extends string>(items: SegItem<T>[], value: T, onPick:
return { width: l.getBoundingClientRect().width, opacity: +s.opacity, filter: s.filter, marginLeft: s.marginLeft };
});
[...btns, ...labels].forEach((x) => x.getAnimations().forEach((a) => a.cancel()));
// Every name back at its start; the picked one glides once it has its place, if the pointer is still on it.
marquees.forEach((m) => m.reset());
window.setTimeout(() => {
if (value === v && btns[to].matches(':hover') && !touch) marquees[to].go(true);
}, SMOOTH.duration);
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;
// The picked name's own width (its words, up to the 180 px CSS gives a picked name), not the room it has
// now: the room changes while it opens (AmneziaVPN's dense code widens the sheet), and a width measured
// before that would jump to the new room when the animation hands back to CSS. Where there is less room,
// the item squeezes the name (it shrinks to its place: controls.css), so the end is where CSS puts it.
const w1 = Math.min(180, (labels[to].firstElementChild as HTMLElement).offsetWidth);
btns.forEach((b, i) => {
const g1 = i === to ? 1 : 0;
const f1 = getComputedStyle(b).flexBasis;
@@ -184,6 +276,7 @@ export function iconSeg<T extends string>(items: SegItem<T>[], value: T, onPick:
sync(v) {
if (v === value) return;
value = v;
marquees.forEach((m) => m.reset());
mark();
placePill();
},