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

- Portal redesigned from scratch. No header bar: the page opens with the
  server's name and the person's and fades under the edges. Device cards
  show the status, the last 7 days (hover a day for its figures) and a
  Connect or Update button; "Your access" folds into rows: what they can
  reach (with the names at home), data this month day by day, and when
  access ends. The page follows the system's light or dark theme
- Adding a device: pick the kind (PC, Mobile, Router, Other) and a name, or
  add it from the device itself with the page's QR code. The set-up sheet
  then shows the app for that system and the connection, waits for the
  first connection, says "<device> connected" and closes on its own
- Switching apps in the set-up sheet changes only what differs: the old
  words blur into the new ones, and the menu path is shown for iOS and
  Android in one line. Names, numbers and statuses that change on the page
  morph in place
- Dialogs open in the middle on a computer, on the same spring as the menu;
  buttons that wait for the router show a spinner at once
- A paused account gets one card that says so; the page's messages are
  short and no longer send people to the admin. A QR code of the page sits
  beside the breadcrumb, to open it on another device
- Allowed hours are shown in the visitor's own time zone
- The portal's Title setting is gone: the page and its tab take the
  server's name. A title set before is removed on upgrade
- The admin names .conf files after the server too, as the portal does
  (Outline-Home.conf); its device menu says "Download AmneziaWG config" and
  "Copy AmneziaVPN config", and its QR codes use the portal's round look in
  the admin's light or dark colours
- README rewritten, with screenshots made from a demo cast
  (scripts/capture-screenshots.mjs --demo)
This commit is contained in:
Aemeath committed 2026-10-19 21:07:14 +03:00
1 parent edeb1506fd
commit 4f12ca19e7
94 files changed
+8076 -5009

No files matched your search

+39
View File
@@ -0,0 +1,39 @@
// The portal's API: one fetch per call to the router, under the personal link.
// No sessions and no cookies: the code in the path is the key. A refused call
// throws an ApiError carrying the status and, for a plain-HTTP visitor, the
// HTTPS twin of the link.
import { base } from './state';
export class ApiError extends Error {
constructor(
public status: number,
message: string,
/** The HTTPS twin of this link, when the answer was "not over plain HTTP". */
public httpsUrl?: string,
) {
super(message);
}
}
export async function call<T>(path: string, body?: unknown): Promise<T> {
const res = await fetch(`${base}/api/${path}`, {
method: body === undefined ? 'GET' : 'POST',
credentials: 'omit',
headers: body === undefined ? {} : { 'Content-Type': 'application/json' },
body: body === undefined ? undefined : JSON.stringify(body),
cache: 'no-store',
});
// Any shape: an error answer may be empty or not JSON at all.
let data: { error?: string; https_url?: string } | null = null;
try {
data = await res.json();
} catch {
/* empty */
}
if (!res.ok) throw new ApiError(res.status, data?.error ?? `Request failed (${res.status})`, data?.https_url || undefined);
return data as T;
}
/** The link stopped working (code regenerated, person removed). */
export const gone = (e: unknown) => e instanceof ApiError && (e.status === 404 || e.status === 401);
+78
View File
@@ -0,0 +1,78 @@
// The days and hours the access section draws, as plain data: the weeks left
// as a calendar, the admin's hours moved into the visitor's time, the month as
// one bar a day. Pure (no DOM): page/access.ts draws it; dates are the
// router's (`today` from its state), never the browser's calendar.
import { addDays, parseDay } from '../shared/format';
export type CellKind = 'past' | 'today' | 'left' | 'end' | 'after';
export interface Cell {
day: string;
kind: CellKind;
}
/**
* The weeks from this one to the one the access ends in, Monday first, one
* cell a day: gone, today, left, the last day, after it. Null when that would
* take more than `maxWeeks` (far ends: the number of days says it alone).
*/
export function calendar(today: string, end: string, maxWeeks = 10): Cell[] | null {
const dow = (d: string) => (parseDay(d).getDay() + 6) % 7;
const first = addDays(today, -dow(today));
const last = addDays(end, 6 - dow(end));
const cells: Cell[] = [];
for (let d = first; d <= last; d = addDays(d, 1)) {
cells.push({ day: d, kind: d < today ? 'past' : d === today ? 'today' : d < end ? 'left' : d === end ? 'end' : 'after' });
if (cells.length > maxWeeks * 7) return null;
}
return cells;
}
const HM = /^([01]?\d|2[0-3]):([0-5]\d)$/;
/** "08:30" → 510, or null for anything else. */
export function minuteOf(t: string): number | null {
const m = HM.exec(t.trim());
return m ? +m[1] * 60 + +m[2] : null;
}
const wrap = (m: number) => ((m % 1440) + 1440) % 1440;
export const clockOf = (m: number) => `${String(Math.floor(wrap(m) / 60)).padStart(2, '0')}:${String(wrap(m) % 60).padStart(2, '0')}`;
export interface Hours {
/** Start and end, minutes after midnight in the visitor's time. */
from: number;
to: number;
/** In the visitor's time (the router told its offset), or the router's own. */
yours: boolean;
}
/**
* The admin's hours ("08:00-22:00", router time) in the visitor's time. The
* offsets are minutes east of UTC; without the router's offset the hours stay
* in the router's time. Null when they cannot be read.
*/
export function hoursFor(hours: string, routerOffset: number | undefined, visitorOffset: number): Hours | null {
const [a, b] = hours.split('-');
const from = minuteOf(a ?? '');
const to = minuteOf(b ?? '');
if (from == null || to == null) return null;
const shift = routerOffset == null ? 0 : visitorOffset - routerOffset;
return { from: wrap(from + shift), to: wrap(to + shift), yours: routerOffset != null };
}
/** The window as stretches of the day: one, or two when it runs past midnight. */
export const stretches = (h: Hours): [number, number][] =>
h.from < h.to
? [[h.from, h.to]]
: [
[h.from, 1440],
[0, h.to],
];
/** The moment `nowSec` (epoch seconds) as minutes after midnight at `offset` minutes east of UTC. */
export const minuteAt = (nowSec: number, offset: number) => wrap(Math.floor(nowSec / 60) + offset);
/** The days of today's month: how many, and which one today is (1-based). */
export function monthOf(today: string): { days: number; day: number } {
const d = parseDay(today);
return { days: new Date(d.getFullYear(), d.getMonth() + 1, 0).getDate(), day: d.getDate() };
}
+28 -13
View File
@@ -1,12 +1,22 @@
// The portal's two DOM builders: an element from a tag, attributes and
// children, and an icon. No framework; shared by the page (main.ts) and the
// pieces drawn outside it (waitpath.ts).
// The portal's DOM builders: an element from a tag, attributes and children;
// an icon; markup that is ours (icons, glass icons, QR codes) as an element.
// No framework. The page's CSP forbids inline styles, so nothing here writes a
// `style` attribute: styles set from script go through `el.style`.
import { iconSvg } from '../shared/icons';
export type Attrs = Record<string, string | number | boolean | EventListener | null | undefined>;
export type Kid = Node | string | null | undefined | false | Kid[];
function append(el: Node, kids: Kid[]) {
const add = (c: Kid) => {
if (c == null || c === false) return;
if (Array.isArray(c)) c.forEach(add);
else el.appendChild(typeof c === 'string' ? document.createTextNode(c) : c);
};
kids.forEach(add);
}
export function h(tag: string, attrs: Attrs = {}, ...kids: Kid[]): HTMLElement {
const el = document.createElement(tag);
for (const [k, v] of Object.entries(attrs)) {
@@ -16,17 +26,22 @@ export function h(tag: string, attrs: Attrs = {}, ...kids: Kid[]): HTMLElement {
else if (v === true) el.setAttribute(k, '');
else el.setAttribute(k, String(v));
}
const add = (c: Kid) => {
if (c == null || c === false) return;
if (Array.isArray(c)) c.forEach(add);
else el.appendChild(typeof c === 'string' ? document.createTextNode(c) : c);
};
kids.forEach(add);
append(el, kids);
return el;
}
export function ic(name: string): HTMLElement {
const s = h('span', { class: 'ic' });
s.innerHTML = iconSvg(name, 'ic-svg');
return s;
/** Replace what `el` holds with `kids` (nested lists flattened, empty ones skipped). */
export function put(el: HTMLElement, ...kids: Kid[]) {
el.replaceChildren();
append(el, kids);
}
/** Our own markup (never anything a visitor or the router typed) as one element. */
export function markup(html: string): Element {
const t = document.createElement('template');
t.innerHTML = html.trim();
return t.content.firstElementChild!;
}
/** A line icon (`svg.i`, stroke = currentColor), sized by CSS. */
export const ic = (name: string, cls = 'i'): Element => markup(iconSvg(name, cls));
+214
View File
@@ -0,0 +1,214 @@
// 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.
import type { ClientConfig, Kind } from '../../shared/types';
import { KIND_LABEL } from '../../shared/format';
import { ApiError, call } from '../api';
import { h, ic } from '../dom';
import { EASE_OUT, play } from '../motion';
import { addLink } from '../setup';
import { pageUrl, repaint, setState, state, type State } from '../state';
import { linkRow, qrBox } from '../ui/codes';
import { once, toast } from '../ui/feedback';
import { glass } from '../ui/glass';
import { morphText } from '../ui/morph';
import { go, head, hint, openSheet, sub, type View } from '../ui/sheet';
import { secureFirst, showSecure } from './secure';
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'],
[/^SM-S92/, 'Galaxy S24'],
[/^SM-S91/, 'Galaxy S23'],
[/^SM-S90/, 'Galaxy S22'],
[/^SM-G99/, 'Galaxy S21'],
[/^SM-F9/, 'Galaxy Z Fold'],
[/^SM-F7/, 'Galaxy Z Flip'],
[/^SM-A5/, 'Galaxy A5x'],
[/^SM-A3/, 'Galaxy A3x'],
[/^SM-X/, 'Galaxy Tab'],
];
/** Android model from Client Hints (Chrome); filled in shortly after the page loads. */
let MODEL = '';
const modelReady: Promise<string> = (async () => {
const uad = (navigator as Navigator & { userAgentData?: { getHighEntropyValues(h: string[]): Promise<{ model?: string }> } })
.userAgentData;
if (!uad || !/Android/.test(UA)) return '';
try {
const m = ((await uad.getHighEntropyValues(['model'])).model ?? '').trim();
if (!m || m === 'K') return '';
const g = GALAXY.find(([re]) => re.test(m));
MODEL = g ? `${g[1]} (${m})` : /^SM-/.test(m) ? `Galaxy ${m}` : m;
} catch {
/* not offered */
}
return MODEL;
})();
function guessName(kind: Kind): string {
if (/iPhone/.test(UA)) return 'iPhone';
if (IPAD) return 'iPad';
if (/Android/.test(UA)) return MODEL || (kind === 'tablet' ? 'Android tablet' : 'Android phone');
if (/CrOS/.test(UA)) return 'Chromebook';
if (/Mac OS X/.test(UA)) return 'Mac';
if (/Windows/.test(UA)) return 'Windows PC';
if (/Linux/.test(UA)) return 'Linux PC';
return KIND_LABEL[kind];
}
/*
* Phones and tablets are one choice. The device is still kept as a phone or a
* tablet (the lines say "the tablet"): on the device itself the browser tells
* which; picked from elsewhere it is a phone.
*/
type Pick = 'computer' | 'mobile' | 'router' | 'other';
const PICK_LABEL: Record<Pick, string> = { computer: 'PC', mobile: 'Mobile', router: 'Router', other: 'Other' };
const pickOf = (k: Kind): Pick => (k === 'phone' || k === 'tablet' ? 'mobile' : k);
const kindOf = (p: Pick): Kind => (p !== 'mobile' ? p : guessKind() === 'tablet' ? 'tablet' : 'phone');
export function startAdd() {
const st = state();
if (!st || st.locked) return;
if (!st.can_add) return toast(`You have reached your limit of ${st.person.device_limit} devices`, true);
if (secureFirst()) return;
openSheet(vAdd);
}
function vAdd(): 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 taken = new Set(p.devices.map((d) => d.name.toLowerCase()));
const suggest = (k: Pick) => {
const n = k === pickOf(guessKind()) ? guessName(kindOf(k)) : k === 'mobile' ? 'Phone' : KIND_LABEL[k];
if (!taken.has(n.toLowerCase())) return n;
for (let i = 2; i < 20; i++) if (!taken.has(`${n} ${i}`.toLowerCase())) return `${n} ${i}`;
return n;
};
const kinds = h('div', { class: 'kinds', role: 'radiogroup', 'aria-label': 'What is it?' });
kinds.style.setProperty('--n', String(picks.length));
const tiles = picks.map((k) => {
const t = h(
'button',
{ type: 'button', class: 'kind', role: 'radio', 'aria-label': PICK_LABEL[k], onclick: () => choose(k) },
h('span', { class: 'kind-tile' }, glass(k, 'blue')),
h('span', { class: 'kind-lbl' }, PICK_LABEL[k]),
);
kinds.appendChild(t);
return t;
});
const input = h('input', { type: 'text', maxlength: 48, required: true, 'aria-label': 'Name', autocomplete: 'off' }) as HTMLInputElement;
const goBtn = h('button', { class: 'go ready', type: 'submit', 'aria-label': 'Create connection' }, ic('arrow')) as HTMLButtonElement;
const 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);
input.addEventListener('input', () => {
edited = true;
goBtn.classList.toggle('ready', !!input.value.trim());
err.hidden = true;
});
// 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);
});
// The picked tile rings itself where it stands (the ring does not travel between tiles).
function choose(k: Pick) {
pick = k;
tiles.forEach((t, i) => {
const on = picks[i] === k;
t.classList.toggle('on', on);
t.setAttribute('aria-checked', String(on));
});
if (!edited) {
input.value = suggest(k);
goBtn.classList.add('ready');
}
}
choose(pick);
const form = h('form', { class: 'field', autocomplete: 'off' }, input, goBtn);
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.');
void once(goBtn, async () => {
try {
const r = await call<{ id: string; config: ClientConfig; state: State }>('devices', { name, kind: kindOf(pick) });
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);
say((er as Error).message);
}
});
});
const viaLink = h(
'button',
{ type: 'button', class: 'btn soft block', onclick: () => go(vLink) },
ic('qr'),
h('span', {}, 'Add it from the device'),
);
const free = p.device_limit - p.devices.length;
const el = h(
'div',
{ class: 'view' },
head('Add a device'),
sub(`${free} of ${p.device_limit} slots free`),
kinds,
hint('Phones and tablets get a smaller packet size that suits mobile networks.'),
form,
err,
h('div', { class: 'or' }, 'OR'),
viaLink,
);
el.querySelector('.hint')!.classList.add('kinds-note');
return { el, label: 'Add a device' };
}
/** The page on the device itself, ready to add it: the link as a code for its camera, and as text. */
function vLink(): View {
const link = addLink(pageUrl());
const el = h(
'div',
{ class: 'view' },
head('Open on the device', { back: true }),
sub('Point its camera at the code: your page opens there with this device ready to add.'),
qrBox(link, true),
linkRow(link),
);
return { el, label: 'Open on the device' };
}
+142
View File
@@ -0,0 +1,142 @@
// 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.
import type { ClientConfig, Device } from '../../shared/types';
import { call } from '../api';
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, head, onClosed, openSheet, type View } from '../ui/sheet';
import { secureFirst } from './secure';
import { continueSetup } from './setup-view';
/** A question before something that cannot be undone: the action's icon in its colour, what happens, Cancel and the action. */
function ask(o: { icon: string; tone: Tone; title: string; text: string; action: string; cls: string; run: () => Promise<void> }): View {
const ok = h(
'button',
{ type: 'button', class: `btn ${o.cls}`, onclick: (ev: Event) => once(ev.currentTarget as HTMLButtonElement, o.run) },
// In an element: a busy button blurs its content away for the orb (ui/busy.ts).
h('span', {}, o.action),
) as HTMLButtonElement;
const el = h(
'div',
{ class: 'view' },
h(
'div',
{ class: 'center-col ask' },
glass(o.icon, o.tone, 'gi xl'),
h('h3', {}, o.title),
h('p', {}, o.text),
h('div', { class: 'btnrow' }, h('button', { type: 'button', class: 'btn soft', onclick: () => closeSheet() }, 'Cancel'), ok),
),
);
return { el, label: o.title, asks: true };
}
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);
return { el: h('div', { class: 'view' }, head(`Rename ${d.name}`), form), label: `Rename ${d.name}` };
});
}
/**
* 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.
*/
export function reconnect(d: Device) {
if (secureFirst()) return;
const here = state()?.here === d.id;
openSheet(() =>
ask({
icon: 'refresh',
tone: 'orange',
title: `Reconnect ${d.name}?`,
text: here
? 'It gets new keys. This device is connected through its current settings: it disconnects a few seconds after you confirm. Add the new ones that open next.'
: 'It gets new keys and its current settings stop working. Set it up again with the new ones that open next.',
action: 'Reconnect',
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);
}
},
}),
);
}
export function removeDevice(d: Device) {
openSheet(() =>
ask({
icon: 'trash',
tone: 'red',
title: `Remove ${d.name}?`,
text: 'Its connection stops working at once. You can add it again later.',
action: 'Remove',
cls: 'red',
run: async () => {
try {
const r = await call<{ state: State }>(`devices/${d.id}`, { action: 'delete' });
setState(r.state);
// The card goes first; the rest then glide into its place.
onClosed(() => {
const card = document.querySelector(`.dev[data-id="${CSS.escape(d.id)}"]`);
const done = () => {
repaint();
toast('Device removed');
};
if (!card) return done();
play(
card,
[
{ opacity: 1, transform: 'none', filter: 'none' },
{ opacity: 0, transform: 'scale(.9)', filter: 'blur(6px)' },
],
{
duration: 220,
easing: EASE_IN,
fill: 'forwards',
},
).onfinish = done;
});
closeSheet();
} catch (er) {
toast((er as Error).message, true);
}
},
}),
);
}
+22
View File
@@ -0,0 +1,22 @@
// This page on another device: from the breadcrumb, its link as a code for a
// phone's camera, and the link itself to copy or share.
import { h } from '../dom';
import { pageUrl } from '../state';
import { linkRow, qrBox } from '../ui/codes';
import { head, openSheet, sub } from '../ui/sheet';
export function showPageCode() {
openSheet(() => {
const url = pageUrl();
const el = h(
'div',
{ class: 'view' },
head('Open on another device'),
sub('Point its camera at the code: this page opens there.'),
qrBox(url, true),
linkRow(url),
);
return { el, label: 'Open on another device' };
});
}
+39
View File
@@ -0,0 +1,39 @@
// A plain-HTTP link (an IP address) shows the page, but keys only travel
// encrypted: adding or setting up a device sends the visitor to the HTTPS twin
// first. Its certificate is the router's own, so the browser warns once; say so.
import { h, ic } from '../dom';
import { httpsTwin } from '../state';
import { glass } from '../ui/glass';
import { head, hint, openSheet, sub, type View } from '../ui/sheet';
function vSecure(url: string): View {
const el = h(
'div',
{ class: 'view' },
head('Open the link securely'),
sub('Connection settings only travel encrypted'),
h(
'div',
{ class: 'center-col secure' },
glass('lock', 'blue', 'gi xl'),
h('p', {}, 'This page is open without encryption. To add or set up a device, open the same link over HTTPS:'),
),
// The same tab: the HTTPS page replaces this one.
h('a', { class: 'btn accent block', href: url }, ic('lock'), h('span', {}, 'Open securely')),
hint('The browser may warn that the certificate is not trusted: it is this router’s own. Choose to continue (“Advanced” → “Proceed”).'),
);
el.lastElementChild!.classList.add('secure-note');
return { el, label: 'Open the link securely' };
}
/** The HTTPS twin's sheet (here, or the one the router named in a refusal). */
export const showSecure = (url: string) => openSheet(() => vSecure(url));
/** Over plain HTTP: the twin's sheet instead, and true (the caller stops). */
export function secureFirst(): boolean {
const twin = httpsTwin();
if (!twin) return false;
showSecure(twin);
return true;
}
+408
View File
@@ -0,0 +1,408 @@
// The pieces the set-up sheet is made of: store badges, the step that adds the
// connection (a link, the share sheet, a key or a file, as the app and the
// device allow), the panel that sends the connection to another device, the
// .conf for a router, the Download / Copy keys beside × and the line saying
// where an app scans a code. The rules behind them are setup.ts.
import type { ClientConfig, Device } from '../../shared/types';
import { h, ic, type Kid } from '../dom';
import { EASE_OUT, POP, SMOOTH, play } from '../motion';
import {
APP_NAME,
PLATFORM_LABEL,
importSteps,
keyFileName,
opensKeyLinks,
routerStore,
scanPath,
storeFor,
type AppId,
type Platform,
type Store,
} from '../setup';
import { accordion } from '../ui/accordion';
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';
export const APP_ICON: Record<AppId, string> = { vpn: 'amnezia', awg: 'amneziawg', 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;
} catch {
return null;
}
}
export function rememberApp(d: Device, app: AppId) {
try {
localStorage.setItem(memo(d), app);
} catch {
/* private mode */
}
}
/** What the steps work with: the device, its configuration, the key, and the choices made. */
export interface SetupCtx {
d: Device;
cfg: ClientConfig;
key: string;
/** The platform this page is open on. */
pf: Platform;
/** "the phone": the device in a sentence. */
there: string;
app(): AppId;
/** The page is open on the device being set up. */
same(): boolean;
}
/**
* A badge: the mark in a tile, two lines, a chevron (an action) or the open
* mark (a store page, in a new tab). `primary`: the one thing to tap in step 2.
*/
export function badge(
st: { href?: string; top: string; main: string; mark: string; onclick?: (ev: Event) => void },
primary = false,
): HTMLElement {
const inner = [
h('span', { class: 'b-ic' }, ic(st.mark)),
h('span', { class: 'b-t' }, h('span', { class: 'b-top' }, st.top), h('span', { class: 'b-main' }, st.main)),
ic(st.onclick || st.href?.startsWith('vpn:') ? 'chevron' : 'open'),
];
const cls = `badge${primary ? ' primary' : ''}`;
if (st.onclick) return h('button', { type: 'button', class: cls, onclick: st.onclick }, inner);
// A vpn:// key opens the app in place: no new tab.
const app = st.href?.startsWith('vpn:');
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[] {
const st: Store | null = router ? routerStore(app) : storeFor(app, os);
if (!st) return [hint(`Get ${APP_NAME[app]} on the ${PLATFORM_LABEL[os]} and come back here.`)];
// 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)];
}
const howto = (steps: [string, string][]) =>
h(
'ol',
{ class: 'howto' },
steps.map(([text, bold]) => h('li', {}, text.replace(/ → $/, ' ›'), bold ? [' ', h('b', {}, bold)] : null)),
);
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. */
export function connectKids(c: SetupCtx): Kid[] {
const app = c.app();
const name = APP_NAME[app];
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.
const inHand = c.same() && hereHandheld;
const copyKey = (ev: Event) => copy(c.key, 'Key copied', ev.currentTarget);
const send = app === 'vpn' && inHand && !opensKeyLinks(c.pf) ? shareFile(keyFileName(c.cfg.filename), c.key) : null;
if (app === 'vpn' && inHand && (opensKeyLinks(c.pf) || send))
return [
send
? badge({ top: 'Then come back here and tap', main: 'Send to AmneziaVPN', mark: 'amnezia', onclick: () => void send() }, true)
: badge({ href: c.key, top: 'Then come back here and tap', main: 'Open in AmneziaVPN', mark: 'amnezia' }, true),
hint(
send ? 'Pick AmneziaVPN in the share sheet. Not there? ' : 'Nothing opened? ',
linkBtn('Copy the key', copyKey),
' and add it in the app.',
),
];
if (app === 'vpn')
return [
badge({ top: 'The connection as one key', main: 'Copy the key', mark: 'copy', onclick: copyKey }, true),
howto([
['Open AmneziaVPN', ''],
['Add server › ', 'Insert key'],
['Paste the key and connect', ''],
]),
];
const share = hereHandheld ? shareFile(c.cfg.filename, c.cfg.conf) : null;
return [
share
? badge(
{
top: c.same() ? `Straight into ${name}` : `Send it to the ${c.there}`,
main: 'Share the file',
mark: 'share',
onclick: () => void share(),
},
true,
)
: badge(
{
top: 'Then import it in the app',
main: 'Download the file',
mark: 'download',
onclick: () => download(c.cfg.filename, c.cfg.conf),
},
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())),
];
}
/** A computer set up from elsewhere: the connection to send there, as the key 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 === 'vpn') {
const file = keyFileName(c.cfg.filename);
const share = !!shareFile(file, c.key);
return [
h('p', { class: 'desc' }, `Send it to the ${c.there} in a message or a note, then in AmneziaVPN: Add server › Insert key.`),
h(
'div',
{ class: 'btnrow2' },
btn('copy', 'Copy the key', (ev) => copy(c.key, 'Key copied', ev.currentTarget)),
btn(share ? 'share' : 'download', share ? 'Share as a file' : 'Download the key', () => sendFile(file, c.key)),
),
];
}
const share = !!shareFile(c.cfg.filename, c.cfg.conf);
return [
h('p', { class: 'desc' }, `Send it to the ${c.there}, then import `, h('b', {}, c.cfg.filename), ` in ${APP_NAME[app]}.`),
h(
'div',
{ class: 'btnrow2' },
btn(share ? 'share' : 'download', share ? 'Share the file' : 'Download the file', () => sendFile(c.cfg.filename, c.cfg.conf)),
btn('copy', 'Copy the configuration', (ev) => copy(c.cfg.conf, 'Configuration copied', ev.currentTarget)),
),
];
}
/** One configuration line, highlighted; private and preshared keys masked unless shown. */
function confLine(line: string, reveal: boolean): 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);
return h('span', {}, h('span', { class: 'k' }, m[1]), ' ', secret && !reveal ? h('span', { class: 'mask' }, '••••••••••••••••') : m[2]);
}
/** 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 share = !!shareFile(cfg.filename, cfg.conf);
const eye = h(
'button',
{
type: 'button',
class: 'btn soft sm',
onclick: () => {
reveal = !reveal;
eye.replaceChildren(ic(reveal ? 'x' : 'key'), h('span', {}, reveal ? 'Hide key' : 'Show key'));
paint();
// A key shown comes into focus out of a blur; hidden again, the mask fades back.
pre.querySelectorAll('.mask, .k').forEach((x) =>
play(
x,
[
{ filter: 'blur(4px)', opacity: 0.4 },
{ filter: 'none', opacity: 1 },
],
{ duration: 320, easing: EASE_OUT },
),
);
},
},
ic('key'),
h('span', {}, 'Show key'),
);
const cp = h(
'button',
{ type: 'button', class: 'btn soft sm', onclick: (ev: Event) => copy(cfg.conf, 'Configuration copied', ev.currentTarget) },
ic('copy'),
h('span', { class: 'lbl' }, 'Copy'),
);
const card = h(
'div',
{ class: 'filecard' },
h(
'div',
{ class: 'fc-row' },
h('span', { class: 'filecard-ic' }, '.conf'),
h('span', { class: 't' }, h('span', { class: 'mono' }, cfg.filename), h('span', {}, 'For computers and routers')),
),
h(
'button',
{ type: 'button', class: 'btn accent sm block', onclick: () => sendFile(cfg.filename, cfg.conf) },
ic(share ? 'open' : 'download'),
h('span', {}, share ? 'Share file' : 'Download'),
),
);
const conf = accordion([{ icon: glass('file'), title: 'Configuration', body: [h('div', { class: 'confbar' }, eye, cp), pre] }], {
inset: true,
});
return h('div', { class: 'step-box' }, card, conf.el);
}
export interface ScanLine {
el: HTMLElement;
/** Another app picked: its name and its path morph in place. */
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]);
const path = menuLine(scanPath(app, 'ios'), scanPath(app, 'android'));
return {
el: h('span', { class: 'scanline' }, h('span', {}, 'In ', name, ':'), path.el),
set(a) {
morphText(name, APP_NAME[a], undefined, { whole: true });
path.set(scanPath(a, 'ios'), scanPath(a, 'android'));
},
};
}
export interface ConnPill {
el: HTMLElement;
/** The labels follow the app picked. */
sync(): void;
}
/**
* 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.
*/
export function connPill(get: () => { text: string; msg: string; file: string; app: string }): 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);
const dl = h('button', { type: 'button', class: 'hp-b', onclick: () => sendFile(get().file, get().text) }, ic('download'));
const cp = h('button', { type: 'button', class: 'hp-b' }, ic('copy'));
const el = h('div', { class: 'hpill', role: 'group', 'aria-label': 'The connection', 'data-key': 'conn' }, dl, cp, tip);
let tipFor: HTMLElement | null = null;
let tipT = 0;
let warmUntil = 0;
const words = (b: HTMLElement) => (b === cp && cp.classList.contains('done') ? 'Copied' : (b.getAttribute('aria-label') ?? ''));
// Centred under its key, but never past the sheet's edge (× and its margin to the right).
const centre = (b: HTMLElement, t: string) => {
tm.textContent = t;
const w = tm.offsetWidth + 20;
return Math.min(b.offsetLeft + b.offsetWidth / 2, el.offsetWidth + 46 - w / 2);
};
const at = (x: number) => `translateX(${x}px) translateX(-50%)`;
const glideTo = (x: number) => {
const from = getComputedStyle(tip).transform;
tip.getAnimations().forEach((a) => a.cancel());
tip.style.transform = at(x);
play(tip, [{ transform: from }, { 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);
const show = (b: HTMLElement) => {
clearTimeout(tipT);
if (tipFor === b && tip.classList.contains('on')) return;
tipFor = b;
if (tip.classList.contains('on')) {
const t = words(b);
glideTo(centre(b, t));
return reword(t);
}
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,
[
{ opacity: 0, transform: `${at(x)} translateY(-3px) scale(.96)`, filter: 'blur(3px)' },
{ opacity: 1, transform: at(x), filter: 'blur(0px)' },
],
{
duration: 220,
easing: EASE_OUT,
},
);
};
if (performance.now() < warmUntil) up();
else tipT = window.setTimeout(up, 420);
};
const hide = () => {
clearTimeout(tipT);
tipFor = null;
if (!tip.classList.contains('on')) return;
warmUntil = performance.now() + 500;
tip.classList.remove('on');
play(tip, [{ opacity: 1 }, { opacity: 0 }], { duration: 120, easing: 'ease-out' });
};
for (const b of [dl, cp]) {
b.addEventListener('pointerenter', (e) => {
if (e.pointerType === 'mouse') show(b);
});
b.addEventListener('focus', () => {
if (b.matches(':focus-visible')) show(b);
});
b.addEventListener('blur', hide);
}
el.addEventListener('pointerleave', hide);
const icon = (name: string) => {
const n = ic(name);
cp.querySelector('svg')!.replaceWith(n);
play(
n,
[
{ opacity: 0, transform: 'scale(.6)', filter: 'blur(3px)' },
{ opacity: 1, transform: 'none', filter: 'none' },
],
{ duration: POP.duration, easing: POP.easing },
);
};
// Copied: the key shows a check and the tooltip says so, then both go back.
const sayCopy = () => {
if (tipFor !== cp || !tip.classList.contains('on')) return;
const t = words(cp);
glideTo(centre(cp, t));
reword(t);
};
let back = 0;
cp.addEventListener('click', () => {
const c = get();
void copy(c.text, c.msg);
clearTimeout(back);
if (!cp.classList.contains('done')) {
cp.classList.add('done');
icon('check');
sayCopy();
}
back = window.setTimeout(() => {
cp.classList.remove('done');
icon('copy');
sayCopy();
}, 1600);
});
return {
el,
sync() {
const app = get().app;
dl.setAttribute('aria-label', `Download ${app} config`);
cp.setAttribute('aria-label', `Copy ${app} config`);
},
};
}
+254
View File
@@ -0,0 +1,254 @@
// Setting a device up: one sheet. Its layout follows where the page is open:
// 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
// server's disguise and the platform (setup.ts). The wait for the first
// connection sits on top the whole time (wait.ts).
import type { ClientConfig, Device } from '../../shared/types';
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 { pageUrl, platform, preset, repaint } from '../state';
import { accordion } from '../ui/accordion';
import { codeRow, linkRow, type CodeRow } from '../ui/codes';
import { once, toast } from '../ui/feedback';
import { glass } from '../ui/glass';
import { morphInto, morphText } from '../ui/morph';
import { iconSeg, type IconSeg } from '../ui/seg';
import { glide, go, head, onClosed, onLeave, openSheet, sub, type View } from '../ui/sheet';
import { notice } from '../page/notices';
import { secureFirst, showSecure } from './secure';
import {
APP_ICON,
connPill,
connectKids,
filePane,
recallApp,
rememberApp,
scanLine,
type ScanLine,
sendKids,
storeBlock,
type SetupCtx,
} from './setup-parts';
import { arrive, waitWay, watchFirstConnection } from './wait';
async function getConfig(d: Device): Promise<ClientConfig | null> {
try {
return await call<ClientConfig>(`devices/${d.id}/config`);
} catch (e) {
if (e instanceof ApiError && e.httpsUrl) showSecure(e.httpsUrl);
else toast((e as Error).message, true);
return 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) {
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));
};
if (from instanceof HTMLButtonElement) await once(from, run);
else await run();
}
/** Further in a flow (Add, Reconnect): the configuration the router just sent, in the open sheet. */
export async function continueSetup(d: Device, cfg: ClientConfig) {
const key = await vpnKey(cfg, cfg.server);
go(() => setupView(d, cfg, key));
}
/** A numbered step: its number, a title, what to do. */
function step(n: string, title: Node | string, kids: (Node | null)[]): HTMLElement {
return h(
'div',
{ class: 'step' },
h('span', { class: 'step-n' }, n),
h('div', { class: 'step-b' }, typeof title === 'string' ? h('span', { class: 'step-t' }, title) : title, kids),
);
}
/** Fold a block away (height, then gone) or bring it back; `instant` without motion. */
function foldBlock(el: HTMLElement, fold: boolean, instant: boolean) {
const cur = el.hidden ? 0 : el.getBoundingClientRect().height;
el.getAnimations().forEach((a) => a.cancel());
if (instant) {
el.hidden = fold;
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 = () => {
el.style.overflow = '';
el.hidden = fold;
};
}
type Layout = 'same' | 'router' | 'away' | 'pc-away';
export function setupView(d: Device, cfg: ClientConfig, key: string): 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 layout: Layout = same ? 'same' : router ? 'router' : handheld ? 'away' : 'pc-away';
const there = deviceNoun(d.kind);
// 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');
if (!choices.some((a) => a.id === app)) app = choices[0].id;
const c: SetupCtx = { d, cfg, key, 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.
const segs: IconSeg<AppId>[] = [];
const picker = () => {
if (choices.length < 2) return null;
const s = iconSeg(
choices.map((a) => ({ value: a.id, label: a.name, icon: APP_ICON[a.id] })),
app,
(v) => {
app = v;
rememberApp(d, v);
segs.forEach((x) => x.sync(v));
// The sheet glides to its new height; inside, what changed morphs (morphInto).
glide(fill);
},
);
segs.push(s);
return s.el;
};
const title1 = h('span', { class: 'step-t' });
const getBox = h('div', { class: 'step-box' });
const addBox = h('div', { class: 'step-box' });
const codeBox = h('div', { class: 'step-box' });
const sendBox = h('div', { class: 'step-box' });
let code: CodeRow | null = null;
let scan: ScanLine | null = null;
let codeApp: AppId | null = null;
const pill =
layout === 'away'
? connPill(() => ({
...(app === 'vpn'
? { text: key, msg: 'Key copied', file: keyFileName(cfg.filename) }
: { text: cfg.conf, msg: 'Configuration copied', file: cfg.filename }),
app: APP_NAME[app],
}))
: null;
/** Everything a pick changes, refilled in place. */
function fill() {
morphText(title1, router ? `Get ${APP_NAME[app]} on the router` : `Get ${APP_NAME[app]}`, undefined, { whole: true });
morphInto(getBox, storeBlock(app, pf, router));
// The router's file is the same for either app: it stays as it is (a folded configuration stays folded).
if (!router) morphInto(addBox, connectKids(c));
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);
}
} else {
scan = scanLine(app);
code = codeRow(text, [scan.el]);
codeBox.replaceChildren(code.el);
}
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
: h('p', { class: 'desc' }, `Open this link on the ${there} to set it up there.`),
linkRow(linkThere),
];
const step1 = () => step('1', title1, [picker(), getBox]);
const step2 = () => step('2', router ? 'Import the configuration' : 'Add the connection', [addBox]);
const body = h('div', { class: 'setup' });
if (inWebview(navigator.userAgent))
body.appendChild(
notice('warn', 'shield', null, 'Open this page in Safari or Chrome: the store opens from here, but the app handoff does not.'),
);
if (layout === 'same') {
// Opened, the way round folds the steps away: the device is not in hand.
const steps = h('div', { class: 'steps-wrap' }, h('div', { class: 'steps-gap' }), step1(), step2());
const round = accordion([{ icon: glass('link'), title: `Not on the ${there} right now?`, body: linkBody() }], {
inset: true,
onToggle: (_i, open, instant) => foldBlock(steps, open, instant),
});
body.append(round.el, steps);
} else if (layout === 'router') body.append(step1(), step2());
// 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(
accordion(
[
{ icon: glass('link'), title: `Open your link on the ${there}`, body: linkBody() },
{ icon: glass('app'), title: 'Already has the app', body: [picker(), codeBox] },
],
{ 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.
else
body.appendChild(
accordion(
[
{ icon: glass('link'), title: `Open your link on the ${there}`, body: linkBody() },
{ icon: glass('key'), title: 'Copy or save the connection', body: [picker(), sendBox] },
],
{ inset: true, open: 0 },
).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 =
layout === 'same' ? 'Two steps, about a minute' : router ? 'The packages and the file for OpenWrt' : `The app goes on the ${there}.`;
const el = h('div', { class: 'view' }, head(`Set up ${d.name}`, { acts: !!pill }), sub(subline), way.el, body);
return { el, label: `Set up ${d.name}`, acts: pill?.el ?? null };
}
+171
View File
@@ -0,0 +1,171 @@
// 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.
import type { Device } from '../../shared/types';
import { gone, call } from '../api';
import { h, ic } from '../dom';
import { EASE_OUT, play } from '../motion';
import { now, repaint, setState, type State } from '../state';
import { menuOpen } from '../ui/menu';
import { morphText } from '../ui/morph';
import { closeSheet, onClosed, scrollTop, settle, showing } from '../ui/sheet';
export interface Way {
el: HTMLElement;
connected(): void;
gaveUp(): void;
}
export function waitWay(d: Device): Way {
const line = h('b', {}, 'Waiting for the connection');
const more = h('span', { class: 'ws', hidden: true });
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)),
);
return {
el,
connected() {
el.classList.add('done');
morphText(line, `${d.name} connected`);
},
gaveUp() {
el.classList.add('stopped');
morphText(line, 'No connection yet');
more.textContent = 'Close this and open it again to keep checking.';
more.hidden = false;
play(
line.parentElement!,
[
{ opacity: 0, filter: 'blur(4px)' },
{ opacity: 1, filter: 'none' },
],
{ duration: 280, easing: EASE_OUT },
);
},
};
}
/**
* 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".
*/
function catchUp(id: string, tries = 4) {
window.setTimeout(async () => {
try {
const st = await call<State>('state');
setState(st);
if (!menuOpen()) repaint();
if (!st.person.devices.find((x) => x.id === id)?.online && tries > 1) catchUp(id, tries - 1);
} catch {
/* a hiccup: the page keeps the last answer, as on load */
}
}, 1500);
}
/**
* 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.
*/
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.
const opened = now();
let timer = 0;
let polls = 0;
let done = false;
const started = Date.now();
const poll = async () => {
timer = 0;
if (done) return;
if (Date.now() - started > 600_000) {
done = true;
gaveUp();
return;
}
if (document.hidden) return schedule();
try {
const st = await call<State>('state');
setState(st);
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;
}
} catch (e) {
if (gone(e)) {
done = true;
return;
}
}
polls++;
schedule();
};
const schedule = () => {
if (!done && !timer) timer = window.setTimeout(poll, polls < 6 ? 5000 : polls < 12 ? 15000 : 30000);
};
const onVisible = () => {
if (!document.hidden && !done && !timer) void poll();
};
document.addEventListener('visibilitychange', onVisible);
schedule();
return () => {
done = true;
if (timer) clearTimeout(timer);
document.removeEventListener('visibilitychange', onVisible);
};
}
const beat = (ms: number) => new Promise((r) => setTimeout(r, ms));
/**
* 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.
*/
export async function arrive(way: Way, rest: HTMLElement, d: Device) {
way.connected();
settle();
scrollTop();
await beat(400);
if (!showing(way.el)) return;
rest.style.overflow = 'hidden';
play(
rest,
[
{ height: `${rest.offsetHeight}px`, opacity: 1, filter: 'none' },
{ height: '0px', opacity: 0, filter: 'blur(4px)' },
],
{
duration: 520,
easing: EASE_OUT,
fill: 'forwards',
},
);
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();
}
+113 -1929
View File
File diff suppressed because it is too large. Load diff
+80 -438
View File
@@ -1,36 +1,91 @@
// Portal motion: the moves between two states the DOM alone would snap
// between — a sheet's height following its content, cards that changed place
// after a repaint, a pane swapped for another, a sheet pulled down, a copy
// button saying it worked. This module measures and starts them; the curves,
// durations and every one-shot keyframe live in portal.css ("Motion").
// Portal motion: the springs and curves every animation runs on, the one way
// to start an animation from script, and the pure decisions behind a sheet
// pulled down. What moves and when lives with each piece (ui/, page/, flows/);
// one-shot CSS keyframes live in the stylesheets.
//
// Everything checks `calm()` (prefers-reduced-motion) and then only fades.
// The pure decisions (rubber band, when a pull dismisses) are exported for tests.
// Springs are physical (stiffness, damping) and sampled into CSS `linear()`, so
// a transition in CSS and an animation from script follow the same curve:
// BOUNCY is the skiper103 accordion (about 11% overshoot), SMOOTH the skiper21
// tab pill (critically damped). Reduced motion keeps fades and drops travel.
/** The visitor asked for less motion: fades only, nothing travels. */
export const calm = (): boolean => typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
/** The curves of portal.css, for animations started from script. */
const EASE = {
out: 'cubic-bezier(0.23, 1, 0.32, 1)',
in: 'cubic-bezier(0.55, 0, 1, 0.45)',
drawer: 'cubic-bezier(0.32, 0.72, 0, 1)',
};
export interface Spring {
/** Until it settles within 0.15% of the end. */
duration: number;
/** The curve as CSS `linear()`. */
easing: string;
/** Progress at `ms` (overshoots past 1 on a bouncy spring). */
at(ms: number): number;
}
/** A spring of stiffness `k` and damping `c` (mass 1), sampled into 64 steps. */
export function spring(k: number, c: number, m = 1): Spring {
const w0 = Math.sqrt(k / m);
const z = c / (2 * Math.sqrt(k * m));
const x = (t: number): number => {
if (z < 0.999) {
const wd = w0 * Math.sqrt(1 - z * z);
return 1 - Math.exp(-z * w0 * t) * (Math.cos(wd * t) + ((z * w0) / wd) * Math.sin(wd * t));
}
if (z <= 1.001) return 1 - Math.exp(-w0 * t) * (1 + w0 * t);
const r = Math.sqrt(z * z - 1);
const s1 = -w0 * (z - r);
const s2 = -w0 * (z + r);
return 1 - (s2 * Math.exp(s1 * t) - s1 * Math.exp(s2 * t)) / (s2 - s1);
};
let end = 0;
for (let t = 0; t < 3; t += 0.004) if (Math.abs(1 - x(t)) > 0.0015) end = t;
end += 0.004;
const pts: number[] = [];
for (let i = 0; i <= 64; i++) pts.push(+x((end * i) / 64).toFixed(4));
pts[64] = 1;
const duration = Math.round(end * 1000);
return { duration, easing: `linear(${pts.join(', ')})`, at: (ms) => (ms >= duration ? 1 : x(ms / 1000)) };
}
/** The accordion, the toast, a card that pops in. */
export const BOUNCY = spring(300, 20);
/** Pills, widths and heights: no overshoot. */
export const SMOOTH = spring(300, 35);
/** Small things that pop: a check, a menu. */
export const POP = spring(520, 24);
/** The leading edge of a stretching pill: faster than SMOOTH, no overshoot. */
export const LEAD = spring(520, 46);
/** A dialog on a computer and the accordions: the menu's pop made softer (about 4% over, 90% there at ~140 ms). */
export const SOFT = spring(380, 28);
/** What follows the pointer (a menu's highlight): there in about 130 ms, no overshoot. */
export const QUICK = spring(900, 60);
export const EASE_OUT = 'cubic-bezier(0.23, 1, 0.32, 1)';
export const EASE_IN = 'cubic-bezier(0.55, 0, 1, 0.45)';
export const DRAWER = 'cubic-bezier(0.32, 0.72, 0, 1)';
/** The springs as CSS variables, for transitions written in the stylesheets. */
export function publishSprings(root: HTMLElement) {
root.style.setProperty('--spring-bouncy', BOUNCY.easing);
root.style.setProperty('--spring-bouncy-dur', `${BOUNCY.duration}ms`);
root.style.setProperty('--spring-smooth', SMOOTH.easing);
root.style.setProperty('--spring-smooth-dur', `${SMOOTH.duration}ms`);
root.style.setProperty('--spring-soft', SOFT.easing);
root.style.setProperty('--spring-soft-dur', `${SOFT.duration}ms`);
root.style.setProperty('--spring-quick', QUICK.easing);
root.style.setProperty('--spring-quick-dur', `${QUICK.duration}ms`);
}
/**
* A block inside a sheet animating its own height: the sheet's edge follows it
* frame by frame on its own, so followHeight holds off meanwhile (a count:
* several such blocks may move at once).
* Start an animation. With reduced motion, an animation that fades keeps only
* its fade (short); one that only moves or resizes jumps to its end.
*/
function hold(el: Element): () => void {
const panel = el.closest<HTMLElement>('.sheet-panel');
if (!panel) return () => undefined;
panel.dataset.hold = String(+(panel.dataset.hold ?? 0) + 1);
return () => {
const n = +(panel.dataset.hold ?? 1) - 1;
if (n > 0) panel.dataset.hold = String(n);
else delete panel.dataset.hold;
};
export function play(el: Element, frames: Keyframe[], o: KeyframeAnimationOptions): Animation {
if (!calm()) return el.animate(frames, o);
if (frames.some((f) => 'opacity' in f))
return el.animate(
frames.map((f) => ('opacity' in f ? { opacity: f.opacity } : {})),
{ duration: Math.min(Number(o.duration ?? 200), 160), easing: 'ease-out', fill: o.fill },
);
return el.animate(frames, { ...o, duration: 0, delay: 0 });
}
/** Distance past an edge → how far it actually goes: resistance grows with the pull. */
@@ -46,416 +101,3 @@ export function dismisses(dy: number, velocity: number, height: number): boolean
if (dy <= 0 || velocity < -0.1) return false;
return velocity > 0.4 || dy > height / 3;
}
/** A height change takes longer the further it goes, inside the house range. */
export const morphMs = (dist: number): number => Math.round(Math.min(380, Math.max(220, 200 + dist * 0.35)));
/** Restart a one-shot CSS animation class on an element that already had it. */
export function replay(el: Element, cls: string) {
el.classList.remove(cls);
void (el as HTMLElement).offsetWidth;
el.classList.add(cls);
}
/**
* Keep `panel`'s size following `content`: whatever changes inside (a tab, a
* fold, a whole new sheet), the panel eases from the height it shows to the new
* one instead of jumping. Interruptible: a change mid-way starts from where it
* is. A width change (a window resize) only records, unless the panel asked for
* it (`data-morph="width"`: a question turning into a sheet), and then width
* and height morph together. Returns the stop.
*/
export function followHeight(panel: HTMLElement, content: HTMLElement): () => void {
let lastH = 0,
lastW = 0,
widthToo = false;
let anim: Animation | null = null;
const ro = new ResizeObserver(() => {
// Something inside moves its own height (hold): only keep up with the size.
if (panel.dataset.hold) {
anim?.cancel();
panel.classList.remove('morphing', 'morphing-w');
lastH = panel.offsetHeight;
lastW = panel.offsetWidth;
return;
}
const cs = getComputedStyle(panel);
const shownH = anim ? parseFloat(cs.height) : lastH;
const shownW = anim ? parseFloat(cs.width) : lastW;
anim?.cancel();
// Measure the natural size: without the uncapped width of a morph still under way.
panel.classList.remove('morphing', 'morphing-w');
const h = panel.offsetHeight,
w = panel.offsetWidth;
// Asked now, or still on its way from an earlier ask.
const asked = panel.dataset.morph === 'width' || widthToo;
delete panel.dataset.morph;
const resized = lastW !== 0 && w !== lastW;
lastH = h;
lastW = w;
if (!shownH || calm() || (resized && !asked)) return;
const dh = Math.abs(h - shownH),
dw = asked ? Math.abs(w - shownW) : 0;
if (dh < 2 && dw < 2) return;
widthToo = dw >= 2;
panel.classList.add('morphing');
panel.classList.toggle('morphing-w', widthToo);
const a = panel.animate(
widthToo
? [
{ height: `${shownH}px`, width: `${shownW}px` },
{ height: `${h}px`, width: `${w}px` },
]
: [{ height: `${shownH}px` }, { height: `${h}px` }],
{ duration: morphMs(Math.max(dh, dw)), easing: EASE.out },
);
anim = a;
const done = () => {
if (anim !== a) return;
anim = null;
widthToo = false;
panel.classList.remove('morphing', 'morphing-w');
};
a.onfinish = done;
a.oncancel = done;
});
ro.observe(content);
return () => ro.disconnect();
}
/**
* Swap `box`'s content for `next`: the old content fades out where it was
* (lifted out of the flow, so the box already takes the new height) while the
* new one comes in. `dir` -1 / 1: the new content comes from the left / right.
*/
export function swap(box: HTMLElement, next: Node[], dir = 0) {
const old = [...box.childNodes];
if (!old.length || !box.isConnected) {
box.replaceChildren(...next);
return;
}
// The ghost lays the old content out as the box did, over the box's padding edge.
const cs = getComputedStyle(box);
const ghost = document.createElement('div');
ghost.className = 'ghost';
ghost.setAttribute('aria-hidden', 'true');
ghost.inert = true;
Object.assign(ghost.style, {
display: cs.display === 'flex' ? 'flex' : 'block',
flexDirection: cs.flexDirection,
alignItems: cs.alignItems,
gap: cs.gap,
top: cs.paddingTop,
left: cs.paddingLeft,
right: cs.paddingRight,
});
ghost.append(...old);
box.replaceChildren(ghost, ...next);
// The old content drops away fast (it sits under the new one, see .ghost) so the two never read together.
const still = calm();
const out = ghost.animate(
[
{ opacity: 1, transform: 'none' },
{ opacity: 0, transform: still ? 'none' : `translateX(${-dir * 8}px)` },
],
{ duration: 120, easing: EASE.out, fill: 'forwards' },
);
const drop = () => ghost.remove();
out.onfinish = drop;
out.oncancel = drop;
for (const n of next)
if (n instanceof HTMLElement)
n.animate(
still
? [{ opacity: 0 }, { opacity: 1 }]
: [
{ opacity: 0, transform: `translate(${dir * 12}px, ${dir ? 0 : 6}px)`, filter: 'blur(4px)' },
{ opacity: 1, transform: 'none', filter: 'blur(0)' },
],
{ duration: still ? 160 : 280, delay: 50, easing: EASE.out, fill: 'backwards' },
);
}
/** Play an element's way out before it is removed (it keeps its place until then). */
export function leave(el: Element | null | undefined): Promise<void> {
if (!el || !el.isConnected) return Promise.resolve();
const a = el.animate(
calm()
? [{ opacity: 1 }, { opacity: 0 }]
: [
{ opacity: 1, transform: 'none', filter: 'blur(0)' },
{ opacity: 0, transform: 'scale(0.96)', filter: 'blur(4px)' },
],
{ duration: 200, easing: EASE.in, fill: 'forwards' },
);
return a.finished.then(
() => undefined,
() => undefined,
);
}
/** A beat between the steps of a sequence; none when the visitor asked for less motion. */
export const beat = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, calm() ? 0 : ms));
/**
* The accordion's look: the height closes on the drawer curve over `ms`; the
* content dissolves faster, from the start, as blocks leave elsewhere (blur, a
* small rise and shrink, on the strong ease-out over `contentMs`).
*/
const FOLD = { ms: 520, contentMs: 300, blur: 4, drift: 6, scale: 0.98 };
/**
* Fold a block shut like an accordion and take it out: its height closes from
* the bottom edge (the sheet's edge comes with it) while its content dissolves
* into a blur. Less motion: it fades.
*/
export async function fold(el: HTMLElement): Promise<void> {
if (!el.isConnected) return;
const release = hold(el);
const gap = parseFloat(getComputedStyle(el.parentElement as HTMLElement).rowGap) || 0;
const h = el.offsetHeight;
el.style.overflow = 'hidden';
el.style.transformOrigin = '50% 0';
el.inert = true;
const done = () => undefined;
if (calm())
await el.animate([{ opacity: 1 }, { opacity: 0 }], { duration: 160, easing: EASE.out, fill: 'forwards' }).finished.then(done, done);
else {
el.animate(
[
{ opacity: 1, filter: 'blur(0px)', transform: 'none' },
{ opacity: 0, filter: `blur(${FOLD.blur}px)`, transform: `translateY(${-FOLD.drift}px) scale(${FOLD.scale})` },
],
{ duration: FOLD.contentMs, easing: EASE.out, fill: 'forwards' },
);
await el
.animate(
[
{ height: `${h}px`, marginTop: '0px' },
{ height: '0px', marginTop: `${-gap}px` },
],
{ duration: FOLD.ms, easing: EASE.drawer, fill: 'forwards' },
)
.finished.then(done, done);
}
el.remove();
release();
}
/**
* The opposite, for a line that just got something to say: it opens from no
* height to its own (the sheet's edge comes with it) and comes into focus.
*/
export function grow(el: HTMLElement) {
if (!el.isConnected || calm()) return replay(el, 'swap');
const release = hold(el);
const gap = parseFloat(getComputedStyle(el.parentElement as HTMLElement).rowGap) || 0;
const h = el.offsetHeight;
el.style.overflow = 'hidden';
const a = el.animate(
[
{ height: '0px', marginTop: `${-gap}px`, opacity: 0, filter: 'blur(4px)' },
{ height: `${h}px`, marginTop: '0px', opacity: 1, filter: 'blur(0px)' },
],
{ duration: 380, easing: EASE.drawer },
);
const end = () => {
el.style.overflow = '';
release();
};
a.onfinish = end;
a.oncancel = end;
}
/**
* The page's first paint: the blocks matching `selector` rise in, in reading
* order (top to bottom, then left to right, whatever the layout), at most
* eight steps apart. portal.css draws `.intro`; `--i` is the step.
*/
export function intro(root: ParentNode, selector: string) {
const els = [...root.querySelectorAll<HTMLElement>(selector)].map((el) => ({ el, r: el.getBoundingClientRect() }));
els.sort((a, b) => Math.round(a.r.top - b.r.top) || a.r.left - b.r.left);
els.forEach(({ el }, i) => {
el.style.setProperty('--i', String(Math.min(i, 8)));
el.classList.add('intro');
});
}
/** Where the keyed blocks of a page are and what its keyed values say, before a repaint. */
export interface Snap {
at: Map<string, { x: number; y: number }>;
text: Map<string, string>;
}
export function snap(root: ParentNode): Snap {
const at = new Map<string, { x: number; y: number }>();
const text = new Map<string, string>();
root.querySelectorAll<HTMLElement>('[data-key]').forEach((el) => {
const r = el.getBoundingClientRect();
at.set(el.dataset.key as string, { x: r.left + scrollX, y: r.top + scrollY });
});
root.querySelectorAll<HTMLElement>('[data-v]').forEach((el) => text.set(el.dataset.v as string, el.textContent ?? ''));
return { at, text };
}
/**
* After a repaint: a keyed block that moved glides from where it was (FLIP),
* one that is new rises in, a keyed value that changed comes into focus.
* Keyed blocks are never nested, so no move is counted twice.
*/
export function settle(root: ParentNode, before: Snap) {
const still = calm();
root.querySelectorAll<HTMLElement>('[data-key]').forEach((el) => {
const was = before.at.get(el.dataset.key as string);
if (!was) {
el.classList.add('enter');
return;
}
if (still) return;
const r = el.getBoundingClientRect();
const dx = was.x - (r.left + scrollX),
dy = was.y - (r.top + scrollY);
if (Math.abs(dx) < 1 && Math.abs(dy) < 1) return;
el.animate([{ transform: `translate(${dx}px, ${dy}px)` }, { transform: 'none' }], {
duration: morphMs(Math.hypot(dx, dy)),
easing: EASE.out,
});
});
root.querySelectorAll<HTMLElement>('[data-v]').forEach((el) => {
const was = before.text.get(el.dataset.v as string);
if (was != null && was !== el.textContent) el.classList.add('swap');
});
}
/**
* A repaint of a sheet's content that keeps its motion: keyed controls
* (`data-m`) that flipped on or off get `to-on` / `to-off`, whose keyframes
* start from the other look; one whose text changed comes into focus (`swap`);
* one marked `data-glide` that moved within its parent (a chip beside a chevron
* that went) glides there.
*/
export function restyle(root: ParentNode, paint: () => void) {
const state = (el: Element) => el.classList.contains('on') || el.classList.contains('open');
// What it says: its text, or `data-sig` where the text says nothing (a QR code).
const says = (el: HTMLElement) => el.dataset.sig ?? el.textContent ?? '';
const inParent = (el: HTMLElement) => {
const r = el.getBoundingClientRect(),
p = (el.parentElement as HTMLElement).getBoundingClientRect();
return { x: r.left - p.left, y: r.top - p.top };
};
const before = new Map<string, { on: boolean; says: string }>();
root.querySelectorAll<HTMLElement>('[data-m]').forEach((el) => before.set(el.dataset.m as string, { on: state(el), says: says(el) }));
const placed = new Map<string, { x: number; y: number }>();
root.querySelectorAll<HTMLElement>('[data-glide]').forEach((el) => placed.set(el.dataset.glide as string, inParent(el)));
paint();
if (!calm())
root.querySelectorAll<HTMLElement>('[data-glide]').forEach((el) => {
const was = placed.get(el.dataset.glide as string);
if (!was) return;
const now = inParent(el);
const dx = was.x - now.x,
dy = was.y - now.y;
if (Math.abs(dx) >= 1 || Math.abs(dy) >= 1)
el.animate([{ transform: `translate(${dx}px, ${dy}px)` }, { transform: 'none' }], { duration: 280, easing: EASE.out });
});
root.querySelectorAll<HTMLElement>('[data-m]').forEach((el) => {
const was = before.get(el.dataset.m as string);
if (!was) return;
if (was.on !== state(el)) el.classList.add(state(el) ? 'to-on' : 'to-off');
else if (was.says !== says(el)) el.classList.add('swap');
});
}
/** A copy button in its "Copied" moment: what to put back, and when. */
const COPIED = new WeakMap<HTMLElement, { timer: number; icon: string | null; label: string | null }>();
/**
* A copy button says it worked where the finger is: its icon turns into a
* check and a "Copy" label into "Copied", for a moment. Other labels (a host
* name on a chip) stay. `check` is the check icon's markup.
*/
export function copied(btn: HTMLElement | null | undefined, check: string) {
if (!btn) return;
const icon = btn.querySelector<HTMLElement>('.ic');
const label =
btn.querySelector<HTMLElement>('.badge-main') ??
btn.querySelector<HTMLElement>(':scope > span:not(.ic)') ??
(btn.children.length ? null : btn);
const was = COPIED.get(btn) ?? { timer: 0, icon: icon?.innerHTML ?? null, label: label?.textContent ?? null };
clearTimeout(was.timer);
const says = !!label && (label.classList.contains('badge-main') || /^copy$/i.test(was.label ?? ''));
const show = (svg: string | null, text: string | null) => {
if (icon && svg != null && icon.innerHTML !== svg) {
icon.innerHTML = svg;
replay(icon, 'swap-ic');
}
if (label && says && text != null && label.textContent !== text) {
label.textContent = text;
replay(label, 'swap');
}
};
show(check, 'Copied');
btn.classList.add('copied');
was.timer = window.setTimeout(() => {
COPIED.delete(btn);
btn.classList.remove('copied');
show(was.icon, was.label);
}, 1600);
COPIED.set(btn, was);
}
/** A button waiting for the router: after a beat (no flash on a quick answer) a spinner takes the label's place. */
export function busy(btn: HTMLElement): () => void {
const t = window.setTimeout(() => btn.classList.add('busy'), 250);
return () => {
clearTimeout(t);
btn.classList.remove('busy');
};
}
/**
* Let a bottom sheet be pulled down by its grab bar and head (a question: all of it): the panel
* follows the finger (with resistance upwards), the scrim fades with it, and
* on release it either goes (`close`) or springs back. Only while `bottom()`
* (the sheet sits at the bottom: phones). The release transitions start from
* the dragged spot because the inline transform and `.dragging` go together.
*/
export function pullToClose(panel: HTMLElement, scrim: HTMLElement, close: () => void, bottom: () => boolean) {
panel.addEventListener('pointerdown', (e) => {
const t = e.target as Element;
if (!bottom() || e.button !== 0 || !t.closest('.grab, .sheet-head, .ask') || t.closest('button, a, input')) return;
const y0 = e.clientY,
h = panel.offsetHeight;
let dy = 0;
const trail: { t: number; y: number }[] = [{ t: e.timeStamp, y: e.clientY }];
try {
panel.setPointerCapture(e.pointerId);
} catch {
/* a pointer the browser no longer tracks: the pull still follows while it is over the panel */
}
panel.classList.add('dragging');
const move = (ev: PointerEvent) => {
const raw = ev.clientY - y0;
dy = raw < 0 ? -rubber(-raw, h) : raw;
panel.style.transform = `translateY(${dy}px)`;
scrim.style.opacity = String(1 - Math.max(0, dy) / h);
trail.push({ t: ev.timeStamp, y: ev.clientY });
while (trail.length > 2 && ev.timeStamp - trail[0].t > 100) trail.shift();
};
const up = (ev: PointerEvent) => {
panel.removeEventListener('pointermove', move);
panel.removeEventListener('pointerup', up);
panel.removeEventListener('pointercancel', up);
const first = trail[0],
last = trail[trail.length - 1];
const v = last.t > first.t ? (last.y - first.y) / (last.t - first.t) : 0;
panel.classList.remove('dragging');
panel.style.transform = '';
scrim.style.opacity = '';
if (ev.type === 'pointerup' && dismisses(dy, v, h)) close();
};
panel.addEventListener('pointermove', move);
panel.addEventListener('pointerup', up);
panel.addEventListener('pointercancel', up);
});
}
+311
View File
@@ -0,0 +1,311 @@
// "Your access", set by the admin: one accordion of three rows. What the
// 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.
import type { Person } from '../../shared/types';
import { ACCESS_LABEL, byDeviceState, bytes, date, daysLeft, endsSoon, parseDay } from '../../shared/format';
import { h, ic, markup } from '../dom';
import { calendar, clockOf, hoursFor, minuteAt, monthOf, stretches } from '../days';
import { now, today, type State } from '../state';
import { accordion, type Accordion } from '../ui/accordion';
import { copy } from '../ui/feedback';
import { glass } from '../ui/glass';
import { morphChanged, setText, textsOf } from '../ui/morph';
import { reachableFromHome } from './devices';
const desc = (text: string) => h('p', { class: 'desc' }, text);
/** A share of a length, as a CSS percentage. */
const pc = (part: number, whole: number) => `${((part / whole) * 100).toFixed(2)}%`;
/** What the access reaches, as two tiles: the home network and the internet, each in or out. */
function reachTiles(access: Person['access']): HTMLElement {
const tile = (on: boolean, icon: string, name: string, sub: string) =>
h(
'div',
{ class: `reach-tile${on ? '' : ' off'}` },
glass(icon, on ? 'blue' : 'grey', 'gi rt-ic'),
h('b', {}, name),
h('span', { class: 'rt-sub' }, on ? sub : 'Not included'),
h('span', { class: 'rt-mark', 'aria-label': on ? 'Included' : 'Not included' }, ic(on ? 'check' : 'minus')),
);
return h(
'div',
{ class: 'reach2' },
tile(access !== 'internet', 'home', 'Home network', 'Devices at home'),
tile(access !== 'lan', 'globe', 'Internet', 'Through the router'),
);
}
/** How other devices at home reach this person's devices: once, here, only where the router lets them through. */
function namesAtHome(p: Person, mesh: boolean): Node[] {
const named = byDeviceState(p.devices).filter((d) => d.hostname && reachableFromHome(p, d));
if (!named.length) return [];
const first = named[0].hostname;
const dot0 = first.indexOf('.');
const domain = dot0 > 0 ? first.slice(dot0) : '';
return [
h(
'span',
{ class: 'lbl-s' },
mesh ? 'Devices at home and on this VPN reach yours as ' : 'Other devices at home reach yours as ',
h('span', { class: 'mono' }, `name${domain}`),
),
h(
'div',
{ class: 'names' },
named.map((d) => {
const dot = d.hostname.indexOf('.');
return h(
'button',
{
type: 'button',
class: 'namechip',
title: d.name,
'aria-label': `Copy ${d.hostname}`,
onclick: (ev: Event) => copy(d.hostname, 'Address copied', ev.currentTarget),
},
h('span', {}, dot > 0 ? [d.hostname.slice(0, dot), h('span', { class: 'faint' }, d.hostname.slice(dot))] : d.hostname),
ic('copy'),
);
}),
),
];
}
/** Used against the limit, as a small ring (its colour: fine, nearly full, full). */
function ring(pct: number): Element {
const c = 2 * Math.PI * 6;
const tone = pct >= 100 ? ' bad' : pct >= 90 ? ' warn' : '';
return markup(
`<svg class="ring" viewBox="0 0 16 16" aria-hidden="true"><circle class="trk" cx="8" cy="8" r="6" fill="none" stroke-width="2.4"/>` +
`<circle class="arc${tone}" cx="8" cy="8" r="6" fill="none" stroke-width="2.4" stroke-linecap="round" stroke-dasharray="${((c * pct) / 100).toFixed(2)} ${c.toFixed(2)}"/></svg>`,
);
}
function meter(pct: number): HTMLElement {
const i = h('i', { class: pct >= 100 ? 'bad' : pct >= 90 ? 'warn' : '' });
i.style.width = `${pct.toFixed(1)}%`;
return h('div', { class: 'meter' }, i);
}
/** The month as one bar a day (today in blue, days to come faint), and the total under it. */
function month(p: Person, used: number, pct: number): HTMLElement {
const { days, day } = monthOf(today());
const series = p.month_days ?? [];
const max = Math.max(1, ...series);
const short = (d: number) =>
parseDay(`${today().slice(0, 8)}${String(d).padStart(2, '0')}`).toLocaleDateString('en-GB', { day: 'numeric', month: 'short' });
// The total, and a bar under the pointer in its place, at once: no morph while the pointer moves.
const total = h('b', { class: 'num', 'data-t': 'm-used' }, bytes(used));
const tail = h('span', {}, ' used');
const read = h('span', { class: 'mread' }, total, tail);
const bars = h('div', { class: 'mbars' });
for (let i = 0; i < days; i++) {
if (i >= day) {
bars.appendChild(h('i', { class: 'future' }));
continue;
}
const v = series[i] ?? 0;
const b = h('i', { class: i === day - 1 ? 'today' : '' });
b.style.height = `${Math.max(3, Math.round((v / max) * 64))}px`;
b.addEventListener('pointerenter', () => {
setText(total, bytes(v));
setText(tail, ` on ${short(i + 1)}`);
});
b.addEventListener('pointerleave', () => {
setText(total, bytes(used));
setText(tail, ' used');
});
bars.appendChild(b);
}
// "Today" under its bar; the month's ends step aside when it comes close.
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)),
);
return h(
'div',
{ class: 'month' },
bars,
axis,
h(
'div',
{ class: 'month-read' },
read,
h(
'span',
{ class: `num${p.state === 'quota' ? ' bad-t' : ''}`, 'data-t': 'm-left' },
p.quota_limit ? `${bytes(Math.max(0, p.quota_limit - used))} left` : 'No limit',
),
),
p.quota_limit ? meter(pct) : null,
);
}
/** The days left as a number over a calendar of the weeks to the end (the last day ringed). */
function untilCal(p: Person, left: number): HTMLElement {
const day = (d: string) => parseDay(d).toLocaleDateString('en-GB', { weekday: 'short', day: 'numeric', month: 'short' });
const cells = calendar(today(), p.expires);
const cal = cells
? h(
'div',
{ class: 'cal', 'aria-hidden': 'true' },
h(
'div',
{ class: 'cal-h' },
['M', 'T', 'W', 'T', 'F', 'S', 'S'].map((x) => h('span', {}, x)),
),
h(
'div',
{ class: 'cal-g' },
cells.map((c, i) => {
const el = h('i', { class: c.kind, title: day(c.day) });
el.style.setProperty('--i', String(i));
return el;
}),
),
)
: null;
return h(
'div',
{ class: `until${endsSoon(p, left) ? ' soon' : ''}` },
h(
'div',
{ class: 'until-num' },
h('b', { class: 'num' }, String(left)),
h('span', {}, `${left === 1 ? 'day' : 'days'} left`),
h('span', { class: 'until-sub' }, `Ends ${day(p.expires)}`),
),
cal,
);
}
/** The day as 24 hours in the visitor's time: the admin's window filled, now marked. */
function hoursBar(hours: string, tzOffset: number | undefined): HTMLElement | null {
const visitor = -new Date().getTimezoneOffset();
const hw = hoursFor(hours, tzOffset, visitor);
if (!hw) return null;
// The router's clock, read in the visitor's zone (or the router's, without its offset).
const at = minuteAt(now(), hw.yours ? visitor : (tzOffset ?? visitor));
const segs = stretches(hw);
const inside = segs.some(([a, b]) => at >= a && at < b);
const bar = h('div', { class: 'hours-bar' });
for (const [a, b] of segs) {
const i = h('i');
i.style.left = pc(a, 1440);
i.style.width = pc(b - a, 1440);
bar.appendChild(i);
}
const mark = h('span', { class: `hours-now${inside ? '' : ' out'}`, title: `Now, ${clockOf(at)}` });
mark.style.left = pc(at, 1440);
bar.appendChild(mark);
return h(
'div',
{ class: 'hours' },
h(
'div',
{ class: 'hours-top' },
h('span', {}, hw.yours ? 'Hours, your time' : 'Hours, router time'),
h('b', { class: 'num' }, `${clockOf(hw.from)}–${clockOf(hw.to)}`),
),
bar,
h(
'div',
{ class: 'hours-axis' },
['00', '06', '12', '18', '24'].map((x) => h('span', {}, x)),
),
);
}
/** The access accordion for this state; `open`: the row to keep open (a repaint), else the data. */
export function accessAccordion(st: State, open = 1): Accordion {
const p = st.person;
const used = p.quota_used || p.month[0] + p.month[1];
const pct = p.quota_limit ? Math.min(100, (used / p.quota_limit) * 100) : 0;
// A total over the whole access only with a limit; otherwise it is this month's count.
const total = p.quota_period === 'total' && !!p.quota_gb;
const left = daysLeft(p.expires, today());
const untilVal = p.expires
? h(
'span',
{ class: 'until-val' },
h('span', { class: 'num', 'data-t': 'until-date' }, date(p.expires).replace(/ \d{4}$/, '')),
left != null
? h(
'span',
{ class: `num ${left < 0 ? 'bad-t' : endsSoon(p, left) ? 'warn-t' : 'ok-t'}`, 'data-t': 'until-left' },
left >= 0 ? `${left} day${left === 1 ? '' : 's'}` : 'ended',
)
: null,
)
: h('span', {}, 'No end date');
const untilBody = [
!p.expires ? null : left != null && left < 0 ? desc(`It ended on ${date(p.expires)}.`) : untilCal(p, left ?? 0),
p.hours ? hoursBar(p.hours, st.tz_offset) : null,
];
return accordion(
[
{
icon: glass(p.access === 'internet' ? 'globe' : p.access === 'lan' ? 'home' : 'shield'),
title: ACCESS_LABEL[p.access],
body: [reachTiles(p.access), ...namesAtHome(p, !!st.server.device_mesh)],
},
{
icon: glass('chart'),
title: total ? 'Data used' : 'Data this month',
val: h(
'span',
{ class: 'data-val' },
p.quota_limit ? ring(pct) : null,
h(
'span',
{ class: 'num', 'data-t': 'data-val' },
`${bytes(used)}${p.quota_limit ? ` / ${bytes(p.quota_limit)}` : ' · no limit'}`,
),
),
valHide: true,
body: [
total ? desc(`${bytes(used)} of ${bytes(p.quota_limit)} in total.`) : month(p, used, pct),
desc(
!p.quota_limit
? 'No data limit. The count starts again on the 1st.'
: total
? 'A total for your whole access, it does not reset.'
: 'Resets on the 1st.',
),
],
},
// 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 },
);
}
/** The section, built once; `fillAccess` puts the accordion in. */
export function accessSection(): HTMLElement {
return h(
'section',
{ class: 'access', id: 'access', 'aria-label': 'Your access' },
h('div', { class: 'sec-head' }, h('h2', {}, 'Your access')),
h('div', { class: 'acc-slot' }),
);
}
let shown: Accordion | null = null;
/** The accordion for this state, the same row open as before. */
export function fillAccess(section: HTMLElement, st: State) {
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;
}
+293
View File
@@ -0,0 +1,293 @@
// "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
// connected rings green for a moment. What a card's buttons start lives in
// flows/.
import type { Device, Person } from '../../shared/types';
import { addDays, ago, byDeviceState, bytes, parseDay } from '../../shared/format';
import { h, ic } from '../dom';
import { BOUNCY, EASE_IN, EASE_OUT, SMOOTH, play } from '../motion';
import { now, today, type RepaintOpts, type State } from '../state';
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 { startAdd } from '../flows/add';
import { reconnect, removeDevice, rename } from '../flows/device-actions';
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] {
if (d.disabled) return ['', 'Disabled'];
// The Update pill beside it says what to do.
if (d.config_stale && d.handshake) return ['warn-t', 'Settings changed'];
// Over the data limit or outside the hours the tunnel stays up but passes nothing: the app says
// "connected", so say here why nothing works.
if (d.online && p.state === 'quota') return ['warn-t', 'Connected, no data left'];
if (d.online && p.state === 'hours') return ['warn-t', 'Connected, outside your hours'];
if (d.online) return ['ok-t', 'Connected'];
if (!d.handshake) return ['warn-t', 'Not set up yet'];
return ['', `Last connected ${ago(d.handshake, now())}`];
}
function menuItems(d: Device, st: State): (MenuItem | null)[] {
return [
// How devices at home reach it: only where the router actually lets them through.
...(reachableFromHome(st.person, d)
? [
{ label: 'Copy IP address', icon: 'copy', run: () => copy(d.address, 'IP address copied') },
...(d.hostname ? [{ label: 'Copy local address', icon: 'home', run: () => copy(d.hostname, 'Address copied') }] : []),
null,
]
: []),
// A device the admin turned off can't be renamed, set up again or removed here (the router refuses).
...(d.disabled
? []
: [
{ label: 'Rename', icon: 'edit', run: () => rename(d) },
{ label: 'Reconnect', icon: 'refresh', tone: 'warn' as const, run: () => reconnect(d) },
{ label: 'Remove', icon: 'trash', tone: 'bad' as const, run: () => removeDevice(d) },
]),
];
}
/** "Today", "Yesterday", "Tue 13 Oct": a spark bar's day, on the router's calendar. */
function dayName(back: number): string {
if (back === 0) return 'Today';
if (back === 1) return 'Yesterday';
return parseDay(addDays(today(), -back)).toLocaleDateString('en-GB', { weekday: 'short', day: 'numeric', month: 'short' });
}
/** Last 7 days as a number and bars; a bar under the pointer puts its own day in the number's place. */
function usage(d: Device, stale: boolean): HTMLElement {
const week = d.spark.reduce((a, b) => a + b, 0);
const lbl = h('span', { class: 'use-lbl' }, 'Last 7 days');
const val = h('span', { class: 'use-val num', 'data-t': `${d.id}:use` }, bytes(week));
let side: HTMLElement;
if (stale)
side = h(
'button',
{
type: 'button',
class: 'upd-pill',
'aria-label': 'Update the connection',
title: 'Its settings changed: update the connection',
onclick: () => reconnect(d),
},
ic('refresh'),
h('span', {}, 'Update'),
);
else {
const max = Math.max(1, ...d.spark);
side = h('div', { class: 'spark' });
d.spark.forEach((v, i) => {
const back = d.spark.length - 1 - i;
const b = h('i', { class: back === 0 ? 'today' : '' });
b.style.height = `${Math.max(3, Math.round((v / max) * 34))}px`;
// What the pointer reads off the bars changes at once: no morph while it moves.
b.addEventListener('pointerenter', () => {
setText(lbl, dayName(back));
setText(val, bytes(v));
});
b.addEventListener('pointerleave', () => {
setText(lbl, 'Last 7 days');
setText(val, bytes(week));
});
side.appendChild(b);
});
}
return h('div', { class: 'dev-use' }, h('div', { class: 'use-txt' }, lbl, val), side);
}
function card(d: Device, st: State): HTMLElement {
const p = st.person;
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 setUp = !d.handshake && !d.disabled;
const stale = d.config_stale && !setUp && !locked && !d.disabled;
// On one line; the exact time, or the whole wording, on hover.
const title =
!here && d.handshake && !d.online && !d.disabled && !d.config_stale
? new Date(d.handshake * 1000).toLocaleString('en-GB')
: stale
? 'Settings changed, update needed'
: words;
const items = menuItems(d, st);
const more =
locked || !items.length
? null
: h(
'button',
{ type: 'button', class: 'knob more', 'aria-label': `${d.name} options`, 'aria-haspopup': 'menu', 'aria-expanded': 'false' },
ic('more'),
);
more?.addEventListener('click', () => openMenu(more, items));
return h(
'article',
{ class: `dev${here ? ' is-here' : ''}${d.disabled ? ' off' : ''}`, 'data-id': d.id },
h(
'div',
{ class: 'dev-top' },
glass(d.kind, here ? 'blue' : 'grey'),
h(
'div',
{ class: 'dev-id' },
h('span', { class: 'dev-name', 'data-t': `${d.id}:name` }, d.name),
h('span', { class: `dev-stat ${cls}`, title, 'data-t': `${d.id}:stat` }, words),
),
more,
),
// Stopped by the admin: a device never set up has nothing to show.
setUp && locked
? null
: setUp
? h(
'button',
{
type: 'button',
class: 'btn tint block setup-btn',
'aria-label': `Set up ${d.name}`,
onclick: (ev: Event) => openSetup(d, ev.currentTarget),
},
ic('qr'),
h('span', {}, 'Connect'),
)
: usage(d, stale),
);
}
/** Nothing yet: one card that says what comes, with the button. */
const firstCard = (mobile: boolean) =>
h(
'div',
{ class: 'dev first', 'data-id': 'first' },
glass('plus', 'blue'),
h('b', {}, 'Add your first device'),
h('p', {}, 'Two steps, about a minute: get the app, then add the connection.'),
h(
'button',
{ type: 'button', class: 'btn accent block', onclick: startAdd },
ic('plus'),
h('span', {}, mobile ? 'Add this phone' : 'Add this device'),
),
);
const addCard = () =>
h('button', { type: 'button', class: 'dev add', 'data-id': 'add', onclick: startAdd }, glass('plus'), h('span', {}, 'Add device'));
/** The section, built once; `fill` puts the cards in. */
export function devicesSection(): HTMLElement {
return h(
'section',
{ class: 'devices', id: 'devices', 'aria-label': 'Your devices' },
h('div', { class: 'sec-head' }, h('h2', {}, 'Your devices'), h('span', { class: 'aside num' })),
h('div', { class: 'dgrid' }),
h('p', { class: 'note-s limit', hidden: true }),
);
}
/** The cards for this state, moving from where they were. */
export function fillDevices(section: HTMLElement, st: State, o: RepaintOpts = {}) {
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.
const order = byDeviceState(p.devices).sort((a, b) => Number(b.id === st.here) - Number(a.id === st.here));
const cards = order.map((d) => card(d, st));
const free = st.locked ? 0 : Math.max(0, p.device_limit - p.devices.length);
const mobile = matchMedia('(max-width: 959px)').matches || /Android|iPhone|iPad/.test(navigator.userAgent);
if (!p.devices.length && free) cards.push(firstCard(mobile));
// Paused or ended: the router refuses a new device, so there is no card to offer one (the notice says why).
else if (st.can_add && !st.locked) cards.push(addCard());
grid.classList.toggle('empty', !p.devices.length);
grid.replaceChildren(...cards);
for (const c of cards) {
const f = first.get(c.dataset.id);
const l = c.getBoundingClientRect();
if (c.dataset.id === o.pop)
play(
c,
[
{ opacity: 0, transform: 'scale(.9)', filter: 'blur(6px)' },
{ opacity: 1, transform: 'none', filter: 'none' },
],
{
duration: BOUNCY.duration,
easing: BOUNCY.easing,
},
);
else if (f && (f.left !== l.left || f.top !== l.top))
play(c, [{ transform: `translate(${f.left - l.left}px, ${f.top - l.top}px)` }, { transform: 'none' }], {
duration: SMOOTH.duration,
easing: SMOOTH.easing,
});
// New on a repaint (Add device once a slot frees up): it comes in the way a removed card leaves, a beat after.
else if (!f && repainting)
play(
c,
[
{ opacity: 0, transform: 'scale(.9)', filter: 'blur(6px)' },
{ opacity: getComputedStyle(c).opacity, transform: 'none', filter: 'none' },
],
{
duration: SMOOTH.duration,
delay: 60,
easing: SMOOTH.easing,
fill: 'backwards',
},
);
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',
});
}
if (repainting) morphChanged(grid, said);
const count = section.querySelector('.sec-head .aside') as HTMLElement;
const n = `${p.devices.length} of ${p.device_limit}`;
if (repainting) morphText(count, n);
else count.textContent = n;
// 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 = `You have reached your limit of ${p.device_limit} 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(
limit,
[
{ opacity: 1, filter: 'none' },
{ opacity: 0, filter: 'blur(4px)' },
],
{ duration: 200, easing: EASE_IN, fill: 'forwards' },
);
a.onfinish = () => {
limit.hidden = true;
a.cancel();
};
} else {
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 },
);
}
}
+61
View File
@@ -0,0 +1,61 @@
// The page's frame: no navbar. The page fades out under the screen's top and
// bottom edges (the top fade only once it scrolls, so the breadcrumb at rest
// stays crisp), and opens with a breadcrumb: the Dawnline mark, the place (the
// server's name) and the person. The content goes in `body`.
import { h, ic, markup } from '../dom';
import { placeName, state } from '../state';
import { showPageCode } from '../flows/page-code';
// The sun rises from behind the horizon once, on the visit's first paint.
const LOGO =
'<svg class="logo" viewBox="0 0 24 24" aria-hidden="true"><defs><clipPath id="dl-sky"><rect width="24" height="17"/></clipPath></defs>' +
'<g clip-path="url(#dl-sky)"><path class="sun" d="M3 15a9 9 0 0 1 18 0z"/></g><rect class="bar" x="2" y="17" width="20" height="2" rx="1"/></svg>';
let crumbsEl: HTMLElement | null = null;
let bodyEl: HTMLElement | null = null;
let pageEl: HTMLElement | null = null;
/** The frame, built once into #app; returns the slot the page's content goes in. */
export function frame(app: HTMLElement): HTMLElement {
if (bodyEl) return bodyEl;
crumbsEl = h('header', { class: 'crumbs' });
bodyEl = h('div', { class: 'page-body' });
app.replaceChildren(
h('div', { class: 'edge-fade top', 'aria-hidden': 'true' }),
h('div', { class: 'edge-fade bot', 'aria-hidden': 'true' }),
(pageEl = h('main', { class: 'page' }, crumbsEl, bodyEl)),
);
const onScroll = () => document.body.classList.toggle('scrolled', scrollY > 2);
addEventListener('scroll', onScroll, { passive: true });
onScroll();
return bodyEl;
}
/** 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);
}
/**
* The breadcrumb: the place, then the person (none when the link stopped
* working); at its end, this page's code for another device, on the page
* itself only (not over a card: paused, link gone, nothing loaded).
*/
export function crumbs(gone = false, card = false) {
if (!crumbsEl) return;
const p = gone ? null : state()?.person;
const place = h('span', { class: p ? '' : 'cur', 'aria-current': p ? null : 'page' }, placeName());
crumbsEl.replaceChildren(
h('span', { class: 'cr-mark' }, markup(LOGO)),
h(
'nav',
{ class: 'cr-path', 'aria-label': 'Breadcrumb' },
place,
p ? [ic('chevron'), h('span', { class: 'cur', 'aria-current': 'page' }, p.name)] : null,
),
...(p && !card
? [h('button', { type: 'button', class: 'knob cr-qr', 'aria-label': 'Open on another device', onclick: showPageCode }, ic('qr'))]
: []),
);
}
+53
View File
@@ -0,0 +1,53 @@
// 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.
import type { Person } from '../../shared/types';
import { daysLeft, date, endsIn, endsSoon } from '../../shared/format';
import { h } from '../dom';
import { clockOf, hoursFor } from '../days';
import { state, today } from '../state';
import { glass } from '../ui/glass';
export type Tone = 'warn' | 'bad';
export function notice(tone: Tone, icon: string, title: string | null, sub: string): HTMLElement {
return h(
'div',
{ class: `notice ${tone}` },
glass(icon, tone === 'bad' ? 'red' : 'orange'),
h('div', { class: 't' }, title ? h('b', {}, title) : null, h('span', {}, sub)),
);
}
/** The admin's hours as the visitor reads them: "08:00–22:00 your time" (or the router's, said so). */
export function hoursText(hours: string): string {
const hw = hoursFor(hours, state()?.tz_offset, -new Date().getTimezoneOffset());
if (!hw) return `${hours.replace('-', '–')} (router time)`;
return `${clockOf(hw.from)}–${clockOf(hw.to)} ${hw.yours ? 'your time' : '(router time)'}`;
}
/** Why the person's devices can't connect: icon, a short title, and a line that adds to it (never says it again). */
export function stateNotice(p: Person): [string, string, string] {
switch (p.state) {
case 'server_off':
return ['server', 'Server is disabled', 'Your devices can’t connect until it’s enabled again.'];
case 'no_server':
return ['server', 'No server yet', 'You haven’t been added to one.'];
case 'quota':
return ['chart', 'Out of data', 'Nothing gets through until it resets.'];
case 'expired':
return ['calendar', 'Access ended', 'Your devices can’t connect until it’s extended.'];
case 'hours':
return ['clock', 'Outside your hours', `Open ${hoursText(p.hours)}.`];
default:
return ['pause', 'Access paused', 'Your devices can’t connect until it’s resumed.'];
}
}
/** The page's notice, or null when nothing stands in the way. */
export function pageNotice(p: Person): HTMLElement | null {
if (p.state !== 'active') return notice(p.state === 'quota' || p.state === 'expired' ? 'bad' : 'warn', ...stateNotice(p));
const left = daysLeft(p.expires, today());
return endsSoon(p, left) ? notice('warn', 'calendar', `Access ${endsIn(left as number)}`, `On ${date(p.expires)}.`) : null;
}
File diff suppressed because it is too large. Load diff
+13 -34
View File
@@ -1,5 +1,5 @@
// Setting up a device: which app, where it comes from, and whether the page
// is open on the device being set up. Pure: the sheet in main.ts draws it.
// is open on the device being set up. Pure: the set-up sheet (flows/) draws it.
import type { Kind } from '../shared/types';
@@ -33,45 +33,21 @@ export function sameDevice(kind: Kind, platform: Platform): boolean {
return true;
}
/**
* The systems a kind may run, when that is the person's call: a computer's
* desktop systems, any system for an "other" device (a TV box runs Android, a
* NAS Linux). A phone's or a tablet's is read from the browser.
*/
export const osGroup = (kind: Kind): Platform[] =>
kind === 'computer' ? ['windows', 'mac', 'linux'] : kind === 'other' ? ['ios', 'android', 'windows', 'mac', 'linux'] : [];
export interface AppChoice {
id: AppId;
name: string;
/** The version this server needs, as "4.8.12" or ""; "current" when only the newest will do. */
need: string;
sub: string;
}
/** The apps that connect to a server with this disguise, the recommended one first. */
/** The apps that connect to a server with this disguise, the recommended one first; any WireGuard app without one. */
export function appsFor(preset: Preset): AppChoice[] {
const need = {
off: { vpn: '', awg: '' },
balanced: { vpn: '4.8.12', awg: '2.0' },
max: { vpn: 'current', awg: '3.1' },
legacy: { vpn: '', awg: '' },
}[preset];
const out: AppChoice[] = [
{ id: 'vpn', name: APP_NAME.vpn, need: need.vpn, sub: 'Connects from a link, no files' },
{ id: 'awg', name: APP_NAME.awg, need: need.awg, sub: 'The light client: a file or a QR code' },
{ id: 'vpn', name: APP_NAME.vpn },
{ id: 'awg', name: APP_NAME.awg },
];
if (preset === 'off') out.push({ id: 'wg', name: APP_NAME.wg, need: '', sub: 'Any WireGuard app: this server has no disguise' });
if (preset === 'off') out.push({ id: 'wg', name: APP_NAME.wg });
return out;
}
/** "This server needs AmneziaVPN 4.8.12 or newer. …", or "" when any version will do. */
export function updateLine(app: AppChoice): string {
if (!app.need) return '';
const what = app.need === 'current' ? `the current version of ${app.name}` : `${app.name} ${app.need} or newer`;
return `This server needs ${what}. Installed a while ago? Update it in the store.`;
}
export type Mark = 'appstore' | 'googleplay' | 'windows' | 'apple' | 'linux' | 'openwrt' | 'github' | 'site';
export interface Store {
@@ -157,7 +133,8 @@ export const routerStore = (app: AppId): Store =>
main: 'wireguard-tools',
mark: 'openwrt',
}
: { href: 'https://openwrt.org/packages/start', top: 'OpenWrt packages', main: 'amneziawg-tools + kmod', mark: 'openwrt' };
: // One line on a phone: the kernel module goes on top.
{ href: 'https://openwrt.org/packages/start', top: 'OpenWrt packages + kmod', main: 'amneziawg-tools', mark: 'openwrt' };
/**
* Does AmneziaVPN here open a `vpn://` link? Only the Android app registers the
@@ -234,13 +211,15 @@ export function setupFromHash(hash: string): string | null {
return /^#setup=(d_[0-9a-f]{8})$/.exec(hash)?.[1] ?? null;
}
/** The personal link that opens straight on "Add a device": for the device itself to add, from its own browser. */
export const addLink = (page: string): string => `${page}#add`;
/** Does the link ask to add a device (`#add`)? */
export const wantsAdd = (hash: string): boolean => hash === '#add';
/**
* "the phone", "the computer": the device being set up, in a sentence. The
* sheet's title already names it; the lines under it do not repeat the name.
*/
export const deviceNoun = (kind: Kind): string =>
({ phone: 'phone', tablet: 'tablet', computer: 'computer', router: 'router', other: 'device' })[kind];
/** "This iPhone", "This Mac": the pill for the device in hand. */
export const hereLabel = (platform: Platform): string =>
({ ios: 'This iPhone', android: 'This phone', windows: 'This PC', mac: 'This Mac', linux: 'This PC', unknown: 'This device' })[platform];
+74
View File
@@ -0,0 +1,74 @@
// The page's state: the router's last answer, its clock and calendar, where the
// page is open and what the server runs. Everything that draws reads it from
// here. It also holds the one hook back to the page (`repaint`), so a flow can
// redraw the page without knowing how the page is built (main.ts sets it).
import type { Kind, Person } from '../shared/types';
import { isoDay } from '../shared/format';
import { platformOf, type Platform, type Preset } from './setup';
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 };
/** The device this page was opened from (through the tunnel), if any. */
here?: string | null;
can_add: boolean;
/** The admin stopped the person (paused, access ended): the page only shows. */
locked?: boolean;
/** Over plain HTTP: the same link over HTTPS, where the connection settings are. */
https_url?: string | null;
kinds: Kind[];
version: string;
/** The router's day (YYYY-MM-DD) when it sends one; the browser's otherwise. */
today?: string;
/** The router's clock (epoch seconds): relative times are measured against it, not the phone's. */
now?: number;
/** The router's UTC offset in minutes: the admin sets hours in its time, the page shows the visitor's. */
tz_offset?: number;
}
let current: State | null = null;
export const state = (): State | null => current;
export function setState(st: State | null) {
current = st;
}
const app = document.getElementById('app')!;
/** The page's path: the personal link. Its last part is the code (no sessions). */
export const base = app.dataset.base ?? '';
export const code = /^\/[a-z]{6}-[a-z]{6}-[a-z]{6}$/.test(base) ? base.slice(1) : '';
/** This page's own address, without the fragment: what a link to another device carries. */
export const pageUrl = () => location.origin + location.pathname;
/** Today on the router, for days left and chart labels. */
export const today = () => current?.today ?? isoDay(new Date());
/** Now on the router (seconds), for "last connected 3 min ago". */
export const now = () => current?.now ?? Date.now() / 1000;
/** The platform this page is open on (iPad on Safari says Mac; touch points tell). */
export const platform = (): Platform => platformOf(navigator.userAgent, navigator.maxTouchPoints);
/** The server's disguise is off: plain WireGuard, so any WireGuard app connects. */
export const plainWg = () => current?.server.awg_disguise === false;
/** The server's disguise generation, for which apps and versions connect. */
export const preset = (): Preset => current?.server.preset ?? (plainWg() ? 'off' : 'max');
/** The secure twin when this page is plain HTTP, else null. */
export const httpsTwin = () => current?.https_url || null;
/** The place this page belongs to: the server's name, "Dawnline" where there is none to name. */
export const placeName = () => current?.server.name || 'Dawnline';
export interface RepaintOpts {
/** A card that is new: it pops in. */
pop?: string;
/** A card that just connected: a green ring fades on it. */
flash?: string;
}
let painter: (o: RepaintOpts) => void = () => undefined;
/** main.ts: how to draw the page again. */
export function onRepaint(fn: (o: RepaintOpts) => void) {
painter = fn;
}
/** Draw the page again from the current state (a flow changed something). */
export const repaint = (o: RepaintOpts = {}) => painter(o);
+345
View File
@@ -0,0 +1,345 @@
/* "Your access": what it reaches as two tiles and the names at home; the data as a ring in the head
and the month day by day inside; until when as the days left over a calendar of the weeks, and
the hours as a bar of the day. */
.reach2 {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 8px;
}
.reach-tile {
position: relative;
display: flex;
flex-direction: column;
gap: 1px;
padding: 12px 12px 12px 14px;
border-radius: 16px;
background: var(--field);
min-width: 0;
}
.reach-tile .rt-ic {
width: 28px;
height: 28px;
margin-bottom: 10px;
}
.reach-tile b {
font-size: 14px;
line-height: 20px;
font-weight: 500;
letter-spacing: -0.015em;
}
.reach-tile .rt-sub {
font-size: 12px;
line-height: 16px;
color: var(--text-2);
}
.reach-tile .rt-mark {
position: absolute;
top: 12px;
right: 12px;
width: 20px;
height: 20px;
border-radius: 50%;
display: grid;
place-items: center;
background: var(--ok-soft);
color: var(--ok);
}
.reach-tile .rt-mark .i {
width: 12px;
height: 12px;
stroke-width: 2.4;
}
.reach-tile.off b {
color: var(--text-2);
}
.reach-tile.off .rt-sub {
color: var(--text-3);
}
.reach-tile.off .rt-ic {
opacity: 0.45;
}
.reach-tile.off .rt-mark {
background: var(--knob);
color: var(--text-3);
}
.lbl-s {
font-size: 12px;
font-weight: 500;
color: var(--text-2);
}
.names {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.namechip {
display: inline-flex;
align-items: center;
gap: 8px;
height: 32px;
padding: 0 10px 0 12px;
border-radius: 10px;
background: var(--field);
font-family: var(--mono);
font-size: 13px;
letter-spacing: 0;
transition:
background-color 150ms,
transform 150ms var(--ease-out);
}
.namechip:hover {
background: var(--knob);
}
.namechip:active {
transform: scale(0.96);
}
.namechip .faint {
color: var(--text-3);
}
.namechip .i {
width: 14px;
height: 14px;
color: var(--text-2);
}
.ring {
width: 16px;
height: 16px;
transform: rotate(-90deg);
}
.ring .trk {
stroke: var(--bar);
}
.ring .arc {
stroke: var(--accent);
}
.ring .arc.warn {
stroke: var(--warn);
}
.ring .arc.bad {
stroke: var(--bad);
}
.month {
display: flex;
flex-direction: column;
gap: 8px;
}
.mbars {
display: flex;
align-items: flex-end;
gap: 3px;
height: 64px;
}
.mbars i {
flex: 1;
border-radius: 2.5px;
background: var(--bar);
min-height: 3px;
transition: background-color 120ms;
}
.mbars i.future {
background: color-mix(in srgb, var(--bar) 45%, transparent);
}
.mbars i.today {
background: var(--accent);
}
.mbars i:not(.future):hover {
background: var(--text-2);
}
.month-axis {
position: relative;
display: flex;
justify-content: space-between;
font-size: 11px;
color: var(--text-3);
font-weight: 500;
}
.month-axis .td {
position: absolute;
transform: translateX(-50%);
color: var(--accent);
}
.month-axis .hide {
visibility: hidden;
}
.month-read {
display: flex;
justify-content: space-between;
align-items: baseline;
margin-top: 10px;
font-size: 13px;
color: var(--text-2);
}
.month-read b {
color: var(--text);
font-weight: 500;
font-size: 15px;
letter-spacing: -0.02em;
}
.meter {
height: 6px;
border-radius: 3px;
background: var(--bar);
overflow: hidden;
}
.meter > i {
display: block;
height: 100%;
border-radius: 3px;
background: var(--accent);
}
.meter > i.warn {
background: var(--warn);
}
.meter > i.bad {
background: var(--bad);
}
.until {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
padding: 14px 16px;
border-radius: 16px;
background: var(--field);
}
.until-num {
display: flex;
flex-direction: column;
min-width: 0;
}
.until-num b {
font-size: 36px;
line-height: 40px;
font-weight: 600;
letter-spacing: -0.045em;
}
.until-num span {
font-size: 13px;
line-height: 18px;
color: var(--text-2);
}
.until-num .until-sub {
margin-top: 8px;
font-size: 12px;
color: var(--text-3);
}
.until.soon .until-num b {
color: var(--warn);
}
.cal {
display: flex;
flex-direction: column;
gap: 6px;
flex: none;
}
.cal-h,
.cal-g {
display: grid;
grid-template-columns: repeat(7, 10px);
gap: 5px;
}
.cal-h span {
font-size: 9px;
line-height: 10px;
font-weight: 600;
color: var(--text-3);
text-align: center;
}
.cal-g i {
width: 10px;
height: 10px;
border-radius: 3px;
background: color-mix(in srgb, var(--text) 16%, transparent);
}
.cal-g i.past {
background: color-mix(in srgb, var(--text) 5%, transparent);
}
.cal-g i.today {
background: var(--accent);
}
.cal-g i.end {
background: transparent;
box-shadow: inset 0 0 0 1.5px var(--accent);
}
.cal-g i.after {
background: transparent;
}
.until.soon .cal-g i.today {
background: var(--warn);
}
.until.soon .cal-g i.end {
box-shadow: inset 0 0 0 1.5px var(--warn);
}
.acc-row.open .cal-g i {
animation: cal-in 360ms var(--ease-out) backwards;
animation-delay: calc(var(--i) * 7ms);
}
@keyframes cal-in {
from {
opacity: 0;
transform: scale(0.4);
}
}
.hours {
display: flex;
flex-direction: column;
gap: 8px;
padding: 14px 16px;
border-radius: 16px;
background: var(--field);
}
.hours-top {
display: flex;
justify-content: space-between;
align-items: baseline;
font-size: 13px;
color: var(--text-2);
}
.hours-top b {
color: var(--text);
font-weight: 500;
font-size: 15px;
letter-spacing: -0.02em;
}
.hours-bar {
position: relative;
height: 8px;
border-radius: 4px;
background: color-mix(in srgb, var(--text) 8%, transparent);
}
.hours-bar i {
position: absolute;
top: 0;
bottom: 0;
border-radius: 4px;
background: color-mix(in srgb, var(--ok) 70%, transparent);
}
.hours-now {
position: absolute;
top: -4px;
width: 2px;
height: 16px;
margin-left: -1px;
border-radius: 1px;
background: var(--text);
box-shadow: 0 0 0 2px var(--field);
}
.hours-now.out {
background: var(--warn);
}
.hours-axis {
display: flex;
justify-content: space-between;
font-size: 10px;
color: var(--text-3);
font-weight: 500;
}
@media (prefers-reduced-motion: reduce) {
.acc-row.open .cal-g i {
animation: none;
}
}
+136
View File
@@ -0,0 +1,136 @@
/* The bouncy accordion: rows touch while closed and share their rounded ends; an open row lifts
out with 10px gaps and its own corners (ui/accordion.ts animates between the two shapes). Inside
the sheet ("inset") the rows sit one step lighter than the sheet. */
.acc {
display: flex;
flex-direction: column;
}
.acc-row {
background: var(--raised);
overflow: hidden;
border-radius: 0;
padding: 0 8px;
transition: background-color 150ms;
}
.acc-row.rt {
border-top-left-radius: var(--r-row);
border-top-right-radius: var(--r-row);
}
.acc-row.rb {
border-bottom-left-radius: var(--r-row);
border-bottom-right-radius: var(--r-row);
}
.acc-row.open {
margin-block: 10px;
}
.acc-row.open:first-child {
margin-top: 0;
}
.acc-row.open:last-child {
margin-bottom: 0;
}
.acc-row:not(.open):not(.still):hover {
background: color-mix(in srgb, var(--raised), var(--knob) 40%);
}
.acc-head {
width: 100%;
display: flex;
align-items: center;
gap: 10px;
height: 52px;
padding: 0 6px 0 8px;
text-align: left;
}
.acc-row.still .acc-head {
cursor: default;
padding-right: 10px;
}
.acc-head .gi {
width: 22px;
height: 22px;
}
.acc-title {
flex: 1;
min-width: 0;
font-size: 15px;
font-weight: 500;
letter-spacing: -0.02em;
display: flex;
align-items: center;
gap: 8px;
}
.acc-title .t {
min-width: 0;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
/* A row whose body shows its numbers drops them from its head while open. */
.acc-val {
display: flex;
align-items: center;
gap: 8px;
color: var(--text-2);
font-size: 14px;
white-space: nowrap;
transition:
opacity 200ms var(--ease-out),
filter 200ms var(--ease-out),
transform 260ms var(--ease-out);
}
.acc-val > span {
display: inline-flex;
align-items: center;
gap: 8px;
}
.acc-row.open .acc-val.hide-open {
opacity: 0;
filter: blur(4px);
transform: translateX(8px);
pointer-events: none;
}
.acc-chev {
width: 16px;
height: 16px;
color: var(--text-2);
transform: rotate(90deg);
transition: transform var(--spring-soft-dur, 470ms) var(--spring-soft, ease);
}
.acc-row.open .acc-chev {
transform: rotate(-90deg);
}
.acc-body {
display: none;
padding: 0 8px 16px 40px;
}
.acc-row.open .acc-body,
.acc-row.closing .acc-body {
display: flex;
flex-direction: column;
gap: 12px;
}
.acc .desc {
margin: 0;
font-size: 14px;
line-height: 20px;
opacity: 0.6;
}
.acc.inset .acc-row {
background: var(--field);
}
.acc.inset .acc-row:not(.open):not(.still):hover {
background: color-mix(in srgb, var(--field), var(--knob) 50%);
}
.acc.inset .acc-body {
padding-left: 8px;
}
.acc.inset .seg {
background: color-mix(in srgb, var(--knob) 65%, var(--field));
}
@media (prefers-reduced-motion: reduce) {
.acc-chev {
transition: none;
}
}
+151
View File
@@ -0,0 +1,151 @@
/* The ground every part stands on: the reset, the type, focus and selection, the small utilities,
the icons (line icons and the glass ones). */
* {
box-sizing: border-box;
}
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;
}
body {
margin: 0;
background: var(--bg);
color: var(--text);
font: 400 15px/22px var(--font);
letter-spacing: -0.011em;
-webkit-font-smoothing: antialiased;
min-height: 100vh;
min-height: 100dvh;
/* An app, not a document: the arrow over text. Controls set the hand; what is typed or copied by
hand (fields, the link, the configuration) keeps the I-beam. */
cursor: default;
}
body.locked {
overflow: hidden;
}
input,
textarea,
.linkrow .mono,
.conf {
cursor: text;
}
::selection {
background: var(--sel-bg);
color: var(--sel-fg);
}
button {
font: inherit;
color: inherit;
letter-spacing: inherit;
background: none;
border: 0;
padding: 0;
margin: 0;
cursor: pointer;
-webkit-tap-highlight-color: transparent;
}
button:disabled {
cursor: default;
}
a {
color: inherit;
text-decoration: none;
}
:focus {
outline: none;
}
:focus-visible {
outline: 2px solid color-mix(in srgb, var(--accent) 65%, transparent);
outline-offset: 2px;
}
[hidden] {
display: none !important;
}
.offscreen {
position: fixed;
left: -9999px;
top: 0;
opacity: 0;
}
.mono {
font-family: var(--mono);
letter-spacing: 0;
}
.num {
font-variant-numeric: tabular-nums;
}
.ok-t {
color: var(--ok);
}
.warn-t {
color: var(--warn);
}
.bad-t {
color: var(--bad);
}
.here-t {
color: var(--accent);
}
/* line icons */
.i {
width: 18px;
height: 18px;
flex: none;
}
/* glass icons: the colours come from here (the CSP drops style attributes) */
.gi {
width: 24px;
height: 24px;
flex: none;
overflow: visible;
--ta: var(--t-grey-a);
--tb: var(--t-grey-b);
}
.gi.t-blue {
--ta: var(--t-blue-a);
--tb: var(--t-blue-b);
}
.gi.t-green {
--ta: var(--t-green-a);
--tb: var(--t-green-b);
}
.gi.t-red {
--ta: var(--t-red-a);
--tb: var(--t-red-b);
}
.gi.t-orange {
--ta: var(--t-orange-a);
--tb: var(--t-orange-b);
}
.gi .ta {
stop-color: var(--ta);
}
.gi .tb {
stop-color: var(--tb);
}
.gi .fa {
stop-color: var(--gi-a);
}
.gi .fb {
stop-color: var(--gi-b);
}
.gi .fc {
stop-color: var(--ta);
stop-opacity: 0.28;
}
.gi .ge {
stroke: var(--gi-edge);
}
.gi .gr {
stroke: var(--gi-rim);
}
.gi .gd {
stroke: var(--gi-detail);
}
.gi .gdf {
color: var(--gi-detail);
}
+660
View File
@@ -0,0 +1,660 @@
/* 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. */
.knob {
width: 32px;
height: 32px;
border-radius: 50%;
background: var(--knob);
color: var(--text);
display: grid;
place-items: center;
flex: none;
transition:
transform 150ms var(--ease-out),
background-color 150ms;
}
.knob:hover {
background: color-mix(in srgb, var(--knob), var(--text) 6%);
}
.knob:active {
transform: scale(0.8);
}
.knob .i {
width: 16px;
height: 16px;
}
.knob.back .i {
transform: rotate(180deg);
}
.knob[aria-expanded='true'] {
background: color-mix(in srgb, var(--knob), var(--text) 10%);
}
.btn {
height: 48px;
border-radius: 999px;
display: inline-flex;
align-items: center;
justify-content: center;
gap: 8px;
padding: 0 20px;
font-size: 16px;
font-weight: 500;
letter-spacing: -0.015em;
user-select: none;
-webkit-user-select: none;
transition:
transform 200ms var(--ease-out),
background-color 200ms var(--ease-out),
color 200ms var(--ease-out);
}
.btn:active {
transform: scale(0.95);
}
.btn.block {
width: 100%;
}
.btn.sm {
height: 40px;
font-size: 15px;
padding: 0 16px;
}
.btn.accent {
background: var(--accent);
color: var(--accent-ink);
font-weight: 600;
}
.btn.accent:hover {
background: color-mix(in srgb, var(--accent) 82%, transparent);
}
/* The quiet accent: a card's Connect, tinted rather than filled. */
.btn.tint {
background: var(--accent-soft);
color: var(--accent);
font-weight: 600;
}
.btn.tint:hover {
background: color-mix(in srgb, var(--accent) 20%, transparent);
}
.btn.tint:active {
background: color-mix(in srgb, var(--accent) 24%, transparent);
}
.btn.soft {
background: var(--knob);
color: var(--text);
}
.btn.soft:hover {
background: color-mix(in srgb, var(--knob), var(--text) 6%);
}
.btn.red {
background: var(--bad);
color: #fff;
font-weight: 600;
}
/* 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,
softer in between; a second breathes in the middle. */
.busy {
position: relative;
}
.orb {
position: absolute;
inset: 0;
margin: auto;
width: 28px;
height: 28px;
overflow: hidden;
contain: strict;
pointer-events: none;
}
.orb i {
position: absolute;
left: 50%;
top: 50%;
width: 7px;
height: 7px;
margin: -3.5px 0 0 -3.5px;
border-radius: 50%;
background: currentColor;
animation: orb-converge 1.8s linear infinite both;
}
.orb i:nth-child(2) {
animation: orb-breathe 1.8s ease-in-out infinite both;
}
/* Top, bottom right, bottom left: a beat at each corner, then away (ease-in) and in (ease-out). */
@keyframes orb-converge {
0% {
transform: translate(0px, -5px) scale(1);
filter: blur(0);
animation-timing-function: linear;
}
10% {
transform: translate(0px, -5px) scale(1);
filter: blur(0);
animation-timing-function: cubic-bezier(0.55, 0, 1, 0.45);
}
22% {
transform: translate(2.15px, -1.25px) scale(0.72);
filter: blur(0.8px);
animation-timing-function: cubic-bezier(0.33, 1, 0.68, 1);
}
33% {
transform: translate(4.3px, 2.5px) scale(1);
filter: blur(0);
animation-timing-function: linear;
}
43% {
transform: translate(4.3px, 2.5px) scale(1);
filter: blur(0);
animation-timing-function: cubic-bezier(0.55, 0, 1, 0.45);
}
55% {
transform: translate(0px, 2.5px) scale(0.72);
filter: blur(0.8px);
animation-timing-function: cubic-bezier(0.33, 1, 0.68, 1);
}
66% {
transform: translate(-4.3px, 2.5px) scale(1);
filter: blur(0);
animation-timing-function: linear;
}
77% {
transform: translate(-4.3px, 2.5px) scale(1);
filter: blur(0);
animation-timing-function: cubic-bezier(0.55, 0, 1, 0.45);
}
88% {
transform: translate(-2.15px, -1.25px) scale(0.72);
filter: blur(0.8px);
animation-timing-function: cubic-bezier(0.33, 1, 0.68, 1);
}
100% {
transform: translate(0px, -5px) scale(1);
filter: blur(0);
}
}
@keyframes orb-breathe {
0%,
100% {
opacity: 0.16;
filter: blur(2.4px);
transform: scale(1.2);
}
50% {
opacity: 0.32;
filter: blur(1.6px);
transform: scale(0.98);
}
}
.field {
height: 48px;
border-radius: var(--r-field);
background: var(--field);
display: flex;
align-items: center;
gap: 12px;
padding: 0 4px 0 16px;
overflow: hidden;
transition: box-shadow 200ms var(--ease-out);
}
.field:focus-within {
box-shadow: inset 0 0 0 1.5px color-mix(in srgb, var(--text) 16%, transparent);
}
.field input {
flex: 1;
min-width: 0;
border: 0;
outline: 0;
background: transparent;
padding: 0;
font: 500 16px/24px var(--font);
color: var(--text);
letter-spacing: -0.012em;
}
.field input::placeholder {
color: var(--text-3);
}
.go {
width: 48px;
height: 40px;
border-radius: 12px;
background: var(--knob);
color: var(--text-3);
display: grid;
place-items: center;
flex: none;
transition:
background-color 200ms var(--ease-out),
color 200ms var(--ease-out),
transform 200ms var(--ease-out);
}
.go .i {
width: 20px;
height: 20px;
}
.go.ready {
background: var(--accent);
color: var(--accent-ink);
}
.go.ready:active {
transform: scale(0.9);
}
.go:not(.ready) {
cursor: not-allowed;
}
/* The icon picker (skiper21's tabs): icons only, the picked one widens and shows its name. */
.seg {
position: relative;
display: flex;
align-items: center;
height: 48px;
padding: 0 4px;
border-radius: var(--r-field);
background: var(--field);
}
.seg-pill {
position: absolute;
left: 0;
top: 4px;
height: 40px;
border-radius: 12px;
background: var(--seg);
box-shadow: var(--seg-shadow);
pointer-events: none;
}
.seg-b {
position: relative;
z-index: 1;
height: 40px;
font-size: 16px;
font-weight: 500;
color: var(--text-3);
white-space: nowrap;
transition: color 200ms var(--ease-out);
}
.seg-b.on {
color: var(--text);
}
.seg-b:not(.on):hover {
color: var(--text-2);
}
.appseg .seg-b {
flex: 0 0 56px;
display: flex;
align-items: center;
justify-content: center;
justify-content: safe center;
gap: 8px;
padding: 0 18px;
overflow: hidden;
}
.appseg .seg-b.on {
flex: 1 1 56px;
}
.appseg .seg-b .i {
width: 20px;
height: 20px;
}
.appseg .seg-l {
max-width: 0;
opacity: 0;
margin-left: -8px;
overflow: hidden;
white-space: nowrap;
}
.appseg .seg-b.on .seg-l {
max-width: 180px;
opacity: 1;
margin-left: 0;
}
/* Three apps on a phone: the icons take less room, so the picked one's name fits whole. */
.appseg {
container-type: inline-size;
}
@container (max-width: 300px) {
.appseg .seg-b {
flex-basis: 44px;
padding: 0 12px;
}
}
/* What a new device is: four tiles, the picked one ringed in place; the label under its tile. */
.kinds {
display: grid;
grid-template-columns: repeat(var(--n, 4), minmax(0, 1fr));
gap: 8px;
position: relative;
container-type: inline-size;
}
.kind {
position: relative;
z-index: 1;
display: flex;
flex-direction: column;
align-items: center;
gap: 8px;
min-width: 0;
color: var(--text-3);
font-size: 12px;
line-height: 16px;
font-weight: 500;
transition: color 200ms var(--ease-out);
}
.kind-tile {
width: 100%;
height: 56px;
border-radius: 14px;
background: var(--field);
display: grid;
place-items: center;
transition:
background-color 200ms var(--ease-out),
transform 200ms var(--ease-out),
box-shadow 220ms var(--ease-out);
}
.kind.on .kind-tile {
box-shadow: inset 0 0 0 1.5px var(--accent);
}
.kind-lbl {
white-space: nowrap;
}
.kind:hover .kind-tile,
.kind:focus-visible .kind-tile {
background: var(--knob);
}
.kind:active .kind-tile {
transform: scale(0.94);
}
.kind:focus-visible {
outline: none;
}
.kind:focus-visible .kind-lbl,
.kind.on {
color: var(--text);
}
.kind .gi {
width: 26px;
height: 26px;
filter: grayscale(1);
opacity: 0.55;
transition:
filter 260ms var(--ease-out),
opacity 260ms var(--ease-out);
}
.kind.on .gi {
filter: none;
opacity: 1;
}
@container (max-width: 330px) {
.kind-tile {
height: 50px;
}
.kind {
font-size: 11.5px;
}
}
.or {
display: flex;
align-items: center;
gap: 12px;
margin: 22px 0;
color: var(--text-3);
font-size: 12px;
font-weight: 500;
letter-spacing: 0.06em;
}
.or::before,
.or::after {
content: '';
flex: 1;
height: 1px;
background: var(--line);
}
/* A store (or an action) as a tile: its mark, two lines, a chevron or the open mark. */
.badge {
width: 100%;
text-align: left;
display: flex;
align-items: center;
gap: 12px;
height: 60px;
padding: 0 14px 0 12px;
border-radius: 18px;
background: var(--field);
transition:
background-color 200ms,
transform 200ms var(--ease-out);
}
.badge:hover {
background: var(--knob);
}
.badge:active {
transform: scale(0.98);
}
.badge .b-ic {
width: 36px;
height: 36px;
border-radius: 10px;
background: var(--text);
color: var(--raised);
display: grid;
place-items: center;
flex: none;
}
.badge .b-ic .i {
width: 20px;
height: 20px;
}
.badge .b-t {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
}
.badge .b-top {
font-size: 12px;
line-height: 16px;
color: var(--text-2);
}
.badge .b-main {
font-size: 15px;
line-height: 20px;
font-weight: 500;
}
.badge > .i {
color: var(--text-3);
width: 16px;
height: 16px;
}
/* Step 2 is neutral like the other tiles; only its mark keeps the accent. */
.badge.primary .b-ic {
background: var(--accent-soft);
color: var(--accent);
}
.badges2 {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 8px;
}
.badges2 .badge {
padding: 0 10px;
gap: 10px;
}
.badges2 .badge > .i {
display: none;
}
.badges2 .b-ic {
width: 32px;
height: 32px;
}
.hint {
margin: 0;
font-size: 13px;
line-height: 18px;
color: var(--text-2);
}
.hint a,
.hint button {
color: var(--accent);
font-weight: 500;
}
.howto {
margin: 0;
padding: 0;
list-style: none;
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 6px;
font-size: 13px;
color: var(--text-2);
}
.howto li {
display: inline-flex;
align-items: center;
gap: 6px;
}
.howto li + li::before {
content: '›';
color: var(--text-3);
}
.howto b {
color: var(--text);
font-weight: 500;
}
.linkrow {
display: flex;
align-items: center;
gap: 8px;
height: 44px;
padding: 0 4px 0 14px;
border-radius: 14px;
background: color-mix(in srgb, var(--knob) 72%, var(--field));
}
.view > .linkrow {
background: var(--field);
}
.linkrow .mono {
flex: 1;
min-width: 0;
font-size: 13px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
user-select: all;
}
.linkrow .knob {
width: 36px;
height: 36px;
border-radius: 10px;
background: transparent;
}
.linkrow .knob:hover {
background: var(--knob);
}
/* QR codes: the night look on a dark theme, dark on white on a light one; a dense code fills its row. */
.qrbox {
position: relative;
width: 148px;
height: 148px;
flex: none;
border-radius: 18px;
overflow: hidden;
background: var(--qr-bg);
}
.qrbox.light {
box-shadow: inset 0 0 0 1px var(--line);
}
.qrbox.big {
width: 208px;
height: 208px;
border-radius: 24px;
align-self: center;
}
.qrbox.big + .linkrow {
margin-top: 16px;
}
.qrbox.dense {
width: 100%;
max-width: none;
height: auto;
aspect-ratio: 1;
align-self: stretch;
border-radius: 22px;
}
.qrbox svg {
display: block;
width: 100%;
height: 100%;
}
/* A code swapping for another: the old one lies over the new one while it fades. */
.qrbox > svg.old {
position: absolute;
inset: 0;
}
.coderow {
display: flex;
gap: 14px;
align-items: flex-start;
}
.coderow.stacked {
flex-direction: column;
align-items: stretch;
}
.coderow .side {
position: relative;
display: flex;
flex-direction: column;
gap: 8px;
min-width: 0;
font-size: 14px;
line-height: 20px;
color: var(--text-2);
}
.coderow .side b {
color: var(--text);
font-weight: 500;
}
.side .words {
display: flex;
flex-direction: column;
gap: 8px;
}
.side .words.old {
position: absolute;
left: 0;
right: 0;
top: 0;
pointer-events: none;
}
.side .arr {
color: var(--text-2);
font-weight: 400;
margin: 0 6px;
}
@media (max-width: 380px) {
.coderow {
flex-direction: column;
}
}
@media (prefers-reduced-motion: reduce) {
/* The orb's own still frame: the front circle sharp, the other two a soft halo behind it. */
.orb i {
animation: none;
opacity: 0.3;
filter: blur(1.4px);
}
.orb i:first-child {
opacity: 1;
filter: none;
}
}
+201
View File
@@ -0,0 +1,201 @@
/* "Your devices": the grid, a card per device (its glass icon, name and one-line status, ⋯; the week
as a number and bars, the Update pill, or Connect), the card that adds one, the first device. */
.dgrid {
display: grid;
gap: 10px;
grid-template-columns: minmax(0, 1fr);
}
@media (min-width: 560px) {
.dgrid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
.dev {
background: var(--raised);
border-radius: var(--r-card);
padding: 8px;
display: flex;
flex-direction: column;
gap: 8px;
min-width: 0;
}
.dev.is-here {
box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--accent) 32%, transparent);
}
.dev.off {
opacity: 0.5;
}
.dev-top {
display: flex;
align-items: center;
gap: 12px;
padding: 8px 6px 6px 10px;
}
.dev-top .gi {
width: 32px;
height: 32px;
}
.dev-id {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
}
.dev-name {
font-size: 16px;
line-height: 22px;
font-weight: 500;
letter-spacing: -0.02em;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
/* Every card the same height: a one-line status. */
.dev-stat {
font-size: 13px;
line-height: 18px;
color: var(--text-2);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.dev-stat.ok-t {
color: var(--ok);
}
.dev-stat.warn-t {
color: var(--warn);
}
.dev-stat.here-t {
color: var(--accent);
}
.dev-use {
margin-top: auto;
background: var(--field);
border-radius: var(--r-row);
padding: 12px 14px 12px 16px;
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 12px;
min-height: 66px;
}
.use-txt {
display: flex;
flex-direction: column;
min-width: 0;
}
.use-lbl {
font-size: 13px;
line-height: 18px;
color: var(--text-2);
white-space: nowrap;
}
.use-val {
font-size: 17px;
line-height: 24px;
font-weight: 500;
letter-spacing: -0.02em;
}
.spark {
display: flex;
align-items: flex-end;
gap: 4px;
height: 34px;
}
.spark i {
width: 6px;
border-radius: 3px;
background: var(--bar);
transition: background-color 150ms;
}
.spark i.today {
background: var(--accent);
}
.spark i:hover {
background: var(--text-2);
}
.spark i.today:hover {
background: color-mix(in srgb, var(--accent) 75%, var(--text));
}
.dev .setup-btn {
margin-top: auto;
}
.upd-pill {
display: inline-flex;
align-items: center;
align-self: center;
gap: 6px;
height: 32px;
padding: 0 12px 0 10px;
border-radius: 999px;
flex: none;
background: color-mix(in srgb, var(--warn) 14%, transparent);
color: var(--warn);
font-size: 13px;
font-weight: 600;
transition:
background-color 150ms,
transform 150ms var(--ease-out);
}
.upd-pill:hover {
background: color-mix(in srgb, var(--warn) 22%, transparent);
}
.upd-pill:active {
transform: scale(0.94);
}
.upd-pill .i {
width: 14px;
height: 14px;
}
.dev.add {
align-items: center;
justify-content: center;
min-height: 144px;
gap: 10px;
color: var(--text-2);
font-weight: 500;
transition:
background-color 200ms var(--ease-out),
transform 200ms var(--ease-out);
}
.dev.add:hover {
background: color-mix(in srgb, var(--raised), var(--knob) 45%);
}
.dev.add:active {
transform: scale(0.98);
}
.dev.add .gi {
width: 36px;
height: 36px;
}
/* Nothing yet: one card across the grid, what comes and the button. */
.dev.first {
grid-column: 1 / -1;
align-items: center;
text-align: center;
padding: 28px 24px 24px;
gap: 6px;
}
.dev.first .gi {
width: 44px;
height: 44px;
margin-bottom: 8px;
}
.dev.first b {
font-size: 18px;
line-height: 24px;
font-weight: 500;
letter-spacing: -0.02em;
}
.dev.first p {
margin: 0 0 14px;
color: var(--text-2);
font-size: 14px;
line-height: 20px;
max-width: 34ch;
text-wrap: balance;
}
.dev.first .btn {
max-width: 320px;
}
+13
View File
@@ -0,0 +1,13 @@
/* Dawnline personal portal: the stylesheet, one file per part, joined into one portal.css by the
build (tsup.config.ts). Order matters only where a later part refines an earlier one. */
@import './tokens.css';
@import './base.css';
@import './controls.css';
@import './morph.css';
@import './accordion.css';
@import './page.css';
@import './devices.css';
@import './access.css';
@import './sheet.css';
@import './setup.css';
@import './menu-toast.css';
+109
View File
@@ -0,0 +1,109 @@
/* The ⋯ menu (a highlight that glides after the pointer, tinted for Reconnect and Remove) and the
toast slot at the bottom. */
.menu {
position: fixed;
z-index: 60;
min-width: 224px;
padding: 6px;
border-radius: 20px;
background: var(--field);
box-shadow:
var(--pop-shadow),
inset 0 0 0 1px var(--line);
}
.menu-hl {
position: absolute;
left: 6px;
right: 6px;
top: 6px;
height: 40px;
border-radius: 14px;
background: var(--knob);
opacity: 0;
transition: opacity 150ms var(--ease-out);
pointer-events: none;
}
.menu-hl.moving {
transition:
opacity 150ms var(--ease-out),
transform var(--spring-quick-dur, 300ms) var(--spring-quick, ease-out),
background-color 150ms;
}
.menu-hl.bad {
background: var(--bad-soft);
}
.menu-hl.warn {
background: color-mix(in srgb, var(--warn) 13%, transparent);
}
.mi {
position: relative;
z-index: 1;
display: flex;
align-items: center;
gap: 12px;
width: 100%;
height: 40px;
padding: 0 12px;
border-radius: 14px;
font-size: 14px;
font-weight: 500;
text-align: left;
}
.mi .i {
width: 16px;
height: 16px;
color: var(--text-2);
}
.mi.warn,
.mi.warn .i {
color: var(--warn);
}
.mi.bad,
.mi.bad .i {
color: var(--bad);
}
.menu-sep {
height: 1px;
margin: 6px 12px;
background: var(--line);
}
/* One toast at a time; a new one comes in over the leaving one. */
.toasts {
position: fixed;
left: 0;
right: 0;
height: 42px;
bottom: calc(24px + env(safe-area-inset-bottom, 0px));
z-index: 70;
display: flex;
justify-content: center;
align-items: flex-end;
pointer-events: none;
padding-left: var(--gutter-l);
padding-right: var(--gutter-r);
}
.toast {
position: absolute;
display: flex;
align-items: center;
gap: 8px;
height: 42px;
padding: 0 18px 0 13px;
border-radius: 999px;
background: var(--toast);
color: var(--toast-fg);
font-size: 14px;
font-weight: 500;
box-shadow: var(--pop-shadow);
white-space: nowrap;
}
.toast .i {
width: 18px;
height: 18px;
color: var(--ok);
}
.toast.bad .i {
color: var(--bad);
}
+27
View File
@@ -0,0 +1,27 @@
/* A text morphing in place (ui/morph.ts): the new letters in the flow, the old ones laid over them
against the edge that stays put while they go; done, it is plain text again. */
.mt {
position: relative;
}
.mt-ib {
display: inline-block;
white-space: nowrap;
}
.mt-new {
white-space: nowrap;
}
.mt-old {
position: absolute;
white-space: nowrap;
pointer-events: none;
}
.mt-new.w,
.mt-old.w {
white-space: inherit;
}
.mt-new i,
.mt-old i {
font-style: normal;
display: inline-block;
white-space: pre;
}
+238
View File
@@ -0,0 +1,238 @@
/* The page's frame: the edge fades, the breadcrumb, the two columns and their heads, the notice that
says what stops the devices, and the card that stands alone when the link stopped working. */
/* The page fades out under the edges (iconiqui's dia-text, measured): on top a blur that thins out
over a darkening ramp, once the page scrolls; at the bottom only the ramp. Above the page, under
sheets, menus and toasts. */
.edge-fade {
position: fixed;
left: 0;
right: 0;
z-index: 30;
pointer-events: none;
}
.edge-fade.top {
top: 0;
height: calc(80px + env(safe-area-inset-top, 0px));
opacity: 0;
transition: opacity 200ms;
background: linear-gradient(var(--bg) 0%, color-mix(in srgb, var(--bg) 75%, transparent) 50%, transparent 100%);
-webkit-backdrop-filter: blur(12px);
backdrop-filter: blur(12px);
-webkit-mask-image: linear-gradient(#000 0%, rgba(0, 0, 0, 0.88) 44%, transparent 100%);
mask-image: linear-gradient(#000 0%, rgba(0, 0, 0, 0.88) 44%, transparent 100%);
}
body.scrolled .edge-fade.top {
opacity: 1;
}
.edge-fade.bot {
bottom: 0;
height: calc(96px + env(safe-area-inset-bottom, 0px));
background: linear-gradient(to top in oklab, var(--bg) 0%, transparent 100%);
}
/* The breadcrumb (iconiqui, measured): 32px high, the mark in a 32px box, 15px crumbs 6px apart
with a 14px chevron, the current one brighter. The mark is one colour: the text's. */
.crumbs {
display: flex;
align-items: center;
gap: 10px;
height: 32px;
margin: 0 0 32px;
}
.cr-mark {
width: 32px;
height: 32px;
display: grid;
place-items: center;
flex: none;
}
.logo {
width: 24px;
height: 24px;
flex: none;
overflow: hidden;
}
.logo .sun,
.logo .bar {
fill: var(--text);
}
.cr-path {
flex: 1;
min-width: 0;
display: flex;
align-items: center;
gap: 6px;
font-size: 15px;
line-height: 22px;
letter-spacing: -0.15px;
color: var(--text-2);
}
.cr-path span {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.cr-path .cur {
color: var(--text);
font-weight: 500;
}
.cr-path .i {
width: 14px;
height: 14px;
}
/* Phones: one column, access first. From 960px: devices left, access right and sticky. The foot
clears the bottom fade at the end of the scroll. */
.page {
max-width: 1072px;
margin: 0 auto;
padding-left: var(--gutter-l);
padding-right: var(--gutter-r);
padding-block: calc(40px + env(safe-area-inset-top, 0px)) 112px;
}
.cols {
display: grid;
gap: 40px;
}
.cols > .access {
order: -1;
}
@media (min-width: 960px) {
.cols {
grid-template-columns: minmax(0, 1fr) 384px;
gap: 36px;
align-items: start;
}
.cols > .access {
order: 0;
position: sticky;
top: calc(84px + env(safe-area-inset-top, 0px));
}
}
.sec-head {
display: flex;
align-items: baseline;
gap: 8px;
padding: 0 4px 12px;
}
.sec-head h2 {
margin: 0;
font-size: 20px;
line-height: 28px;
font-weight: 500;
letter-spacing: -0.025em;
}
.sec-head .aside {
color: var(--text-3);
font-size: 14px;
font-weight: 500;
}
.sec-head .aside.warn-t {
color: var(--warn);
}
.note-s {
margin: 12px 4px 0;
color: var(--text-3);
font-size: 13px;
line-height: 18px;
}
/* A notice wears its tone: the fill tinted, the rim a little stronger. */
.notice {
display: flex;
align-items: center;
gap: 14px;
padding: 14px 18px 14px 14px;
border-radius: 24px;
background: var(--raised);
margin: 0 0 22px;
}
.notice .gi {
width: 36px;
height: 36px;
}
.notice .t {
display: flex;
flex-direction: column;
min-width: 0;
}
.notice b {
font-weight: 500;
font-size: 15px;
line-height: 22px;
letter-spacing: -0.02em;
}
.notice span {
color: var(--text-2);
font-size: 14px;
line-height: 20px;
}
.notice.warn {
background: color-mix(in srgb, var(--warn) 10%, var(--raised));
box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--warn) 22%, transparent);
}
.notice.bad {
background: color-mix(in srgb, var(--bad) 10%, var(--raised));
box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--bad) 22%, transparent);
}
/* The page when there is nothing else: the link stopped working, or nothing could load. */
/* One card in place of the page: the breadcrumb over it, the two together in the middle of the screen. */
.page.single {
min-height: 100vh;
min-height: 100dvh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding-block: calc(24px + env(safe-area-inset-top, 0px)) calc(24px + env(safe-area-inset-bottom, 0px));
}
/* Centred on its words, the mark hanging to their left, then nudged right by about half the mark's width:
to the eye the mark and words together sit in the middle. The row keeps room for the mark on both sides. */
.page.single .crumbs {
position: relative;
left: 12px;
max-width: calc(100% - 84px);
margin: 0 0 16px;
}
.page.single .cr-mark {
position: absolute;
right: calc(100% + 10px);
top: 0;
}
.page.single .page-body {
width: 100%;
max-width: 400px;
}
.page.single .gone {
margin: 0;
}
.gone {
max-width: 400px;
margin: 12vh auto 0;
padding: 32px 24px 28px;
border-radius: var(--r-sheet);
background: var(--raised);
text-align: center;
display: flex;
flex-direction: column;
align-items: center;
}
.gone .gi {
width: 56px;
height: 56px;
margin-bottom: 16px;
}
.gone h1 {
margin: 0;
font-size: 22px;
line-height: 28px;
font-weight: 500;
letter-spacing: -0.03em;
}
.gone p {
margin: 6px 0 0;
color: var(--text-2);
text-wrap: balance;
}
+318
View File
@@ -0,0 +1,318 @@
/* 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. */
.setup {
display: flex;
flex-direction: column;
}
.setup .notice {
margin: 0 0 16px;
}
/* The steps fold to nothing under the way round: their gap is a block inside them, not padding
(a border-box never folds below its padding). */
.steps-gap {
height: 22px;
}
.step {
display: flex;
gap: 12px;
}
.step + .step {
margin-top: 20px;
}
.step-n {
width: 24px;
height: 24px;
border-radius: 50%;
background: var(--knob);
font-size: 13px;
font-weight: 600;
display: grid;
place-items: center;
flex: none;
}
.step-b {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 10px;
}
.step-t {
font-size: 16px;
line-height: 24px;
font-weight: 500;
letter-spacing: -0.02em;
}
.step-box {
display: flex;
flex-direction: column;
gap: 10px;
}
/* The way, as on the old portal: one dotted line, three layers through the same dots (the dots, the
light along them that runs and rests a beat, the green that fills them from the device); the
router's end lights up last, when the green gets there. */
.way {
display: flex;
flex-direction: column;
padding: 12px 14px;
border-radius: 20px;
background: var(--field);
margin-bottom: 18px;
}
.way-row {
display: flex;
align-items: center;
gap: 10px;
}
.way-end {
width: 34px;
height: 34px;
border-radius: 11px;
background: var(--knob);
display: grid;
place-items: center;
flex: none;
color: var(--text-2);
transition:
background-color 400ms var(--ease-out),
color 400ms var(--ease-out);
}
.way-end .i {
width: 17px;
height: 17px;
}
.way-end.home {
color: var(--accent);
background: color-mix(in srgb, var(--accent) 14%, transparent);
}
.way-track {
position: relative;
flex: 1;
height: 8px;
}
.way-track::before,
.way-glow,
.way-fill {
content: '';
position: absolute;
inset: 0;
-webkit-mask: radial-gradient(circle, #000 1.4px, transparent 1.9px) 0 50% / 9px 8px repeat-x;
mask: radial-gradient(circle, #000 1.4px, transparent 1.9px) 0 50% / 9px 8px repeat-x;
}
.way-track::before {
background: var(--text-3);
opacity: 0.8;
}
.way-glow {
overflow: hidden;
transition: opacity 200ms var(--ease-out);
}
.way-glow i {
position: absolute;
inset: 0;
background: linear-gradient(90deg, transparent 32%, var(--accent) 50%, transparent 68%);
transform: translateX(-70%);
animation: way-run 2s cubic-bezier(0.45, 0, 0.55, 1) infinite;
}
@keyframes way-run {
0% {
transform: translateX(-70%);
}
72%,
100% {
transform: translateX(70%);
}
}
.way-fill {
background: var(--ok);
clip-path: inset(0 100% 0 0);
transition: clip-path 700ms var(--ease-out) 80ms;
}
.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 {
transition-delay: 600ms;
}
.way.done .way-end.home .i {
animation: way-pop 420ms var(--spring-bouncy, ease) 600ms backwards;
}
@keyframes way-pop {
from {
transform: scale(0.6);
}
to {
transform: none;
}
}
.way-text {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 30px;
margin-top: 10px;
text-align: center;
}
.way-text .t {
display: flex;
flex-direction: column;
align-items: center;
min-width: 0;
}
/* The line morphs into "<device> connected" (ui/morph.ts) and turns green. */
.way-text b {
position: relative;
display: inline-flex;
justify-content: center;
white-space: nowrap;
font-weight: 500;
font-size: 14px;
line-height: 20px;
transition: color 300ms var(--ease-out);
}
.way-text .ws {
color: var(--text-2);
font-size: 13px;
line-height: 18px;
}
.way.done .way-text b {
color: var(--ok);
}
/* The .conf for a router: a file card, and the configuration folded with its keys masked. */
.filecard {
display: flex;
flex-direction: column;
gap: 10px;
padding: 12px;
border-radius: 18px;
background: var(--field);
}
.fc-row {
display: flex;
align-items: center;
gap: 12px;
min-width: 0;
}
.filecard-ic {
width: 38px;
height: 46px;
border-radius: 9px;
background: var(--knob);
font: 600 10px/1 var(--mono);
display: grid;
place-items: center;
color: var(--text-2);
flex: none;
}
.filecard .t {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
}
.filecard .t .mono {
font-size: 13px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.filecard .t span:last-child {
font-size: 12px;
color: var(--text-2);
line-height: 16px;
}
.confbar {
display: flex;
gap: 8px;
}
.conf {
margin: 0;
padding: 12px 14px;
border-radius: 14px;
background: var(--field);
font: 12px/18px var(--mono);
max-height: 16rem;
overflow: auto;
white-space: pre;
color: var(--text-2);
}
.conf .k {
color: var(--text);
}
.conf .sec {
color: var(--accent);
}
.conf .mask {
color: var(--text-3);
letter-spacing: 1px;
}
/* Where the app scans, for both phone systems: the mark and the word that differs change in place. */
.osm {
white-space: normal;
}
.osm-ic {
display: inline-grid;
width: 1.05em;
height: 1.05em;
margin-right: 0.25em;
vertical-align: -0.16em;
}
.osm-ic > svg {
grid-area: 1 / 1;
width: 100%;
height: 100%;
}
.osm-ic .eye {
fill: var(--field);
}
.osm-p {
display: inline-block;
white-space: pre;
}
/* "In AmneziaWG:" and the path on one line; where they don't fit, the path goes under it whole, and
stays there while it morphs (never split, never a part dropping on its own). */
.scanline {
display: flex;
flex-wrap: wrap;
align-items: baseline;
column-gap: 0.3em;
}
.scanline .osm {
white-space: nowrap;
}
/* A narrow screen: the path under the label for every app, so switching apps never moves it between lines. */
@media (max-width: 440px) {
.scanline {
flex-direction: column;
align-items: flex-start;
}
}
.way-text b .mt-old {
color: var(--text-2);
}
@media (prefers-reduced-motion: reduce) {
.way-glow {
display: none;
}
.way-fill {
transition: none;
}
.way.done .way-end.home .i {
animation: none;
}
}
+281
View File
@@ -0,0 +1,281 @@
/* 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). */
/* 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
quick close and reopen (a double tap on Reconnect), and the sheet opened empty but for its buttons. */
.sheet-root {
position: fixed;
inset: 0;
z-index: 50;
display: none;
}
.sheet-root.open {
display: block;
}
.scrim {
position: absolute;
inset: 0;
background: var(--scrim);
-webkit-backdrop-filter: blur(8px);
backdrop-filter: blur(8px);
}
.sheet {
position: absolute;
left: var(--gutter-l);
right: var(--gutter-r);
bottom: calc(16px + env(safe-area-inset-bottom, 0px));
margin: 0 auto;
max-width: 400px;
max-height: calc(100% - 32px - env(safe-area-inset-top, 0px) - env(safe-area-inset-bottom, 0px));
background: var(--raised);
border-radius: var(--r-sheet);
box-shadow: var(--sheet-shadow);
overflow: hidden;
display: flex;
flex-direction: column;
}
/* On a computer (and a tablet held wide): a dialog in the middle of the screen, which comes up from
its centre (ui/sheet.ts); a phone keeps the drawer at the bottom. The breakpoint is the one the
sheet widens at for a dense code. Centred by the layout, not a transform, so its text stays on the
pixel grid and its own transform stays free for the motion. */
@media (min-width: 760px) {
.sheet-root.open {
display: flex;
align-items: center;
justify-content: center;
}
.sheet {
position: relative;
left: auto;
right: auto;
bottom: auto;
margin: 0;
width: calc(100% - var(--gutter-l) - var(--gutter-r));
}
}
.sheet .x {
position: absolute;
z-index: 3;
right: 22px;
top: 22px;
}
.vp {
position: relative;
overflow: hidden;
flex: none;
}
.sheet-scroll {
flex: 1 1 auto;
min-height: 0;
overflow-y: auto;
overscroll-behavior: contain;
}
.view {
padding: 0 24px 24px;
display: flex;
flex-direction: column;
}
/* Pulled down by its head to close: the head takes the touch, the rest scrolls. */
.vhead {
display: flex;
align-items: center;
gap: 12px;
height: 76px;
padding-right: 44px;
flex: none;
cursor: grab;
touch-action: none;
}
.vhead h2 {
flex: 1;
margin: 0;
font-size: 20px;
line-height: 28px;
font-weight: 500;
letter-spacing: -0.5px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.vhead.center h2 {
text-align: center;
}
.vhead.with-acts {
padding-right: 126px;
}
.vsub {
margin: -16px 0 18px;
color: var(--text-2);
font-size: 14px;
line-height: 20px;
}
.vhead.center + .vsub {
text-align: center;
margin: -6px auto 24px;
max-width: 32ch;
text-wrap: balance;
}
.kinds-note {
margin: 14px 2px 16px;
}
.view > .hint.bad-t {
margin-top: 8px;
}
.secure-note {
margin-top: 12px;
text-align: center;
}
/* A view's own buttons beside × and pinned like it: icons only, each the size and colour of ×; the
two join with tighter inner corners. */
.sheet-acts {
position: absolute;
z-index: 3;
top: 22px;
right: 58px;
}
.hpill {
position: relative;
display: flex;
gap: 2px;
}
.hp-b {
display: grid;
place-items: center;
width: 38px;
height: 32px;
background: var(--knob);
color: var(--text);
transition:
background-color 150ms,
transform 150ms var(--ease-out);
}
.hp-b:first-of-type {
border-radius: 16px 6px 6px 16px;
}
.hp-b:last-of-type {
border-radius: 6px 16px 16px 6px;
}
.hp-b .i {
width: 16px;
height: 16px;
}
.hp-b:hover {
background: color-mix(in srgb, var(--knob), var(--text) 6%);
}
.hp-b:active {
transform: scale(0.94);
}
.hp-b.done {
color: var(--ok);
}
/* Their tooltip: a small toast-coloured pill under the keys, one for both. */
.hp-tip {
position: absolute;
z-index: 4;
left: 0;
top: calc(100% + 8px);
height: 26px;
padding: 0 10px;
display: flex;
align-items: center;
border-radius: 999px;
background: var(--toast);
color: var(--toast-fg);
font: 500 12px/1 var(--font);
letter-spacing: -0.1px;
white-space: nowrap;
box-shadow:
0 0 0 1px var(--line-glass),
var(--pop-shadow);
opacity: 0;
pointer-events: none;
overflow: hidden;
transform-origin: 50% 0;
}
.hp-tip.on {
opacity: 1;
}
.hp-tip .tt {
position: relative;
display: inline-flex;
justify-content: center;
white-space: nowrap;
}
.hp-tip .tt-m {
position: absolute;
left: 0;
top: 0;
visibility: hidden;
white-space: nowrap;
}
/* Connected: nothing is left to do here, so × and the view's buttons step away; the sheet then closes by itself. */
.sheet .x,
.sheet-acts {
transition:
transform 150ms var(--ease-out),
background-color 150ms,
opacity 240ms var(--ease-out),
filter 240ms var(--ease-out),
scale 240ms var(--ease-out);
}
.sheet.arrived .x,
.sheet.arrived .sheet-acts {
opacity: 0;
filter: blur(3px);
scale: 0.9;
pointer-events: none;
}
/* A question before something that cannot be undone. */
.center-col {
display: flex;
flex-direction: column;
align-items: center;
text-align: center;
}
.center-col.ask {
padding-top: 28px;
}
.center-col.secure {
padding-top: 4px;
}
.center-col .gi.xl {
width: 64px;
height: 64px;
margin: 8px 0 16px;
}
.center-col h3 {
margin: 0;
font-size: 20px;
line-height: 28px;
font-weight: 500;
letter-spacing: -0.5px;
}
.center-col p {
margin: 6px 0 22px;
color: var(--text-2);
font-size: 15px;
line-height: 21px;
max-width: 30ch;
text-wrap: balance;
}
.center-col.secure p {
margin-top: 0;
}
.btnrow {
display: flex;
gap: 8px;
width: 100%;
}
.btnrow .btn {
flex: 1;
}
.btnrow2 {
display: grid;
gap: 8px;
}
.btnrow2 .btn {
width: 100%;
}
+130
View File
@@ -0,0 +1,130 @@
/* The portal's fonts and tokens. Dark first (the skiper21 palette, measured), light by the system's
choice. Surfaces step up in brightness (ground → raised → field → knob) instead of borders; the
accent is the one sky blue, colour otherwise only means state (ok green, warn orange, bad red). */
@font-face {
font-family: Geist;
src: url(geist-latin-wght-normal.woff2) format('woff2');
font-weight: 100 900;
font-display: swap;
unicode-range:
U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+20AC, U+2122, U+2190-21FF, U+2212, U+2215;
}
@font-face {
font-family: Geist;
src: url(geist-cyrillic-wght-normal.woff2) format('woff2');
font-weight: 100 900;
font-display: swap;
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
@font-face {
font-family: 'Geist Mono';
src: url(geist-mono-latin-wght-normal.woff2) format('woff2');
font-weight: 100 900;
font-display: swap;
}
:root {
color-scheme: dark;
--bg: #080808;
--raised: #121212;
--field: #161616;
--knob: #232323;
--seg: rgba(237, 237, 237, 0.05);
--seg-shadow: none;
--line: rgba(255, 255, 255, 0.06);
--text: #ededed;
--text-2: #8c8c8a;
--text-3: #4f4f4e;
--accent: #4eafff;
--accent-ink: #ffffff;
--accent-soft: rgba(78, 175, 255, 0.13);
--ok: #57d64b;
--ok-soft: rgba(87, 214, 75, 0.14);
--warn: #ff8a3d;
--bad: #ff5c5c;
--bad-soft: rgba(255, 92, 92, 0.13);
--sel-bg: rgba(131, 209, 255, 0.25);
--sel-fg: #64c6ff;
--scrim: rgba(8, 8, 8, 0.8);
--line-glass: rgba(255, 255, 255, 0.07);
--pop-shadow: 0 18px 48px -14px rgba(0, 0, 0, 0.75);
--sheet-shadow: 0 24px 64px -16px rgba(0, 0, 0, 0.6);
--bar: rgba(237, 237, 237, 0.13);
--toast: #232323;
--toast-fg: #ededed;
--qr-bg: #0a0a0a;
/* glass icons: the frosted pane, its rim and edge, the detail strokes; the tones' two stops */
--gi-a: rgba(255, 255, 255, 0.58);
--gi-b: rgba(255, 255, 255, 0.14);
--gi-rim: rgba(255, 255, 255, 0.5);
--gi-edge: rgba(0, 0, 0, 0);
--gi-detail: #ffffff;
--t-grey-a: #cfcfcd;
--t-grey-b: #5a5a59;
--t-blue-a: #a6d9ff;
--t-blue-b: #1d84e6;
--t-green-a: #a8f29c;
--t-green-b: #3aa32c;
--t-red-a: #ffadad;
--t-red-b: #dc3a3a;
--t-orange-a: #ffc08f;
--t-orange-b: #ec6a12;
--font: Geist, -apple-system, system-ui, 'Segoe UI', sans-serif;
--mono: 'Geist Mono', ui-monospace, 'SF Mono', Menlo, monospace;
--r-sheet: 36px;
--r-card: 28px;
--r-row: 20px;
--r-field: 16px;
--r-tile: 12px;
--ease-out: cubic-bezier(0.23, 1, 0.32, 1);
--gutter-l: max(16px, env(safe-area-inset-left, 0px));
--gutter-r: max(16px, env(safe-area-inset-right, 0px));
}
@media (prefers-color-scheme: light) {
:root {
color-scheme: light;
--bg: #f2f2f1;
--raised: #ffffff;
--field: #f3f3f2;
--knob: #e8e8e7;
--seg: #ffffff;
--seg-shadow: 0 1px 2px rgba(0, 0, 0, 0.08), 0 0 0 0.5px rgba(0, 0, 0, 0.05);
--line: rgba(0, 0, 0, 0.07);
--text: #0b0b0b;
--text-2: #6d6d6b;
--text-3: #a6a6a4;
--accent: #2b9dff;
--accent-soft: rgba(43, 157, 255, 0.12);
--ok: #33a328;
--ok-soft: rgba(51, 163, 40, 0.12);
--warn: #ee6a12;
--bad: #e5484d;
--bad-soft: rgba(229, 72, 77, 0.1);
--sel-bg: rgba(78, 175, 255, 0.22);
--sel-fg: #0a76cf;
--scrim: rgba(236, 236, 235, 0.62);
--line-glass: rgba(0, 0, 0, 0.07);
--pop-shadow: 0 18px 44px -14px rgba(0, 0, 0, 0.2);
--sheet-shadow: 0 24px 64px -18px rgba(0, 0, 0, 0.22);
--bar: rgba(11, 11, 11, 0.11);
--toast: #0b0b0b;
--toast-fg: #f2f2f1;
--qr-bg: #ffffff;
--gi-a: rgba(250, 250, 249, 0.72);
--gi-b: rgba(206, 206, 204, 0.5);
--gi-rim: rgba(255, 255, 255, 0.9);
--gi-edge: rgba(0, 0, 0, 0.11);
--gi-detail: rgba(28, 28, 28, 0.72);
--t-grey-a: #a9a9a7;
--t-grey-b: #3d3d3c;
--t-blue-a: #7cc4ff;
--t-blue-b: #0a6fd6;
--t-green-a: #82e070;
--t-green-b: #2e8a22;
--t-red-a: #ff9090;
--t-red-b: #c92a2a;
}
}
+140
View File
@@ -0,0 +1,140 @@
// The accordion (skiper103's motion, on a softer spring): rows touch while
// closed and share their rounded ends; an open row lifts out with 10 px gaps
// 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.
import { h, ic } from '../dom';
import { EASE_IN, SOFT, play } from '../motion';
import { planWidth, startWidth } from './sheet';
export interface AccItem {
icon: Element;
title: string;
/** Beside the title (a chip). */
tag?: Node | null;
/** At the head's end (numbers). */
val?: Node | null;
/** The body shows the same numbers: the head drops them while open. */
valHide?: boolean;
body: (Node | null | false | undefined)[];
}
export interface Accordion {
el: HTMLElement;
/** The open row, or -1. */
openIndex(): number;
/** Open this row (or none), without motion: a repaint keeps what was open. */
setOpen(i: number): void;
}
/** The properties the rows animate between their closed and open shapes. */
const PROPS = [
'height',
'marginTop',
'marginBottom',
'borderTopLeftRadius',
'borderTopRightRadius',
'borderBottomLeftRadius',
'borderBottomRightRadius',
] as const;
export function accordion(
items: AccItem[],
o: { inset?: boolean; open?: number; onToggle?: (i: number, open: boolean, instant: boolean) => void } = {},
): Accordion {
const acc = h('div', { class: `acc${o.inset ? ' inset' : ''}` });
const rows = items.map((it, i) => {
const kids = it.body.filter((k): k is Node => !!k);
const still = !kids.length;
const inner = [
it.icon,
h('span', { class: 'acc-title' }, h('span', { class: 't' }, it.title), it.tag ?? null),
it.val ? h('span', { class: `acc-val${it.valHide ? ' hide-open' : ''}` }, it.val) : null,
];
const open = i === o.open && !still;
const headEl = still
? h('div', { class: 'acc-head' }, ...inner)
: h(
'button',
{ type: 'button', class: 'acc-head', 'aria-expanded': String(open), onclick: () => toggle(r) },
...inner,
ic('chevron', 'i acc-chev'),
);
const r = h(
'div',
{ class: `acc-row${still ? ' still' : ''}${open ? ' open' : ''}` },
headEl,
h('div', { class: 'acc-body' }, ...kids),
);
acc.appendChild(r);
return r;
});
const bodyOf = (r: HTMLElement) => r.querySelector('.acc-body') as HTMLElement;
const corners = () =>
rows.forEach((r, i) => {
const op = r.classList.contains('open');
r.classList.toggle('rt', i === 0 || op || rows[i - 1].classList.contains('open'));
r.classList.toggle('rb', i === rows.length - 1 || op || rows[i + 1].classList.contains('open'));
});
const read = (x: HTMLElement) => {
const cs = getComputedStyle(x);
const out: Record<string, string> = {};
for (const p of PROPS) out[p] = p === 'height' ? `${x.getBoundingClientRect().height}px` : cs[p];
return out;
};
const aria = () =>
rows.forEach((x) => x.querySelector('button.acc-head')?.setAttribute('aria-expanded', String(x.classList.contains('open'))));
function toggle(r: HTMLElement) {
const before = rows.map(read);
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));
rows.forEach((x) => {
x.classList.remove('closing');
if (x !== r) x.classList.remove('open');
});
r.classList.toggle('open', willOpen);
corners();
const plan = planWidth();
rows.forEach((x, i) => {
const after = read(x);
if (!PROPS.some((p) => before[i][p] !== after[p])) return;
if (closing.includes(x)) x.classList.add('closing');
play(x, [before[i], after], { duration: SOFT.duration, easing: SOFT.easing }).onfinish = () => x.classList.remove('closing');
});
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)' },
);
startWidth(plan);
aria();
o.onToggle?.(rows.indexOf(r), willOpen, false);
}
corners();
return {
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')));
corners();
aria();
rows.forEach((x, k) => o.onToggle?.(k, x.classList.contains('open'), true));
},
};
}
+68
View File
@@ -0,0 +1,68 @@
// A button held busy while the router answers: its content blurs away and an
// orb comes up through the blur in its place, then the other way round. The orb
// is B4 Converge from aicss.dev's Orbs (controls.css draws it). Each change starts
// from where the last one stands, so an answer that lands mid-change turns back
// without a jump.
import { h } from '../dom';
import { EASE_IN, EASE_OUT, play } from '../motion';
const SHOWN: Keyframe = { opacity: 1, filter: 'blur(0px)', transform: 'none' };
const GONE: Keyframe = { opacity: 0, filter: 'blur(5px)', transform: 'scale(.86)' };
const ORB_GONE: Keyframe = { opacity: 0, filter: 'blur(5px)', transform: 'scale(.6)' };
/** Out quick, in a little later and slower: the two cross in the blur. */
const OUT = { duration: 180, easing: EASE_IN, fill: 'forwards' } as const;
const IN = { duration: 340, delay: 70, easing: EASE_OUT, fill: 'backwards' } as const;
/** Until the orb is all the way in: a quicker answer waits for it, so the orb never just flickers. */
export const BUSY_IN = IN.delay + IN.duration;
const runs = new WeakMap<HTMLElement, Animation[]>();
/** Where an element stands now, mid-animation included. */
function now(el: Element): Keyframe {
const s = getComputedStyle(el);
return { opacity: s.opacity, filter: s.filter === 'none' ? 'blur(0px)' : s.filter, transform: s.transform };
}
/** What gives way: the button's own elements (a bare word goes into a span first). */
function content(btn: HTMLElement): Element[] {
for (const n of [...btn.childNodes])
if (n.nodeType === Node.TEXT_NODE && n.textContent?.trim()) n.replaceWith(h('span', {}, n.textContent));
return [...btn.children].filter((c) => !c.classList.contains('orb'));
}
/** The new change takes over: the old one stops once the new one is in place (nothing paints between). */
function hand(btn: HTMLElement, next: Animation[]) {
const old = runs.get(btn) ?? [];
runs.set(btn, next);
old.forEach((a) => a.cancel());
}
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);
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)]);
}
export function busyOff(btn: HTMLElement) {
const orb = btn.querySelector(':scope > .orb');
const parts = content(btn);
const next = [...(orb ? [play(orb, [now(orb), ORB_GONE], OUT)] : []), ...parts.map((p) => play(p, [now(p), SHOWN], IN))];
hand(btn, next);
btn.removeAttribute('aria-busy');
Promise.all(next.map((a) => a.finished)).then(
() => {
if (runs.get(btn) !== next) return; // busy again meanwhile
runs.delete(btn);
next.forEach((a) => a.cancel());
orb?.remove();
btn.classList.remove('busy');
},
() => {},
);
}
+117
View File
@@ -0,0 +1,117 @@
// What goes to another device: a QR code and the words that go with it, and a
// 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).
import { denseQr, qrSvg } from '../../shared/qr';
import { h, ic } from '../dom';
import { EASE_IN, EASE_OUT, 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));
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);
}
export function qrBox(text: string, big = false): HTMLElement {
const box = h('div', { class: `qrbox${big ? ' big' : ''}` });
paint(box, text);
return box;
}
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!);
}),
);
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);
const side = h('div', { class: 'side' }, shown);
const el = h('div', { class: `coderow${box.classList.contains('dense') ? ' stacked' : ''}` }, box, side);
return {
el,
swap(next, nextWords) {
// 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;
const oldWords = shown;
shown = h('div', { class: 'words' }, nextWords);
side.appendChild(shown);
oldWords.classList.add('old');
play(
shown,
[
{ opacity: 0, filter: 'blur(3px)' },
{ opacity: 1, filter: 'blur(0px)' },
],
{ 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();
},
};
}
/** A link as text with Copy and, where the browser has one, the share sheet. */
export function linkRow(url: string): HTMLElement {
const share = typeof navigator.share === 'function';
return h(
'div',
{ class: 'linkrow' },
h('span', { class: 'mono' }, url.replace(/^https?:\/\//, '')),
h(
'button',
{ type: 'button', class: 'knob', 'aria-label': 'Copy the link', onclick: (ev: Event) => copy(url, 'Link copied', ev.currentTarget) },
ic('copy'),
),
share
? h(
'button',
{
type: 'button',
class: 'knob',
'aria-label': 'Share the link',
onclick: () => navigator.share({ url, title: placeName() }).catch(() => undefined),
},
ic('share'),
)
: null,
);
}
+157
View File
@@ -0,0 +1,157 @@
// What a tap answers with: a toast, a copy (and the check on the control that
// copied), a file shared or downloaded, a button held busy until the router
// answers. Toasts sit in one bottom slot, one at a time.
import { h, ic } from '../dom';
import { BOUNCY, EASE_IN, POP, calm, play } from '../motion';
import { platform } from '../state';
import { BUSY_IN, busyOff, busyOn } from './busy';
import { morphText, textOf } from './morph';
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());
/** 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);
const t = h('div', { class: `toast${bad ? ' bad' : ''}`, role: 'status' }, ic(bad ? 'alert' : 'check'), h('span', {}, msg));
slot.appendChild(t);
shown = t;
play(
t,
[
{ opacity: 0, transform: 'translateY(18px) scale(.9)', filter: 'blur(6px)' },
{ opacity: 1, transform: 'none', filter: 'none' },
],
{
duration: BOUNCY.duration,
easing: BOUNCY.easing,
},
);
clearTimeout(timer);
timer = window.setTimeout(() => {
if (shown !== t) return;
shown = null;
leave(t, [{ opacity: 1 }, { opacity: 0, transform: 'translateY(6px) scale(.96)', filter: 'blur(4px)' }], 180);
}, 2400);
}
/**
* The control that copied says so for a moment: its icon turns into a check
* and a "Copy…" label (`.lbl`, a badge's main line) into "Copied".
*/
function copied(from: Element) {
if (from.classList.contains('copied')) return;
const icon = from.querySelector('svg.i');
const label = from.querySelector<HTMLElement>('.lbl, .b-main');
const was = label ? textOf(label) : '';
from.classList.add('copied');
let check: Element | null = null;
if (icon) {
check = ic('check', icon.getAttribute('class') ?? 'i');
icon.replaceWith(check);
play(
check,
[
{ opacity: 0, transform: 'scale(.6)', filter: 'blur(3px)' },
{ opacity: 1, transform: 'none', filter: 'none' },
],
{
duration: POP.duration,
easing: POP.easing,
},
);
}
if (label && /^Copy/.test(was)) morphText(label, 'Copied');
setTimeout(() => {
if (check && icon) check.replaceWith(icon);
if (label && /^Copy/.test(was)) morphText(label, was);
from.classList.remove('copied');
}, 1600);
}
/** `from`: the control that copied, which then shows a check for a moment. */
export async function copy(text: string, what = 'Copied', from?: EventTarget | null) {
try {
await navigator.clipboard.writeText(text);
} catch {
const ta = h('textarea', { class: 'offscreen' }, text) as HTMLTextAreaElement;
document.body.appendChild(ta);
ta.select();
const ok = document.execCommand('copy');
ta.remove();
if (!ok) return toast('Copying is blocked here. Select the text and copy it by hand.', true);
}
if (from instanceof Element) copied(from);
toast(what);
}
/**
* On an iPhone a share sheet hands the file straight to the VPN app, where a
* download would land in Files. Returns the action, or null where files
* cannot be shared.
*/
export function shareFile(name: string, text: string): (() => Promise<void>) | null {
const nav = navigator as Navigator & { canShare?: (d: unknown) => boolean };
// Only iOS: there AmneziaWG, WireGuard and AmneziaVPN take a file from the
// share sheet. On Android neither app is a share target (and Chrome does not
// share .conf files), so a download goes into the app's own file picker;
// desktop browsers claim they can share files and then do nothing.
if (platform() !== 'ios') return null;
if (typeof nav.share !== 'function' || typeof File === 'undefined') return null;
const file = new File([text], name, { type: 'application/octet-stream' });
if (!nav.canShare?.({ files: [file] })) return null;
return async () => {
try {
// The file alone: with a title, "Save to Files" also writes the title as a .txt.
await nav.share({ files: [file] });
} catch (e) {
// Cancelled: nothing to do. Refused by the browser: the file still has to get out.
if ((e as Error)?.name !== 'AbortError') download(name, text);
}
};
}
export function download(name: string, text: string) {
// Not text/plain: Safari would save "name.conf.txt".
const url = URL.createObjectURL(new Blob([text], { type: 'application/octet-stream' }));
const a = h('a', { href: url, download: name, class: 'offscreen' });
document.body.appendChild(a);
a.click();
setTimeout(() => {
URL.revokeObjectURL(url);
a.remove();
}, 1000);
}
/** The file out: the share sheet where the browser hands it to an app, a download elsewhere. */
export function sendFile(name: string, text: string) {
const share = shareFile(name, text);
if (share) void share();
else download(name, text);
}
/**
* Run an action once: its button goes busy (the orb) on the click and stays
* disabled until the router answers; a quick answer keeps the orb until it is
* all the way in.
*/
export async function once(btn: HTMLButtonElement, fn: () => Promise<void>) {
if (btn.disabled) return;
btn.disabled = true;
busyOn(btn);
const t0 = performance.now();
try {
await fn();
} finally {
const wait = calm() ? 0 : BUSY_IN - (performance.now() - t0);
if (wait > 0) await new Promise((r) => setTimeout(r, wait));
busyOff(btn);
btn.disabled = false;
}
}
+153
View File
@@ -0,0 +1,153 @@
// Glass icons: a tinted back shape, the same shape blurred behind a frosted
// front pane, a rim, and the detail strokes on top. The shapes are ours; every
// colour comes from the stylesheet (tone classes and the --gi-* tokens), never
// from a style attribute, which the page's CSP would drop.
import { iconSvg } from '../../shared/icons';
import { markup } from '../dom';
export type Tone = 'grey' | 'blue' | 'green' | 'red' | 'orange';
interface Shape {
/** The tinted back shape. */
b: string;
/** The frosted front pane. */
f: string;
/** Detail strokes on the pane; null: the AmneziaVPN mark instead. */
d: string | null;
}
const GL: Record<string, Shape> = {
phone: {
b: '<rect x="10" y="2" width="10" height="16" rx="3"/>',
f: '<rect x="4" y="5" width="11.5" height="17" rx="3.2"/>',
d: '<path d="M8.3 19h3.9"/>',
},
mobile: {
b: '<rect x="8.5" y="2" width="13.5" height="17" rx="2.6"/>',
f: '<rect x="2.5" y="7" width="9.5" height="15" rx="2.6"/>',
d: '<path d="M6 19.4h2.5"/>',
},
tablet: {
b: '<rect x="9.5" y="2" width="12" height="15" rx="2.6"/>',
f: '<rect x="2.5" y="5.5" width="14.5" height="16.5" rx="2.8"/>',
d: '<path d="M8 19h3.5"/>',
},
computer: {
b: '<rect x="6" y="14" width="17" height="7" rx="2.2"/>',
f: '<rect x="1.5" y="3.5" width="19" height="13" rx="2.6"/>',
d: '<path d="M5.5 12.5h5"/>',
},
router: {
b: '<rect x="5.5" y="2" width="2.8" height="11" rx="1.4"/><rect x="15.7" y="2" width="2.8" height="11" rx="1.4"/>',
f: '<rect x="2" y="10.5" width="20" height="10.5" rx="3"/>',
d: '<path d="M6.6 15.75h.4M10 15.75h.4" stroke-width="2.4"/>',
},
other: { b: '<circle cx="16" cy="8" r="6"/>', f: '<rect x="2.5" y="8" width="14" height="14" rx="3.6"/>', d: '' },
plus: {
b: '<rect x="9" y="2" width="13" height="13" rx="4"/>',
f: '<circle cx="10" cy="14" r="8"/>',
d: '<path d="M10 10.6v6.8M6.6 14h6.8"/>',
},
globe: {
b: '<circle cx="16" cy="8" r="6"/>',
f: '<circle cx="10.5" cy="13.5" r="8.5"/>',
d: '<path d="M2.5 13.5h16" stroke-width="1.1"/><path d="M10.5 5.2c2.4 2.6 2.4 14 0 16.6M10.5 5.2c-2.4 2.6-2.4 14 0 16.6" stroke-width="1.1"/>',
},
home: {
b: '<rect x="12" y="2" width="10" height="10" rx="3"/>',
f: '<path d="M2.5 11.6 10.5 5l8 6.6V20a2 2 0 0 1-2 2h-12a2 2 0 0 1-2-2z"/>',
d: '<path d="M8.8 22v-4.2h3.4V22"/>',
},
shield: {
b: '<circle cx="16" cy="8" r="6"/>',
f: '<path d="M10.5 4.5l7.5 2.8v5.4c0 4.6-3.2 7.4-7.5 8.8C6.2 20.1 3 17.3 3 12.7V7.3z"/>',
d: '<path d="M7.3 13.2l2.3 2.3 4.2-4.6"/>',
},
chart: {
b: '<rect x="14.5" y="2" width="7" height="20" rx="2.6"/>',
f: '<rect x="2.5" y="8.5" width="14" height="13.5" rx="3.4"/>',
d: '<path d="M6 18l2.8-3 2.2 1.8L14 12.8"/>',
},
calendar: {
b: '<rect x="8.5" y="2" width="13.5" height="13" rx="3"/>',
f: '<rect x="2" y="6" width="15.5" height="16" rx="3.4"/>',
d: '<path d="M2.4 10.6h14.7" stroke-width="1"/><path d="M6.2 14.6h.4M9.5 14.6h.4M12.8 14.6h.4M6.2 18h.4M9.5 18h.4" stroke-width="2.2"/>',
},
clock: { b: '<circle cx="16" cy="8" r="6"/>', f: '<circle cx="10.5" cy="13.5" r="8.5"/>', d: '<path d="M10.5 9v4.8l3 1.8"/>' },
pause: {
b: '<rect x="12" y="2" width="10" height="10" rx="3"/>',
f: '<circle cx="10.5" cy="13.5" r="8.5"/>',
d: '<path d="M8.6 10.5v6M12.4 10.5v6"/>',
},
server: {
b: '<rect x="7" y="2" width="15" height="8" rx="2.6"/>',
f: '<rect x="2" y="8" width="16" height="14" rx="3"/>',
d: '<path d="M5.5 12.5h.4M5.5 17.5h.4" stroke-width="2.4"/><path d="M2.4 15h15.2" stroke-width="1"/>',
},
link: {
b: '<rect x="11.5" y="1.5" width="8" height="14" rx="4" transform="rotate(45 15.5 8.5)"/>',
f: '<rect x="4.5" y="8.5" width="8" height="14" rx="4" transform="rotate(45 8.5 15.5)"/>',
d: '<path d="M9.8 14.2l4.4-4.4"/>',
},
key: {
b: '<rect x="10" y="10" width="12.5" height="5" rx="2.5"/><rect x="17" y="13" width="3.4" height="6" rx="1.4"/>',
f: '<circle cx="8" cy="12.5" r="6.5"/>',
d: '<circle cx="6.6" cy="12.5" r="1.7"/>',
},
lock: {
b: '<rect x="7" y="2" width="10" height="11" rx="5"/>',
f: '<rect x="3" y="9" width="18" height="13" rx="3.4"/>',
d: '<path d="M12 14v3"/>',
},
check: {
b: '<circle cx="14.5" cy="9.5" r="7.5"/>',
f: '<circle cx="10.5" cy="13.5" r="8.5"/>',
d: '<path d="M6.6 13.8l2.7 2.7 5.3-5.6"/>',
},
trash: {
b: '<rect x="3" y="2.5" width="18" height="5" rx="2.3"/>',
f: '<path d="M4.8 8.5h14.4l-1.1 11.6a2.2 2.2 0 0 1-2.2 1.9H8.1a2.2 2.2 0 0 1-2.2-1.9z"/>',
d: '<path d="M10 12v6M14 12v6"/>',
},
refresh: {
b: '<circle cx="16" cy="8" r="6"/>',
f: '<circle cx="10.5" cy="13.5" r="8.5"/>',
d: '<path d="M14.2 11.3a4.2 4.2 0 1 0 .3 3.6"/><path d="M14.6 8.8v2.8h-2.8"/>',
},
app: { 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: null },
file: {
b: '<rect x="9" y="2" width="12.5" height="15" rx="3"/>',
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"/>',
},
};
/** The AmneziaVPN mark without its own svg: drawn on the "app" pane. */
const amneziaMark = () =>
iconSvg('amnezia', '')
.replace(/^<svg[^>]*>/, '')
.replace(/<\/svg>$/, '');
let gid = 0;
/** A glass icon as markup (`cls`: its classes, e.g. "gi xl"). */
export function glassSvg(name: string, tone: Tone = 'grey', cls = 'gi'): string {
const g = GL[name] ?? GL.other;
const id = `gl${++gid}`;
const detail =
g.d === null
? `<g class="gdf" transform="translate(5.15 10.15) scale(.385)">${amneziaMark()}</g>`
: `<g class="gd" fill="none" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">${g.d}</g>`;
return (
`<svg class="${cls} t-${tone}" viewBox="0 0 24 24" aria-hidden="true"><defs>` +
`<linearGradient id="${id}b" x1="0" y1="0" x2="1" y2="1"><stop offset="0" class="ta"/><stop offset="1" class="tb"/></linearGradient>` +
`<linearGradient id="${id}f" x1="0" y1="0" x2="0" y2="1"><stop offset="0" class="fa"/><stop offset=".55" class="fb"/><stop offset="1" class="fc"/></linearGradient>` +
`<clipPath id="${id}c">${g.f}</clipPath><filter id="${id}x" x="-40%" y="-40%" width="180%" height="180%"><feGaussianBlur stdDeviation="1.5"/></filter></defs>` +
`<g fill="url(#${id}b)">${g.b}</g><g clip-path="url(#${id}c)"><g fill="url(#${id}b)" filter="url(#${id}x)">${g.b}</g></g>` +
`<g fill="url(#${id}f)">${g.f}</g><g class="ge" fill="none" stroke-width="1.1">${g.f}</g>` +
`<g class="gr" fill="none" stroke-width=".6">${g.f}</g>${detail}</svg>`
);
}
/** A glass icon as an element. */
export const glass = (name: string, tone: Tone = 'grey', cls = 'gi'): Element => markup(glassSvg(name, tone, cls));
+104
View File
@@ -0,0 +1,104 @@
// The ⋯ menu: a small panel under (or over) its button, items with an icon,
// a highlight that glides after the pointer and takes the item's colour
// (orange for Reconnect, red for Remove). One at a time; it closes on a press
// outside, on scroll, on Escape and when its button is pressed again.
import { h, ic } from '../dom';
import { EASE_IN, POP, play } from '../motion';
export interface MenuItem {
label: string;
icon: string;
tone?: 'warn' | 'bad';
run: () => unknown;
}
let menuEl: HTMLElement | null = null;
/** The button the open menu belongs to: pressing it again closes the menu. */
let anchorEl: HTMLElement | null = null;
export const menuOpen = () => !!menuEl;
/** `now`: gone at once (Escape, or another menu opening). */
export function closeMenu(now = false) {
const m = menuEl;
if (!m) return;
menuEl = null;
anchorEl?.setAttribute('aria-expanded', 'false');
anchorEl = null;
if (now) {
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();
}
/** `items`: null is a separator, kept only between items. */
export function openMenu(anchor: HTMLElement, all: (MenuItem | null)[]) {
if (anchorEl === anchor && menuEl) return closeMenu();
closeMenu(true);
const items = all.filter((it, i) => it || (i > 0 && all[i - 1] && all.slice(i + 1).some(Boolean)));
const hl = h('span', { class: 'menu-hl' });
const m = h('div', { class: 'menu', role: 'menu' }, hl);
for (const it of items) {
if (!it) {
m.appendChild(h('div', { class: 'menu-sep' }));
continue;
}
const b = h(
'button',
{
type: 'button',
role: 'menuitem',
class: `mi ${it.tone ?? ''}`,
onclick: () => {
closeMenu();
it.run();
},
},
ic(it.icon),
h('span', {}, it.label),
);
// The highlight comes in where the pointer is, then glides from item to item.
b.addEventListener('pointerenter', () => {
hl.className = `menu-hl${hl.style.opacity === '1' ? ' moving' : ''} ${it.tone ?? ''}`;
hl.style.transform = `translateY(${b.offsetTop - 6}px)`;
hl.style.opacity = '1';
});
m.appendChild(b);
}
m.addEventListener('pointerleave', () => (hl.style.opacity = '0'));
document.body.appendChild(m);
const r = anchor.getBoundingClientRect();
const w = m.offsetWidth;
const mh = m.offsetHeight;
// Under the button, or over it where the screen ends: it grows out of the button either way.
const below = r.bottom + 8 + mh < innerHeight - 8;
m.style.left = `${Math.max(12, Math.min(r.right - w, innerWidth - w - 12))}px`;
m.style.top = `${below ? r.bottom + 8 : r.top - 8 - mh}px`;
m.style.transformOrigin = `${below ? 'top' : 'bottom'} right`;
play(
m,
[
{ opacity: 0, transform: 'scale(.9)', filter: 'blur(4px)' },
{ opacity: 1, transform: 'none', filter: 'none' },
],
{
duration: POP.duration,
easing: POP.easing,
},
);
menuEl = m;
anchorEl = anchor;
anchor.setAttribute('aria-expanded', 'true');
}
document.addEventListener('pointerdown', (e) => {
const t = e.target as Element;
if (menuEl && !menuEl.contains(t) && !anchorEl?.contains(t)) closeMenu();
});
addEventListener('scroll', () => closeMenu(), { passive: true });
+585
View File
@@ -0,0 +1,585 @@
// Words that change in place morph letter by letter: the old letters lift away
// with a blur, the new ones rise in one after another, and the width glides
// between them. Every text the page or a sheet changes while it shows goes
// 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").
import { h, ic, markup, put, type Kid } from '../dom';
import { EASE_IN, EASE_OUT, POP, SMOOTH, calm, play } from '../motion';
/** Each character as its own inline box, so each can move. */
const letters = (w: string): HTMLElement[] => [...w].map((ch) => h('i', {}, ch));
interface Run {
/** What it is turning into. */
text: string;
timer: number;
}
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 ?? '';
/** Where `el`'s words sit (their own box, not the element's). */
function wordsBox(el: HTMLElement): DOMRect {
const r = document.createRange();
r.selectNodeContents(el);
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;
if (!node || node.nodeType !== Node.TEXT_NODE) return [];
const r = document.createRange();
const out: number[] = [];
let o = 0;
for (const ch of node.textContent ?? '') {
r.setStart(node, o);
r.setEnd(node, o + ch.length);
out.push(r.getBoundingClientRect().left);
o += ch.length;
}
return out.map((x) => x - out[0]);
}
/**
* The letters stood where the plain text's characters stand. One by one they
* lose the font's kerning, so the word turning back into text would shift on
* its last frame; a nudge each and they land exactly on it.
*/
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;
if (Math.abs(dx) > 0.01) c.style.marginLeft = `${dx}px`;
});
}
/**
* The letters both texts keep, in order: pairs of [old index, new index]. What
* they share at the start and at the end stays together; in between, the
* longest run of letters in common (a longest common subsequence).
*/
export function kept(a: string[], b: string[]): [number, number][] {
let p = 0;
while (p < a.length && p < b.length && a[p] === b[p]) p++;
let q = 0;
while (q < a.length - p && q < b.length - p && a[a.length - 1 - q] === b[b.length - 1 - q]) q++;
const A = a.slice(p, a.length - q);
const B = b.slice(p, b.length - q);
const L = Array.from({ length: A.length + 1 }, () => new Array<number>(B.length + 1).fill(0));
for (let i = A.length - 1; i >= 0; i--)
for (let j = B.length - 1; j >= 0; j--) L[i][j] = A[i] === B[j] ? L[i + 1][j + 1] + 1 : Math.max(L[i + 1][j], L[i][j + 1]);
const out: [number, number][] = [];
for (let i = 0; i < p; i++) out.push([i, i]);
for (let i = 0, j = 0; i < A.length && j < B.length; ) {
if (A[i] === B[j]) out.push([p + i++, p + j++]);
else if (L[i + 1][j] >= L[i][j + 1]) i++;
else j++;
}
for (let k = q; k > 0; k--) out.push([a.length - k, b.length - k]);
return out;
}
/** A morph under way on `el` ends where it was going: its words as plain text. */
function finish(el: HTMLElement) {
const r = runs.get(el);
if (!r) return;
clearTimeout(r.timer);
runs.delete(el);
el.getAnimations().forEach((a) => a.cancel());
el.classList.remove('mt', 'mt-ib');
el.textContent = r.text;
}
/** Plain, at once: a morph under way on `el` stops where it is going. */
export function setText(el: HTMLElement, text: string) {
finish(el);
el.textContent = text;
}
export interface MorphOpts {
/** The words change as a whole instead: the old blur away where they stood as the new come in. */
whole?: boolean;
/** false where something else moves what follows (a width gliding inside a wrapping list would reflow it mid-way). */
glide?: boolean;
/**
* Where the old words stand on screen now, when `el` no longer holds them in
* the same layout (morphInto: put back, they could wrap another way): whole
* words go from there, and the width does not glide.
*/
at?: DOMRect;
}
/**
* `el`'s text turns into `next`, letter by letter: the letters both say stay
* and slide to their new places, the others lift away or rise in. `from`: what
* it said before a repaint rebuilt it (the new element already says `next`).
* 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.
*/
export function morphText(el: HTMLElement, next: string, from = textOf(el), o: MorphOpts = {}) {
const { whole = false, at } = o;
// 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;
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) {
el.textContent = next;
return;
}
const cs = getComputedStyle(el);
// Letters need a box whose width can glide; words that change whole keep the text's own flow (they
// may wrap), and what follows them is moved by the caller (morphInto) instead.
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 at0: number[] = [];
if (!t0) {
el.textContent = from;
r0 = el.getBoundingClientRect();
t0 = wordsBox(el);
at0 = spacing(el);
}
el.textContent = next;
const r1 = el.getBoundingClientRect();
const at1 = spacing(el);
const w0 = midway ?? 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));
// Whole words wrap as they did: the old ones keep the width they took.
if (whole) old.style.width = `${t0.width + 1}px`;
el.replaceChildren(neu, old);
// 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` }], {
duration: SMOOTH.duration,
easing: SMOOTH.easing,
fill: 'forwards',
});
// The old letters go from exactly where they stood on screen, against the box as it is now: a box
// its text left empty sits lower (on the baseline), and would carry them down with it.
const r2 = el.getBoundingClientRect();
const place = (dx: number, dy: number) => {
old.style.top = `${dy}px`;
if (edge === 'end') old.style.right = `${-dx}px`;
else if (edge === 'middle') {
old.style.left = '50%';
old.style.translate = `calc(-50% + ${dx}px) 0`;
} else old.style.left = `${dx}px`;
};
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);
place(x0 + t0.left - t2.left, t0.top - r2.top + t0.top - t2.top);
if (whole) {
play(
old,
[
{ opacity: 1, filter: 'blur(0px)' },
{ opacity: 0, filter: 'blur(4px)' },
],
{ duration: 180, easing: EASE_IN, fill: 'forwards' },
);
play(
neu,
[
{ opacity: 0, filter: 'blur(4px)' },
{ opacity: 1, filter: 'blur(0px)' },
],
{ duration: 280, delay: 60, easing: EASE_OUT, fill: 'backwards' },
);
const ends = Math.max(340, glides ? SMOOTH.duration : 0) + 40;
runs.set(el, { text: next, timer: window.setTimeout(() => finish(el), ends) });
return;
}
space(neu, at1);
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[];
const now = [...neu.children] as HTMLElement[];
const pairs = 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();
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 out = was.filter((_, i) => !stays.has(i));
const inn = now.filter((_, j) => !comes.has(j));
// A long text keeps the same overall sweep: the steps shorten instead.
const so = Math.min(12, 160 / Math.max(1, out.length));
const si = Math.min(22, 260 / Math.max(1, inn.length));
out.forEach((c, i) =>
play(
c,
[
{ opacity: 1, filter: 'blur(0px)', transform: 'none' },
{ opacity: 0, filter: 'blur(4px)', transform: 'translateY(-0.45em)' },
],
{ duration: 220, delay: i * so, easing: EASE_IN, fill: 'forwards' },
),
);
inn.forEach((c, i) =>
play(
c,
[
{ opacity: 0, filter: 'blur(4px)', transform: 'translateY(0.45em)' },
{ opacity: 1, filter: 'blur(0px)', transform: 'none' },
],
{ duration: 380, delay: 120 + i * si, easing: EASE_OUT, fill: 'backwards' },
),
);
const ends =
Math.max(220 + out.length * so, inn.length ? 120 + inn.length * si + 380 : 0, glides || pairs.length ? SMOOTH.duration : 0) + 40;
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)]));
}
/** After the repaint: each keyed text that changed morphs from what it said. */
export function morphChanged(root: ParentNode, was: Map<string, string>) {
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);
});
}
/** What a box shows, piece by piece, keyed by where each sits (child indexes): its kind, its words, its drawing, its place. */
interface Piece {
kind: string;
text: string;
svg: string;
at: DOMRect | null;
/** Where its words stand (a morph under way: the words it is turning into). */
words: DOMRect | null;
node: Node;
}
/** 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');
function pieces(box: Element): Map<string, Piece> {
const out = new Map<string, Piece>();
const walk = (n: Node, path: string) =>
n.childNodes.forEach((c, i) => {
const p = `${path}/${i}`;
if (c.nodeType === Node.TEXT_NODE) {
if (c.textContent?.trim()) {
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 });
}
return;
}
if (!(c instanceof Element)) 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 });
if (!svg) walk(c, p);
});
walk(box, '');
return out;
}
/** Something with nothing to change from comes in through a blur. */
const appear = (el: Element) =>
play(
el,
[
{ opacity: 0, filter: 'blur(4px)' },
{ opacity: 1, filter: 'blur(0px)' },
],
{ duration: 280, delay: 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.
*/
export function morphInto(box: HTMLElement, kids: Kid) {
const was = pieces(box);
const box0 = box.getBoundingClientRect();
put(box, kids);
if (!was.size || calm()) 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][] = [];
const seen = new Set<string>();
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]);
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. */
const glideFrom = (el: Element, at: DOMRect, carried: [number, number]): [number, number] => {
const r = el.getBoundingClientRect();
const dx = at.left - box0.left - (r.left - box1.left);
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 });
return [dx, dy];
};
const walk = (n: Node, path: string, carried: [number, number]) =>
[...n.childNodes].forEach((c, i) => {
const p = `${path}/${i}`;
seen.add(p);
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;
// 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 (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),
);
return;
}
if (!(c instanceof Element)) return;
const r = c.getBoundingClientRect();
if (!w || w.kind !== kindOf(c) || (w.at && Math.abs(w.at.height - r.height) > 1 && !(c instanceof SVGElement)))
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));
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),
);
return;
}
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]);
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');
};
}
}
/** The Android robot's head; its eyes take the colour of what it sits on. */
const ANDROID =
'<svg class="i" viewBox="0 0 24 24" aria-hidden="true"><path d="M2.5 19a9.5 9.5 0 0 1 19 0z" fill="currentColor"/>' +
'<path d="M6.9 11.2 4.6 7.4M17.1 11.2l2.3-3.8" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round"/>' +
'<circle class="eye" cx="8.3" cy="15" r="1.25"/><circle class="eye" cx="15.7" cy="15" r="1.25"/></svg>';
const marks = (): Element[] => [ic('apple'), markup(ANDROID)];
/** One step of a path, cut where iOS and Android word it differently: [what comes before, iOS word, Android word, what comes after]. */
type Step = [string, string, string, string];
function cut(ios: string, android: string): Step {
if (ios === android) return ['', ios, ios, ''];
const A = ios.split(' ');
const B = android.split(' ');
let p = 0;
while (p < A.length && p < B.length && A[p] === B[p]) p++;
let q = 0;
while (q < A.length - p && q < B.length - p && A[A.length - 1 - q] === B[B.length - 1 - q]) q++;
const pre = A.slice(0, p).join(' ');
const suf = A.slice(A.length - q).join(' ');
return [pre ? `${pre} ` : '', A.slice(p, A.length - q).join(' '), B.slice(p, B.length - q).join(' '), suf ? ` ${suf}` : ''];
}
export interface MenuLine {
el: HTMLElement;
/** Another app's path in its place: each part morphs, the arrows stay, the system's mark comes or goes. */
set(ios: string, android: string): void;
}
/**
* A menu path ("+ → Create from QR code") for both phone systems in one line,
* its steps in bold with grey arrows between them. Where iOS and Android word a
* step differently, that word turns between the two every few seconds, the
* system's mark beside it.
*/
export function menuLine(ios: string, android: string): MenuLine {
const body = h('span', { 'aria-hidden': 'true' });
const el = h('b', { class: 'osm', role: 'text' }, body);
let steps: Step[] = [];
let parts: { pre: HTMLElement; word: HTMLElement; suf: HTMLElement }[] = [];
/** The step that differs (its mark stands before its word), or -1. */
let at = -1;
let icEl: HTMLElement | null = null;
/** Which system's wording shows: 0 iOS, 1 Android. */
let k = 0;
const wordOf = (s: Step) => (k ? s[2] : s[1]);
const part = (t: string) => h('span', { class: 'osm-p' }, t);
/** Drawn afresh, no motion (the first time, or a path with another number of steps). */
const draw = () => {
at = steps.findIndex((s) => s[1] !== s[2]);
if (at < 0) k = 0;
parts = steps.map((s) => ({ pre: part(s[0]), word: part(wordOf(s)), suf: part(s[3]) }));
icEl = at >= 0 ? h('span', { class: 'osm-ic' }, marks()[k]) : null;
body.replaceChildren(
...parts
.flatMap((p, i) => [i ? h('span', { class: 'arr' }, '›') : null, p.pre, i === at ? icEl : null, p.word, p.suf])
.filter((n): n is HTMLElement => !!n),
);
};
const MARK = { width: '1.05em', marginRight: '0.25em' };
const markOut = (m: HTMLElement) =>
(play(
m,
[
{ opacity: 1, filter: 'blur(0px)', ...MARK },
{ opacity: 0, filter: 'blur(3px)', width: '0px', marginRight: '0px' },
],
{ duration: 220, easing: EASE_IN, fill: 'forwards' },
).onfinish = () => m.remove());
const markIn = (m: HTMLElement) =>
play(
m,
[
{ opacity: 0, filter: 'blur(3px)', width: '0px', marginRight: '0px' },
{ opacity: 1, filter: 'blur(0px)', ...MARK },
],
{ duration: SMOOTH.duration, easing: SMOOTH.easing },
);
const set = (i: string, a: string) => {
el.setAttribute('aria-label', (i === a ? i : `${i} (Android: ${a.split(' → ').pop()})`).replace(/ → /g, ' › '));
const I = i.split(' → ');
const A = a.split(' → ');
const next = I.map((s, n) => cut(s, A[n] ?? s));
if (!parts.length || next.length !== steps.length) {
steps = next;
return draw();
}
const was = at;
steps = next;
at = steps.findIndex((s) => s[1] !== s[2]);
if (at < 0) k = 0;
// Another app's path: each part blurs from the old words into the new (the system's turn morphs, below).
steps.forEach((s, n) => {
morphText(parts[n].pre, s[0], undefined, { whole: true });
morphText(parts[n].word, wordOf(s), undefined, { whole: true });
morphText(parts[n].suf, s[3], undefined, { whole: true });
});
if (at === was) return;
if (icEl) markOut(icEl);
icEl = at >= 0 ? h('span', { class: 'osm-ic' }, marks()[k]) : null;
if (icEl) {
parts[at].word.before(icEl);
markIn(icEl);
}
};
set(ios, android);
// The other system's wording, every few seconds: its word morphs, its mark turns in.
const turn = () => {
if (!el.isConnected) return clearInterval(timer);
// Not on screen (a folded row): wait for the next turn.
if (at < 0 || !icEl || !el.offsetParent) return;
k = 1 - k;
morphText(parts[at].word, wordOf(steps[at]));
const oi = icEl.firstElementChild as Element;
const ni = marks()[k];
if (calm()) {
oi.replaceWith(ni);
return;
}
icEl.appendChild(ni);
play(
oi,
[
{ opacity: 1, filter: 'blur(0px)', transform: 'none' },
{ opacity: 0, filter: 'blur(3px)', transform: 'scale(.5) rotate(-40deg)' },
],
{ duration: 200, easing: EASE_IN, fill: 'forwards' },
).onfinish = () => oi.remove();
play(
ni,
[
{ opacity: 0, filter: 'blur(3px)', transform: 'scale(.5) rotate(40deg)' },
{ opacity: 1, filter: 'blur(0px)', transform: 'none' },
],
{ duration: POP.duration, delay: 80, easing: POP.easing, fill: 'backwards' },
);
};
const timer = window.setInterval(turn, 3000);
return { el, set };
}
+125
View File
@@ -0,0 +1,125 @@
// The icon picker (the apps): icons only, the picked one widens and shows its
// name. The pill stretches like skiper21's tabs: its leading edge reaches the
// new item first and the trailing edge follows, so the name fading in is always
// inside it. Items grow by flex-grow (a share of the track, not pixels), so
// they stay right while the sheet around them changes width.
import { h, ic } from '../dom';
import { EASE_OUT, LEAD, SMOOTH, calm, play } from '../motion';
export interface SegItem<T extends string> {
value: T;
label: string;
icon: string;
}
export interface IconSeg<T extends string> {
el: HTMLElement;
/** Show this value without telling anyone (another copy of the picker changed it). */
sync(v: T): void;
}
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);
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) },
ic(it.icon),
h('span', { class: 'seg-l' }, it.label),
);
b.dataset.v = it.value;
el.appendChild(b);
return b;
});
const labelOf = (b: HTMLElement) => b.querySelector('.seg-l') as HTMLElement;
const mark = () =>
btns.forEach((b) => {
const on = b.dataset.v === value;
b.classList.toggle('on', on);
b.setAttribute('aria-selected', String(on));
});
const edges = (): [number, number] | null => {
const b = btns.find((x) => x.dataset.v === value);
return b && b.offsetWidth ? [b.offsetLeft, el.clientWidth - b.offsetLeft - b.offsetWidth] : null;
};
const placePill = () => {
const e = edges();
if (!e) return;
pill.style.left = `${e[0]}px`;
pill.style.right = `${e[1]}px`;
};
let raf = 0;
function pick(v: T) {
if (v === value) return;
const from = btns.findIndex((b) => b.dataset.v === value);
const to = btns.findIndex((b) => b.dataset.v === v);
const cs = getComputedStyle(pill);
const l0 = parseFloat(cs.left) || 0;
const r0 = parseFloat(cs.right) || 0;
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()));
value = v;
mark();
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 });
});
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;
const t0 = performance.now();
const end = Math.max(SMOOTH.duration, lead.duration);
const eL = right ? SMOOTH : lead;
const eR = right ? lead : SMOOTH;
cancelAnimationFrame(raf);
const step = () => {
const t = calm() ? end : performance.now() - t0;
const e = edges();
if (!e) {
raf = 0;
return;
}
pill.style.left = `${l0 + (e[0] - l0) * eL.at(t)}px`;
pill.style.right = `${r0 + (e[1] - r0) * eR.at(t)}px`;
raf = t < end ? requestAnimationFrame(step) : 0;
if (!raf) placePill();
};
raf = requestAnimationFrame(step);
onPick(v);
}
mark();
new ResizeObserver(() => {
if (!raf) placePill();
}).observe(el);
return {
el,
sync(v) {
if (v === value) return;
value = v;
mark();
placePill();
},
};
}
+477
View File
@@ -0,0 +1,477 @@
// 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
// 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.
import { h, ic } from '../dom';
import { BOUNCY, DRAWER, EASE_IN, EASE_OUT, SMOOTH, SOFT, dismisses, play, rubber } from '../motion';
import { closeMenu } from './menu';
/** A view: its root, and what the sheet reads from it. */
export interface View {
el: HTMLElement;
/** The sheet's accessible name while this view shows (its title). */
label: string;
/** A question (Remove, Reconnect): an alert dialog. */
asks?: boolean;
/** Its own buttons, pinned beside × while it shows. */
acts?: HTMLElement | null;
}
export type ViewFactory = () => View;
let root: HTMLElement;
let scrim: HTMLElement;
let sheetEl: HTMLElement;
let closeBtn: HTMLElement;
let actsEl: HTMLElement;
let scroller: HTMLElement;
let vp: HTMLElement;
let stack: ViewFactory[] = [];
let closed: (() => void) | null = null;
let left: (() => void) | null = null;
let ownsHistory = false;
let returnFocus: HTMLElement | null = null;
export const sheetOpen = () => !!root?.classList.contains('open');
/* ---------- width: a dense code scans from a screen at about 3 px a module ---------- */
const SHEET_W = 400;
const QR_PAD = 80;
// 3.2 px a module: 6–7 device pixels on a retina screen, still a sure read for a phone camera.
const PX_PER_MODULE = 3.2;
/** A computer, or a tablet held wide: the sheet is a dialog in the middle (sheet.css), and may widen for a dense code. */
const wide = () => matchMedia('(min-width: 760px)').matches;
let sheetW = SHEET_W;
let shownQr: HTMLElement | null = null;
export interface WidthPlan {
from: number;
want: number;
reveal: HTMLElement | null;
}
/**
* 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.
*/
export function planWidth(): WidthPlan | null {
if (!root || !sheetOpen()) return null;
if (!wide()) {
if (sheetEl.style.maxWidth) sheetEl.style.maxWidth = '';
sheetW = SHEET_W;
return null;
}
const qr = [...vp.querySelectorAll<HTMLElement>('.qrbox.dense')].find((b) => {
const row = b.closest('.acc-row');
return b.offsetWidth && (!row || row.classList.contains('open')) && !b.closest('.leaving');
});
let want = SHEET_W;
if (qr) {
// The code itself fits the screen; the rest of the sheet may scroll around it.
const room = Math.min(innerWidth - 32 - QR_PAD, innerHeight - 120);
want = Math.max(SHEET_W, Math.round(Math.min(+(qr.dataset.mods ?? 0) * PX_PER_MODULE, room) + QR_PAD));
}
const reveal = qr && qr !== shownQr ? qr : null;
shownQr = qr ?? 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());
sheetEl.style.maxWidth = `${want}px`;
return { from, want, reveal };
}
export function startWidth(p: WidthPlan | null) {
if (!p) return;
if (Math.abs(p.from - p.want) > 1)
play(sheetEl, [{ maxWidth: `${p.from}px` }, { maxWidth: `${p.want}px` }], { duration: SMOOTH.duration, easing: SMOOTH.easing });
// The code has to be on screen whole: scroll it into view once the sheet has its size.
const q = p.reveal;
if (q)
setTimeout(() => {
if (!q.isConnected) return;
const a = scroller.getBoundingClientRect();
const b = q.getBoundingClientRect();
const d = b.bottom > a.bottom - 16 ? b.bottom - a.bottom + 16 : b.top < a.top + 16 ? b.top - a.top - 16 : 0;
if (d) scroller.scrollBy({ top: d, behavior: 'smooth' });
}, BOUNCY.duration);
}
/* ---------- the drawer ---------- */
function build() {
closeBtn = h('button', { type: 'button', class: 'knob x', 'aria-label': 'Close', onclick: () => closeSheet() }, ic('x'));
actsEl = h('div', { class: 'sheet-acts' });
vp = h('div', { class: 'vp' });
scroller = h('div', { class: 'sheet-scroll' }, vp);
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);
document.body.appendChild(root);
new ResizeObserver(() => startWidth(planWidth())).observe(vp);
pullToClose();
}
function label(v: View) {
sheetEl.setAttribute('aria-label', v.label);
sheetEl.setAttribute('role', v.asks ? 'alertdialog' : 'dialog');
}
/** The view being left (a new one, or the sheet closing) lets go of what it holds. */
function leave() {
const f = left;
left = null;
f?.();
}
/** What the current view holds and must stop (a poll): called when it is left. */
export function onLeave(fn: () => void) {
left = fn;
}
/** After this sheet closes (once). */
export function onClosed(fn: () => void) {
closed = fn;
}
export function openSheet(factory: ViewFactory) {
if (!root) build();
closeMenu(true);
leave();
if (sheetOpen()) {
// Already open: the new flow takes the place of the old one, history and all.
stack = [factory];
swapView(factory());
return;
}
returnFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null;
stack = [factory];
closed = null;
sheetW = SHEET_W;
shownQr = null;
sheetEl.style.maxWidth = '';
sheetEl.classList.remove('arrived');
const v = factory();
vp.replaceChildren(v.el);
setActs(v, false);
label(v);
root.classList.add('open');
root.setAttribute('aria-hidden', 'false');
document.body.classList.add('locked');
const p0 = planWidth();
if (p0) startWidth({ ...p0, from: p0.want });
sheetEl.getAnimations().forEach((a) => a.cancel());
scrim.getAnimations().forEach((a) => a.cancel());
sheetEl.style.transform = '';
// A dialog comes up from its centre the way a ⋯ menu pops (menu.ts), on a softer spring; the drawer rises from the bottom edge.
if (wide())
play(
sheetEl,
[
{ opacity: 0, transform: 'scale(.9)', filter: 'blur(4px)' },
{ opacity: 1, transform: 'none', filter: 'none' },
],
{ duration: SOFT.duration, easing: SOFT.easing },
);
else play(sheetEl, [{ transform: 'translateY(calc(100% + 40px))' }, { transform: 'none' }], { duration: 500, easing: DRAWER });
// The dim behind keeps time with the sheet: with the dialog's pop on a computer, with the drawer's rise on a phone.
play(
scrim,
[{ opacity: 0 }, { opacity: 1 }],
wide() ? { duration: SOFT.duration, easing: SOFT.easing } : { duration: 420, easing: 'ease-out' },
);
if (!ownsHistory) {
try {
history.pushState({ sheet: true }, '');
ownsHistory = true;
} catch {
/* no history */
}
}
}
/** `now`: gone at once (Escape: what the keyboard does never animates). */
export function closeSheet(now = false) {
if (!sheetOpen() || root.dataset.closing) 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();
root.dataset.closing = '1';
const from = getComputedStyle(sheetEl).transform;
sheetEl.getAnimations().forEach((a) => a.cancel());
play(
scrim,
[{ opacity: getComputedStyle(scrim).opacity }, { 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: 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;
}
// The phone's back button closes the sheet instead of leaving the page.
addEventListener('popstate', () => {
if (!sheetOpen()) return;
ownsHistory = false;
closeSheet();
});
/** 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) {
const neu = v.acts ?? null;
const old = actsEl.firstElementChild as HTMLElement | null;
if (neu === old) return;
// No motion asked, or the same buttons for a rebuilt view: swapped in place.
if (!anim || (old && neu && old.dataset.key === neu.dataset.key)) return actsEl.replaceChildren(...(neu ? [neu] : []));
if (old) {
Object.assign(old.style, { position: 'absolute', right: '0', top: '0', pointerEvents: 'none' });
play(
old,
[
{ opacity: 1, transform: 'none', filter: 'none' },
{ opacity: 0, transform: 'scale(.9)', filter: 'blur(3px)' },
],
{
duration: 180,
easing: 'cubic-bezier(.2,0,0,1)',
fill: 'forwards',
},
).onfinish = () => old.remove();
}
if (neu) {
actsEl.appendChild(neu);
play(
neu,
[
{ opacity: 0, transform: 'scale(.9)', filter: 'blur(3px)' },
{ opacity: 1, transform: 'none', filter: 'none' },
],
{
duration: 260,
delay: 110,
easing: 'cubic-bezier(.2,0,0,1)',
fill: 'backwards',
},
);
}
}
/** 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) => {
o.classList.add('leaving');
Object.assign(o.style, { position: 'absolute', left: '0', right: '0', top: '0', pointerEvents: 'none' });
o.inert = true;
});
vp.appendChild(v.el);
// A tap that lands where the new view's button appears must not press it.
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()),
);
play(
v.el,
[
{ opacity: 0, transform: 'scale(.96)', filter: 'blur(4px)' },
{ opacity: 1, transform: 'none', filter: 'none' },
],
{
duration: 280,
delay: 110,
easing: 'cubic-bezier(.2,0,0,1)',
fill: 'backwards',
},
);
}
/** Further into a flow (Add → Open on the device). */
export function go(factory: ViewFactory) {
if (!sheetOpen()) return openSheet(factory);
leave();
stack.push(factory);
swapView(factory());
}
export function back() {
if (stack.length < 2) return;
leave();
stack.pop();
swapView(stack[stack.length - 1]());
}
/**
* Content inside the open sheet changed: it glides to its new height, what
* stayed but moved (a block above it grew or shrank) glides to its new place,
* the changed blocks come into focus.
*/
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;
const was = new Map<Element, DOMRect>();
view?.querySelectorAll('*').forEach((e) => {
if (!(e instanceof SVGElement) || e instanceof SVGSVGElement) was.set(e, e.getBoundingClientRect());
});
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.
const moved = new Set<Element>();
for (const [e, r] of was) {
if (!e.isConnected || !r.width || !r.height) continue;
const n = e.getBoundingClientRect();
if (!n.width || !n.height) continue;
const dx = r.left - n.left;
const dy = r.top - n.top;
if (Math.abs(dx) < 0.5 && Math.abs(dy) < 0.5) continue;
moved.add(e);
// Once, on the outermost that moved: what it holds moves with it.
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 });
}
for (const el of focus)
if (el)
play(
el,
[
{ opacity: 0, filter: 'blur(4px)' },
{ opacity: 1, filter: 'none' },
],
{ duration: 280, easing: EASE_OUT },
);
}
/** 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 sheet scrolls back to the top (a device connected under a scrolled sheet). */
export const scrollTop = () => scroller?.scrollTo({ top: 0, behavior: 'smooth' });
/** Is this element in the sheet that shows now (not one being swapped out)? */
export const showing = (el: Element) => sheetOpen() && vp.contains(el) && !el.closest('.leaving');
/* ---------- pull down by the header to close ---------- */
function pullToClose() {
let drag: { y: number; t: number; dy: number; v: 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 };
sheetEl.setPointerCapture(e.pointerId);
});
sheetEl.addEventListener('pointermove', (e) => {
if (!drag) return;
const raw = e.clientY - drag.y;
const t = performance.now();
// Down follows the finger; up resists, more the further it goes.
const dy = raw > 0 ? raw : -rubber(-raw, sheetEl.offsetHeight);
drag.v = (dy - drag.dy) / Math.max(1, t - drag.t);
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));
});
const end = () => {
if (!drag) return;
const { dy, v } = drag;
drag = null;
if (dismisses(dy, v, sheetEl.offsetHeight)) return closeSheet();
const from = sheetEl.style.transform;
sheetEl.style.transform = '';
scrim.style.opacity = '';
if (dy !== 0) play(sheetEl, [{ transform: from }, { transform: 'none' }], { duration: SMOOTH.duration, easing: SMOOTH.easing });
};
sheetEl.addEventListener('pointerup', end);
sheetEl.addEventListener('pointercancel', end);
}
/* ---------- the parts every view is made of ---------- */
/** A view's head: its title (and Back, inside a flow). */
export function head(title: string, o: { back?: boolean; acts?: boolean } = {}): HTMLElement {
return h(
'div',
{ class: `vhead${o.back ? ' center' : ''}${o.acts ? ' with-acts' : ''}` },
o.back ? h('button', { type: 'button', class: 'knob back', 'aria-label': 'Back', onclick: back }, ic('chevron')) : null,
h('h2', {}, title),
);
}
/** The line under a view's title. */
export const sub = (text: string) => h('p', { class: 'vsub' }, text);
/** A small line of help. */
export const hint = (...kids: (Node | string | null)[]) => h('p', { class: 'hint' }, ...kids);
-60
View File
@@ -1,60 +0,0 @@
// The set-up sheets' "waiting for the first connection" card: the way from
// the device (its icon; the sheet's title names it) to the home server, a light
// running along its dots while the page waits; the dots fill green when it connects.
// It only draws and switches its states; main.ts (watchFirstConnection)
// decides when, and what leaves around it. A live region: the changes are read out.
import type { Kind } from '../shared/types';
import { h, ic } from './dom';
import { grow, replay } from './motion';
export interface Way {
el: HTMLElement;
/** The first connection arrived. */
connected(): void;
/** The page stopped asking (ten minutes): say so instead of waiting on forever. */
gaveUp(): void;
}
export function waitPath(kind: Kind): Way {
const title = h('span', { class: 'strong s' }, 'Waiting for the connection');
// Nothing to add while it waits: the line comes with "You're all set" or the give-up.
const sub = h('span', { class: 'faint s' });
// The router end: the server's icon, as on the admin's map.
const home = h('span', { class: 'way-end home' }, ic('server'));
const el = h(
'div',
{ class: 'way', role: 'status', 'aria-live': 'polite' },
h(
'div',
{ class: 'way-row' },
h('span', { class: 'way-end' }, ic(kind)),
h('span', { class: 'way-track' }, h('span', { class: 'way-glow' }, h('i')), h('span', { class: 'way-fill' })),
home,
),
h('div', { class: 'way-text' }, title, sub),
);
const say = (t: string, s: string) => {
if (title.textContent !== t) {
title.textContent = t;
replay(title, 'swap');
}
if (sub.textContent === s) return;
// The line under the title only appears now: it opens rather than pushing the card.
const opens = !sub.textContent;
sub.textContent = s;
if (opens) grow(sub);
else replay(sub, 'swap');
};
return {
el,
connected: () => {
el.classList.add('done');
say('Connected', 'You’re all set.');
},
gaveUp: () => {
el.classList.add('stopped');
say('No connection yet', 'Close this and open it again to keep checking.');
},
};
}