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

+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);