Dawnline 0.14.0
Build packages / CI (push) Blocked by required conditions
Build packages / Version (push) Waiting to run
CI / Web (format, types, tests, bundles) (push) Blocked by required conditions
CI / ShellCheck (push) Blocked by required conditions
CI / ucode static checks (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 24.10) (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 25.12) (push) Blocked by required conditions

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

No files matched your search

+122 -27
View File
@@ -3,8 +3,12 @@
// and its own corners. One row open at a time. A row with nothing to open is a
// plain head: no chevron, no click. Inside the sheet it tells the sheet first,
// so a code that comes into view gets its width. A row the person opens is
// `.opened` until it closes: what enters inside it (the calendar's days) keys on
// that, so a repaint that rebuilds the row open doesn't play it again.
// `.opened` until it has shut: what enters inside it (the calendar's days) keys
// on that, so a repaint that rebuilds the row open doesn't play it again, and a
// row opened again before it has shut carries on. A click mid-way (a double
// click) turns every row and body back from where it stands, and a row around
// them glides on with them (`regrow`, which the set-up sheet also uses when a
// pick changes a row still opening); the sheet follows its view by itself.
import { h, ic } from '../dom';
import { EASE_IN, SOFT, play } from '../motion';
@@ -41,9 +45,79 @@ const PROPS = [
'borderBottomRightRadius',
] as const;
/** A body not showing (display: none) stands where an opening one starts. */
const HIDDEN: Keyframe = { opacity: 0, filter: 'blur(2px)' };
/** A body's new fade takes over from the one under way, which stops once the new one is in place. */
function fade(body: HTMLElement, frames: Keyframe[], o: KeyframeAnimationOptions) {
const old = body.getAnimations();
play(body, frames, o);
old.forEach((a) => a.cancel());
}
/** What a keyframe holds besides the properties it animates. */
const META = new Set(['offset', 'computedOffset', 'easing', 'composite']);
const kebab = (p: string) => p.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`);
/**
* Content changed under a glide still heading for a height it measured before
* (a row opening, a fold coming back): each element from `from` up whose
* height glides to what its content gives it carries on from where it stands
* to what its content gives it now, on its own curve, so it neither clips what
* grew nor jumps when the glide ends. A row closing (its height is its head's,
* not its content's) or a fold shutting keeps its end. Called with what changed
* in its end shape, before that moves. The heights are taken at the sheet's end
* width (a dense code widening it).
*/
export function regrow(...from: (Element | null | undefined)[]) {
const runs: { el: HTMLElement; a: Animation; t: CSSNumberish | null; cur: Keyframe; to: Keyframe }[] = [];
const widths: { a: Animation; t: CSSNumberish | null }[] = [];
const seen = new Set<Element>();
for (const start of from)
for (let el: Element | null | undefined = start; el && !seen.has(el); el = el.parentElement) {
seen.add(el);
if (!(el instanceof HTMLElement) || el.classList.contains('closing')) continue;
for (const a of el.getAnimations()) {
const ks = a.playState === 'running' && a.effect instanceof KeyframeEffect ? a.effect.getKeyframes() : [];
const end = ks[ks.length - 1];
if (end && ('width' in end || 'maxWidth' in end)) widths.push({ a, t: a.currentTime });
if (!end?.height || end.height === '0px') continue;
const cs = getComputedStyle(el);
const cur: Keyframe = {};
const to: Keyframe = {};
for (const p of Object.keys(end))
if (!META.has(p)) {
cur[p] = cs.getPropertyValue(kebab(p));
to[p] = end[p];
}
runs.push({ el, a, t: a.currentTime, cur, to });
}
}
if (!runs.length) return;
// Measured with every glide lifted, the widths too; those not aimed anew go on from where they were.
[...runs, ...widths].forEach((r) => r.a.cancel());
const ends = runs.map((r) => getComputedStyle(r.el).height);
for (const w of widths) {
w.a.play();
w.a.currentTime = w.t;
}
runs.forEach((r, i) => {
r.a.play();
// Its content gives it the height it was heading for: it carries on as it was.
if (Math.abs(parseFloat(ends[i]) - parseFloat(String(r.to.height))) < 0.5) r.a.currentTime = r.t;
else (r.a.effect as KeyframeEffect).setKeyframes([r.cur, { ...r.to, height: ends[i] }]);
});
}
export function accordion(
items: AccItem[],
o: { inset?: boolean; open?: number; onToggle?: (i: number, open: boolean, instant: boolean) => void } = {},
o: {
inset?: boolean;
open?: number;
onToggle?: (i: number, open: boolean, instant: boolean) => void;
/** On the page: holds its height as a click reshapes the rows; what it returns lets go once their new shape is measured. */
hold?: () => () => void;
} = {},
): Accordion {
const acc = h('div', { class: `acc${o.inset ? ' inset' : ''}` });
const rows = items.map((it, i) => {
@@ -87,43 +161,57 @@ export function accordion(
};
const aria = () =>
rows.forEach((x) => x.querySelector('button.acc-head')?.setAttribute('aria-expanded', String(x.classList.contains('open'))));
/** A row shows its body while open and while it closes (`.closing`). */
const shows = (x: HTMLElement) => x.classList.contains('open') || x.classList.contains('closing');
/** Where a body's fade stands now, mid-fade included. */
const faded = (x: HTMLElement): Keyframe => {
if (!shows(x)) return HIDDEN;
const cs = getComputedStyle(bodyOf(x));
return { opacity: cs.opacity, filter: cs.filter === 'none' ? 'blur(0px)' : cs.filter };
};
function toggle(r: HTMLElement) {
const before = rows.map(read);
const fades = rows.map(faded);
const release = o.hold?.();
rows.forEach((x) => x.getAnimations().forEach((a) => a.cancel()));
rows.forEach((x) =>
bodyOf(x)
.getAnimations()
.forEach((a) => a.cancel()),
);
const willOpen = !r.classList.contains('open');
const closing = rows.filter((x) => x.classList.contains('open') && (x === r || willOpen));
// Every row showing its body shuts, still closing from a click before included, but the one that opens.
const closing = rows.filter((x) => shows(x) && !(x === r && willOpen));
rows.forEach((x) => {
x.classList.remove('closing');
if (x !== r) x.classList.remove('open', 'opened');
if (x !== r) x.classList.remove('open');
});
r.classList.toggle('open', willOpen);
r.classList.toggle('opened', willOpen);
if (willOpen) r.classList.add('opened');
corners();
const plan = planWidth();
const after = rows.map(read);
release?.();
// The row this accordion sits in glides on to its new height with them (the sheet follows its view by itself).
regrow(acc.parentElement);
rows.forEach((x, i) => {
const after = read(x);
if (!PROPS.some((p) => before[i][p] !== after[p])) return;
// Shut: what enters inside it plays again the next time it opens.
const shut = () => {
x.classList.remove('closing');
if (!x.classList.contains('open')) x.classList.remove('opened');
};
if (!PROPS.some((p) => before[i][p] !== after[i][p])) return shut();
if (closing.includes(x)) x.classList.add('closing');
play(x, [before[i], after], { duration: SOFT.duration, easing: SOFT.easing }).onfinish = () => x.classList.remove('closing');
play(x, [before[i], after[i]], { duration: SOFT.duration, easing: SOFT.easing }).onfinish = shut;
});
closing.forEach((x) =>
play(bodyOf(x), [{ opacity: 1 }, { opacity: 0, filter: 'blur(2px)' }], { duration: 160, easing: EASE_IN, fill: 'forwards' }),
);
if (willOpen)
play(
bodyOf(r),
[
{ opacity: 0, filter: 'blur(2px)' },
{ opacity: 1, filter: 'blur(0px)' },
],
{ duration: 300, easing: 'cubic-bezier(0,0,.58,1)' },
);
// Each body fades on from where it stands (a double click turns it back), over what is left of its way.
closing.forEach((x) => {
const f = fades[rows.indexOf(x)];
fade(bodyOf(x), [f, { opacity: 0, filter: 'blur(2px)' }], { duration: 160 * Number(f.opacity), easing: EASE_IN, fill: 'forwards' });
});
if (willOpen) {
const f = fades[rows.indexOf(r)];
fade(bodyOf(r), [f, { opacity: 1, filter: 'blur(0px)' }], {
duration: 300 * (1 - Number(f.opacity)),
easing: 'cubic-bezier(0,0,.58,1)',
});
}
startWidth(plan);
aria();
o.onToggle?.(rows.indexOf(r), willOpen, false);
@@ -134,7 +222,14 @@ export function accordion(
el: acc,
openIndex: () => rows.findIndex((x) => x.classList.contains('open')),
setOpen(i) {
rows.forEach((x, k) => x.classList.toggle('open', k === i && !x.classList.contains('still')));
rows.forEach((x, k) => {
// Without motion: whatever was under way stops where it was going.
[x, bodyOf(x)].forEach((e) => e.getAnimations().forEach((a) => a.cancel()));
const open = k === i && !x.classList.contains('still');
x.classList.toggle('open', open);
x.classList.remove('closing');
if (!open) x.classList.remove('opened');
});
corners();
aria();
rows.forEach((x, k) => o.onToggle?.(k, x.classList.contains('open'), true));
+69
View File
@@ -0,0 +1,69 @@
// The red line under a name field (Add a device, Rename): why the name is refused, the router's word or the
// field's own as it is typed (shared/name-guard.ts). It comes and goes without the sheet snapping: in, it rises in
// as the sheet glides open; out, it blurs away first, then the sheet glides shut. Either way it turns back from
// where it stands on screen. A view already swapped out (the answer came late) changes alone: the sheet's height is
// the new view's. Another reason while it shows: its words change in place.
import { h } from '../dom';
import { EASE_IN, EASE_OUT, play } from '../motion';
import { morphText, setText, textOf } from './morph';
import { glide, showing } from './sheet';
/** Away and shown. */
const GONE: Keyframe = { opacity: 0, transform: 'translateY(-4px)', filter: 'blur(4px)' };
const SHOWN: Keyframe = { opacity: 1, transform: 'none', filter: 'none' };
export interface BadLine {
el: HTMLElement;
say: (msg: string) => void;
unsay: () => void;
}
export function badLine(): BadLine {
const err = h('p', { class: 'hint bad-t', hidden: true });
const reflow = (change: () => void) => (showing(err) ? glide(change) : change());
let fade: Animation | null = null;
let hiding = 0;
const now = (): Keyframe => {
const s = getComputedStyle(err);
return { opacity: s.opacity, transform: s.transform, filter: s.filter };
};
// The new fade takes over from the old one once it is in place (nothing paints between).
const fadeTo = (from: Keyframe, to: Keyframe, o: KeyframeAnimationOptions) => {
const was = fade;
fade = play(err, [from, to], o);
was?.cancel();
};
const say = (msg: string) => {
if (err.hidden) {
reflow(() => {
setText(err, msg);
err.hidden = false;
});
return fadeTo(GONE, SHOWN, { duration: 220, easing: EASE_OUT });
}
// Already showing: its words change in place. On its way out, it comes back from where it stands as they do.
const from = hiding ? now() : null;
morphText(err, msg);
if (!from) return;
clearTimeout(hiding);
hiding = 0;
fadeTo(from, SHOWN, { duration: 220, easing: EASE_OUT });
};
const unsay = () => {
if (err.hidden || hiding) return;
const from = now();
// A morph under way ends where it was going: its end would cancel the fade.
setText(err, textOf(err));
fadeTo(from, GONE, { duration: 180, easing: EASE_IN, fill: 'forwards' });
hiding = window.setTimeout(() => {
hiding = 0;
reflow(() => {
err.hidden = true;
fade?.cancel();
fade = null;
});
}, 170);
};
return { el: err, say, unsay };
}
+8 -4
View File
@@ -39,14 +39,18 @@ function hand(btn: HTMLElement, next: Animation[]) {
}
export function busyOn(btn: HTMLElement) {
btn.querySelector(':scope > .orb')?.remove();
const parts = content(btn);
const from = parts.map(now);
const orb = h('span', { class: 'orb', 'aria-hidden': 'true' }, h('i'), h('i'));
btn.append(orb);
// An orb still on its way out (pressed again right after an answer) turns back from where it stands, at once.
const was = btn.querySelector<HTMLElement>(':scope > .orb');
const orb = was ?? h('span', { class: 'orb', 'aria-hidden': 'true' }, h('i'), h('i'));
if (!was) btn.append(orb);
btn.classList.add('busy');
btn.setAttribute('aria-busy', 'true');
hand(btn, [...parts.map((p, i) => play(p, [from[i], GONE], OUT)), play(orb, [ORB_GONE, SHOWN], IN)]);
hand(btn, [
...parts.map((p, i) => play(p, [from[i], GONE], OUT)),
play(orb, [was ? now(was) : ORB_GONE, SHOWN], was ? { ...IN, delay: 0 } : IN),
]);
}
export function busyOff(btn: HTMLElement) {
+270
View File
@@ -0,0 +1,270 @@
// The name fields' own caret and, with a mouse or trackpad, their own selection
// (`smoothCaret` on a `.field`). The caret glides to where the next letter goes
// and blinks as macOS draws it; a selection is an accent wash with a handle at
// each end, as iOS draws it, growing out of the caret and fading back into it.
// The input stays the browser's own (typing, IME, its native selection, made
// see-through): this only draws over it. On a touch screen the system draws its
// own selection and handles, so ours stays off and the caret steps aside while
// one shows. The look is in styles/controls.css; like the rest of the page this
// writes styles through `el.style` only (the CSP drops style attributes).
//
// Places come from a hidden mirror with the input's own font: the width of the
// text up to a position, less how far the input has scrolled. The pure parts
// (`glideStep`, `places`) are what the tests run.
import { h } from '../dom';
import { calm } from '../motion';
/** One edge that glides: where it is, how fast it moves, where it goes. */
export interface Glide {
x: number;
v: number;
t: number;
}
/** The frame the glide is tuned to, in ms. */
const FRAME = 16.67;
/**
* Move a glide on by `frames` frames (after bencho.dev's one-time code, a softer pull: per frame
* v += (t − x)·0.12, v ·= 0.62, x += v; 90% of the way in ~134 ms, about 2% over, no stretch).
* At most 2.5 frames at once; after a long gap (a hidden tab) it is simply there. False once it
* rests, then exactly on its target.
*/
export function glideStep(g: Glide, frames: number): boolean {
if (frames > 15) {
g.x = g.t;
g.v = 0;
return false;
}
const dt = Math.min(2.5, Math.max(0, frames));
g.v += (g.t - g.x) * 0.12 * dt;
g.v *= Math.pow(0.62, dt);
g.x += g.v * dt;
if (Math.abs(g.t - g.x) < 0.05 && Math.abs(g.v) < 0.05) {
g.x = g.t;
g.v = 0;
return false;
}
return true;
}
/** What an input shows now, as `places` reads it. */
export interface FieldText {
value: string;
/** The selection (equal: a caret), and which end the caret is at. */
start: number;
end: number;
backward: boolean;
/** The input's box in the field: its left edge and width, and how far its text has scrolled. */
left: number;
width: number;
scroll: number;
}
/** Where the caret and a selection's ends go, in px from the field's left edge. */
export interface Places {
caret: number;
start: number;
end: number;
/** A selection, not just a caret. */
range: boolean;
}
/**
* The places for `f`, with `measure` the width of a text in the input's font. A selection that
* runs past the input's edges (a long name, scrolled) stops at them: the wash never covers the
* go button.
*/
export function places(f: FieldText, measure: (text: string) => number): Places {
const x = (i: number) => Math.min(f.left + f.width, Math.max(f.left, f.left + measure(f.value.slice(0, i)) - f.scroll));
const start = x(f.start);
const end = f.end === f.start ? start : x(f.end);
return { caret: f.backward ? start : end, start, end, range: f.start !== f.end };
}
/** The input's font, as the mirror needs it to measure the same widths. */
const FONT = ['fontFamily', 'fontSize', 'fontWeight', 'letterSpacing', 'fontFeatureSettings', 'fontVariationSettings'] as const;
/**
* Give the input of `field` (a `.field`) the glide caret and, with a fine pointer, the selection.
* Call it once, as the field is built (it measures only once the field is on the page).
*/
export function smoothCaret(field: HTMLElement) {
const input = field.querySelector('input');
if (!input) return;
const fine = matchMedia('(pointer: fine)').matches;
field.classList.add('own-caret');
if (fine) field.classList.add('own-sel');
const wash = h('span', { class: 'caret-sel' });
const h0 = h('span', { class: 'caret-hd s' });
const h1 = h('span', { class: 'caret-hd e' });
const caret = h('span', { class: 'caret' });
const mirror = h('span', { class: 'caret-mirror', 'aria-hidden': 'true' });
field.append(wash, h0, h1, caret, mirror);
// In the field's own px: while the sheet scales in (the rename field selects its text then), the
// box on screen is smaller than the one the caret is drawn in.
const measure = (text: string) => {
mirror.textContent = text;
const shown = field.getBoundingClientRect().width;
return mirror.getBoundingClientRect().width * (shown ? field.offsetWidth / shown : 1);
};
const now = (): Places =>
places(
{
value: input.value,
start: input.selectionStart ?? 0,
end: input.selectionEnd ?? 0,
backward: input.selectionDirection === 'backward',
left: input.offsetLeft,
width: input.clientWidth,
scroll: input.scrollLeft,
},
measure,
);
const glide = (): Glide => ({ x: 0, v: 0, t: 0 });
const cur = glide();
const s0 = glide();
const s1 = glide();
const all = [cur, s0, s1];
const jump = (g: Glide, x: number) => {
g.x = g.t = x;
g.v = 0;
};
let selecting = false;
const focused = () => document.activeElement === input;
const draw = () => {
caret.style.transform = `translateX(${(cur.x - 1).toFixed(2)}px)`;
wash.style.transform = `translateX(${Math.min(s0.x, s1.x).toFixed(2)}px)`;
wash.style.width = `${Math.abs(s1.x - s0.x).toFixed(2)}px`;
h0.style.transform = `translateX(${(s0.x - 1).toFixed(2)}px)`;
h1.style.transform = `translateX(${(s1.x - 1).toFixed(2)}px)`;
};
// One loop for the three edges; it stops when all of them rest.
let raf = 0;
let last = 0;
const step = (t: number) => {
const frames = last ? (t - last) / FRAME : 1;
last = t;
let busy = false;
for (const g of all) if (glideStep(g, frames)) busy = true;
draw();
raf = busy ? requestAnimationFrame(step) : 0;
if (!raf) last = 0;
};
const follow = () => {
// Less motion: everything is where it goes at once.
if (calm()) {
all.forEach((g) => jump(g, g.t));
return draw();
}
if (!raf) raf = requestAnimationFrame(step);
};
let first = true;
let rest = 0;
let faded = 0;
let fading = false;
let pressedAt = 0;
const place = () => {
if (!focused()) {
clearTimeout(rest);
caret.classList.remove('on', 'blink');
field.classList.remove('selecting');
selecting = false;
return draw();
}
if (first) {
// Measured here, not when built: a field not on the page yet has no font to copy.
const cs = getComputedStyle(input);
for (const k of FONT) mirror.style[k] = cs[k];
}
const p = now();
if (first) {
all.forEach((g) => jump(g, p.start));
first = false;
}
if (p.range && fine) {
// Selecting: the wash grows out of where the caret is, and the caret steps aside. A wash still fading from
// the last selection turns back instead and glides from its old ends to the new ones.
if (!selecting) {
clearTimeout(faded);
if (!fading) {
s0.x = s1.x = cur.x;
s0.v = s1.v = 0;
}
fading = false;
}
selecting = true;
s0.t = p.start;
s1.t = p.end;
cur.t = p.caret;
field.classList.add('selecting');
caret.classList.remove('on', 'blink');
} else if (p.range) {
// A touch screen: the system's own selection shows.
caret.classList.remove('on', 'blink');
return;
} else {
// Collapsed: the wash fades where it stands, and its ends join the caret once it is gone.
// A click puts the caret where it was clicked at once, as macOS does; typing and the arrows glide.
if (selecting) {
field.classList.remove('selecting');
clearTimeout(faded);
fading = true;
faded = window.setTimeout(() => {
fading = false;
if (selecting) return;
jump(s0, cur.t);
jump(s1, cur.t);
draw();
}, 160);
} else if (!fading) {
jump(s0, p.start);
jump(s1, p.start);
}
selecting = false;
if (performance.now() - pressedAt < 400) jump(cur, p.caret);
else cur.t = p.caret;
// Solid while it moves or they type, blinking again half a second after.
caret.classList.add('on');
caret.classList.remove('blink');
clearTimeout(rest);
rest = window.setTimeout(() => {
if (focused()) caret.classList.add('blink');
}, 500);
}
follow();
};
// After the event: by then the browser has moved its own caret.
let queued = 0;
const soon = () => {
if (!queued)
queued = requestAnimationFrame(() => {
queued = 0;
place();
});
};
for (const ev of ['pointerdown', 'pointerup']) input.addEventListener(ev, () => (pressedAt = performance.now()));
for (const ev of ['input', 'keydown', 'keyup', 'pointerup', 'select', 'scroll']) input.addEventListener(ev, soon);
input.addEventListener('pointermove', (e) => {
if (e.buttons) soon();
});
// A selection made any other way (the keyboard's, a double click, the page's own select()).
const onSelect = () => {
if (focused()) soon();
};
input.addEventListener('focus', () => {
first = true;
document.addEventListener('selectionchange', onSelect);
soon();
});
input.addEventListener('blur', () => {
document.removeEventListener('selectionchange', onSelect);
soon();
});
}
+128 -39
View File
@@ -2,71 +2,165 @@
// link as text with Copy and Share. Codes follow the theme: the night look
// (light dots on black) on a dark one, the same dots dark on white on a light
// one, redrawn in place when the system's theme changes. A dense code (an
// AmneziaVPN key) fills its row; the sheet widens for it (ui/sheet.ts).
// AmneziaVPN key) fills its row; the sheet widens for it (ui/sheet.ts). A code
// too long for a camera gives its place to a stand-in (the device's set-up link).
import { denseQr, qrSvg } from '../../shared/qr';
import { h, ic } from '../dom';
import { EASE_IN, EASE_OUT, play } from '../motion';
import { denseQr, qrSvg, scannable } from '../../shared/qr';
import { h, ic, markup } from '../dom';
import { EASE_IN, EASE_OUT, SMOOTH, play } from '../motion';
import { placeName } from '../state';
import { copy } from './feedback';
const LIGHT = matchMedia('(prefers-color-scheme: light)');
const look = () => (LIGHT.matches ? 'day' : 'night');
function paint(box: HTMLElement, text: string) {
box.dataset.qr = text;
box.classList.toggle('dense', denseQr(text));
/** The code for `text` in the theme's look, tagged with what it says. */
function drawn(text: string): SVGSVGElement {
const svg = markup(qrSvg(text, 3, true, look())) as SVGSVGElement;
svg.dataset.qr = text;
return svg;
}
/** The box shows `svg` (or is about to): its size, and the sheet's width, follow that code. */
function holds(box: HTMLElement, svg: SVGSVGElement) {
box.dataset.qr = svg.dataset.qr;
box.classList.toggle('dense', denseQr(svg.dataset.qr!));
box.classList.toggle('light', LIGHT.matches);
box.innerHTML = qrSvg(text, 3, true, look());
// The modules across: how wide the sheet must be for a camera to read it.
box.dataset.mods = String((box.firstElementChild as SVGSVGElement | null)?.viewBox.baseVal.width ?? 0);
box.dataset.mods = String(svg.viewBox.baseVal.width);
}
export function qrBox(text: string, big = false): HTMLElement {
const box = h('div', { class: `qrbox${big ? ' big' : ''}` });
paint(box, text);
const svg = drawn(text);
box.append(svg);
holds(box, svg);
return box;
}
// Each code is redrawn in the other look where it stands: a cross-fade under way carries on.
LIGHT.addEventListener('change', () =>
document.querySelectorAll<HTMLElement>('.qrbox[data-qr]').forEach((b) => {
// Mid cross-fade a box holds two codes: the old one goes, the new one is drawn again.
b.querySelector('svg.old')?.remove();
paint(b, b.dataset.qr!);
b.querySelectorAll<SVGSVGElement>(':scope > svg[data-qr]').forEach((s) => s.replaceChildren(...drawn(s.dataset.qr!).childNodes));
b.classList.toggle('light', LIGHT.matches);
}),
);
/** Where an element's fade stands now, mid-fade included. */
function now(el: Element): Keyframe {
const s = getComputedStyle(el);
return { opacity: s.opacity, filter: s.filter === 'none' ? 'blur(0px)' : s.filter };
}
export interface CodeRow {
el: HTMLElement;
/** Another code in the same place: it comes in over the old one, which then goes; new words too, if given (else they stay, to change in place). */
swap(next: string, words?: Node[]): void;
}
/** A code and its words: side by side, or a dense code full width with the words under it. */
export function codeRow(text: string, words: Node[]): CodeRow {
const box = qrBox(text);
let shown = h('div', { class: 'words' }, words);
/** What a code row shows instead of a code a camera cannot read: another code, and words that say why (made each time it shows). */
export interface StandIn {
text: string;
words: () => Node[];
}
/**
* A code and its words: side by side, or a dense code full width with the
* words under it. With a stand-in, a code too long to scan shows the stand-in
* and its words; the row's own words come back with a code that fits.
*/
export function codeRow(text: string, words: Node[], standIn?: StandIn): CodeRow {
const instead = (t: string) => !!standIn && !scannable(t);
let own = words;
let out = instead(text);
const box = qrBox(out ? standIn!.text : text);
let shown = h('div', { class: 'words' }, out ? standIn!.words() : own);
const side = h('div', { class: 'side' }, shown);
const el = h('div', { class: `coderow${box.classList.contains('dense') ? ' stacked' : ''}` }, box, side);
/**
* Another code in the box: it comes in under the one showing, which lies over
* it and goes after it, so the place is never empty. Nothing on screen changes
* its place in the stack: the codes lie in the box in the order they paint (the
* one in flow first, under the rest). A swap under way carries on from where
* each code stands; a code turned back to fades up again where it lies, what
* lies over it going, and what lies under it goes once it shows whole. A code
* of the other size (dense or not) takes the box from its size on screen to its
* own on SMOOTH, the codes in it scaling with it, while the sheet glides the
* rest (glide() in ui/sheet.ts).
*/
let sizing: Animation | null = null;
/** The codes on their way out: a later swap leaves their fade as it is. */
const going = new WeakSet<Element>();
const cross = (code: string) => {
const svgs = [...box.querySelectorAll<SVGSVGElement>(':scope > svg')];
const op = new Map(svgs.map((s) => [s, +getComputedStyle(s).opacity]));
const cs = getComputedStyle(box);
const r0 = box.getBoundingClientRect();
// Its corners as they look now: a resize under way scales them with the box.
const round0 = parseFloat(cs.borderTopLeftRadius) * new DOMMatrix(cs.transform).a;
const neu = svgs.find((s) => s.dataset.qr === code) ?? drawn(code);
const at = svgs.indexOf(neu);
// A new code goes under them all; one still in the box stays where it lies.
if (at < 0) box.prepend(neu);
const over = svgs.slice(at + 1).filter((s) => !going.has(s));
const under = svgs.slice(0, Math.max(0, at));
const fades = [neu, ...over].flatMap((s) => s.getAnimations());
going.delete(neu);
holds(box, neu);
el.classList.toggle('stacked', box.classList.contains('dense'));
const o0 = op.get(neu) ?? 0;
play(neu, [{ opacity: o0 }, { opacity: 1 }], { duration: 200 * (1 - o0), easing: EASE_OUT }).onfinish = () => {
// Whole: what lies under it, hidden now, goes, and it takes the box's flow under what still fades over it.
under.forEach((s) => s.remove());
neu.classList.remove('old');
};
// What lies over it goes from how it shows, where it lies (the code that showed, over the new one); one already going goes on.
over.forEach((s) => {
s.classList.add('old');
going.add(s);
play(s, [{ opacity: op.get(s)! }, { opacity: 0 }], {
duration: 220 * op.get(s)!,
delay: 110,
easing: EASE_IN,
fill: 'both',
}).onfinish = () => s.remove();
});
fades.forEach((a) => a.cancel());
sizing?.cancel();
sizing = null;
const r1 = box.getBoundingClientRect();
const sx = r0.width / r1.width;
const sy = r0.height / r1.height;
// Not on screen (a folded row): nothing to watch move.
if (r0.width && r1.width && (Math.abs(sx - 1) > 0.005 || Math.abs(sy - 1) > 0.005))
sizing = play(
box,
[
{ transform: `scale(${sx}, ${sy})`, transformOrigin: '0 0', borderRadius: `${round0 / sx}px` },
{ transform: 'none', transformOrigin: '0 0', borderRadius: getComputedStyle(box).borderTopLeftRadius },
],
{ duration: SMOOTH.duration, easing: SMOOTH.easing },
);
};
return {
el,
swap(next, nextWords) {
if (nextWords) own = nextWords;
const was = out;
out = instead(next);
const code = out ? standIn!.text : next;
// The same code for another app (AmneziaWG and WireGuard take one file): only the words change.
const oldSvg = box.dataset.qr === next ? null : box.querySelector('svg');
if (oldSvg) {
paint(box, next);
el.classList.toggle('stacked', box.classList.contains('dense'));
const newSvg = box.querySelector('svg')!;
oldSvg.classList.add('old');
box.appendChild(oldSvg);
// The new code comes in first, the old one goes after it: the place is never empty.
play(newSvg, [{ opacity: 0 }, { opacity: 1 }], { duration: 200, easing: EASE_OUT });
play(oldSvg, [{ opacity: 1 }, { opacity: 0 }], { duration: 220, delay: 110, easing: EASE_IN, fill: 'forwards' }).onfinish = () =>
oldSvg.remove();
}
if (!nextWords) return;
if (box.dataset.qr !== code) cross(code);
// The stand-in's words stay while they say the same (they may follow what it stands in for); the row's own
// come back with a code that fits.
let put = out ? standIn!.words() : (nextWords ?? (was ? own : null));
if (out && was && put!.map((n) => n.textContent).join('') === shown.textContent) put = null;
if (!put) return;
const oldWords = shown;
shown = h('div', { class: 'words' }, nextWords);
// From where they stand: words still coming in (a pick right after a pick) go from there.
const from = now(oldWords);
const fades = oldWords.getAnimations();
shown = h('div', { class: 'words' }, put);
side.appendChild(shown);
oldWords.classList.add('old');
play(
@@ -77,14 +171,9 @@ export function codeRow(text: string, words: Node[]): CodeRow {
],
{ duration: 220, easing: EASE_OUT },
);
play(
oldWords,
[
{ opacity: 1, filter: 'blur(0px)' },
{ opacity: 0, filter: 'blur(3px)' },
],
{ duration: 200, delay: 90, easing: EASE_IN, fill: 'forwards' },
).onfinish = () => oldWords.remove();
play(oldWords, [from, { opacity: 0, filter: 'blur(3px)' }], { duration: 200, delay: 90, easing: EASE_IN, fill: 'both' }).onfinish =
() => oldWords.remove();
fades.forEach((a) => a.cancel());
},
};
}
+20 -11
View File
@@ -12,13 +12,22 @@ let slot: HTMLElement | null = null;
let shown: HTMLElement | null = null;
let timer = 0;
const leave = (t: HTMLElement, frames: Keyframe[], ms: number) =>
(play(t, frames, { duration: ms, easing: EASE_IN, fill: 'forwards' }).onfinish = () => t.remove());
/** A toast goes from where it stands: one still rising (a new one took its place) goes from there. */
function leave(t: HTMLElement, to: Keyframe, ms: number) {
const s = getComputedStyle(t);
const a = play(t, [{ opacity: s.opacity, transform: s.transform, filter: s.filter }, to], {
duration: ms,
easing: EASE_IN,
fill: 'forwards',
});
t.getAnimations().forEach((x) => x !== a && x.cancel());
a.onfinish = () => t.remove();
}
/** One toast at a time: a new one sends the last away first. */
export function toast(msg: string, bad = false) {
slot ??= document.body.appendChild(h('div', { class: 'toasts' }));
if (shown) leave(shown, [{ opacity: 1 }, { opacity: 0, transform: 'scale(.96)', filter: 'blur(4px)' }], 140);
if (shown) leave(shown, { opacity: 0, transform: 'scale(.96)', filter: 'blur(4px)' }, 140);
const t = h('div', { class: `toast${bad ? ' bad' : ''}`, role: 'status' }, ic(bad ? 'alert' : 'check'), h('span', {}, msg));
slot.appendChild(t);
shown = t;
@@ -37,13 +46,13 @@ export function toast(msg: string, bad = false) {
timer = window.setTimeout(() => {
if (shown !== t) return;
shown = null;
leave(t, [{ opacity: 1 }, { opacity: 0, transform: 'translateY(6px) scale(.96)', filter: 'blur(4px)' }], 180);
leave(t, { opacity: 0, transform: 'translateY(6px) scale(.96)', filter: 'blur(4px)' }, 180);
}, 2400);
}
/** An icon that changes in place: the new one pops in where the old one stood. */
export function swapIcon(icon: Element, name: string): Element {
const next = ic(name, icon.getAttribute('class') ?? 'i');
/** An icon that changes in place: the new one (by name, or one to put back) pops in where the old one stood. */
export function swapIcon(icon: Element, to: string | Element): Element {
const next = typeof to === 'string' ? ic(to, icon.getAttribute('class') ?? 'i') : to;
icon.replaceWith(next);
play(
next,
@@ -61,9 +70,9 @@ export function swapIcon(icon: Element, name: string): Element {
/**
* The control that copied says so for a moment: its icon turns into a check
* and its "Copy…" label (`.lbl`, a badge's main line) into "Copied". Every
* control that copies with a label says "Copy…" (in any language), so the
* label is not read for the word.
* and its "Copy…" label (`.lbl`, a badge's main line) into "Copied", then both
* turn back the way they came. Every control that copies with a label says
* "Copy…" (in any language), so the label is not read for the word.
*/
function copied(from: Element) {
if (from.classList.contains('copied')) return;
@@ -74,7 +83,7 @@ function copied(from: Element) {
const check = icon ? swapIcon(icon, 'check') : null;
if (label) morphText(label, _('Copied'));
setTimeout(() => {
if (check && icon) check.replaceWith(icon);
if (check && icon) swapIcon(check, icon);
if (label) morphText(label, was);
from.classList.remove('copied');
}, 1600);
+5
View File
@@ -121,6 +121,11 @@ const GL: Record<string, Shape> = {
f: '<rect x="2.5" y="6" width="13.5" height="16" rx="3.2"/>',
d: '<path d="M6.2 11h6.5M6.2 14.5h6.5M6.2 18h4"/>',
},
lan: {
b: '<circle cx="16" cy="8" r="6"/>',
f: '<rect x="2.5" y="7.5" width="14.5" height="14.5" rx="4.2"/>',
d: '<rect x="8.3" y="10.4" width="2.9" height="2.6" rx=".7"/><rect x="5.2" y="16.4" width="2.9" height="2.6" rx=".7"/><rect x="11.4" y="16.4" width="2.9" height="2.6" rx=".7"/><path d="M9.75 13v1.8M6.65 16.4v-1.6h6.2v1.6"/>',
},
};
/** The AmneziaVPN mark without its own svg: drawn on the "app" pane. */
+21 -7
View File
@@ -34,11 +34,22 @@ export function closeMenu(now = false) {
m.remove();
return;
}
play(m, [{ opacity: 1 }, { opacity: 0, transform: 'scale(.96)', filter: 'blur(3px)' }], {
duration: 120,
easing: EASE_IN,
fill: 'forwards',
}).onfinish = () => m.remove();
// From where it stands: one closed while it still pops in (a scroll, a second press) goes from there.
const s = getComputedStyle(m);
const a = play(
m,
[
{ opacity: s.opacity, transform: s.transform, filter: s.filter },
{ opacity: 0, transform: 'scale(.96)', filter: 'blur(3px)' },
],
{
duration: 120,
easing: EASE_IN,
fill: 'forwards',
},
);
m.getAnimations().forEach((x) => x !== a && x.cancel());
a.onfinish = () => m.remove();
}
/** `items`: null is a separator, kept only between items. */
@@ -68,9 +79,12 @@ export function openMenu(anchor: HTMLElement, all: (MenuItem | null)[]) {
it.checked === undefined ? ic(it.icon ?? '') : ic('check', it.checked ? 'i' : 'i off'),
h('span', {}, it.label),
);
// The highlight comes in where the pointer is, then glides from item to item.
// The highlight comes in where the pointer is, then glides from item to item. Whether it shows is read off the
// screen: one still fading out (the pointer left and came back) turns back and glides from where it stands;
// only one gone altogether is placed at once.
b.addEventListener('pointerenter', () => {
hl.className = `menu-hl${hl.style.opacity === '1' ? ' moving' : ''} ${it.tone ?? ''}`;
const seen = +getComputedStyle(hl).opacity > 0.01;
hl.className = `menu-hl${seen ? ' moving' : ''} ${it.tone ?? ''}`;
hl.style.transform = `translateY(${b.offsetTop - 6}px)`;
hl.style.opacity = '1';
});
+328 -105
View File
@@ -4,7 +4,9 @@
// through `morphText`: a card's name and status after a repaint, the counts and
// values, a label that says "Copied", a line that says what happened (the way:
// "iPad connected"), and a menu path for another app or the other phone system
// (`menuLine`: where the app scans, iOS "Create", Android "Scan").
// (`menuLine`: where the app scans, iOS "Create", Android "Scan"). Turned again
// half-way, a morph or a refill goes on from what shows: words still coming in
// leave from as far as they came, what was leaving keeps leaving.
import { fmt } from '../../shared/i18n';
import { h, ic, markup, put, type Kid } from '../dom';
@@ -23,6 +25,22 @@ const runs = new WeakMap<HTMLElement, Run>();
/** What `el` says: while it morphs, what it is turning into. */
export const textOf = (el: HTMLElement): string => runs.get(el)?.text ?? el.textContent ?? '';
/** How something shows: its opacity and blur, part of the way while a fade or a morph runs. */
export interface Look {
opacity: number;
filter: string;
}
const SHOWN: Look = { opacity: 1, filter: 'blur(0px)' };
const settled = (s: Look) => s.opacity > 0.99 && (s.filter === 'none' || s.filter === 'blur(0px)');
/** How `el` shows now (on the page: a detached element has no style), with the words a whole-word morph brings in. */
export function look(el: Element): Look {
const cs = getComputedStyle(el);
const words = el.querySelector(':scope > .mt-new');
const ws = words && getComputedStyle(words);
return { opacity: +cs.opacity * (ws ? +ws.opacity : 1), filter: cs.filter === 'none' && ws ? ws.filter : cs.filter };
}
/** Where `el`'s words sit (their own box, not the element's). */
function wordsBox(el: HTMLElement): DOMRect {
const r = document.createRange();
@@ -30,6 +48,13 @@ function wordsBox(el: HTMLElement): DOMRect {
return r.getBoundingClientRect();
}
/** Where a text's glyphs stand (only as high as the font, not the line). */
function glyphs(n: Node): DOMRect {
const r = document.createRange();
r.selectNodeContents(n);
return r.getBoundingClientRect();
}
/** Where each character of `el`'s plain text starts, from the first (kerning and all). */
function spacing(el: HTMLElement): number[] {
const node = el.firstChild;
@@ -54,10 +79,11 @@ function spacing(el: HTMLElement): number[] {
function space(box: Element, at: number[]) {
const kids = [...box.children] as HTMLElement[];
if (!kids.length) return;
const start = kids[0].getBoundingClientRect().left;
kids.forEach((c, i) => {
if (!i || at[i] === undefined) return;
const dx = start + at[i] - c.getBoundingClientRect().left;
// Against the first letter as it stands now: in a centred line every nudge moves the whole run
// by half of it, the first letter too, and a start read once would let the nudges add up.
const dx = kids[0].getBoundingClientRect().left + at[i] - c.getBoundingClientRect().left;
if (Math.abs(dx) > 0.01) c.style.marginLeft = `${dx}px`;
});
}
@@ -105,6 +131,20 @@ export function setText(el: HTMLElement, text: string) {
el.textContent = text;
}
/**
* A morph under way on `el`, taken out as it shows: the words it brings in (and where they stand), and all still
* leaving (one turned again before has more than one).
*/
function lift(el: HTMLElement): { words: HTMLElement; at: DOMRect; going: HTMLElement[] } | null {
const words = el.querySelector<HTMLElement>(':scope > .mt-new');
if (!words) return null;
const going = [...el.querySelectorAll<HTMLElement>(':scope > .mt-old')];
const at = wordsBox(words);
words.remove();
going.forEach((g) => g.remove());
return { words, at, going };
}
export interface MorphOpts {
/** The words change as a whole instead: the old blur away where they stood as the new come in. */
whole?: boolean;
@@ -116,6 +156,10 @@ export interface MorphOpts {
* words go from there, and the width does not glide.
*/
at?: DOMRect;
/** How the old words show, against `el` (they were still coming in when the caller rebuilt them): they leave from there. */
shows?: Look;
/** The old words' colour, where `el` took another with the new ones (a status turned green): they keep it, the new turn from it. */
color?: string;
}
/**
@@ -125,14 +169,21 @@ export interface MorphOpts {
* The old letters keep to the edge
* that stays put while the width changes (the start of a line, the end of a
* value on the right, the middle of a centred line). Done, it holds plain text
* again: a box that ends in an ellipsis keeps it.
* again: a box that ends in an ellipsis keeps it. Turned again half-way, the
* words that were coming in leave from as far as they came (a letter both
* texts keep slides on from where it is), and those leaving go on leaving.
*/
export function morphText(el: HTMLElement, next: string, from = textOf(el), o: MorphOpts = {}) {
const { whole = false, at } = o;
const run = runs.get(el);
// Asked again for what it is already turning into: the morph under way goes on.
if (run && from === run.text && next === run.text) return;
// Placed by the caller, the width does not glide: what follows is moved by the caller too.
const glide = (o.glide ?? true) && !at;
// Interrupted mid-way: the width carries on from where it is on screen, not from where that morph was going.
const midway = runs.has(el) ? el.getBoundingClientRect().width : null;
// Interrupted mid-way: the width carries on from where it is on screen, not from where that morph was going,
// and what shows of it is taken out as it stands.
const midway = run ? el.getBoundingClientRect() : null;
const live = run && from === run.text && !calm() && el.getClientRects().length ? lift(el) : null;
finish(el);
// Nothing to watch move: no motion asked for, or not on screen (a folded row, a closed sheet).
if (from === next || calm() || !el.getClientRects().length) {
@@ -145,8 +196,8 @@ export function morphText(el: HTMLElement, next: string, from = textOf(el), o: M
const flow = whole && cs.display === 'inline';
if (cs.display === 'inline' && !whole) el.classList.add('mt-ib');
if (cs.position === 'static') el.classList.add('mt');
let r0: DOMRect | null = null;
let t0 = at ?? null;
let r0: DOMRect | null = live ? midway : null;
let t0 = live?.at ?? at ?? null;
let at0: number[] = [];
if (!t0) {
el.textContent = from;
@@ -157,15 +208,25 @@ export function morphText(el: HTMLElement, next: string, from = textOf(el), o: M
el.textContent = next;
const r1 = el.getBoundingClientRect();
const at1 = spacing(el);
const w0 = midway ?? r0?.width ?? r1.width;
const w0 = midway?.width ?? r0?.width ?? r1.width;
const glides = glide && !flow && !!r0 && Math.abs(r1.width - w0) > 0.5;
const edge = !glides || !r0 || Math.abs(r1.left - r0.left) < 0.5 ? 'start' : Math.abs(r1.right - r0.right) < 0.5 ? 'end' : 'middle';
const neu = h('span', { class: whole ? 'mt-new w' : 'mt-new' }, whole ? next : letters(next));
const old = h('span', { class: whole ? 'mt-old w' : 'mt-old', 'aria-hidden': 'true' }, whole ? from : letters(from));
// The old words: those that were coming in, as they show, or the old text built afresh.
const old = live?.words ?? h('span', { class: whole ? 'mt-old w' : 'mt-old' }, whole ? from : letters(from));
old.classList.replace('mt-new', 'mt-old');
old.setAttribute('aria-hidden', 'true');
// Whole words wrap as they did: the old ones keep the width they took.
if (whole) old.style.width = `${t0.width + 1}px`;
if (old.classList.contains('w')) old.style.width = `${t0.width + 1}px`;
el.replaceChildren(neu, old);
// What was still leaving goes on leaving where it is.
if (live) el.append(...live.going);
if (o.color) {
old.style.color = o.color;
const c1 = getComputedStyle(el).color;
if (c1 !== o.color) play(neu, [{ color: o.color }, { color: c1 }], { duration: 280, easing: EASE_OUT });
}
// Held at the plain text's width until the letters turn back into it, so what follows never steps.
if (glides)
play(el, [{ width: `${w0}px` }, { width: `${r1.width}px` }], {
@@ -186,18 +247,28 @@ export function morphText(el: HTMLElement, next: string, from = textOf(el), o: M
};
const x0 = edge === 'end' ? t0.right - r2.right : edge === 'middle' ? (t0.left + t0.right - r2.left - r2.right) / 2 : t0.left - r2.left;
place(x0, t0.top - r2.top);
// Then onto the old words exactly: the box's top is not the text's (the line's leading sits above it).
const t2 = wordsBox(old);
// Then onto the old words exactly: the box's top is not the text's (the line's leading sits above it), nor is a
// letter's (a box of its own, a line high): built afresh, the first letter's glyphs go where the text's stood.
const first = !live && old.querySelector('i')?.firstChild;
const t2 = first ? glyphs(first) : wordsBox(old);
place(x0 + t0.left - t2.left, t0.top - r2.top + t0.top - t2.top);
if (whole) {
// How the old words show: those that were coming in as far as they came.
const s0 = live ? look(old) : (o.shows ?? SHOWN);
/** The old words go as one, from how they show. */
const leave = () => {
const prior = old.getAnimations();
play(
old,
[
{ opacity: 1, filter: 'blur(0px)' },
{ opacity: s0.opacity, filter: s0.filter },
{ opacity: 0, filter: 'blur(4px)' },
],
{ duration: 180, easing: EASE_IN, fill: 'forwards' },
{ duration: 180 * s0.opacity, easing: EASE_IN, fill: 'forwards' },
);
prior.forEach((a) => a.cancel());
};
if (whole) {
leave();
play(
neu,
[
@@ -211,26 +282,36 @@ export function morphText(el: HTMLElement, next: string, from = textOf(el), o: M
return;
}
space(neu, at1);
space(old, at0);
if (!live) space(old, at0);
// The letters both texts keep slide from where they stood to where they go, on the width's spring;
// the old ones' places in the overlay stay empty.
const was = [...old.children] as HTMLElement[];
// the old ones' places in the overlay stay empty. Old words that came whole have no letters to keep.
const was = old.classList.contains('w') ? [] : ([...old.children] as HTMLElement[]);
const now = [...neu.children] as HTMLElement[];
const pairs = kept([...from], [...next]);
const pairs = was.length ? kept([...from], [...next]) : [];
const stays = new Set(pairs.map(([i]) => i));
const comes = new Set(pairs.map(([, j]) => j));
pairs.forEach(([i, j]) => {
const a = was[i].getBoundingClientRect();
const b = now[j].getBoundingClientRect();
// A letter still rising when the morph turned comes along from as far as it rose.
const s = live ? look(was[i]) : s0;
was[i].style.visibility = 'hidden';
if (Math.abs(a.left - b.left) > 0.5 || Math.abs(a.top - b.top) > 0.5)
play(now[j], [{ transform: `translate(${a.left - b.left}px, ${a.top - b.top}px)` }, { transform: 'none' }], {
duration: SMOOTH.duration,
easing: SMOOTH.easing,
});
const moves = Math.abs(a.left - b.left) > 0.5 || Math.abs(a.top - b.top) > 0.5;
const shows = settled(s) ? null : s;
if (moves || shows)
play(
now[j],
[
{ transform: `translate(${a.left - b.left}px, ${a.top - b.top}px)`, ...shows },
{ transform: 'none', ...(shows && SHOWN) },
],
{ duration: SMOOTH.duration, easing: SMOOTH.easing },
);
});
const out = was.filter((_x, i) => !stays.has(i));
// Turned half-way, the old words leave as one: each of their letters is somewhere on its own way.
const out = live ? [] : was.filter((_x, i) => !stays.has(i));
if (live) leave();
const inn = now.filter((_x, j) => !comes.has(j));
// A long text keeps the same overall sweep: the steps shorten instead.
const so = Math.min(12, 160 / Math.max(1, out.length));
@@ -239,7 +320,7 @@ export function morphText(el: HTMLElement, next: string, from = textOf(el), o: M
play(
c,
[
{ opacity: 1, filter: 'blur(0px)', transform: 'none' },
{ opacity: s0.opacity, filter: s0.filter, transform: 'none' },
{ opacity: 0, filter: 'blur(4px)', transform: 'translateY(-0.45em)' },
],
{ duration: 220, delay: i * so, easing: EASE_IN, fill: 'forwards' },
@@ -260,17 +341,32 @@ export function morphText(el: HTMLElement, next: string, from = textOf(el), o: M
runs.set(el, { text: next, timer: window.setTimeout(() => finish(el), ends) });
}
/** The keyed texts under `root` (`data-t`), before a repaint rebuilds them. */
export function textsOf(root: ParentNode): Map<string, string> {
return new Map([...root.querySelectorAll<HTMLElement>('[data-t]')].map((el) => [el.dataset.t!, textOf(el)]));
/** What a keyed text said, and in which colour. */
export interface Said {
text: string;
color: string;
}
/** After the repaint: each keyed text that changed morphs from what it said. */
export function morphChanged(root: ParentNode, was: Map<string, string>) {
/** The keyed texts under `root` (`data-t`), before a repaint rebuilds them. */
export function textsOf(root: ParentNode): Map<string, Said> {
return new Map(
[...root.querySelectorAll<HTMLElement>('[data-t]')].map((el) => [
el.dataset.t!,
{ text: textOf(el), color: getComputedStyle(el).color },
]),
);
}
/**
* After the repaint: each keyed text that changed morphs from what it said (one already turning into it goes on).
* `fresh`: what a refill brought in whole (morphInto), its words with it: the old words fade where they stood.
*/
export function morphChanged(root: ParentNode, was: Map<string, Said>, fresh: Element[] = []) {
root.querySelectorAll<HTMLElement>('[data-t]').forEach((el) => {
const before = was.get(el.dataset.t!);
const now = el.textContent ?? '';
if (before !== undefined && before !== now) morphText(el, now, before);
const now = textOf(el);
if (!before || before.text === now || runs.has(el) || fresh.some((f) => f.contains(el))) return;
morphText(el, now, before.text, { color: before.color });
});
}
@@ -283,11 +379,87 @@ interface Piece {
/** Where its words stand (a morph under way: the words it is turning into). */
words: DOMRect | null;
node: Node;
/** How it shows: part of the way while it still comes in. */
shows: Look;
}
/** What can fade out where it stood. */
type Drawn = HTMLElement | SVGElement;
const isDrawn = (n: Node): n is Drawn => n instanceof HTMLElement || n instanceof SVGElement;
/** A piece as something that can fade where it stood: bare words go into a span of their own. */
const drawn = (n: Node): Drawn => (isDrawn(n) ? n : h('span', {}, n));
/** Its tag and classes, less a morph's own (a piece still changing is the same piece). */
const kindOf = (el: Element) => `${el.tagName}.${[...el.classList].filter((c) => c !== 'mt' && c !== 'mt-ib').join(' ')}`;
/** A drawing as markup, less the ids each build makes up (a glass icon's gradients): the same icon twice is the same. */
const drawing = (el: Element) => el.outerHTML.replace(/\bgl\d+/g, 'gl');
/** What fades out where it stood (`fadeAway`), each with the element it is laid over. */
const fading = new Map<Element, Element>();
/** How many fade over each element, and those made a positioned box for them. */
const holding = new WeakMap<Element, number>();
const boxed = new WeakSet<Element>();
/** Inside something already fading out (under `box`): it goes with it. */
function within(el: Element, box: Element): boolean {
for (let p = el.parentElement; p && p !== box; p = p.parentElement) if (fading.has(p)) return true;
return false;
}
function hold(host: Element) {
const n = holding.get(host) ?? 0;
if (!n && getComputedStyle(host).position === 'static') {
host.classList.add('mt');
boxed.add(host);
}
holding.set(host, n + 1);
}
/** The last to fade over `host` is gone: a box made positioned for them is static again. */
function release(host: Element) {
const n = (holding.get(host) ?? 1) - 1;
holding.set(host, n);
if (!n && boxed.delete(host)) host.classList.remove('mt');
}
/**
* `e`, which stood at `at` on screen, fades out there, laid over `host` (which
* stood at `from`): a piece a refill crossed or left out (morphInto), a card's
* old foot (page/devices.ts). One already fading only moves over its new host
* and goes on; another starts from how it showed (`shows`: it may still have
* been coming in), over what is left of its way.
*/
export function fadeAway(e: Drawn, at: DOMRect, host: Element, from: DOMRect, shows: Look = SHOWN) {
const over = fading.get(e);
if (over) release(over);
hold(host);
fading.set(e, host);
e.style.position = 'absolute';
e.style.margin = '0';
e.style.left = `${at.left - from.left - host.clientLeft}px`;
e.style.top = `${at.top - from.top - host.clientTop}px`;
e.style.right = '';
e.style.translate = '';
e.style.width = `${at.width}px`;
e.style.pointerEvents = 'none';
e.setAttribute('aria-hidden', 'true');
host.appendChild(e);
if (over) return;
const prior = e.getAnimations();
const a = play(
e,
[
{ opacity: shows.opacity, filter: shows.filter },
{ opacity: 0, filter: 'blur(4px)' },
],
{ duration: 180 * shows.opacity, easing: EASE_IN, fill: 'forwards' },
);
prior.forEach((x) => x.cancel());
// Gone, or stopped by whatever stops what moves around it: it was leaving either way.
a.onfinish = a.oncancel = () => {
const last = fading.get(e);
if (!last) return;
fading.delete(e);
release(last);
e.remove();
};
}
function pieces(box: Element): Map<string, Piece> {
const out = new Map<string, Piece>();
const walk = (n: Node, path: string) =>
@@ -298,58 +470,121 @@ function pieces(box: Element): Map<string, Piece> {
const r = document.createRange();
r.selectNodeContents(c);
const at = r.getBoundingClientRect();
out.set(p, { kind: '#text', text: c.textContent, svg: '', at, words: at, node: c });
out.set(p, { kind: '#text', text: c.textContent, svg: '', at, words: at, node: c, shows: SHOWN });
}
return;
}
if (!(c instanceof Element)) return;
// What is on its way out already (crossed by a refill before, words a morph lifts away) goes on by itself.
if (!(c instanceof Element) || fading.has(c) || c.classList.contains('mt-old')) return;
const svg = c instanceof SVGElement ? drawing(c) : '';
const words = c instanceof HTMLElement && !svg ? wordsBox(c.querySelector<HTMLElement>(':scope > .mt-new') ?? c) : null;
out.set(p, { kind: kindOf(c), text: c instanceof HTMLElement ? textOf(c) : '', svg, at: c.getBoundingClientRect(), words, node: c });
out.set(p, {
kind: kindOf(c),
text: c instanceof HTMLElement ? textOf(c) : '',
svg,
at: c.getBoundingClientRect(),
words,
node: c,
shows: look(c),
});
if (!svg) walk(c, p);
});
walk(box, '');
return out;
}
/** Something with nothing to change from comes in through a blur. */
const appear = (el: Element) =>
/**
* `el` glides back to its place from `(dx, dy)` away, on SMOOTH. A transform
* does nothing to words in a line (an inline box): those move by a relative
* offset instead, theirs only for the glide.
*/
function shift(el: Element, dx: number, dy: number) {
const o = { duration: SMOOTH.duration, easing: SMOOTH.easing };
if (!(el instanceof HTMLElement) || getComputedStyle(el).display !== 'inline')
return play(el, [{ transform: `translate(${dx}px, ${dy}px)` }, { transform: 'none' }], o);
const own = el.style.position;
if (getComputedStyle(el).position === 'static') el.style.position = 'relative';
const a = play(
el,
[
{ left: `${dx}px`, top: `${dy}px` },
{ left: '0px', top: '0px' },
],
o,
);
a.onfinish = a.oncancel = () => (el.style.position = own);
return a;
}
/**
* Something with nothing to change from comes in through a blur, to its own
* opacity (a part the stylesheet dims stays dimmed); `shows`: it was on its way
* in already, and goes on from as far as it came.
*/
export function appear(el: Element, shows?: Look) {
const own = +getComputedStyle(el).opacity;
const o0 = shows?.opacity ?? 0;
play(
el,
[
{ opacity: 0, filter: 'blur(4px)' },
{ opacity: 1, filter: 'blur(0px)' },
{ opacity: o0, filter: shows?.filter ?? 'blur(4px)' },
{ opacity: own, filter: 'blur(0px)' },
],
{ duration: 280, delay: 60, easing: EASE_OUT, fill: 'backwards' },
{ duration: 280 * Math.min(1, Math.max(0, own - o0) / (own || 1)), delay: shows ? 0 : 60, easing: EASE_OUT, fill: 'backwards' },
);
}
/**
* `box` refilled with `kids` and nothing blinks: what is the same stays still;
* a piece in the same place with other words blurs from the old words into the
* new where it stands; a drawing that changed comes in through a blur; a piece
* that changed its kind or its height (another block, a list that wraps over
* more lines) crosses whole, the old one blurring out exactly where it stood as
* the new one blurs in, and so does what is gone. A piece that kept its kind
* and size but moved glides from where it stood. Places are taken against the
* box, which its sheet moves as a whole; an old piece fades inside its own
* parent's new self (the same kind, in the same place), so it keeps its look.
* new where it stands (a keyed text, `data-t`, is left to morphChanged, which
* letter-morphs it from what it said); a piece that changed its kind, its
* height (another block, a list that wraps over more lines) or its drawing
* crosses whole, the old one blurring out exactly where it stood as the new one
* blurs in, and so does what is gone. A piece that kept its kind and size but
* moved glides from where it stood. Places are taken against the box, which its
* sheet moves as a whole; an old piece fades inside its own parent's new self
* (the same kind, in the same place), so it keeps its look. Refilled again
* half-way, what was fading goes on fading where it is, and what was still
* coming in goes on from as far as it came. Returns what came in whole.
*/
export function morphInto(box: HTMLElement, kids: Kid) {
export function morphInto(box: HTMLElement, kids: Kid): Element[] {
const was = pieces(box);
const box0 = box.getBoundingClientRect();
// What is on its way out already, with what it sat in: it goes on over that one's new self.
const going = [...fading.keys(), ...box.querySelectorAll('.mt-old')]
.filter((g): g is Drawn => box.contains(g) && !within(g, box) && isDrawn(g))
.map((g) => ({ g, at: g.getBoundingClientRect(), over: g.parentElement, shows: fading.has(g) ? undefined : look(g) }));
const pathOf = new Map([...was].map(([p, w]) => [w.node, p]));
put(box, kids);
if (!was.size || calm()) return;
/** The new element at each place. */
const placed = new Map<string, Element>();
const carry = () =>
going.forEach(({ g, at, over, shows }) => {
const p = over && pathOf.get(over);
const host = p && placed.get(p);
const w = p && was.get(p);
if (host && w && w.at && w.kind === kindOf(host)) fadeAway(g, at, host, w.at, shows);
else fadeAway(g, at, box, box0, shows);
});
if (!was.size || calm()) {
carry();
return [];
}
const box1 = box.getBoundingClientRect();
/** Where something that stood at `r` in the box's old place stands now, the pieces having glided back there. */
const here = (r: DOMRect | null) => r && new DOMRect(r.left - box0.left + box1.left, r.top - box0.top + box1.top, r.width, r.height);
const morphs: (() => void)[] = [];
/** An old piece, where it stood, the new parent it fades in and where that parent stood. */
const ghosts: [Element, DOMRect, Element, DOMRect][] = [];
/** An old piece, where it stood, the new parent it fades in, where that parent stood, and how the piece showed. */
const ghosts: [Drawn, DOMRect, Element, DOMRect, Look][] = [];
const seen = new Set<string>();
/** What comes in whole. */
const came: Element[] = [];
const cross = (el: Element, w: Piece | undefined, path: string) => {
const host = el.parentElement;
const from = path ? was.get(path)?.at : box0;
if (w?.at && w.node instanceof Element) ghosts.push(host && from ? [w.node, w.at, host, from] : [w.node, w.at, box, box0]);
if (w?.at) ghosts.push(host && from ? [drawn(w.node), w.at, host, from, w.shows] : [drawn(w.node), w.at, box, box0, w.shows]);
came.push(el);
morphs.push(() => appear(el));
};
/** Moves `el` from where it stood (`at`, in the box's old place) to where it is, less what its parent already carries. */
@@ -359,8 +594,7 @@ export function morphInto(box: HTMLElement, kids: Kid) {
const dy = at.top - box0.top - (r.top - box1.top);
const ox = dx - carried[0];
const oy = dy - carried[1];
if (Math.abs(ox) > 0.5 || Math.abs(oy) > 0.5)
play(el, [{ transform: `translate(${ox}px, ${oy}px)` }, { transform: 'none' }], { duration: SMOOTH.duration, easing: SMOOTH.easing });
if (Math.abs(ox) > 0.5 || Math.abs(oy) > 0.5) shift(el, ox, oy);
return [dx, dy];
};
const walk = (n: Node, path: string, carried: [number, number]) =>
@@ -370,75 +604,58 @@ export function morphInto(box: HTMLElement, kids: Kid) {
const w = was.get(p);
if (c.nodeType === Node.TEXT_NODE) {
const t = c.textContent ?? '';
if (!t.trim() || (w?.kind === '#text' && w.text === t)) return;
if (!t.trim()) return;
// Words: a bare word before, or one the last refill put in a span of its own (it is still that word).
const said = w && (w.kind === '#text' || (w.node instanceof HTMLElement && !w.node.children.length)) ? w.text : null;
const coming = w && w.shows.opacity < 0.99 ? w.shows : null;
if (said === t && !coming) return;
// A bare word among elements goes into a span of its own, so it can change (and glide from where its words were).
const s = h('span', {}, t);
c.replaceWith(s);
if (said === null || Math.max(t.length, said.length) > 40) return cross(s, w, path);
if (w?.at) glideFrom(s, w.at, carried);
morphs.push(() =>
w?.kind === '#text' && t.length <= 40 && w.text.length <= 40
? morphText(s, t, w.text, { whole: true, at: here(w.words) ?? undefined })
: appear(s),
said === t ? appear(s, coming!) : morphText(s, t, said, { whole: true, at: here(w!.words) ?? undefined, shows: w!.shows }),
);
return;
}
if (!(c instanceof Element)) return;
placed.set(p, c);
const r = c.getBoundingClientRect();
if (!w || w.kind !== kindOf(c) || (w.at && Math.abs(w.at.height - r.height) > 1 && !(c instanceof SVGElement)))
const svg = c instanceof SVGElement;
if (!w || w.kind !== kindOf(c) || (svg ? w.svg !== drawing(c) : !!w.at && Math.abs(w.at.height - r.height) > 1))
return cross(c, w, path);
// The same piece somewhere else in the box: it glides there (what it holds rides along, plus its own move).
const own = w.at ? glideFrom(c, w.at, carried) : carried;
if (c instanceof SVGElement) {
if (w.svg !== drawing(c)) morphs.push(() => appear(c));
// Still coming in when the box was refilled: it goes on from as far as it came.
const rest = +getComputedStyle(c).opacity;
const coming = Math.abs(w.shows.opacity - rest) > 0.01 ? w.shows : null;
if (svg) {
if (coming) morphs.push(() => appear(c, coming));
return;
}
if (!c.children.length && c instanceof HTMLElement) {
const t = c.textContent ?? '';
if (t !== w.text)
morphs.push(() =>
t.length <= 40 && w.text.length <= 40
? morphText(c, t, w.text, { whole: true, at: here(w.words) ?? undefined })
: cross(c, w, path),
);
if (t === w.text || c.dataset.t) {
if (coming) morphs.push(() => appear(c, coming));
} else if (t.length <= 40 && w.text.length <= 40) {
// The old words leave from how they showed, against the element that holds them now.
const shows = { opacity: Math.min(1, w.shows.opacity / (rest || 1)), filter: w.shows.filter };
morphs.push(() => morphText(c, t, w.text, { whole: true, at: here(w.words) ?? undefined, shows }));
} else cross(c, w, path);
return;
}
if (coming) morphs.push(() => appear(c, coming));
walk(c, p, own);
});
walk(box, '', [0, 0]);
// What the new box no longer has goes the same way.
for (const [p, w] of was)
if (!seen.has(p) && p.lastIndexOf('/') === 0 && w.at && w.node instanceof Element) ghosts.push([w.node, w.at, box, box0]);
for (const [p, w] of was) if (!seen.has(p) && p.lastIndexOf('/') === 0 && w.at) ghosts.push([drawn(w.node), w.at, box, box0, w.shows]);
morphs.forEach((m) => m());
// The old pieces that cross go from exactly where they stood in their parent (which glides from where it stood).
const hosts = new Map<Element, number>();
for (const [, , host] of ghosts) {
if (!hosts.has(host) && getComputedStyle(host).position === 'static') host.classList.add('mt');
hosts.set(host, (hosts.get(host) ?? 0) + 1);
}
for (const [g, at, host, from] of ghosts) {
const e = g as HTMLElement;
e.style.position = 'absolute';
e.style.margin = '0';
e.style.left = `${at.left - from.left - host.clientLeft}px`;
e.style.top = `${at.top - from.top - host.clientTop}px`;
e.style.width = `${at.width}px`;
e.style.pointerEvents = 'none';
e.setAttribute('aria-hidden', 'true');
host.appendChild(e);
play(
e,
[
{ opacity: 1, filter: 'blur(0px)' },
{ opacity: 0, filter: 'blur(4px)' },
],
{ duration: 180, easing: EASE_IN, fill: 'forwards' },
).onfinish = () => {
e.remove();
const n = hosts.get(host)! - 1;
hosts.set(host, n);
if (!n) host.classList.remove('mt');
};
}
for (const [g, at, host, from, shows] of ghosts) fadeAway(g, at, host, from, shows);
carry();
return came;
}
/** The Android robot's head; its eyes take the colour of what it sits on. */
@@ -502,15 +719,21 @@ export function menuLine(ios: string, android: string): MenuLine {
};
const MARK = { width: '1.05em', marginRight: '0.25em' };
const markOut = (m: HTMLElement) =>
(play(
/** The mark shrinks away from where it stands (one still growing in turns back), over what is left of its width. */
const markOut = (m: HTMLElement) => {
const cs = getComputedStyle(m);
const left = Math.min(1, parseFloat(cs.width) / (1.05 * parseFloat(cs.fontSize)) || 0);
const prior = m.getAnimations();
play(
m,
[
{ opacity: 1, filter: 'blur(0px)', ...MARK },
{ opacity: cs.opacity, filter: cs.filter, width: cs.width, marginRight: cs.marginRight },
{ opacity: 0, filter: 'blur(3px)', width: '0px', marginRight: '0px' },
],
{ duration: 220, easing: EASE_IN, fill: 'forwards' },
).onfinish = () => m.remove());
{ duration: 220 * left, easing: EASE_IN, fill: 'forwards' },
).onfinish = () => m.remove();
prior.forEach((a) => a.cancel());
};
const markIn = (m: HTMLElement) =>
play(
m,
+76 -20
View File
@@ -19,6 +19,26 @@ export interface IconSeg<T extends string> {
sync(v: T): void;
}
/** Where a name stands on screen: its width of `full` (its words' whole width), and its opacity. */
export interface LabelAt {
width: number;
full: number;
opacity: number;
}
/**
* How a name fades on a pick, from where it stands (ms): the picked one blurs
* in (280, a beat after the pill sets off), the others fold (220); a fade
* turned back half-way runs only the share of its way it has left, and a name
* already folded has nothing to do (0).
*/
export function labelFade(at: LabelAt, picked: boolean): { duration: number; delay: number } {
const opacity = Math.min(1, Math.max(0, at.opacity));
if (picked) return { duration: 280 * (1 - opacity), delay: 70 * (1 - opacity) };
const left = Math.max(opacity, at.full > 0 ? Math.min(1, at.width / at.full) : 0);
return { duration: left > 0.01 ? 220 * left : 0, delay: 0 };
}
export function iconSeg<T extends string>(items: SegItem<T>[], value: T, onPick: (v: T) => void): IconSeg<T> {
const pill = h('span', { class: 'seg-pill' });
const el = h('div', { class: 'seg appseg', role: 'tablist' }, pill);
@@ -59,32 +79,68 @@ export function iconSeg<T extends string>(items: SegItem<T>[], value: T, onPick:
const cs = getComputedStyle(pill);
const l0 = parseFloat(cs.left) || 0;
const r0 = parseFloat(cs.right) || 0;
// Each item's share as it stands, and its basis (a narrow picker gives a picked item more: controls.css).
const g0 = btns.map((b) => parseFloat(getComputedStyle(b).flexGrow) || 0);
const oldL = labelOf(btns[from]);
const oldW = oldL.getBoundingClientRect().width;
[...btns, ...btns.map(labelOf)].forEach((x) => x.getAnimations().forEach((a) => a.cancel()));
const f0 = btns.map((b) => getComputedStyle(b).flexBasis);
// Every name from where it stands too: a pick turned back half-way (or an item still folding from the one
// before) goes on from there, so neither a name nor the icon beside it jumps.
const labels = btns.map(labelOf);
const now = labels.map((l) => {
const s = getComputedStyle(l);
return { width: l.getBoundingClientRect().width, opacity: +s.opacity, filter: s.filter, marginLeft: s.marginLeft };
});
[...btns, ...labels].forEach((x) => x.getAnimations().forEach((a) => a.cancel()));
value = v;
mark();
// The picked name's whole width, as it will stand once its item has its share.
const w1 = labels[to].getBoundingClientRect().width;
btns.forEach((b, i) => {
const g1 = i === to ? 1 : 0;
if (g0[i] !== g1) play(b, [{ flexGrow: g0[i] }, { flexGrow: g1 }], { duration: SMOOTH.duration, easing: SMOOTH.easing });
const f1 = getComputedStyle(b).flexBasis;
if (g0[i] !== g1 || f0[i] !== f1)
play(
b,
[
{ flexGrow: g0[i], flexBasis: f0[i] },
{ flexGrow: g1, flexBasis: f1 },
],
{ duration: SMOOTH.duration, easing: SMOOTH.easing },
);
});
labels.forEach((l, i) => {
const n = now[i];
const fade = labelFade({ ...n, full: l.scrollWidth }, i === to);
if (i !== to) {
// It folds (its blur, if it was still coming in, stays while it fades).
if (fade.duration)
play(
l,
[
{ opacity: n.opacity, maxWidth: `${n.width}px`, marginLeft: n.marginLeft, filter: n.filter },
{ opacity: 0, maxWidth: '0px', marginLeft: '-8px', filter: n.filter },
],
{ duration: fade.duration, easing: 'ease-out' },
);
return;
}
// The picked name opens with its item's share, inside the pill, and blurs in.
play(
l,
[
{ maxWidth: `${n.width}px`, marginLeft: n.marginLeft },
{ maxWidth: `${w1}px`, marginLeft: '0px' },
],
{ duration: SMOOTH.duration, easing: SMOOTH.easing },
);
play(
l,
[
{ opacity: n.opacity, filter: n.opacity ? n.filter : 'blur(4px)' },
{ opacity: 1, filter: 'none' },
],
{ ...fade, easing: EASE_OUT, fill: 'backwards' },
);
});
play(
oldL,
[
{ opacity: 1, maxWidth: `${oldW}px`, marginLeft: '0px' },
{ opacity: 0, maxWidth: '0px', marginLeft: '-8px' },
],
{ duration: 220, easing: 'ease-out' },
);
play(
labelOf(btns[to]),
[
{ opacity: 0, filter: 'blur(4px)' },
{ opacity: 1, filter: 'none' },
],
{ duration: 280, delay: 70, easing: EASE_OUT, fill: 'backwards' },
);
// The stretch: the leading edge follows the quick spring, the trailing edge the smooth one.
const right = to > from;
const lead = calm() ? SMOOTH : LEAD;
+180 -85
View File
@@ -1,12 +1,13 @@
// The sheet: one drawer floating at the bottom of the screen, on phones and
// desktops alike. It holds a stack of views (go/back), glides to each view's
// height, widens on a desktop for a dense QR code until the code gets its
// pixels, pins a view's own buttons beside ×, and closes by ×, the scrim, a
// The sheet: a drawer at the bottom of a phone's screen, a dialog in the
// middle of a computer's. It holds a stack of views (go/back), glides to each
// view's height, widens on a desktop for a dense QR code until the code gets
// its pixels, pins a view's own buttons beside ×, and closes by ×, the scrim, a
// pull down on its header, Escape, or the phone's back button (it is a history
// entry). Views are built by the flows; this module only moves them.
// entry). A flow that comes while it is on its way out opens once it is gone.
// Views are built by the flows; this module only moves them.
import { h, ic } from '../dom';
import { BOUNCY, DRAWER, EASE_IN, EASE_OUT, SMOOTH, SOFT, dismisses, play, rubber } from '../motion';
import { BOUNCY, DRAWER, EASE_IN, EASE_OUT, SMOOTH, SOFT, dismisses, play, rubber, unrubber } from '../motion';
import { closeMenu } from './menu';
/** A view: its root, and what the sheet reads from it. */
@@ -32,11 +33,19 @@ let vp: HTMLElement;
let stack: ViewFactory[] = [];
let closed: (() => void) | null = null;
let left: (() => void) | null = null;
/** A flow that came while the sheet was on its way out (an answer after Cancel): it opens once the sheet is gone. */
let next: ViewFactory | null = null;
let ownsHistory = false;
let returnFocus: HTMLElement | null = null;
/** Until then clicks in a sheet just opened are the second half of the double click that opened it. */
let quietUntil = 0;
export const sheetOpen = () => !!root?.classList.contains('open');
/** What runs on `el` and moves one of `props`: stopped or waited for without touching the rest. */
const running = (el: Element, ...props: string[]) =>
el.getAnimations().filter((a) => (a.effect as KeyframeEffect | null)?.getKeyframes().some((k) => props.some((p) => p in k)));
/* ---------- width: a dense code scans from a screen at about 3 px a module ---------- */
const SHEET_W = 400;
@@ -56,8 +65,9 @@ export interface WidthPlan {
/**
* The width the sheet needs now, set at once so whatever measures the new
* layout (an accordion, the height glide) measures it at the final width; the
* plan then animates there on the same spring (`startWidth`), so nothing snaps.
* layout (an accordion) measures it at the final width; the plan then animates
* there on the same spring (`startWidth`), so nothing snaps. The sheet's own
* height follows its view through the glide (`glideHeight`).
*/
export function planWidth(): WidthPlan | null {
if (!root || !sheetOpen()) return null;
@@ -81,10 +91,7 @@ export function planWidth(): WidthPlan | null {
if (Math.abs(want - sheetW) < 8) return reveal ? { from: want, want, reveal } : null;
const from = parseFloat(getComputedStyle(sheetEl).maxWidth) || sheetW;
sheetW = want;
sheetEl
.getAnimations()
.filter((a) => (a.effect as KeyframeEffect | null)?.getKeyframes().some((k) => 'maxWidth' in k))
.forEach((a) => a.cancel());
running(sheetEl, 'maxWidth').forEach((a) => a.cancel());
sheetEl.style.maxWidth = `${want}px`;
return { from, want, reveal };
}
@@ -115,6 +122,17 @@ function build() {
sheetEl = h('div', { class: 'sheet', role: 'dialog', 'aria-modal': 'true' }, closeBtn, actsEl, scroller);
scrim = h('div', { class: 'scrim', onclick: () => closeSheet() });
root = h('div', { class: 'sheet-root', 'aria-hidden': 'true' }, scrim, sheetEl);
// The second click of a double click lands on what the first one opened: the scrim would close the sheet again,
// a question's button would answer it.
root.addEventListener(
'click',
(e) => {
if (performance.now() >= quietUntil) return;
e.preventDefault();
e.stopPropagation();
},
true,
);
document.body.appendChild(root);
new ResizeObserver(() => startWidth(planWidth())).observe(vp);
pullToClose();
@@ -148,6 +166,11 @@ export function onClosed(fn: () => void) {
export function openSheet(factory: ViewFactory) {
if (!root) build();
closeMenu(true);
if (root.dataset.closing) {
// Still on its way out: the new flow opens once it is gone, as it would have a moment later.
next = factory;
return;
}
leave();
if (sheetOpen()) {
// Already open: the new flow takes the place of the old one, history and all.
@@ -156,6 +179,7 @@ export function openSheet(factory: ViewFactory) {
return;
}
returnFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null;
quietUntil = performance.now() + 320;
stack = [factory];
closed = null;
sheetW = SHEET_W;
@@ -194,6 +218,9 @@ export function openSheet(factory: ViewFactory) {
if (!ownsHistory) {
try {
history.pushState({ sheet: true }, '');
// The sheet's own entry never moves the page: left behind once the sheet closes, a step forward onto it (Safari's
// swipe in from the right edge) would put the page back where it stood when the sheet opened.
history.scrollRestoration = 'manual';
ownsHistory = true;
} catch {
/* no history */
@@ -203,63 +230,91 @@ export function openSheet(factory: ViewFactory) {
/** `now`: gone at once (Escape: what the keyboard does never animates). */
export function closeSheet(now = false) {
if (!sheetOpen() || root.dataset.closing) return;
if (!sheetOpen()) return;
if (root.dataset.closing) {
// Escape while it goes, or the link stopped working: gone at once, and nothing opens after it.
if (now) {
next = null;
gone();
}
return;
}
leave();
if (ownsHistory) {
ownsHistory = false;
history.back();
}
document.body.classList.remove('locked');
const done = () => {
root.classList.remove('open');
root.setAttribute('aria-hidden', 'true');
delete root.dataset.closing;
sheetEl.style.transform = '';
scrim.style.opacity = '';
sheetEl.getAnimations().forEach((a) => a.cancel());
scrim.getAnimations().forEach((a) => a.cancel());
vp.getAnimations().forEach((a) => a.cancel());
vp.replaceChildren();
actsEl.replaceChildren();
sheetEl.classList.remove('arrived');
sheetEl.style.maxWidth = '';
sheetW = SHEET_W;
stack = [];
if (returnFocus?.isConnected) returnFocus.focus({ preventScroll: true });
returnFocus = null;
const f = closed;
closed = null;
f?.();
};
if (now) return done();
if (now) return gone();
root.dataset.closing = '1';
const from = getComputedStyle(sheetEl).transform;
sheetEl.getAnimations().forEach((a) => a.cancel());
// From where it stands: a dialog still coming up leaves from its present fade, blur and scale.
const cs = getComputedStyle(sheetEl);
const at = cs.transform;
const op = cs.opacity;
const blur = cs.filter === 'none' ? 'blur(0px)' : cs.filter;
const dim = getComputedStyle(scrim).opacity;
running(sheetEl, 'transform', 'opacity').forEach((a) => a.cancel());
scrim.getAnimations().forEach((a) => a.cancel());
play(
scrim,
[{ opacity: getComputedStyle(scrim).opacity }, { opacity: 0 }],
[{ opacity: dim }, { opacity: 0 }],
wide() ? { duration: 120, easing: EASE_IN, fill: 'forwards' } : { duration: 320, easing: 'ease-out', fill: 'forwards' },
);
const at = from === 'none' ? 'none' : from;
// A dialog goes the way a ⋯ menu does, quick and soft into its centre; the drawer goes down past the edge.
play(
sheetEl,
wide()
? [
{ opacity: 1, transform: at, filter: 'blur(0px)' },
{ opacity: op, transform: at, filter: blur },
{ opacity: 0, transform: `${at === 'none' ? '' : at} scale(.96)`.trim(), filter: 'blur(3px)' },
]
: [{ transform: at }, { transform: 'translateY(calc(100% + 40px))' }],
wide() ? { duration: 120, easing: EASE_IN, fill: 'forwards' } : { duration: 420, easing: DRAWER, fill: 'forwards' },
).onfinish = done;
).onfinish = gone;
}
// The phone's back button closes the sheet instead of leaving the page.
/** The sheet is out of the page: emptied, focus back on what opened it, then whatever waited for it. */
function gone() {
// Nothing a view holds (a poll) outlives the sheet.
leave();
root.classList.remove('open');
root.setAttribute('aria-hidden', 'true');
delete root.dataset.closing;
sheetEl.style.transform = '';
scrim.style.opacity = '';
sheetEl.getAnimations().forEach((a) => a.cancel());
scrim.getAnimations().forEach((a) => a.cancel());
vp.replaceChildren();
actsEl.replaceChildren();
sheetEl.classList.remove('arrived');
sheetEl.style.maxWidth = '';
sheetW = SHEET_W;
stack = [];
if (returnFocus?.isConnected) returnFocus.focus({ preventScroll: true });
returnFocus = null;
const f = closed;
closed = null;
f?.();
const n = next;
next = null;
if (n) openSheet(n);
}
/** On the history entry a sheet pushed (openSheet): closing it steps back to the page's own. */
export const onSheetEntry = () => !!(history.state as { sheet?: boolean } | null)?.sheet;
// The phone's back button closes the sheet instead of leaving the page. A sheet's entry is current only while its
// sheet is open: one left behind (a reload with a sheet open, a step forward onto it) is stepped back off at once, so
// Back from there leaves the page instead of putting it back where it stood when that sheet opened.
addEventListener('popstate', () => {
if (!sheetOpen()) return;
if (!sheetOpen()) {
if (onSheetEntry()) history.back();
return;
}
ownsHistory = false;
closeSheet();
});
if (onSheetEntry()) history.back();
/** A view's own buttons beside ×: pinned with it while the sheet scrolls, they come and go with the view. */
function setActs(v: View, anim = true) {
@@ -301,17 +356,38 @@ function setActs(v: View, anim = true) {
}
}
/**
* The viewport glides from `h0`, its height on screen, to its view's: as a gap under the view that closes, or an
* overhang the viewport clips, so what changes inside meanwhile (a row opening, a fold, a poll) carries the sheet's
* edge along instead of landing when the glide ends.
*/
function glideHeight(view: Element | null, h0: number, o: KeyframeAnimationOptions) {
if (!view) return;
running(view, 'marginBottom').forEach((a) => a.cancel());
const d = h0 - vp.getBoundingClientRect().height;
if (Math.abs(d) > 1) play(view, [{ marginBottom: `${d}px` }, { marginBottom: '0px' }], o);
}
/** Another view in the open sheet: the old one fades out over the new one, the sheet glides to its height. */
function swapView(v: View) {
label(v);
setActs(v);
sheetEl.classList.remove('arrived');
const old = [...vp.children] as HTMLElement[];
const h0 = vp.getBoundingClientRect().height;
vp.getAnimations().forEach((a) => a.cancel());
old.forEach((o) => {
// What goes stays where it stands on screen while the scroll goes back to the top under it (the viewport clips it);
// a view already on its way out keeps its own fade.
const st = scroller.scrollTop;
const views = [...vp.children] as HTMLElement[];
const tops = views.map((o) => (o.classList.contains('leaving') ? parseFloat(o.style.top) || 0 : 0) - st);
const old = views.filter((o) => !o.classList.contains('leaving'));
// It fades from how it shows: one still coming in (Back right after a step) goes from as far as it came.
const shown = old.map((o) => {
const cs = getComputedStyle(o);
return { opacity: cs.opacity, transform: cs.transform, filter: cs.filter };
});
views.forEach((o, i) => {
o.classList.add('leaving');
Object.assign(o.style, { position: 'absolute', left: '0', right: '0', top: '0', pointerEvents: 'none' });
Object.assign(o.style, { position: 'absolute', left: '0', right: '0', top: `${tops[i]}px`, pointerEvents: 'none' });
o.inert = true;
});
vp.appendChild(v.el);
@@ -319,25 +395,17 @@ function swapView(v: View) {
v.el.style.pointerEvents = 'none';
setTimeout(() => (v.el.style.pointerEvents = ''), 320);
scroller.scrollTop = 0;
const plan = planWidth();
const h1 = v.el.getBoundingClientRect().height;
play(vp, [{ height: `${h0}px` }, { height: `${h1}px` }], { duration: 360, easing: 'cubic-bezier(.25,1,.5,1)' });
startWidth(plan);
old.forEach(
(o) =>
(play(
o,
[
{ opacity: 1, transform: 'none', filter: 'none' },
{ opacity: 0, transform: 'scale(.96)', filter: 'blur(2px)' },
],
{
duration: 200,
easing: 'cubic-bezier(.2,0,0,1)',
fill: 'forwards',
},
).onfinish = () => o.remove()),
);
startWidth(planWidth());
glideHeight(v.el, h0, { duration: 360, easing: 'cubic-bezier(.25,1,.5,1)' });
old.forEach((o, i) => {
const prior = o.getAnimations();
play(o, [shown[i], { opacity: 0, transform: 'scale(.96)', filter: 'blur(2px)' }], {
duration: 200 * +shown[i].opacity,
easing: 'cubic-bezier(.2,0,0,1)',
fill: 'forwards',
}).onfinish = () => o.remove();
prior.forEach((a) => a.cancel());
});
play(
v.el,
[
@@ -355,14 +423,14 @@ function swapView(v: View) {
/** Further into a flow (Add → Open on the device). */
export function go(factory: ViewFactory) {
if (!sheetOpen()) return openSheet(factory);
if (!sheetOpen() || root.dataset.closing) return openSheet(factory);
leave();
stack.push(factory);
swapView(factory());
}
export function back() {
if (stack.length < 2) return;
if (stack.length < 2 || root.dataset.closing) return;
leave();
stack.pop();
swapView(stack[stack.length - 1]());
@@ -375,19 +443,17 @@ export function back() {
*/
export function glide(change: () => void, focus: (Element | null | undefined)[] = []) {
if (!sheetOpen()) return change();
const h0 = vp.getBoundingClientRect().height;
vp.getAnimations().forEach((a) => a.cancel());
const view = vp.lastElementChild;
// As it all stands on screen, the sheet's own glides under way included.
const was = new Map<Element, DOMRect>();
view?.querySelectorAll('*').forEach((e) => {
if (!(e instanceof SVGElement) || e instanceof SVGSVGElement) was.set(e, e.getBoundingClientRect());
});
const h0 = vp.getBoundingClientRect().height;
change();
const plan = planWidth();
const h1 = vp.getBoundingClientRect().height;
if (Math.abs(h1 - h0) > 1) play(vp, [{ height: `${h0}px` }, { height: `${h1}px` }], { duration: SMOOTH.duration, easing: SMOOTH.easing });
startWidth(plan);
// Measured with the sheet back at its old size (its glides have just started): only what moved inside it moves.
startWidth(planWidth());
glideHeight(view, h0, { duration: SMOOTH.duration, easing: SMOOTH.easing });
// Measured with the sheet back at its size on screen (its glides have just started): only what moved inside it moves.
const moved = new Set<Element>();
for (const [e, r] of was) {
if (!e.isConnected || !r.width || !r.height) continue;
@@ -401,7 +467,13 @@ export function glide(change: () => void, focus: (Element | null | undefined)[]
let p = e.parentElement;
while (p && p !== view && !moved.has(p)) p = p.parentElement;
if (p && p !== view) continue;
play(e, [{ transform: `translate(${dx}px, ${dy}px)` }, { transform: 'none' }], { duration: SMOOTH.duration, easing: SMOOTH.easing });
// Added to a glide still under way (a quick second pick), which runs on to its end underneath: both rects held
// its offset, so this is only the new move, and nothing it had left to go is dropped.
play(e, [{ transform: `translate(${dx}px, ${dy}px)` }, { transform: 'none' }], {
duration: SMOOTH.duration,
easing: SMOOTH.easing,
composite: 'add',
});
}
for (const el of focus)
if (el)
@@ -415,9 +487,12 @@ export function glide(change: () => void, focus: (Element | null | undefined)[]
);
}
/** The view's job is done (a device connected): ×, and the view's own buttons, step away. */
export function settle() {
sheetEl?.classList.add('arrived');
/**
* The view's job is done (a device connected): ×, and the view's own buttons, step away. `false`: it turned out
* not to be (the device left that state): they come back.
*/
export function settle(done = true) {
sheetEl?.classList.toggle('arrived', done);
}
/** The sheet scrolls back to the top (a device connected under a scrolled sheet). */
@@ -428,12 +503,27 @@ export const showing = (el: Element) => sheetOpen() && vp.contains(el) && !el.cl
/* ---------- pull down by the header to close ---------- */
/** The dim a pull alone leaves: it fades as the sheet goes down. */
const dimAt = (dy: number) => Math.max(0, 1 - Math.max(0, dy) / 420);
function pullToClose() {
let drag: { y: number; t: number; dy: number; v: number } | null = null;
// `y`: where the finger would stand with the sheet at rest; `y0`: where the sheet was taken; `off`: how far the dim
// was then from what the pull alone gives (a sheet taken while it still opens).
let drag: { y: number; t: number; dy: number; v: number; y0: number; off: number } | null = null;
sheetEl.addEventListener('pointerdown', (e) => {
const t = e.target as Element;
if (!t.closest('.vhead') || t.closest('button, a, input')) return;
drag = { y: e.clientY, t: performance.now(), dy: 0, v: 0 };
// Not while it leaves, nor while a dialog pops up: its fade and blur ride the same animation as its scale.
if (root.dataset.closing || running(sheetEl, 'opacity').length) return;
// Taken where it stands (still rising, or settling back from the last pull), and the dim with it.
const y0 = new DOMMatrixReadOnly(getComputedStyle(sheetEl).transform).m42;
const o = +getComputedStyle(scrim).opacity;
running(sheetEl, 'transform').forEach((a) => a.cancel());
scrim.getAnimations().forEach((a) => a.cancel());
if (y0) sheetEl.style.transform = `translateY(${y0}px)`;
if (o !== 1) scrim.style.opacity = String(o);
const raw = y0 < 0 ? -unrubber(-y0, sheetEl.offsetHeight) : y0;
drag = { y: e.clientY - raw, t: performance.now(), dy: y0, v: 0, y0, off: o - dimAt(y0) };
sheetEl.setPointerCapture(e.pointerId);
});
sheetEl.addEventListener('pointermove', (e) => {
@@ -446,17 +536,22 @@ function pullToClose() {
drag.dy = dy;
drag.t = t;
sheetEl.style.transform = `translateY(${dy}px)`;
scrim.style.opacity = String(Math.max(0, 1 - Math.max(0, dy) / 420));
scrim.style.opacity = String(Math.min(1, Math.max(0, dimAt(dy) + drag.off)));
});
const end = () => {
if (!drag) return;
const { dy, v } = drag;
const { dy, v, y0 } = drag;
drag = null;
if (dismisses(dy, v, sheetEl.offsetHeight)) return closeSheet();
// A touch that never moved (on a sheet still rising) only lets it settle.
if (dy !== y0 && dismisses(dy, v, sheetEl.offsetHeight)) return closeSheet();
// Back to rest from where the pull left it, the dim with it on the same spring.
const from = sheetEl.style.transform;
const dim = getComputedStyle(scrim).opacity;
sheetEl.style.transform = '';
scrim.style.opacity = '';
if (dy !== 0) play(sheetEl, [{ transform: from }, { transform: 'none' }], { duration: SMOOTH.duration, easing: SMOOTH.easing });
const o = { duration: SMOOTH.duration, easing: SMOOTH.easing };
if (dy !== 0) play(sheetEl, [{ transform: from }, { transform: 'none' }], o);
if (+dim !== 1) play(scrim, [{ opacity: dim }, { opacity: 1 }], o);
};
sheetEl.addEventListener('pointerup', end);
sheetEl.addEventListener('pointercancel', end);
+151
View File
@@ -0,0 +1,151 @@
// A light sweeping across a field's words while they are on their way to the router (a device's name being
// saved), as an assistant's "thinking" line does: a copy of the words laid exactly over the input's dims, and a
// band with a bell-shaped falloff crosses it again and again with a rest between. Stopping holds the band where it
// is and fades the words back to their colour around it; only then does the copy go, so the input's own words
// (or what takes their place) show with nothing changing. The band is the words' own colour over a muted base
// (styles/controls.css, `.shim`). With less motion asked for it only dims and comes back.
import { h } from '../dom';
import { calm } from '../motion';
/** A cubic-bezier easing as a function of progress (0..1). */
function bezier(x1: number, y1: number, x2: number, y2: number): (x: number) => number {
const at = (a: number, b: number, t: number) => 3 * a * t * (1 - t) ** 2 + 3 * b * t * t * (1 - t) + t ** 3;
return (x) => {
let lo = 0;
let hi = 1;
for (let i = 0; i < 24; i++) {
const mid = (lo + hi) / 2;
if (at(x1, x2, mid) < x) lo = mid;
else hi = mid;
}
return at(y1, y2, (lo + hi) / 2);
};
}
const STANDARD = bezier(0.2, 0, 0, 1);
const linear = (x: number) => x;
/** One value that moves; a new move of it stops the old one first. */
class Value {
v: number;
private stop: (() => void) | null = null;
constructor(
v: number,
private paint: () => void,
) {
this.v = v;
}
/** To `to` over `ms` (after `delay`), from where it is: true once there, false if stopped first. */
to(to: number, ms: number, ease: (x: number) => number, delay = 0): Promise<boolean> {
this.halt();
return new Promise((done) => {
let t0 = 0;
let from = this.v;
const step = (now: number) => {
if (!t0) {
t0 = now + delay;
from = this.v;
}
const k = ms <= 0 ? 1 : Math.min(1, Math.max(0, (now - t0) / ms));
if (now >= t0) {
this.v = from + (to - from) * ease(k);
this.paint();
}
if (k < 1) raf = requestAnimationFrame(step);
else {
this.stop = null;
done(true);
}
};
let raf = requestAnimationFrame(step);
this.stop = () => {
cancelAnimationFrame(raf);
this.stop = null;
done(false);
};
});
}
halt() {
this.stop?.();
}
}
/** Half the band's width in em, and its falloff as [offset, strength]. */
const BAND = 2.2;
const FALLOFF = [
[-1, 0],
[-0.5, 0.5],
[-0.2, 0.9],
[0, 1],
[0.2, 0.9],
[0.5, 0.5],
[1, 0],
] as const;
const pct = (x: number) => `${(x * 100).toFixed(1)}%`;
/** The band at sweep `t` (0: left of the words, 1: right of them) over a base `settle` of the way to solid. */
function image(t: number, settle: number): string {
const base = `color-mix(in oklab, var(--shim-high) ${pct(settle)}, var(--shim-base))`;
const stops = FALLOFF.map(
([o, k]) =>
`color-mix(in oklab, var(--shim-high) ${pct(k)}, ${base}) calc(${(t * 100).toFixed(2)}% + ${((2 * t - 1 + o) * BAND).toFixed(3)}em)`,
);
return `linear-gradient(90deg, ${base}, ${stops.join(', ')}, ${base})`;
}
/** The input's font, for a copy of its words that has to sit exactly on them. */
const FONT = ['fontFamily', 'fontSize', 'fontWeight', 'letterSpacing', 'fontFeatureSettings', 'fontVariationSettings'] as const;
/** Seconds for one sweep across the words, and the rest between sweeps (a share of it). */
const SWEEP = 1.8;
const REST = 0.32;
/** How long the words take to fade back to their colour once the answer is in, in ms. */
const SETTLE = 480;
/**
* Start the shimmer over `input` (inside `field`, which it marks `.saving`). Returns the stop, which resolves
* once the words are solid again and the copy is gone.
*/
export function shimmer(field: HTMLElement, input: HTMLInputElement): () => Promise<void> {
const cs = getComputedStyle(input);
// The copy sits in a box the input's size and is clipped to it, scrolled as the input is: a name longer than
// the field shows the same part, never more.
const copy = h('span', { class: 'shim' }, input.value);
const clip = h('span', { class: 'shim-clip', 'aria-hidden': 'true' }, copy);
for (const k of FONT) copy.style[k] = cs[k];
Object.assign(clip.style, {
left: `${input.offsetLeft}px`,
top: `${input.offsetTop}px`,
width: `${input.clientWidth}px`,
height: `${input.offsetHeight}px`,
});
Object.assign(copy.style, { left: `${-input.scrollLeft}px`, lineHeight: `${input.offsetHeight}px` });
const still = calm();
const paint = () => (copy.style.backgroundImage = image(sweep.v, settle.v));
// Solid at first, exactly the input's words: the swap shows nothing, then it dims.
const sweep = new Value(0, paint);
const settle = new Value(1, paint);
paint();
field.append(clip);
field.classList.add('saving');
field.setAttribute('aria-busy', 'true');
let running = !still;
const pass = async (delay: number) => {
if (!running) return;
if (sweep.v >= 1) sweep.v = 0;
if (await sweep.to(1, SWEEP * 1000 * (1 - sweep.v), linear, delay * 1000)) void pass(SWEEP * REST);
};
void pass(0.12);
void settle.to(0, still ? 0 : 240, STANDARD);
return async () => {
// The band stops where it is and the words fade back to their colour around it: nothing races off.
running = false;
sweep.halt();
await settle.to(1, still ? 0 : SETTLE, STANDARD);
field.classList.remove('saving');
field.removeAttribute('aria-busy');
clip.remove();
};
}